OneToMany与复选框的关系作为使用自定义FormType的表单中的选项

时间:2016-01-28 11:29:32

标签: symfony checkbox symfony-forms formbuilder

我有一个模型CostTypeConnection,它与DepartmentConnection有一对多的关系。

我想,DepartmentConnection显示为复选框。

我的CostTypeConnection Class有一个$costType变量,Entity CostType,其中$name可变。

我的DepartmentConnection Class有一个$department变量Entity Department,它还有一个$name变量。

我的CostTypeFormType:

  ....    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('costType', 'text', array(
                'label' => 'costType'
            ))
            ->add('departmentConnections', 'collection', array(
                'type' => new DepartmentConnectionType(),
                'allow_add'    => false,
                'label' => false,
                'by_reference' => false,
                'options' => array('label' => false),

            ))
        ;
    } ...

我的部门连接:

...
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('department', 'text', array(
                'label' => false
            ))
        ;
    }...

所以不可能在我的Formbuilder for department中定义一个checkbox-Type,因为它是一个实体而不是一个变量。有人知道我能做什么吗?这在我的DepartmentConnectionType类中不起作用:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('department', 'choice', array(
                'label' => false
            ))
        ;
    }

完成错误:

The value of type "object" cannot be converted to a valid array key

感谢任何帮助!!!

1 个答案:

答案 0 :(得分:-1)

注意:建议的最低版本symfony 2.7

您应该在表单中使用\ Symfony \ Bridge \ Doctrine \ Form \ Type \ EntityType。

http://symfony.com/doc/2.7/reference/forms/types/choice.htmlhttp://symfony.com/doc/2.7/reference/forms/types/entity.html

以下是一个例子:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('costType', 'text', array(
            'label' => 'Cost type :' // -> <label class="required">Cost type :</label><input value="<?php echo $costTypeConnection->getCostType(); ?> required>
        ))
        ->add('departmentConnections', 'entity', array(
            'class' => 'Acme\Bundle\Entity\DepartmentConnection',
            // before 2.7 use 'property' instead of 'choice_label'
            'choice_label' => 'type', // equals $costTypeConnections->getDepartmentConnexion()->getType();
            'label' => 'Department connexion :',
            'expanded' => true, // will output a set of inputs instead of a select tag
            'multiple' => true, // will output checkboxes instead of radio buttons
            'required' => true, // unused as multiple is true
        ))
    ;
} ...

会输出:

<div id="form_cost_type_connexion_department_connections">
    Department connexion :
    <input type="checkbox" value="on" ... <label>$costTypeConnections->getDepartmentConnections()->getType()
    ...