这是我的班级与Symfony DI合作:
class Car {
protected $wheel;
public function __construct(Wheel $wheel) // We inject the service
{
$this->wheel = $wheel;
}
}
我希望它以data_class
的形式用于Sf2 FormType:
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在new
(Car)上执行data_class
,没有参数,因此所有DI内容都被破坏了。
我该如何处理?它甚至可能吗? 提前谢谢!
答案 0 :(得分:0)
好的,所以解决方案是初始化数据类模型,并将其传递给表单:
// 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
。