2

I want to add to Model entity one choice from Marka entity. I've problem with data from choices form. Form has got all data inside, but when I send the form i get error:

An exception occurred while executing 'INSERT INTO model (nazwa, idm) VALUES (?, ?)' with params ["a", null]:

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

When i check source code I see that value is correctly:

   <select id="namefield_idm" name="namefield[idm]" class="form-control"> 
           <option value="1" >Opel</option>
           <option value="2" >Mazda</option> 
           <option value="3" >Ford</option>
    </select>

I don't have any idea whats wrong. My ModelType.php

  <?php
namespace UTPBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\ORM\EntityRepository;


    class ModelType extends AbstractType

{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    $builder
        ->add('nazwa', 'text', array('label' => 'Nazwa',  'attr' => array(
            'class' => 'form-control')
        ))
        ->add('idm', 'entity', array(
            'label'    => 'Marka',
            'mapped'   => false,
            'class'    => 'UTPBundle:Marka',
            'choice_label' => 'nazwa',
            'attr' => array(
                'class' => 'form-control'
            ),
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('u');
            },
        ))
        ->add('save', 'submit', array('label' => 'Dodaj',  'attr' => array(
            'class' => 'btn btn-success'
        )));
}

public function configureOptions(OptionsResolver $resolver)
{

}

 public function getName()
    {
        return 'namefield';
    }
}
?>

My code from controller looks like:

/**
     * @Route("/model", name="utp_model")
     */
    public function modelAction(Request $request)
    {

        $name = 'Model';


        $model = new Model();
        $marka = new Marka();
        $form = $this->createForm(new ModelType($marka), $model);
        $form->handleRequest($request);

        if ($form->isValid() && $form->isSubmitted()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($model);
                $em->flush();

        }

        return $this->render('UTPBundle:Default:model.html.twig', array(
            'name' => $name,
            'form' => $form->createView()
        ));
    }

And model entity also:

<?php

namespace UTPBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Model
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Model
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nazwa", type="string", length=255)
     */
    private $nazwa;


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


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

    /**
     * Set idm
     *
     * @param integer $idm
     *
     * @return Model
     */
    public function setIdm($idm)
    {
        $this->idm = $idm;

        return $this;
    }

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

    /**
     * Set nazwa
     *
     * @param string $nazwa
     *
     * @return Model
     */
    public function setNazwa($nazwa)
    {
        $this->nazwa = $nazwa;

        return $this;
    }

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

2 Answers 2

1

It is not fully clear from your question but I understand that what you want to do is to have a Model entity which will include a Marka field. If that is the case, then first of all, you do not want to store your Marka as an integer within your Model, you want to store it as a Marka object with a (probably) ManyToOne relationship:

/**
 * @ORM\ManyToOne(targetEntity="Marka")
 * @ORM\JoinColumn(name="idm", referencedColumnName="id")
 */
protected $marka;

Doctrine will take care of using an integer to represent this relationship as an integer within your database, using the idm column

Once you have done this, you can then use it in your ModelType form without using 'mapped' => false:

    ->add('marka', 'entity', array(
        'label'    => 'Marka',
        'class'    => 'UTPBundle:Marka',
        'choice_label' => 'nazwa',
        'attr' => array(
            'class' => 'form-control'
        ),
    ))

(Notice that you do not need the query_builder option since your query builder just returns all the objects and the entity field by default already does that.)

And last you just need to modify your controller a bit since you will not need now to create any Marka object:

    $model = new Model();
    $form = $this->createForm(new ModelType(), $model);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now it's fine :))))))
0

In

->add('idm', 'entity', array(
            'label'    => 'Marka',
            'mapped'   => false,
            'class'    => 'UTPBundle:Marka',
            'choice_label' => 'nazwa',
            'attr' => array(
                'class' => 'form-control'
            ),
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('u');
            },
        ))

Remove the line

'mapped'   => false

Mapped false means don't map that property to the underlying object, so it won't be persisted and will then cause your database error.

2 Comments

Unfortunally, no ;/ i removed this line and now error is: An exception occurred while executing 'INSERT INTO model (nazwa, idm) VALUES (?, ?)' with params ["aaa", {}]: Catchable Fatal Error: Object of class UTPBundle\Entity\Marka could not be converted to string
You might want to look into a data transformer for that: symfony.com/doc/current/cookbook/form/data_transformers.html - because you don't have a proper entity relationship between marka and model. Ideally you would, in which case the answer below (Carlos) is what you should follow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.