0

still getting to grips with Symfony so please excuse me if this is already asked. I don't quite understand how to send data to forms to be processed properly so am need of a bit of guidance.

My issue is i wish to save my logged in user's ID into the database when they are creating a new gecko (so that this gecko's profile shows for only this user logged in). I am using FOSUserBundle by the way.

I know i can get the current user's id by using something like $user = $this->getUser()->getId(); However, i would like to save this into the database.

createAction:

public function createAction(Request $request)
    {
        $entity = new Gecko();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

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

            return $this->redirect($this->generateUrl('gecko_show', array('name' => $entity->getName())));
        }

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

GeckoType:

<?php

namespace Breedr\GeckoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GeckoType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('aquisitionDate')
            ->add('morph')
            ->add('sex', 'choice', array(
                'choices' => array(
                    'Male' => 'Male',
                    'Female' => 'Female'
                )
            ))
            ->add('genetics')
            ->add('bio')
            ->add('bred', 'checkbox', array(
                'required' => false
            ))
            ->add('hatchling', 'checkbox', array(
                'required' => false
            ))
            ->add('clutch', 'text', array(
                'data' => 0,
                'required' => false
            ))
            ->add('imageFile', 'file', array(
                'required' => false
            ))
            ->add('user_id', 'hidden', array(
                'data' => $user,
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Breedr\GeckoBundle\Entity\Gecko'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'breedr_geckobundle_gecko';
    }
}

I would really appreciate any help with this. I just can't understand how the data is used/sent. Thanks in advance :)

Andy

1 Answer 1

3

Firstly sorry if you know this, but you'll need correct relationships set up between your Gecko and User entities.

Note your @ORM annotation may be different from mine (or you could be using YAML or whatever). My use is:

use Doctrine\ORM\Mapping as ORM;

This should be in your Gecko entity

/**
 * @ORM\ManyToOne(targetEntity="Your\NameSpace\Entity\User", inversedBy="geckos")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

This should be in your User entity

/**
 * @ORM\OneToMany(targetEntity="Your\NameSpace\Entity\Gecko",mappedBy="user")
 */
protected $geckos;

Note you'll need to generate getters & setters etc.

To save your new Gecko:

$gecko = new Gecko();
$gecko->setUser($this->getUser());

$form = $this->createForm(new GeckoType(), $gecko);

$entityManager = $this->getDoctrine()->getManager();

if ($request->isMethod('POST')) {

    $form->submit($request);

    if ($form->isValid()) {

        $entityManager->persist($gecko);
        $entityManager->flush();

        // do something with success

    } else {

        // show errors by flash message or whatever
    }
}

I'd suggest you read up on the symfony forms documentation & the databases & doctrine documentation as that has most of the information you need for getting started.

Sign up to request clarification or add additional context in comments.

3 Comments

The outer if is unnecessary. A $form->handleRequest($request); followed by if ($form->isValid()) { is sufficient.
I'm going to try this right now and see if it works. I knew about relationships but i wasn't sure if i needed it for doing this. Thank you for this, will report back soon with any issues :)
@keyboardSmasher i dropped the outer if and it does indeed work fine :)

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.