Question

I am new to Symfony2. I am trying to understand a part of the code generated by CRUD.

In below code, I don't understand why we create an entity (new Image()). When I var_dump it everything inside is NULL. What is its role then? Why to send it inside the return of the action?

public function newAction()
{
    $entity = new Image();
    $form   = $this->createForm(new ImageType(), $entity);
    var_dump($entity);
    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

IMHO, the instance in the the other action (create) is logical.Your explanations are highly appreciated.

 public function createAction(Request $request)
{
    $entity  = new Image();
    $form = $this->createForm(new ImageType(), $entity);
    $form->bind($request);

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

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

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}
Was it helpful?

Solution

The second argument of the createForm() helper should contain the initial data of your form. It may be an entity but it also could be an array.

You don't really need to return the entity from your action, unless you need to use it within your template.

createForm() signature,

public Form createForm(string|FormTypeInterface $type, mixed $data = null, array $options = array())

where,

mixed  |  $data  |  The initial data for the form
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top