【问题标题】:Symfony2 dropdown form from database来自数据库的 Symfony2 下拉表单
【发布时间】:2014-05-01 14:20:53
【问题描述】:

所以我想以下拉形式显示我的数据库中的所有课程。登录的用户然后选择下拉菜单之一,它将用户 ID 和课程 ID 存储到数据库中。我该怎么做呢?

这是我的课程实体 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 我的表单

<?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())
);
}

}

用户.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;
}



}

我还缺少什么我是 symfony2 的新手,只需要一些指导。

干杯

【问题讨论】:

标签: php symfony


【解决方案1】:

您需要使用entity 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
    ))
    // ...

控制器

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();
    }

【讨论】:

  • 这就是我所缺少的吗?干杯
  • 有几种不同的方法可以做到这一点,但这是最简单的,似乎适合您的用例。我建议您有时间阅读各种表单类型。
  • 我已经阅读了它,但我只是在努力从数据库中显示它们并将 ID 插入表中。我的控制器看起来正确吗?干杯
  • 看来您对此的想法有点错误。您希望您的表单修改您的课程对象(即向课程添加用户),因此您需要将其作为第二个参数传递给您的表单。您还需要在您的 Doctrine 实体中创建用户和课程之间的关系。您没有在此处包含用户实体,但我在您的课程实体中看不到任何关系。我确实看到您在构造函数中创建了一个 ArrayCollection,但这还不够。
  • 我会告诉你用户实体,有一个关系。所以我通过表单传递用户对象?干杯
猜你喜欢
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多