Saving HTML to database with Symfony-2.0 form component - mysql

I am trying to save HTML content with the Symfony2 form system but I am facing issues with escaping.
My addPost action looks like this
$em = $this->getDoctrine()->getEntityManager();
$post = new Post();
$postForm = $this->createForm(new PostFormType(), $post);
if ($request->getMethod() == 'POST') {
$postForm->bindRequest($request);
if($postForm->isValid()){
$em->persist($post);
$em->flush();
}
}
The problem is that the post form has a content textarea that allows the user to enter html. When the form is submitted with html like test the content gets saved to the database as test. And then on each subsequent save the backslashes escape themselves again and again...
What is the proper way to store HTML with the Symfony2 form component?

You should remove the backslashes from the string before sending it to the user to edit. You should be able to get the content from the $post object and then strip its slashes and set it back to the post content like so.
$post = new Post();
$post->setContent(stripslashes($post->getContent()));
$postForm = $this->createForm(new PostFormType(), $post);
Now when the form renders it will not have the escape characters.
However, I have found that if you return a response to the same page you will still see the backslashes. To avoid this you can return a RedirectResponse like this
if($postForm->isValid()){
$em->flush();
return new RedirectResponse('route', array('postId' => $postId)));
}

Those slashes are placed there so that the mysql engine doesn't confuse those quotes with sql syntax. I suggest you use a rejex to get rid of all the slashes when you retrieve the field from the database, but before you post it to the client. let me see if I can find the rejex for you, maybe someone will beat me to it :)

Related

$.post(url, data) doesn't work

I'm creating simple twitter_clone using Rails to create json API and ReactJS in frontend.
What I need now is to save new created tweet into DB and then to update an API in json which contain list of tweets to be able to use them to render a view.
To achieve it I try to use post request:
My add tweet function in main.jsx file
addTweet(tweetToAdd){
$.post("/tweets", { body: tweetToAdd }) //after saving to database
.success( savedTweet => {
let newTweetsList = this.state.tweetsList;
newTweetsList.unshift(savedTweet);
this.setState({tweetsList: newTweetsList});
})
.error(error => console.log(error));
}
There is a problem with delivering body of the tweet to database, cause after submitting there is NULL here.
Probably it means that body isn't send to DB ,but rest of parameters there are.
in /tweets there is an json API which looks like:
[{"id":17,"user_id":1,"body":null,"created_at":"2015-12-18T10:11:25.085Z","updated_at":"2015-12-18T10:11:25.085Z","name":"Marek Czyż"}]
When I create tweet manually form console everything works. so the problem must have been in previous piece of code.
Secondly after pressing SUBMIT tweet Ive recevied a warning that
Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of TweetList. See fb.me/react-warning-keys for more information.
although Ive got a key to every Tweet:
let tweets = this.props.tweets.map(tweet => );
Please, help me.
Assuming you're passing the right value as tweetToAdd, make sure you permit the body param in your controller. If it works in the console, it's not a validation problem, rather an unpermitted param.
As for the error you're seeing, you'll need to add a key prop to each rendered tweet. Something like:
render() {
let tweets = this.props.tweets;
return <ul>
{tweets.map(tweet => {
return <li key={tweet.id}>{tweet.body}</li>;
})}
</ul>;
}

How to get a JSON response without template in eZ Publish?

