سؤال

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:

<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. How can i achive this?

Thanks for the time. If you have questions ask them in the comment section. Best Regards, Georgi.

هل كانت مفيدة؟

المحلول

Unfortunately, this is not possible by acting on the FormBuilder the same way you do for customizing the form fields. 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:

public function setDefaultOptions(OptionsResolverInterface $resolver) {

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

For the form name attribute, just implement (on the same class)

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.

نصائح أخرى

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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top