如何多次渲染表单

时间:2014-01-07 03:46:21

标签: forms symfony doctrine-orm

为我的应用程序开发创建学生需求。 我有我的Student实体,该实体包含两个属性:

  1. 用户(用户实体的实例)
  2. 课程(课程实体的实例)
  3. 我构建表单,但我希望通过单击按钮同时呈现表单。通过这种方式,管理员可以添加任何学生而无需刷新页面。

    它有可能吗?如何管理控制器上的提交?

    有什么想法吗?感谢

    注意:我在添加新记录时会搜索类似的Phpmyadmin行为。

1 个答案:

答案 0 :(得分:3)

您应该做的是创建一个新对象和表单(例如StudentCollection),允许使用collection类型添加学生表单。这将允许您更好地管理动态添加/删除学生表单。

有关表单集合的更多信息http://symfony.com/doc/current/cookbook/form/form_collections.html

e.g。假设您有一个名为StudentFormType的学生表单,这样的东西应该可行。如果您想知道如何动态添加/删除学生表单以及处理提交,您应该使用上面的链接上的一个很好的示例。

// src/PathTo/YourBundle/Form/Type/StudentCollectionFormType.php

// Form object
class StudentCollectionFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('students', 'collection', array(
                'type' => new StudentFormType(),
                'allow_add' => true,
                'allow_delete' => true,
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PathTo\YourBundle\Model\StudentCollection',
        ));
    }

    // ...
}



// src/PathTo/YourBundle/Model/StudentCollection.php
namespace PathTo\YourBundle\Model;

// ...
class StudentCollection
{
    // ...
    protected $students;

    public function __construct()
    {
        $this->students = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getStudents()
    {
        return $this->students;
    }

    public function addStudent(Student $student)
    {
        $this->students->add($student);
    }

    public function removeStudent(Student $student)
    {
        $this->students->removeElement($student);
    }
}

然后在您的控制器中

// src/PathTo/YourBundle/Controller/StudentController.php
public function editAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $collection = new StudentCollection();

    // Prepopulate the collection with students
    // ...

    $form = $this->createForm(new StudentCollectionFormType(), $collection);

    $form->handleRequest($request);

    if ($form->isValid()) {
        foreach ($collection->getStudents() as $student) {
            $em->persist($student);
        }

        $em->flush();

        // redirect back to some edit page
        // ...
    }

    // render some form template
    // ...
}
相关问题