问题
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