Symfony2 Pre populate form with data from model?

10,197

Replace

findOneByUser($id)

by

find($id)

Also try passing the $id as a slug from url to your Action. url: example.com/page/id

sampleAction($id){}
Share:
10,197
DJ.MaSs
Author by

DJ.MaSs

Updated on June 04, 2022

Comments

  • DJ.MaSs
    DJ.MaSs almost 2 years

    I have a ProfileType as follows:

    namespace Site\UserBundle\Form\Type;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
    
    class ProfileType extends AbstractType
    {
        public function buildForm(FormBuilder $builder, array $options)
        {       
            $builder->add('facebook', 'text', array('required'=>false))
                ->add('myspace', 'text', array('required'=>false))
                ->add('twitter', 'text', array('required'=>false))
                ->add('soundcloud', 'text', array('required'=>false))
                ->add('youtube', 'text', array('required'=>false))
                ->add('website', 'text', array('required'=>false))
                ->add('bio', 'textarea', array('required'=>false));
        }
    
        public function getName()
        {
            return 'profile';
        }
    }
    

    and I want to pre populate the form fields with data that is already in the database so it is visible in the form.

    My controller:

    namespace Site\UserBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\Security\Core\SecurityContext;
    use Symfony\Component\HttpFoundation\Request;
    use Site\UserBundle\Entity\Profile;
    use Site\UserBundle\Form\Type\ProfileType;
    
    class ProfileController extends Controller
    {
        public function editAction()
        {           
            $em = $this->getDoctrine()->getEntityManager();
            $editprofile = $em->getRepository('SiteUserBundle:Profile')->findOneByUser($user = $this->get('security.context')->getToken()->getUser()->getId());
    
            $form = $this->createForm(new ProfileType(), $editprofile);
    
            $form->bindRequest($this->getRequest());
                if ($form->isValid()) {
                    $editprofile->setUpdated(new \DateTime("now"));
                    $em->flush();
    
                    return $this->redirect($this->generateUrl('SiteUserBundle_login'));
                }
    
            return $this->render(
                'SiteUserBundle:Default:editprofile.html.twig', 
                array('form' => $form->createView())
            );
        }
    }
    

    Any ideas? I thought this way would be easier to update a users profile.