1
votes

i have problem with symfony2:

An exception occurred while executing 'INSERT INTO Municipality (name, region_id) VALUES (?, ?)' with params ["Test message", null]:

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

This is my controller:

public function createAction(Request $request)
{

    $entity = new Municipality();

    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    $params = $this->getRequest()->request->all();

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


        //$entity->setRegionId(21);

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

        return $this->redirect($this->generateUrl('municipality_show', array('id' => $entity->getId())));
    }

    return array(   
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

Bulder:

 /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('regionId', 'entity', array('class' => 'CMSSurveyBundle:Region',
            'query_builder' => function(EntityRepository $er) { return $er->createQueryBuilder('a')->orderBy('a.name', 'ASC'); },
            'attr' => array('control-class' => 'col-lg-6', 'class' => 'form-control'))
        )
        ->add('name')
    ;
}

Entity:

/**
 * @var integer
 *
 * @ORM\Column(name="region_id", type="integer")
 */
private $regionId;

/**
 * @ORM\ManyToOne(targetEntity="Region", inversedBy="municipalities")
 * @ORM\JoinColumn(name="region_id", referencedColumnName="id")
 */

private $region;

$_POST give to controller:

Array
(
    [CMS_surveybundle_municipality] => Array
        (
            [name] => Test message
            [regionId] => 20
            [_token] => 8628f62dd8d398b85685def1d368334ay1d7a816
        )

)
1 

Views:

            <hr/>
        <table>
        <tr>
            <td class="col-lg-4">
                <?php echo $view['form']->label($form['name']); ?>
            </td>
            <td class="col-lg-6">
                <?php echo $view['form']->errors($form['name']); ?>
                <?php echo $view['form']->widget($form['name']); ?>
            </td>
        </tr>
        <tr>
            <td class="col-lg-4">
                <?php echo $view['form']->label($form['regionId']); ?>
            </td>
            <td class="col-lg-6">
                <?php echo $view['form']->errors($form['regionId']); ?>
                <?php echo $view['form']->widget($form['regionId']); ?>
            </td>
        </tr>
        </table>
        <hr/>
2
what's happen when you uncomment //$entity->setRegionId(21); ? - Jihed Ben taher
nothing.. Maybe problem is with entity object in controller $entity = new Municipality();. - Dzi
try to set the entity object like this : $entity->setName($form['name']); $entity->setRegionId($form['regionId']); - Jihed Ben taher
Why do you have both region and region_id? That just doesn't make sense. I suggest removing regionId and relying on objects instead of identifiers... - Jovan Perovic
I remove it, but still not working.. And getting NULL - Dzi

2 Answers

1
votes

As mentioned in another comment having both region and regionId properties in your entity is wrong. It completely breaks the Doctrine2 ORM abstraction and is likely the source of your problem. Also, you have created an entity form field that is mapped to an integer. See below for my suggested changes. I have changed the property mapping for your form from regionId to region and removed the regionId property from the Municipality entity altogether. Should you have some pressing need to access the regionId you can do so with $municipality->getRegion()->getId()

Builder:

 /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('region', 'entity', array('class' => 'CMSSurveyBundle:Region',
            'query_builder' => function(EntityRepository $er) { return $er->createQueryBuilder('a')->orderBy('a.name', 'ASC'); },
            'attr' => array('control-class' => 'col-lg-6', 'class' => 'form-control'))
        )
        ->add('name')
    ;
}

Entity:

/**
 * @ORM\ManyToOne(targetEntity="Region", inversedBy="municipalities")
 * @ORM\JoinColumn(name="region_id", referencedColumnName="id")
 */

private $region;
1
votes

When you dropped regionId did you really purge it from your form and template? Consider updating your question with your new regionId free code.

You might also take a look at the documentation to understand how Doctrine 2 handles relations. Wanting to manupilate the actual id is a common mistake. http://symfony.com/doc/current/book/doctrine.html

Right now you have nothing linking region to your municipality. In your controller you will need:

$municipality = new Municipality(); // Used to be called entity.  Rename for clarity
$region = new Region();
$municipality->setRegion($region);

$form = $this->createCreateForm($municipality);