【问题标题】:Symfony2.1 Embedded Forms and Foreign Key RelationsSymfony2.1 嵌入式表单和外键关系
【发布时间】:2012-08-02 20:57:47
【问题描述】:

我决定完全改写我的问题。希望我的问题通过这种方式更清楚。

如何在实体中嵌入表示外键字段的表单?例如,属性具有状态表(拥有、可用、待售等)的外键。使用嵌入式表单,我不确定如何让我的嵌入式表单(在这种情况下为状态)了解嵌入它的父实体,以便在提交表单时,创建/更改属性上的状态只会更改外键关系。我可以通过调用 $property->setStatus($status) 来查询属性并更改其状态,所以我相信我的 Doctrine 关系是正确的。

现在,我在尝试更改表单提交状态时收到此错误:

Catchable Fatal Error: Object of class Test\Bundle\SystemBundle\Entity\Status could not be converted to string in /home/vagrant/projects/test.dev/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php line 1118 

我的表单创建:

$form = $this->createForm(new PropertyType(), $property);

我的Property实体中Property与Status的实体关系:

/**
 * @var Status $status
 *
 * @ORM\ManyToOne(targetEntity="Test\Bundle\SystemBundle\Entity\Status")
 * @ORM\JoinColumn(name="StatusId", referencedColumnName="Id", nullable=false)
 */
protected $status;

这是我的 PropertyType 类中嵌入 StatusType 类的行:

->add('status', new StatusType())

这是我的 StatusType 表单类:

class StatusType extends AbstractType
{
public $statusType = null;

public function __construct($statusType)
{
    $this->statusType = $statusType;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder->add('name', 'entity', array('label' => 'Status Name',
            'class'     => 'Test\Bundle\SystemBundle\Entity\Status',
            'property'  => 'name'));

}

public function getParent()
{
    return 'form';
}

public function getDefaultOptions(array $options)
{
    return array('data_class' => 'Test\Bundle\SystemBundle\Entity\Status');
}

public function getName()
{
    return 'status';
}
}

【问题讨论】:

    标签: php doctrine-orm twig symfony-2.1


    【解决方案1】:

    没有看到你的Status 实体,听起来你需要向它添加一个__toString() 方法。为了让 Symfony 将实体呈现为文本,它需要知道要显示什么。像这样的...

    class Status
    {    
        public $title;
    
        public function __toString()
        {
            return $this->title;
        }
    }
    

    【讨论】:

    • 我的 Status 实体中有一个 toString 方法。问题不是显示选择列表,而是让 symfony 看到 StatusType 类与 PropertyType 有关系。选择框显示所有状态,但它没有根据属性中的键预先选择值,当我提交具有不同状态的表单时,它会尝试更新状态记录而不是关系。我更新了代码以显示属性与状态的关系以及我如何创建表单。
    【解决方案2】:

    我找到的一个解决方案是将所有逻辑放在 PropertyType 上以获得状态。

    ->add('status', 'entity',
                array('class'   => 'Test\Bundle\SystemBundle\Entity\Status',
                    'property'  => 'name',
                    'query_builder' => function(EntityRepository $er){
                        return $er->createQueryBuilder('status')
                        ->orderBy('status.name', 'ASC');
                    }))
    

    而不是嵌入 StatusType:

    ->add('status', new StatusType())
    

    我不喜欢这种方法,因为每个使用 Status 的实体都会有这个重复,但它暂时可以工作,直到我弄清楚如何让它工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      相关资源
      最近更新 更多