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;
Related
using DomPdf to create PDF from html.
$html = '<html><head><body>Test</body></head></html>
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($html);
$pdf->render();
return $pdf->stream();
Get error:
Call to protected method Barryvdh\DomPDF\PDF::render() from context 'App\Http\Controllers\TestController'
When remove "
$pdf->render();
Create PDF file,but mess html code...
Tnx, P
I'm guessing you're using https://github.com/barryvdh/laravel-dompdf?
You're receiving the error because you're trying to call a protected method from your controller.
The docs say you can do the following:
You can save it to a file, or stream (show in browser) or download.
$pdf->save('myfile.pdf')
$pdf->stream();
$pdf->download('invoice.pdf');
I have a controller that uploads and processes a file. Afterwards, I wish to render the processing result in a modal div. I wanted to know what the best way is to get the results from the controller to the modal div on the gsp. I thought about a template but I didn't know how to specify what the target div for the template should be because this template wouldn't be rendered by a button click where a target for template render is set as an attribute, it would be done on a timed basis (i.e. when the file is done uploading). The other way is to send JSON back from the controller but I don't know how to intercept this JSON at the right time because I still don't quite understand the timings of the information flow between the GSP and the Controller. I know how to send the JSON but how to alert the GSP that "hey, some JSON is now ready for your modal that's about to go up." Here is some pseoducode of basically what I am trying to get done.
Controller:
upload() {
// process file and store results in three integers
// int1 = result1
// int2 = result2
// int3 = result3
// send the three numbers to the gsp
}
Now what is the best way to get these three numbers to the GSP so that they are displayed on a modal dialog which is about to go up like this:
<div id="fileUploadResultsModal">
Results:
${int1}, ${int2}, ${int3}
</div>
Here is the JS associated with my ajax upload function:
$("#chseFile").upload("${createLink(controller: 'customer', action: 'upload',)}",
{dataTypegrp: parseInt(getCheckedValue(document.getElementsByName('dataTypegrp'))),
fileTypegrp: parseInt(getCheckedValue(document.getElementsByName('fileTypegrp')))},
function(success) {
$("#cancel1").trigger("click");
setTimeout(function(){
$("#summary").trigger("click");
}, 250);
displaySuccess(data);
},
function(prog, value) {
console.log(value);
$("#prog").val(value);
if (value == 100) {
$("#prog").hide();
$("#progressbar").html("Uploading and processing. Please wait...");
}
});
but right now JS complains that 'data' is not defined. 'data' is meant to be the JSON coming back from the controller.
Thanks
you can render them as JSON:
render( [ int1:111, int2:222, int3:333 ] as JSON )
or as a HTML-string
render "<div id=\"fileUploadResultsModal\">Results:${int1}, ${int2}, ${int3}</div>"
or use a template
render template:'/yourController/templateName', model:[ int1:111, int2:222, int3:333 ]
or a TagLib
render g.yourResultTag( int1:111, int2:222, int3:333 )
For this tiny bit of information, the performance is not of concern. It's rather a matter of taste, or what is more appropriate for your client.
If the later is JSON-biased, use JSON-rendering. If it has a mix of JSON and HTML, use others.
inside controller at the enf of controller action you can use
render [data:['name':'firstname','surname':'secondName'] as JSON]
this will render the data to GSP
I'm trying to connect to a REST web service with Drupal 7. Data is supplied via a url and I want to pull it into the D7 site to create and populate nodes. I'm using the feeds module to map the content and the JSONPath parser as the parser. I have also included Feeds HTTPFetcher Append Headers module so that I can add custom headers in to make sure it is JSON being returned and not badly formatted xml which I was getting before.
Custom headers:
Accept|application/json
Content-Type|application/json
I have a url that looks like http://192.136.0.31:8080/places/getAll
Further to the above I have the Devel module in place which is returning the feed array in the page using the code below in my template.php:
$request = drupal_http_request('http://192.136.0.31:8080/places/getAll', $options);
dpm(drupal_json_decode($request->data));
This is what Devel returns:
... (Array, 1192 elements)
0 (Array, 17 elements)
Address1 (String, 19 characters ) 1-2 The Road name
Address2 (String, 9 characters ) Shuinnad
The problem I'm having is getting this into feeds and mapping to the relevant fields. I don't know what should go in the context field - I have tried $...*, $.*, $...[*] but no luck.
When I click on an Array element from the devel output it shows $...[0]['Address1'] which suggests that should be the context - no luck.
Quick Update - using the drupal_json_decode function I can split the array out how I need to using php
foreach ($json as $section => $items) {
foreach ($items as $key => $value) {
//if ($key == 'Address1') {
echo "$section:\t$key\t: $value<br>";
//}
// check whether the current item is an array!
if(is_array($value)) {
echo "$key is sub array:<br />";
foreach($value as $subKey => $subValue)
echo "$subKey:\t$subValue<br />";
}
}
}
The question still stands, how do I replicate that in Feeds using the JSON parser?
You may need to try this module: Feeds JSONPath Parser
See this tutorial
Context: is where you put the JSONPath expression that represents the path to the array representing your data. For instance, in my file, this would be $.albums.data.*. If this were a PHP array, that would be basically
foreach($facebook['albums']['data'] as $value);
See more at: http://glassdimly.com/blog/tech/drupal-7-feeds-extensible-parsers-jsonpath-map-json-fields/feeds-extensible-parsers#sthash.BrIutjfl.dpuf
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 :)
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