有一个带有 DI 构造函数的 FormType data_class (Symfony 2.3)
Have a FormType data_class with a DI constructor (Symfony 2.3)
这是我使用 Symfony DI 的 class :
class Car {
protected $wheel;
public function __construct(Wheel $wheel) // We inject the service
{
$this->wheel = $wheel;
}
}
我希望它作为 Sf2 FormType 的 data_class
工作:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Car',
));
}
问题在这里:https://github.com/symfony/Form/blob/2.3/Extension/Core/Type/FormType.php#L135-L141
FormType 在 data_class
(Car) 上执行一个 new
没有参数,所以所有的 DI 东西都坏了。
我该如何处理?有可能吗?
提前致谢!
好的,所以解决方案是初始化数据 class 模型,并将其传递给表单:
// Create an instance of the car model
$car = $this->carFactory()->create($wheel);
// Pass it to the form as data while building it
$form = $this->formFactory->create('MyFormType', $car);
// Add the car field
$form->add('car', $car->getFormType(), $car->getFormOptions());
这样,data_class
永远不会为空,因此 FormType 不会调用 new
。
这是我使用 Symfony DI 的 class :
class Car {
protected $wheel;
public function __construct(Wheel $wheel) // We inject the service
{
$this->wheel = $wheel;
}
}
我希望它作为 Sf2 FormType 的 data_class
工作:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Car',
));
}
问题在这里:https://github.com/symfony/Form/blob/2.3/Extension/Core/Type/FormType.php#L135-L141
FormType 在 data_class
(Car) 上执行一个 new
没有参数,所以所有的 DI 东西都坏了。
我该如何处理?有可能吗? 提前致谢!
好的,所以解决方案是初始化数据 class 模型,并将其传递给表单:
// Create an instance of the car model
$car = $this->carFactory()->create($wheel);
// Pass it to the form as data while building it
$form = $this->formFactory->create('MyFormType', $car);
// Add the car field
$form->add('car', $car->getFormType(), $car->getFormOptions());
这样,data_class
永远不会为空,因此 FormType 不会调用 new
。