Symfony2 custom form field

≯℡__Kan透↙ 提交于 2019-12-14 01:24:15

问题


I am very new to Symfony, so question might seem a little simple, but I need a help.

I have generated new bundle.

I have added a new route in Me\MyBundle\Resources\config\routing.yml:

my_homepage:
    pattern:  /
    defaults: { _controller: MeMyBundle:Default:index }

Bundle controller looks in simple like this:

namespace Me\MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $form = $this->createFormBuilder()
            ->getForm()
        ;
        return $this->render('MeMyBundle::index.html.twig', array(
            'form'        => $form->createView(),
            'param1'      => 'some_string_1',
            'param2'      => 'another string',
        ));
   }
}

In the twig template I can read and process proper params, as I want.

Whole action happens in the generated form, where there are AJAX requests routed to another controller.

What I want to achieve is create a new custom form field, which could be reued in same form multiple times, with different params.

For example, I would like my indexAction() would have looked like this:

    public function indexAction()
    {
        $paramsArr_1 = array(
            'param1'      => 'some_string_1',
            'param2'      => 'another string',
        );
        $paramsArr_2 = array(
            'param1'      => 'some_string_2',
            'param2'      => 'another fine string',
        );
        $form = $this->createFormBuilder()
            ->add(myCustomField, $paramsArr_1)
            ->add(myCustomField_2, $paramsArr_2)
            ->getForm()
        ;
        return $this->render('MeMyBundle::index.html.twig', array(
            'form'        => $form->createView()
        ));
   }

Yes, I did see this article, but it did not help me much. I could not get it working.

Any help is much appreciated.


回答1:


From what I know form fields extends the base form class, so your 'myCustomField' can be another form actually.

Check this: http://symfony.com/doc/current/reference/forms/types/form.html

As you know each Form object has attached an object to it, so instead of your arrays you could create a new object with those values set on it, and then add that form how many times your want with objects containing different data.



来源:https://stackoverflow.com/questions/21436932/symfony2-custom-form-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!