Symfony3 : choice type field filled with array of objects

标签 symfony object entity choice choicefield

我有一个实体 Product .我的产品可以有多个不同语言的名称。一个法语名字,一个英语名字等等。我不想使用自动翻译。

用户必须在产品表单中输入名称并选择相应的语言。借助“添加”按钮,他可以添加任意数量的名称。

所有语言都是由管理员用户创建的(以另一种形式)。所以,Language也是具有名称(例如:英文)和代码(例如:EN)的实体。

我创建了实体 ProductName具有名称和语言(符合用户在产品表单中所写的内容)。

在那种情况下,我不需要关联实体 ProductName与实体 Language .我只想要语言代码。所以,在我的 ProductName 中实体,我有这个属性:

/**
 * @ORM\Column(name="Language_Code", type="string", length=2)
 */
private $language;

我的产品表单 (ProductType) 有一个 CollectionType 字段以添加多个名称。
// Form/ProductType.php

    ->add('infos',      CollectionType::class, array(
        'entry_type'    => ProductInfosType::class,
        'allow_add'     => true,
        'allow_delete'  => true,
        'prototype'     => true,
        'label'         => false,
        'mapped'        => false
    ))

ProductInfosType 表单有 2 个字段:
// Form/ProductInfosType.php

        ->add('name',           TextType::class, array(
            'attr'              => array('size' => 40)
        ))
        ->add('language',       EntityType::class, array(
            'placeholder'       => '',
            'class'             => 'AppBundle:Language',
            'choice_label'      => 'code',
            'attr'              => array('class' => 'lang'),
            'query_builder'     => function (EntityRepository $er) {
                return $er->createQueryBuilder('l')->orderBy('l.code', 'ASC');
            }
        ))

因此,当我进入表单页面时,我有一个包含输入文本字段(名称)和选择字段(语言)的块。选择字段是这样的:
<select id="product_infos_0_language" required="required" name="product[infos][0][language]">
    <option value=""></option>
    <option value="DE">DE</option>
    <option value="EN">EN</option>
    <option value="ES">ES</option>
    <option selected="selected" value="FR">FR</option>
</select> 

在这一点上,一切正常。 我创建了一个添加按钮,以便用户可以添加其他名称等...

但是,当我提交表单时,当我在 ProductController 中检查表单数据时,我注意到它与我想要存储在数据库中的内容不符。
print_r($form->get('infos')->getData());

// returns :
Array
(
    [0] => AppBundle\Entity\ProductName Object
        ( 
            [language:AppBundle\Entity\ProductName:private] => AppBundle\Entity\Language Object
                (
                    [code:AppBundle\Entity\Language:private] => FR
                    [name:AppBundle\Entity\Language:private] => Français
                )

            [name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
        )
)

我想要的是:
Array
(
    [0] => AppBundle\Entity\ProductName Object
        ( 
            [language:AppBundle\Entity\ProductName:private] => FR    
            [name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
        )
)

我不想要语言对象但是 直接语言代码 !

这就是为什么我认为我不应该使用 EntityField在 ProductNameType 形式但 ChoiceType field 。

如何在选择字段中加载存储在 db 中的所有语言?
我希望这个解释更容易理解;-)

最佳答案

感谢这篇文章,我找到了解决方案:Passing data to buildForm() in Symfony 2.8/3.0

ProductController.php :将自定义数据作为选项传递给 createForm()方法。

// ...

// build the form
$em = $this->getDoctrine()->getManager();
$product = new Product();
$languages = $em->getRepository('AppBundle:Language')->findAllOrderedByCode();

$form = $this->createForm(ProductType::class, $product, array(
    'languages' => $languages
));

产品类型表 :在选项解析器中传递自定义数据
public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Product',
        'languages'  => null
    ));
}

然后,在 buildForm()函数,添加一个 entry_options CollectionType 字段中的选项:
$builder->add('infos',  CollectionType::class, array(
    'entry_type'    => ProductInfosType::class,
    'entry_options' => array('languages' => $options['languages']),
    'allow_add'     => true,
    'allow_delete'  => true,
    'prototype'     => true,
    'label'         => false,
    'by_reference'  => false
));

产品信息类型表单 : 在选项解析器中传递自定义数据(与在 ProductForm 中完全相同)
public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\ProductName',
        'languages'  => null
    ));
}

现在,您有两种选择:您希望表单返回实体或简单字符串。

在我的示例中,我只想要语言代码(如 FR、EN 等)。

案例1:表单发布时只返回语言代码:
// Form/ProductInfosType.php

// ...

// Convert array of objects in an array of strings
$choices = array();
foreach ($options['languages'] as $lang) {
    $code = $lang->getCode();
    $choices[$code] = $code;
}

$builder->add('language', ChoiceType::class, array(
    'placeholder'       => '',
    'choices'           => $choices
));

// returns :
Array
(
    [0] => AppBundle\Entity\ProductName Object
        ( 
            [name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
            [language:AppBundle\Entity\ProductName:private] => FR    
        )
)

案例 2:当表单发布时返回语言实体:
// Form/ProductInfosType.php

// ...

$builder->add('language', ChoiceType::class, array(
    'placeholder'       => '',
    'choices'           => $options['languages'],
    'choice_label'      => 'code',
    'choice_value'      => 'code'
));

// returns :
Array
(
    [0] => AppBundle\Entity\ProductName Object
        ( 
            [name:AppBundle\Entity\ProductName:private] => Ceinture lombaire LombaSkin
            [language:AppBundle\Entity\ProductName:private] => AppBundle\Entity\Language Object
                (
                    [code:AppBundle\Entity\Language:private] => FR
                    [name:AppBundle\Entity\Language:private] => Français
                )    
        )
)

使用此解决方案,我们无需将表单创建为服务即可将实体管理器作为参数传递。一切都在 Controller 和表单选项中进行管理。

关于Symfony3 : choice type field filled with array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37006699/

相关文章:

php - 使用 Symfony 2.8 进行 LDAP 身份验证

symfony - EasyAdmin 3.X - 如何查看相关实体 `toString` 而不是列表中的关联数量?

object - 如何使用在 SystemVerilog 中对其进行操作的方法获取实例的名称?

java - Spring : injecting data object in service

php - 什么是php中的实体类

c# - 动态 where 子句 Entity Framework 3.5

php - 从 Symfony 中的路由条件表达式访问全局参数

symfony - 如何使用ElasticSearch仅搜索嵌套对象数组中的第一个对象

javascript - 数组元素和对象属性比较返回 false

javascript - 使用 JavaScript 将对象值替换为同一键的其他对象的值