这是我使用 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 东西都被破坏了。
我该如何处理?有可能吗? 提前致谢!
最佳答案
好的,所以解决方案是初始化数据类模型,并将其传递给表单:
// 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
永远不会为 null,因此 FormType 不会调用 new
。
关于php - 有一个带有 DI 构造函数的 FormType data_class (Symfony 2.3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519754/