php - 有一个带有 DI 构造函数的 FormType data_class (Symfony 2.3)

标签 php symfony 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 东西都被破坏了。

我该如何处理?有可能吗? 提前致谢!

最佳答案

好的,所以解决方案是初始化数据类模型,并将其传递给表单:

// 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/

相关文章:

php - 如何将图片存入数据库

symfony - 如何从 Symfony 4 的日志中排除弃用消息?

forms - Symfony2 Doctrine2 多对多形式不保存实体

php - 想要使用 php 将带有格式和网格的完整 html 表格数据导出到 excel 的单个单元格

php - 在 htaccess 中声明 session 最大生命周期

php - 从SQL数据库使用mysql和php获取信息

php - 登录/注销后显示闪现消息

php - Symfony 如何返回所有登录的事件用户

symfony - FOSUserBundle 反序列化为用户对象抛出 "you must define a type"

php - Symfony2 : Unable to overwrite 'maxSize' and 'maxSizeMessage' in Image/File constraint