简体   繁体   English

在Symfony2表单构建器上设置root元素的属性

[英]Set attributes for root element on Symfony2 form builder

Hi guys i`m using symfony2 form builder and i want to add attributes on the form element the desired effect is something like this: 嗨,大家好我正在使用symfony2表单生成器,我想在表单元素上添加属性,所需的效果是这样的:

<form
    data-login="<?php echo $view['router']->generate('login_check'); ?>"                
    data-register="<?php echo $view['router']->generate('register'); ?>"
    action="<?php echo $view['router']->generate('login_check'); ?>"
    method="post"
    id="ajaxLoginForm"
    name="login_form">

I`m using php templates. 我正在使用php模板。 How can i achive this? 我怎么能做到这一点?

Thanks for the time. 谢谢你的时间。 If you have questions ask them in the comment section. 如果您有疑问,请在评论部分询问。 Best Regards, Georgi. 最诚挚的问候,Georgi。

Unfortunately, this is not possible by acting on the FormBuilder the same way you do for customizing the form fields. 不幸的是,通过像自定义表单字段一样对FormBuilder执行操作是不可能的。 To do it for the root form element, on the setDefaultOptions of your form class (the one which extends AbstractType ) you should return (amongst the others) the attr key, with the corresponding value being an associative array of attribute names => values: 要对根表单元素执行此操作,在表单类的setDefaultOptions (扩展AbstractType那个)上,您应该返回attr键(其中之一),相应的值是属性名称=> values的关联数组:

public function setDefaultOptions(OptionsResolverInterface $resolver) {

    $resolver->setDefaults(array(
        'attr' => array('id' => 'ajaxLoginForm'),
        ...
    ));
}

For the form name attribute, just implement (on the same class) 对于表单name属性,只需实现(在同一个类上)

public function getName() {

    return 'login_form';
}

After implementing the above methods properly, the attributes should be rendered correctly without you having to perform any modifications on your templates or form theme. 正确实现上述方法后,应正确呈现属性,而无需对模板或表单主题执行任何修改。

Note: you may have to inject the router component in the form (or pass it as an option when instantiating it) in order to create the routes you need for your data-login and data-register attributes. 注意:您可能必须在表单中注入路由器组件(或在实例化时将其作为选项传递),以便创建data-logindata-register属性所需的路由。

For attributes use 对于属性使用

<?php echo $view['form']->form($form, array(
    'attr' => array(
        'data-login' => $view['router']->generate('login_check'),                
        'data-register' => $view['router']->generate('register'),
        // etc...
    ),
)) ?>

For specific attributes you can use 对于您可以使用的特定属性

// In form class
$builder->setAction('/login_check');
$builder->setMethod('post');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM