N
N
Nicholas Lindemann2015-02-07 19:23:42
symfony
Nicholas Lindemann, 2015-02-07 19:23:42

How to implement a custom insert?

Hello, when implementing the registration form (email, password), having a user table with the fields "id, first_name, last_name, email, password" it is impossible to insert:

public function registrationAction(Request $request)
{
    $user = new User();
    $form = $this->createForm(new RegistrationType(), $user);

    if ($request->getMethod() == 'POST')
    {
        $form->submit($request);

        if ($form->isValid())
        {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            return $this->redirect($this->generateUrl('confirm'));
        }
    }

    return $this->render('NickUserBundle:Signin:registration.html.twig', array
    (
        'form' => $form->createView(),
    ));
}

I had to cheat and add:
$user->setFirstName('');
$user->setLastName('');

Maybe someone knows how to correctly implement when you need to insert selectively?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Hudinsky, 2015-02-10
@myLizzarD

doctrine explicitly passes all the parameters that have it, and sets the missing ones to null. I want to know what's the catch?

This is the default behavior of the doctrine, and the correct behavior. If you do not have a nullable value in the annotation above the first_name and last_name fields, it will be false by default, which prohibits inserting null values ​​at the database level. If you write a sql query with your hands without specifying these fields when inserting, then when executing the query, you should receive a warning that there is no default value for the field. Insert a record, only an empty string will be written in place of first_name, last_name.
Therefore, you have 2 options: either add nullable=true, or set the default value for the field in the constructor. No other is given.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question