views:

92

answers:

2

My sample widget:

class myWidget extends sfWidgetFormTextarea{
    public function getJavascripts(){
        return array('my_widget.js');
    }

    public function getStylesheets(){
        return array('my_widget.css');
    }
}

Form template:

<?php include_javascripts_for_form($form) ?>
<?php include_stylesheets_for_form($form) ?>
<?php echo $form;?>

The problem is that those 2 functions produce link and script tags right before rendering form. How can I move them to the head section?

+1  A: 

Try adding the .css and .js to your module's view.yml instead of in the template:

formSuccess:
  stylesheets: [my_widget]
  javascripts: [my_widget]

That will get parsed and dumped into your head tag.

If you have access to the current context's response you can call addJavascript or addStylesheet on the response to inject them into the head. From an action:

$this->getContext()->getResponse()->addStylesheet('style');

From a template:

$sf_response->addJavascript('script');
Cryo
Thanks, Cryo, but I want to make widgets more reusable without touching any view.yml files of modules they used in
Darmen
Gotcha. You can enclose the include_javascripts_... and include_stylesheets_... functions in a slot and then use that slot in your layout. If you have access to the current context's response you can call addJavascript or addStylesheet on the response to inject them into the head.
Cryo
Yay, that's what I need, thanks again!
Darmen
Great, glad to hear it. Would you mind marking my response as the correct one? That will let everyone else know this issue has been resolved (and give me a little rep bonus as well).
Cryo
Get your bonus, thanks for help =) And please update your answer
Darmen
Updated. Thanks Darmen.
Cryo
A: 

In a template you should use

<?php use_javascripts_for_form($form) ?>
<?php use_stylesheets_for_form($form) ?>

Note that it is use instead of include.

See also this question and the documentation.

It is a better approach then accessing the response object directly in this case.

Felix Kling