Avoiding duplicate script download when using CActiveForm on Ajax calls
###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,
jquery.yiiactiveform.jskeeps being downloaded to the client. ###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: ~~~ [php] 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: ~~~ [php] // 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.