Symfony2 - ReferencedColumnName id为null

时间:2014-11-04 00:18:52

标签: forms symfony doctrine-orm formcollection

我要关于form collections上的食谱文章,但是当我尝试将其保存到数据库时,我收到一个约束违规错误,其引用的列名称为null。

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

我相信这些实体设置正确且相关性正确,我需要添加到我的表单中我缺少哪些内容?

客户端

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

Clientphone

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

ClientType表单

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,
    ));
}

ClientPhoneType表单

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

ClientController

$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'));
    }

1 个答案:

答案 0 :(得分:4)

找出问题所在。问题出在addClientphone函数中的客户端实体。我不得不更改预先生成的代码:

$this->clientphones[] = $clientphones;

以下内容:

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

    return $this->clientphones;