2

So i want to display all the courses within my database in a drop down form. a user who is logged in then select one of the drop downs and it would store the users ID and the course ID into the database. How would i go about doing this?

Here's my course entity course.php

<?php
// src/Simple/SimpleBundle/Entity/Course.php
namespace Simple\ProfileBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="course")
*/
class Course
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(name="course", type="string", length=255)
 */
protected $course;


public function __construct()
{
    $this->users = new ArrayCollection();
}


   public function setCourse($course)
{
    $this->course = $course;
}

public function getCourse()
{
    return $this->course;
}

 public function setId($id)
{
    $this->id = $id;
}

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

ChooseCourseType.php my form

<?php
// src/Simple/ProfileBundle/Controller/ChooseCourseType.php
namespace Simple\ProfileBundle\Form\Type;

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

class ChooseCourseType extends AbstractType
{
private $course;

public function buildForm(FormBuilderInterface $builder, array $options) {


$builder->add('course', 'choice', array(
    'choices'   => $this->course,
));

$builder->add('Choose Course', 'submit');

}
public function getName()
{
    return 'name';
}     
public function getCourse()
{
    return 'course';
}  



}

Coursecontroller.php

function chooseAction(Request $request)
{
$em = $this->getDoctrine()->getManager();

$form = $this->createForm(new ChooseCourseType(), $CourseType);

$form->handleRequest($request);

if ($form->isValid()) {
    $course = $form->getData();

    $em->persist($course->getCourse());
    $em->flush();


}

return $this->render(
    'SimpleProfileBundle:Course:choosecourse.html.twig',
    array('form' => $form->createView())
);
}

}

User.php

namespace Simple\ProfileBundle\Entity;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User implements UserInterface
{

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(name="user", type="string", length=255)
 */
protected $username;

/**
 * @ORM\Column(name="password", type="string", length=255)
 */
protected $password;

/**
 * @ORM\Column(name="salt", type="string", length=255)
 */
protected $salt;

/**
 * @ORM\ManyToMany(targetEntity="Role")
 * @ORM\JoinTable(name="user_role",
 *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
 * )
 */
protected $roles;

      /**
 * @ORM\ManyToMany(targetEntity="Course")
 * @ORM\JoinTable(name="user_course",
 *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="course_id",   
 referencedColumnName="id")}
 * )
 */
protected $courses;
/**
 * @inheritDoc
 */
public function getUsername()
{
    return $this->username;
}

/**
 * @inheritDoc
 */
public function getSalt()
{
    return '';
}

/**
 * @inheritDoc
 */
public function getPassword()
{
    return $this->password;
}

/**
 * @inheritDoc
 */
public function getRoles()
{
return $this->roles->toArray();
}

  /**
 * @inheritDoc
 */
public function eraseCredentials()
{
}

/**
 * Constructor
 */
public function __construct()
{
    $this->roles = new \Doctrine\Common\Collections\ArrayCollection();
    $this->salt = sha1(uniqid(null, true));
}

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

/**
 * Set user
 *
 * @param string $user
 * @return User
 */
public function setUser($user)
{
    $this->user = $user;

    return $this;
}

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

/**
 * Set password
 *
 * @param string $password
 * @return User
 */
public function setPassword($password)
{
    $this->password = $password;

    return $this;
}

/**
 * Set salt
 *
 * @param string $salt
 * @return User
 */
public function setSalt($salt)
{
    $this->salt = $salt;

    return $this;
}

/**
 * Add roles
 *
 * @param \Simple\ProfileBundle\Entity\Role $roles
 * @return User
 */
public function addRole(\Simple\ProfileBundle\Entity\Role $roles)
{
    $this->roles[] = $roles;

    return $this;
}

/**
 * Remove roles
 *
 * @param \Simple\ProfileBundle\Entity\Role $roles
 */
public function removeRole(\Simple\ProfileBundle\Entity\Role $roles)
{
    $this->roles->removeElement($roles);
}

    /**
 * Add roles
 *
 * @param \Simple\ProfileBundle\Entity\Course $courses
 * @return User
 */
public function addCourse(\Simple\ProfileBundle\Entity\Course $courses)
{
    $this->course[] = $courses;

    return $this;
}



}

What else am i missing i am new to symfony2 and just need some direction.

Cheers

2
  • possible duplicate of symfony2 - adding choices from database Commented May 1, 2014 at 14:23
  • I read over that one and can't really apply it to my example or get my head around how i could do so, thanks Commented May 1, 2014 at 14:33

1 Answer 1

6

You need to use the entity form type.

Form type

<?php
// src/Simple/ProfileBundle/Controller/ChooseCourseType.php
namespace Simple\ProfileBundle\Form\Type;

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

class ChooseCourseType extends AbstractType {
    $builder->add('courses', 'entity', array(
        'label' => 'Courses',
        'class' => 'SimpleSimpleBundle:Course',
        'expanded' => false,
        'multiple' => false
    ))
    // ...

Controller

function chooseAction(Request $request) {
    $em = $this->getDoctrine()->getManager();

    // Replace this with whatever logic you use to find the user
    $user = $em->getRepository('SimpleSimpleBundle:User')->findOneBy(
        array('id' => 1)
    );

    $form = $this->createForm(new ChooseCourseType(), $user);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $user = $form->getData();

        // Since you've bound this user object to the form and properly
        // created a relationship between the course and user entities
        // the relationship between course and user will persist here
        $em->persist($user);
        $em->flush();
    }
Sign up to request clarification or add additional context in comments.

6 Comments

Is this all i am missing then ? Cheers
There are a few different ways to do this, but this is the simplest and seems to fit your use case. I would suggest reading about the various form types when you have some time.
I have read on it but i am just struggling to get my head around displaying them from the database and inserting the ID's into a table. Does my controller look right ? Cheers
It looks like you thinking about this a bit the wrong way. You want your form to modify your Course object (i.e. add a User to the Course), so that is what you need to pass as the second parameter to your form. You also need to create a relationship between User and Course in your Doctrine entities. You don't include the User entity here but I don't see any relationship in your Course entity. I do see you creating an ArrayCollection in the constructor but that's not sufficient.
I will show you the User entity, there is a relationship. So i pass the user object through the form? Cheers
|

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.