I need to load a part of view in phalcon for returning in ajax call. For this i need to set the view in variables. Now what happening is i am getting all templates including header and footer.
You need to disable rest of the view rendering. Example of exact situation (returning JSON response for AJAX)
$viewParams = [
'param1' => '....',
'param2' => '....',
];
$response = new \stdClass();
// Render view into a variable
$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);
$response->html = $this->view->getRender('yourTemplateDir', 'yourTemplateName', $viewParams, function($view) {
$view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);
});
// Disable view
$this->view->disable();
return $this->response->setJsonContent($response);
Related
Given a page retrieved at for example:
http://myapp.dev/path/subfolder?param=abc
Whenever the additional GET parameter called param is present it should be added automatically to all subsequent links in my navigation as constructed in the .volt template. For example:
Go to subfolder 2
I.e. based on this .volt link the the goal is to generate:
Go to subfolder 2
If you want to append Query string parameters only for given links you can go with Luke's solution.
However I think you want to achieve something a bit different and it involves custom logic. For this to happen we should create a custom Volt function.
Custom function definition:
public static function urlFor($params, $queryStringParams = [])
{
$di = \Phalcon\DI::getDefault();
if ($di->getRequest()->has('param')) {
$queryStringParams['param'] = $di->getRequest()->get('param');
}
return $di->getUrl()->get($params, $queryStringParams);
}
The above function acts the same as url() function in Phalcon, it just allows us to write a bit of custom logic before passing the parameters to url().
In your case we check if URL contains desired query param and we add it to every URL generated on the current request. In my case the above function is in Helper file so I can use it anywhere I need to.
This is our View service definition:
$di->set('view', function() use ($di) {
$view = new \Phalcon\Mvc\View();
...
$view->registerEngines([
'.phtml' => function($view, $di) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$options = [
'compiledPath' => $di->getConfig()->site->path->cache . 'volt/frontend/',
'compiledExtension' => '.php',
'compileAlways' => $di->getConfig()->debug,
];
$volt->setOptions($options);
...
// IMPORTANT PART: Overwriting default url() function in Volt
$compiler = $volt->getCompiler();
$compiler->addFunction('url', function($resolvedArgs, $exprArgs){
return 'Helpers\Common::urlFor(' . $resolvedArgs . ')';
});
return $volt;
}
]);
return $view;
});
Please note the IMPORTANT PART comment in the above code block.
Let us finish with example:
User is on this address:
http://myapp.dev/path/subfolder?param=abc
But somewhere in your code you want to generate a link to News page:
News
Our code will catch the param in the URL and will generate the following address:
http://myapp.dev/news/list?param=abc
I have a simple controller action that creates a Guest record and renders a template.
// First bind the form to our Guest:
$form->bind( $_POST, $guest );
// Validate and save, or show error messages
if( $form->isValid($_POST, $guest) ) {
if( $guest->save($_POST) ) {
$this->view->setMainView( 'confirm' );
}
}
This works fine before I add any mailer stuff. However, when I add an event handler inside the Guest model which happens to render a template, the controller renders a WHITE SCREEN OF DEATH instead of my confirm template.
In Guest model:
public function afterCreate() {
return GuestMailer::sendEmailConfirmation( $this );
}
In GuestMailer class:
public static function sendEmailConfirmation( $guest ) {
// create/configure $email message
$view = $guest->getDI()->get('simpleView');
$view->render( // Works without this call...
'confirmation_email',
array( 'guest' => $guest )
);
$content = $view->getContent();
$email->content( $content );
return $email->send();
}
Note that when I remove the above call to render(), the confirm template is rendered successfully.
I thought components in Phalcon were supposed to be highly decoupled? Why is rendering a completely different template causing my controller's view to get messed up? How can I avoid this?
I think this problem is caused by a peculiar configuration of the templating service, in a normal workflow it doesn't causes issues, they appears when you need to render "manually" a template as in your case, you can refer to this PhalconPHP forum discussion linked, in particular the answer refered by the link anchor:
http://forum.phalconphp.com/discussion/109/manually-render-separate-file-template-#C12015
For an implementation of Magnific Popup, I need to pass a post id to the ajax settings. The post id is stored in a data attribute of the element to which Magnific Popup is bound. I would like this to work:
html element:
<a data-id="412">Clicke me</a>
Javascript:
$('.element a').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST',
data: ({
action:'theme_post_example',
id: postId
})
}
}
});
Where postId is read from the data attribute.
Thanks in advance.
$('.element a').magnificPopup({
callbacks: {
elementParse: function(item){
postData = {
action :'theme_post_example',
id : $(item.el[0]).attr('data-id')
}
var mp = $.magnificPopup.instance;
mp.st.ajax.settings.data = postData;
}
},
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST'
}
}
});
Here is how to do it:
html:
<a class="modal" data-id="412" data-action="theme_post_example">Click me</a>
jquery:
$('a.modal').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url : php_array.admin_ajax,
dataType : 'json'
}
},
callbacks: {
elementParse: function() {
this.st.ajax.settings.data = {
action : this.st.el.attr('data-action'),
id : this.st.el.attr('data-id')
}
}
},
parseAjax: function( response )
{
response.data = response.data.html;
}
});
php
function theme_post_example()
{
$id = isset( $_GET['id'] ) ? $_GET['id'] : false;
$html = '<div class="white-popup mfp-with-anim">';
/**
* generate your $html code here ...
*/
$html .= '</div>';
echo json_encode( array( "html" => $html ) );
die();
}
As this answer was the original question regarding inserting data into Magnific's ajax call, I'll post this here.
After many hours of trying to figure this out, you should know that if you're using a gallery with the ability to move between gallery items without closing the popup, using elementParse to set your AJAX data will fail when you visit an item after already viewing it (while the popup is still open).
This is because elementParse is wrapped up in a check that it makes detect if an item has already been 'parsed'. Here's a small explanation as to what happens:
Open gallery at item index 2.
Item has not been parsed yet, so it sets the parsed flag to true and runs the elementParse callback (in that order). Your callback sets the ajax options to fetch this item's data, all is well.
Move (right) to item index 3.
Same as above. The item has not been parsed, so it runs the callback. Your callback sets the data. It works.
Move (left) back to item index 2.
This time the item has been parsed. It skips re-parsing the item's element for assumed potential performance reasons.Your callback is not executed. Magnific's ajax data settings will remain the same as if it were item index 3.
The AJAX call is executed with the old settings, it returns with item index 3's data instead, which is rendered to the user. Magnific will believe it is on index 2, but it is rendering index 3's data.
To resolve this, you need to hook onto a callback which is always executed pre-ajax call, like beforeChange.
The main difference is that the current item isn't passed through into the callback. Fortunately, at this point, magnific has updated their pointers to the correct index. You need to fetch the current item's element by using:
var data = {}; // Your key-value data object for jQuery's $.ajax call.
// For non-closures, you can reference mfp's instance using
// $.magnificPopup.instance instead of 'this'.
// e.g.
// var mfp = $.magnificPopup.instance;
// var itemElement = mfp.items[mfp.index].el;
var itemElement = this.items[this.index].el;
// Set the ajax data settings directly.
if(typeof this.st.ajax.settings !== 'object') {
this.st.ajax.settings = {};
}
this.st.ajax.settings.data = data;
This answer can also be used as a suitable alternative to the currently highest voted, as it will work either way.
You may use open public method to open popup dynamically http://dimsemenov.com/plugins/magnific-popup/documentation.html#public_methods
postId = $(this).attr('data-id')
$(this) retrieve the current element (the link you clicked on), and attr the value of the specified attribute.
Is there a way to make a CGridView Not load data on the initial rendering of the view it lives on, and instead make it load the first page with a subsequent AJAX request after the initial page load?
This is mostly for performance optimization. There is a data model that is rather slow behind that CGridView, and I would like to be able to have the page load in a snappy way, then have the data load up a few seconds later with an AJAX request.
You could modify the action as follows:
public function actionIndex() {
$dataProvider = new CActiveDataProvider('User'); // The dataprovider your grid uses
if (!$this->isAjaxRequest()) {
$dataProvider->criteria->addCondition('1 = 0'); // You could also use 0, but I think this is more clear
}
[...]
}
And then in your view in the javascript section:
$(function() { // If you are using jQuery this is executed when the page is loaded
$.fn.yiiGridView.update("{id-of-your-grid-view}");
});
Brewer Gorge was very close, and thanks to his suggested answer, it put me on the right track. This works:
// Controller, after creating $dataProvider, before calling $this->render...
if (!Yii::app()->request->isAjaxRequest) {
$dataProvider->criteria->addCondition('1 = 0');
}
// View
<script type="text/javascript">
$(window).load(function() {
$('#id-of-grid').yiiGridView('update');
});
</script>
Just write your code in controller like this:
$model= new Data('search');
$model->unsetAttributes();
if(isset($_GET['Data']))
$model->attributes = $_GET['Data'];
if (!Yii::app()->request->isAjaxRequest)
$data->id=0; //or something that sure model return empty
I need to render email templates in variable to send them later (which are stored in .phtml files), and i really don't want to implement my special class for handling this.
Is it possible to render not controller action view, but custom one?
I tried following code, but it outputs NULL :((
// Controller context
$view = new Phalcon\Mvc\View();
$view->setViewsDir('app/views/');
$view->setVar('var1', 'var2');
// Setting some vars...
$view->start();
$view->partial($emailTemplatePath);
$view->finish();
$result = $view->getContent();
var_dump($result); // Gives null
In addition to the response by Nikolaos, you can use $view->getRender() to render a single view returning its output.
$view->setViewsDir('apps/views/');
echo $view->getRender('partials', 'test'); // get apps/views/partials/test.phtml
You need to check the path of the $emailTemplatePath. It should point to the correct file i.e.
// points to app/views/partials/email.phtml
$view->partial('partials/email');
If you are using Volt and have registered that as your engine, then your file will need to be:
// app/views/partials/email.volt
I have a project where I use email and pdf templates and what I did was to have the rendering all take place within components.
Firstly, my folder structure contains (and I will only put here what is relevant) a cache, components and views directory. Let's look at the email setup rather than the PDF as this is more relevant to your situation.
/app
/cache
/email
/components
/views
/email
/elements
Of course there is public, controllers etc but let's not think about them for this.
I'm using Swift mailer for mine but I hope you will be able to use this all the same. In /app/components/Swift.php I have a __construct that calls for this->init_template_engine();
/**
* Create a volt templating engine for generating html
*/
private function init_template_engine() {
$this->_template = new \Phalcon\Mvc\View\Simple();
$di = new \Phalcon\DI\FactoryDefault();
$this->_template->setDI($di);
$this->_template->registerEngines([
'.volt' => function($view, $di) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
$volt->setOptions([
'compiledPath' => APP_DIR."cache".DS."email".DS, // render cache in /app/cache/email/
'compiledSeparator' => '_'
]);
return $volt;
// or use ".phtml" => 'Phalcon\Mvc\View\Engine\Php' if you want,
// both will accept PHP code if ya don't fancy it being a 100% volt.
},
]);
// tell it where your templates are
$this->_template->setViewsDir(APP_DIR.'views'.DS.'email'.DS);
return $this->_template;
}
The constants above (like APP_DIR) are something I have already made in my bootstrap and all they do is store full paths to directories.
Once the $_template variable has a template engine set up I can then use it to render my templates.
/**
* Returns HTML via Phalcon's volt engine.
* #param string $template_name
* #param array $data
*/
private function render_template($template_name = null, $data = null) {
// Check we have some data.
if (empty($data)) {
return false; // or set some default data maybe?
}
// Use the template name given to render the file in views/email
if(is_object($this->_template) && !empty($template_name)) {
return $this->_template->render($template_name, ['data' => $data]);
}
return false;
}
A sample volt email template may look like this:
{{ partial('elements/email_head') }}
<h2>Your Order has been dispatched</h2>
<p>Dear {{ data.name }}</p>
<p>Your order with ACME has now been dispatched and should be with you within a few days.</p>
<p>Do not hesitate to contact us should you have any questions when your waste of money arrives.</p>
<p>Thank you for choosing ACME Inc.</p>
{{ partial('elements/email_foot') }}
All I have to do then is grab the html and use swiftmailer's setBody method and I'm done:
->setBody($this->render_template($template, $data), 'text/html');
You don't need to place separate view engines like this in components, it could become memory hungry like that, but it does show the whole process. Hope that makes sense :)
The easiest way to render a view and return it as a variable is to use the Phalcon\Mvc\View\Simple class. In your controller, declare a new instance of the Simple view class and attach a rendering engine to it. You can then use its render() method to select a view file and pass in variables:
// create a simple view to help render sections of the page
$simple_view = new \Phalcon\Mvc\View\Simple();
$simple_view->setViewsDir( __DIR__ . '/../views/' );
$simple_view->setDI( $this->di );
$simple_view->registerEngines(array(
'.volt' => 'Phalcon\Mvc\View\Engine\Volt'
));
// use the simple view to generate one or more widgets
$widget_html = array();
$widget_objects = $widget_search->getWidgetObjects();
forEach( $widget_objects as $widget ){
$widget_html[] = $simple_view->render('index/widgetview',array('widget'=>$widget));
}
// pass the html snippets as a variable into your regular view
$this->view->setVar('widget_html',$widget_html);
use $view->render('partials/email') instead of calling partial method.
I usually use Volt engine and a simple way is a redefine view in DI container, like that:
$view = $this->view;
$content = $view->getRender('mail', 'show',
array(
"var1" => "some value 1",
"var2" => "some value 2"
),
function($view) {
$view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_LAYOUT);
}
);
echo $content;