开发者

How to use JavaScript in forms?

How to add your own JavaScri开发者_C百科pt to the forms which are generate by Doctrine ?

For example, where can I add a script onFocus in an input form generated by symfony ?

Edit :

@Benoit :

I have tried your method but, it doesn't work.

My function renderJavascript :

public function renderJavascript() {
  $(function() {
    $('.form').focus(function(){this.blur()});
});

And I have override the method render as you show me but there is no error but it does nothing.

I think it is a little error but I begin with symfony and I don't understand all in the forms.


You can pass html attributes to the render method on the form:

<?php echo $form["field_name"]->render(array("onfocus" => "alert('focused!');")) ?>

You could also set "class" attribute in the options array and use jQuery to add javascript to the field.


you should extend your form class (which should already derivate from sfForm) to override the render method.

As of symfony 1.4 the sfForm class has no renderJavascript method. We generally use for all our form and widgets a basse class that will define this method and override render method

class abstractOurForm extends sfFormDoctrine
{
    public function render($attributes = array())
    {
       return parent::render($attributes).
               '<script type="text/javascript">'.$this->renderJavascript().'</script>';
    }
    public function renderJavascript()
    {
        //nothing here
    }
}

This will add a javascript tag at the end of your form (if displayed like generated ones with echo $form )

When you override the doctrine form to implement javascript functionnality tight to the form html (inline validation, ajax integration, dynamic controls, etc.) just do something like this :

class myWhateverForm extends abstractOurForm
{
    public function configure()
    {
         //your widget & validators config here
    }
    public function renderJavascript() 
    {
         //here come the JS code
         $js = <<<EOT
             //example with jquery
             $(function() {
                $('#myElement').focus(function(){
                   if (window.console) console.log('you\'ve done it');
                });
             });

    EOT;
       return $js;
    }
}

The same pattern is applied to our widget so if some javascript code is widget specific it does not have to be repeated on each form class using it.

Hope this will help you !


The right way of doing it would be creating a separated .js file and including it directly on your view, so it would still follow the MVC pattern.

jQuery can grab your form field simply as the form framework gives each field a unique ID, that can be used by jQuery on your .js file for setting a .focus or whatever you want to.

Keep it clean and easy to maintain each layer of your app :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