Yii 1.1: Avoiding duplicate script download when using CActiveForm on Ajax calls

10 followers

Introduction

Sometimes the active form we wish to use to edit/add a new element on our database is too small and we believe that is much better to use an AJAX'ed dialog/slide form rather than reloading the page to just display one or two fields.

The only thing required is simple, we just need to create a view that will be partially rendered by a call to a controller (using renderPartial) and make sure that we process output -setting to true the parameter on the function. Everything will work as expected but...

The issue

If we open firebug (firefox), or developer tools (chrome), or whatever the tool you use in order to see the XmlHttpRequest object calls and resources downloaded, you will see that every time we do call the controller to display the active form, different Yii "core JS" files keeps being downloaded to the client. The JS files downloaded depends on your code but there are at least jquery.js, jquery-ui.js and jquery.yiiactiveform.js.

The solution

The solution is a bit tricky but simple. We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality (the button that opens the modal dialog or slides/shows a layer with AJAX'ed form contents). For example, on index.php view file:

cs()->registerCoreScript('yiiactiveform');

Now, I assume that you have created your function to display the AJAX'ed active form and its contents are returned by a call to a controller's action that will partially render a view. This is what we have to do in our action:

// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();

It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won't stop the duplication of the script.

And that's it, everything is working as it should.

Total 2 comments

#7074 report it
Antonio Ramirez at 2012/02/22 12:01pm
@intel352

For ID conflicts I recommend a good use of the setId() property that lies on each widget. THe resulting #yw0 is due to the automated ID creation of them, to avoid it just set their ID.

#5359 report it
intel352 at 2011/10/06 04:57pm
ID conflicts

What about the dynamic ID conflicts for generated js? Such as #yw0?

Leave a comment

Please to leave your comment.

Write new article