【问题标题】:Automatically build a form using entity (one to one relationship)使用实体自动构建表单(一对一关系)
【发布时间】:2012-03-01 18:33:22
【问题描述】:

我想知道是否可以使用实体构建一个表单,以一对一的关系获取所有字段。澄清一下:

我有一个User.php 实体(包含所有明显的字段、姓名、姓氏、流派等)和一个Address.php 实体。我想要的是在不逐一添加地址实体的属性的情况下构建整个表单,并将其以适当的关系保存在数据库中。

这是我尝试过的(我已经稍微修剪了代码),但显然不是正确的方法:

用户实体:

class User implements UserInterface {

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;


/**
 * @ORM\Column(type="string", length=100, nullable=TRUE)
 */
protected $firstName;

/**
 * @ORM\Column(type="string", length=200)
 * @Assert\NotBlank()
 */
protected $lastNames;

/**
 * @ORM\OneToOne(targetEntity="Capsa\Bundle\ClubCommonBundle\Entity\Address")
 */
protected $address;

地址类

class Address {

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(type="string", length=100, unique=TRUE)
 * @Assert\NotBlank()
 */
protected $streetName;

/**
 * @ORM\Column(type="string", length=50)
 */
protected $streetNumber;

表单生成器:

public function buildForm(FormBuilder $builder, array $options) {
    $builder->add('login', 'text')
            ->add('password', 'password')
            ->add('firstName', 'text', array("required" => FALSE))
            ->add('lastNames', 'text')
            ->add('address', 'entity', array(
                'class' => 'CapsaClubCommonBundle:Address',
                'property'=>'streetName'
            ));
}

这只会获取表的字段 streetName 并将其放入列表中。

【问题讨论】:

    标签: php symfony doctrine-orm formbuilder


    【解决方案1】:

    尝试使用Collection form type 而不是实体字段类型 - 请参阅this tutorial

    【讨论】:

    • 最后我只用这个来加载整个对象:->add('address', new AddressType()); 当然,定义地址类型
    • @Manu 您的评论确实是答案——至少对我有用。谢谢。
    • 在 Manu 的评论之后是更新的语法:->add('address', AddressType::class)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多