Symfony2 - ReferencedColumnName id is null

拟墨画扇 提交于 2019-12-11 04:07:36

问题


I'm going off the cookbook article on form collections however when trying to persist this to the database, I am getting a constraint violation error with the referencedcolumn name id being null.

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

I believe the entities are setup correctly and related properly, is there something I need to add to my form that I'm missing?

Client

/**
 * @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 form

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 form

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:


Figured out the problem. The problem was with the Client entity in the addClientphone function. I had to change the pre-generated code:

$this->clientphones[] = $clientphones;

To the following:

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

    return $this->clientphones;


来源:https://stackoverflow.com/questions/26725679/symfony2-referencedcolumnname-id-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!