I intending to get a json response without rendering a view with eZ Publish.
So I trying to use a custom module to do that:
function jsonConvert(){
$articles = eZFunctionHandler::execute(
'content',
'tree',
array(
'parent_node_id' => '59'
)
);
header("Content-Type: application/json");
return json_encode($articles);
}
echo jsonConvert();
How can I compile this module without using a basic URL that rendering a view like domain.com/module/view/ in order to get a json response without any HTML code?
echo json_encode( YOUR ARRAY );
eZExecution::cleanExit();
It's all what you need in your custom module/view php file to return json.
If I were you :
use the builtin feature that allows you to use a different layout to render a content view. Create a new layout 'MYLAYOUT' within a layout.ini.append.php override (see https://doc.ez.no/eZ-Publish/Technical-manual/4.x/Reference/Configuration-files/layout.ini) and then call your view using /layout/set/MYLAYOUT/your/content/uri
specify the content type in the layout configuration to match your requirements (application/json as the content type)
create a pagelayout.tpl template used by your newly created layout which basically only contains {$module_result.content}
create a template operator to convert your contents into a 'readable' json and call it from the template rendering your content (probably a /node/view/full.tpl override)
alternative (but not that sexy) to #4 => call json_encode directly in your template by allowing the php function to be called in your templates (see https://doc.ez.no/eZ-Publish/Technical-manual/4.x/Reference/Configuration-files/template.ini/PHP/PHPOperatorList)
To get a blank pagelayout in your module, and set a json content type, you can add this following lines in your module php file :
header("Content-Type: application/json");
$Result = array();
$Result['content'] = json_encode($articles);
$Result['pagelayout'] = false;

Zend Jquery Autocomplete populate from Database

Hi I am trying to implement a autocomplete field using Zend Jquery. I followed a tutorial to grab the data from an array and I have extended the code to access the data from my mysql table.
IndexController.php
$this->view->autocompleteElement = new ZendX_JQuery_Form_Element_AutoComplete('ac');
$this->view->autocompleteElement->setLabel('Autocomplete');
$this->view->autocompleteElement->setJQueryParam('source', '/index/city');
This calls the cityAction()
public function cityAction()
{
$results = Application_Model_City::search($this->_getParam('term'));
$this->_helper->json(array_values($results));
}
I then call the Model City
public static function search($term)
{
$region = new Application_Model_DbTable_Regions();
$results = $region->getRegion($term);
return $results;
}
And finally the Regions db model
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
Now when I go the autocomplete field it shows the results but as UNDEFINED , I think its something to do the way I am send the data back to the json helper.
I used firebug and I can see the data is been pulled in the following format.
[{"City":"London"},{"City":"Londonderry"},{"City":"Longfield"},{"City":"Longhope"},{"City":"Longniddry"}]
I think this format is incorrect, please any body dealt with this before?
Cheers
J
The ZendX_JQuery_Form_Element_AutoComplete element is a proxy to the AutoComplete View Helper, which is a proxy to the jQuery UI Autocomplete widget.
If you read the overview on the jQuery UI Autocomplete page, you will note:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
So, the JSON you are returning to the autocomplete should be structured more like:
[{"label":"London","value":"London"},{"label":"Londonderry","value":"Londonderry"},{"label":"Longfield","value":"Longfield"}]
Good luck!
Fixed the problem afters hours of pain!
I modified the below code where it accesses the data
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
I added a line of SQL City AS Value
public function getRegion($term)
{
$select = $this->select()->from($this,'City AS value')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
This seems to have worked!
Cheers
J

Update two different values with one AJAX response

I want to update two different values with one ajax-response.
<span id="nr1">Change this</span>
<span id="nr2">and change this</span>
Now I can just change one value, I do like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText;
Is it possible to do something like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText1;
document.getElementById('nr2').innerHTML = xmlHttp.responseText2;
**** UPDATE ****
The response comes from php.
I'm totally new to JSON.
There are no responseText1 and responseText2 properties of an XMLHTTPRequest(which I assume your xmlHttp is), just responseText, so you have to return something parsable in that responseText field(like JSON). So you server may send back {"firstResponse":"value1","secondResponse":"value2"} and you can fill your fields from that JSON string. Use the json2.js library from json.org
<script type="text/javascript" src="json2.js"></script>
. . .
var theResponse = JSON.parse(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = theResponse.firstResponse;
document.getElementById('nr2').innerHTML = theResponse.secondResponse;
EDIT:
In order to craft this JSON response from PHP you should use the PHP JSON libraries. There are several examples in the json_encode page that can get you started. The other code I posted(and that is posted in other responses) are all browser side javascript code.
$arr = array ('firstResponse'=>'value1','secondResponse'=>'value2');
echo json_encode($arr);
Place that code into your PHP script to generate the JSON string
{"firstResponse":"value1","secondResponse":"value2"}
Then the previously posted javascript code will parse that.
If you trust and control the server, just return a dictionary in JSON for the response and use it on the client side. So:
v = eval(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = v['nr1']
document.getElementById('nr2').innerHTML = v['nr2']
As already said it would make sense to return your Ajax call as a JSON Object. I recommend the more secure JSONP call (don't know if you can use any library that supports this natively).
// Your script returns this
callback123(
{
"nr1" : "This is conten for nr1",
"nr2" : "Some content for nr2"
});
// JavaScript callback looks like this
function callback123(data)
{
for(var key in data)
document.getElementById(key).innerHTML = data[key];
}
use JSON.parse
link text

Submit returning the entire page's HTML

When i submit a FORM on my page, my "response text" returns the HTML of the entire page and not only the FORM that submitted. This is normal?
responseText is XHR speak for "What the server responds to the request with, excluding the HTTP headers".
It is perfectly normal for it to include a complete HTML document if you access a resource designed to respond to a regular form submission.
It sounds like you need to be smarter about what the server responds with.
This simple example (written in Perl, see the link for more context) checks a query string parameter to decide if it should place the data it has fetched in an HTML template and return it, or to convert the data to JSON and return that instead.
if ($view eq "json") {
my $data = $json->convert_blessed->encode($vars);
print $q->header('application/json;charset=utf-8'), $data;
return;
}
my $output;
$tt->process('html.tt', $vars, \$output)
|| die $tt->error(), "\n";
print $q->header('text/html;charset=utf-8'), $output;