forms - Symfony2 - ReferencedColumnName id 为空

标签 forms symfony doctrine-orm formcollection

我要放弃关于 form collections 的食谱文章但是,当尝试将其保留到数据库时,我收到约束冲突错误,引用的列名称 id 为空。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null

我相信实体设置正确并且关联正确,是否需要添加一些我缺少的内容?

客户端

/**
 * @ORM\OneToMany(targetEntity="ClientPhone", mappedBy="clients", cascade={"persist"})
 */
protected $clientphones;

客户端电话

/**
 * @ORM\ManyToOne(targetEntity="Client", inversedBy="clientphones")
 * @ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=false)
 */
protected $clients;

客户类型表单

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('firstName', 'text', array(
            'label' => 'First Name'
    ))
        ->add('lastName', 'text', array(
            'label' => 'Last Name'
    ))
        ->add('email', 'text', array(
            'label' => 'E-mail Address'
    ))
        ->add('clientphones', 'collection', array(
            'type'         => new ClientPhoneType(),
            'allow_add'    => true,
            'allow_delete' => true,
            'by_reference' => false,
    ));
}

客户端电话类型表单

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('home', 'text');
    $builder->add('office', 'text');
    $builder->add('mobile', 'text');
}

客户端 Controller

$client = new Client();

    $phone = new ClientPhone();
//        $phone->home   = '2134959249';
//        $phone->office = '2134959249';
//        $phone->mobile = '2134959249';
    $client->getClientPhones()->add($phone);

    $form = $this->createForm(new ClientType(), $client, array(
        'action' => $this->generateUrl('client'),
        'method' => 'POST',
    ));
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($client);
        $em->flush();

        $session = $request->getSession();
        $session->getFlashBag()->add('message', 'Client successfully saved to database');

        return $this->redirect($this->generateUrl('client'));
    }

最佳答案

问题解决了。问题出在 addClientphone 函数中的 Client 实体。我必须更改预先生成的代码:

$this->clientphones[] = $clientphones;

至以下内容:

if (!$this->clientphones->contains($clientphone)) {
        $clientphone->setClients($this);
        $this->clientphones->add($clientphone);
    }

    return $this->clientphones;

关于forms - Symfony2 - ReferencedColumnName id 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725679/

相关文章:

PHP 表单提交时 SQL 查询结果在空白表中?

php - 连接 PHP 源代码并将表单提交到 MySQL 数据库

symfony - 有没有办法在调用 Twig 过滤器之前检查它是否存在?

php - Symfony 从数据库生成实体

doctrine-orm - Doctrine $query->expr()->lt with setParameter

php - 在 symfony 实体中获取和设置下划线

php - Symfony2 在一个表单中同一类的多个实体

php - 我怎样才能更好地理解 php 中 symfony2 中的服务层

symfony - 使用原则 2 中的多态关系子集的多态附件

javascript - 如何使用函数生成的按钮?