Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7980433
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T10:04:31+00:00 2026-06-04T10:04:31+00:00

In my Symfony2 application, there are two entities: Address and Town. The Address entity

  • 0

In my Symfony2 application, there are two entities: Address and Town. The Address entity has a 4-digit postal code property (“pcNum”), which refers to the id of a Town entity. An address can only have one postal code and hence refer to one town only (however the reverse is possible: a town could have more postal codes).

For both entities I have created a form called TownType and AddressType. Users can enter and save a Town (this works fine). The form for the Address entity allows users to fill in an address, including a postal code. The postal code is linked to the id of a Town entity.

However, when I try to persist a new Address entity retrieved from the AddressType form, I receive the MySql error that the pc_num field (pcNum in the entity) is empty:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘pc_num’ cannot be null

(This is the field of the Address entity that should have contained a ref key to a Town.) Somehow its value is lost before persisting the Address entity. If I fill the field manually in my controller, regardless of the user input in the form, I can persist the new Address without the error. If I drop the link to the Town entity and use an unaware form field, I can also safe without error as long as the postal code happens to exist. But in the way it should be, using two forms and entity-association, I cannot get it to work. I have tried many different things over the past weeks and I am out of ideas. Below is my code. Feel free to comment on anything, maybe my whole approach is wrong.

This is my Town entity:

namespace Xx\xBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Check;

 /**
 *
 * Xx\xBundle\Entity\Town
 *
 * @ORM\Table(name="lib_towns")
 * @ORM\Entity
 */

class Town
{
    #id
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", length="4", nullable=false)
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Check\NotBlank()
     * @Check\MaxLength(4)
     */
    protected $id;

    #name
    /**
     * @ORM\Column(name="name", type="string", length="100", nullable=true)
 * @Check\NotBlank()
     * @Check\MaxLength(100)
     */
    protected $name;

    //some more properties

    #getters and setters

    /**
     * Set id
     *
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     *
     * @return string $name
     */
    public function getName()
    {
        return $this->name;
    }

  //some more getters ans setters

}

This is my Address entity:

namespace Xx\xBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Check;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Xx\xBundle\Entity\Town;

 /**
 *
 * Xx\xBundle\Entity\Address
 *
 * @ORM\Entity
 * @ORM\Table(name="addresses")
 */

class Address
{
    #id
    /**
    * @ORM\Id
     * @ORM\Column(type="integer", length="6", nullable=false)
     * @ORM\GeneratedValue(strategy="AUTO")
 * @Check\NotBlank()
 * @Check\MaxLength(6)
     */
    protected $id;

    #town
    /**
    * @orm\OneToOne(targetEntity="town")
 * @ORM\JoinColumn(name="pc_num", referencedColumnName="id", nullable=false)
    */
    protected $town;

    //some other properties...

    #getters and setters

    /**
     * Set id
     *
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set town entity linked to this address
     *
     */
    public function setTown(town $town = null)
    {
        $this->town = $town;
    }

    /**
     * Get town entity linked to this address
     *
     */
    public function getTown()
    {
        return $this->town;
    }

    //some other functions...

}

Next, this is the form I’ve created for the Address:

namespace Xx\xBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;

class AddressType extends AbstractType
{
    public function buildForm(Formbuilder $builder, array $options)
    {
        $builder->add('id', 'hidden'); //necessary for updates
        $builder->add('town', 'entity', array
            (
                'label' => 'Postal code (4 digits):*',
                'class' => 'XxxBundle:Town',
                'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('t')
            ->orderBy('t.id', 'ASC'); },            
                //'empty_value' => '----',
                'property'=> 'Id',
                'property_path'=> false,
                'expanded' => false,
                'multiple' => false,
                'required'  => true
            ));
        $builder->add('street', 'text', array
            (
                'label' => 'Street:*',
                'required'  => true
            ));
        //some more fields...
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Xx\xBundle\Entity\Address'
        );
    }

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

This is the relevant action function in my Address controller:

public function editAddressAction($id = null)
{
$em = $this->getDoctrine()->getEntityManager();
$address = new Address();
$isNew = is_null($id);
     //this also tests positve after a form has been sent
    if($isNew)
    {
           #fill address object with some defaults
            $address->setCreated(new \DateTime("now"));
         } else
         {
            #fill address object with existing db data
            $address = $em->getRepository('XxxBundle:Address')->find($id);
         }
         #create form and fill it with address object data
         $form = $this->createForm(new AddressType(), $address);
            #if form sent: check input
            $request = $this->get('request');
            if ($request->getMethod() == 'POST')
            {
               $form->bindRequest($request); //calls setters
               if ($form->isValid())
               {
                  //if I leave the following lines in: no error (but also no sense)
                  //because the pcNum should be retrieved from the form
                  $pcNum = 2222;
                  $town = $em->getRepository('XxxBundle:Town')->find($pcNum);
                  $address->setTown($town);
                  //end

                  #persist and flush

                     $id_unknown = is_null($address->getId());
                     if($id_unknown)
                     {
                        #insert address
                        $em->persist($address);
                     }   else
                     {
                        #update address
                        $address->setModified(new \DateTime("now"));
                        $em->merge($address);
                     }
                     #commit
                     $em->flush();
                  #get id of update or insert and redirect user
                     $address_id = $address->getId();
                     return $this->redirect($this->generateUrl('displayAddress', array('id'=>$address_id)));
               }
            }
         return $this->render('XxxBundle:Forms:address.html.twig', array('form'=>$form->createView(), 'new' => $isNew, 'id' => $id));
   }

To conclude, this is the relevant Twig snippet:

   <form action="{{ path('addAddress') }}" method="post" {{ form_enctype(form) }}>
      {{ form_errors(form) }}
      <div class="form_row">
         {{ form_errors(form.town) }}
         {{ form_label(form.town, 'Postal code:*') }} 
         {{ form_widget(form.town, {'attr': { 'class': 'form_pcNum', 'maxlength': '4', 'size': '4' } } ) }} 
      </div>
      <div class="form_row">
        <!-- some more fields here -->
      </div>
      <div class="form_row">
         <button name="btn_add" id="do_add" type="submit" class="" value="btn_add" title="Ok!">Ok</button>
      </div>
      {{ form_rest(form) }}
   </form>

Any help is appreciated…
If you know of a relevant (working) example, that would also be great. Cheers!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T10:04:33+00:00Added an answer on June 4, 2026 at 10:04 am

    I had similar problem with foreign key violation and I solved. Please read Symfony2 form and Doctrine2 – update foreign key in assigned entities fails [solved]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have multiple symfony2 applications which share common entities, but use different database settings.
I have a symfony application with two different applications (frontend, backend) but there is
I'm using a flash component in my symfony2 application which uploads multiple images, and
I have managed to successfully deploy my Symfony2 application to a production web server,
I am developing an application using symfony2 and twig for templates. The problem comes
I'm trying to make a multi-language application with Symfony2 and I'm currently trying to
I'm creating a simple pastebin web application on top of Symfony2, but I can't
I'm constructing an ecommerce application in Symfony, and I have a page which lists
I'm using symfony for one of my projects. The application has already developed and
I've got a very old php application (1999) that has been worked on during

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.