如何使用仅添加,不编辑或删除的多对多关系设置Symfony表单

时间:2019-04-26 17:36:55

标签: forms doctrine-orm symfony4

我在两个实体(用户和课程)之间建立了多对多关系。我已经为用户关系加入了表UserCourse,该表具有一个用于开始日期和到期日期的额外字段。如果我在Doctrine中设置为ManyToMany关系,则可以创建一个EntityTypeform,以允许从用户添加和删除课程,但是,我无法获取它来设置UserCourse到期时间,而该期限需要使用创建UserCourse记录的日期+来自课程实体的subScriptionExpiry期限值(类似于“ +1年”的字符串)。我通过PrePersist尝试过,但是在更新集合时不会触发它。

/**
 * User
 *
 * @ORM\Table(name="user")
 */
class User
{
    /**
     * @ORM\ManyToMany(targetEntity="Course", inversedBy="users")
     * @JoinTable(name="course_user",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="course_id", referencedColumnName="id")}
     *      )
     */
    private $courses;
/**
 * Course
 *
 * @ORM\Table(name="course")
 */
class Course

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="users")
     */
    private $users;

    /**
     * @var string|null
     *
     * @ORM\Column(name="subscription_expiry", type="string", length=20, nullable=true)
     */
    private $subscriptionExpiry;
/**
 * CourseUser
 *
 * @ORM\Table(name="course_user")
 * @ORM\HasLifecycleCallbacks()
 */
class CourseUser
{
    /**
     * @var DateTime
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="created_at", type="datetime", nullable=false, options={"default": "CURRENT_TIMESTAMP"})
     */
    private $createdAt;

    /**
     * @var DateTime|null
     *
     * @ORM\Column(name="expiry", type="datetime", nullable=true)
     */
    private $expiry;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->createdAt = new DateTime();
    }

    /**
     * @ORM\PrePersist
      */
    public function updateExpiry()
    {
        $this->expiry = new DateTime($this->getCourse()->getSubscriptionExpiry());
    }
// UserController Create form
$form = $this->createForm(UserFormType::class, $user);
...
        return $this->render('user/editb.html.twig', [
            'userForm' => $form->createView()
        ]);

// UserFormType
   public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(...) // some user fields
            ->add('courses', EntityType::class, [
                'class' => Course::class,
                'multiple' => true,
                'expanded' => true,
                'choice_label' => 'name',
                'label' => 'Courses',
                'query_builder' => function(CourseRepository $repo) {
                    return $repo->createIsActiveQueryBuilder();
                }
            ])
        ;
{{ form_start(userForm) }}
...
{{ form_row(userForm.courses) }}
<button type="submit" class="btn btn-primary" formnovalidate>Save</button>

{{ form_end(userForm) }}

screenshot

如果将其设置为OneToMany / ManyToOne,则可以创建CollectionType嵌入式表单,但是我需要禁止编辑现有的UserCourse记录,并且CollectionType将UserCourse记录的Course字段显示为可以更改课程的选择字段

/**
 * User
 *
 * @ORM\Table(name="user")
 */
class User
{
    /**
     * @var Collection
     *
     *  @ORM\OneToMany(targetEntity="CourseUser", mappedBy="user", fetch="EXTRA_LAZY", orphanRemoval=true, cascade={"persist"})
     */
    private $userCourses;
/**
 * Course
 *
 * @ORM\Table(name="course")
 */
class Course

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="CourseUser", mappedBy="course", fetch="EXTRA_LAZY", orphanRemoval=true, cascade={"persist"})
     */
    private $courseUsers;
// UserFormType
   public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(...) // some user fields
            ->add('userCourses',CollectionType::class, [
                'entry_type' => UserCourseEmbeddedForm::class,
                'allow_delete' => true,
                'allow_add' => true,
                'by_reference' => false,
                'label' => false
            ])
        ;
// UserCourseEmbeddedForm
        $builder
            ->add('course', EntityType::class, [
                'class' => Course::class,
                'choice_label' => 'name',
                'label' => false,
                'query_builder' => function(CourseRepository $repo) {
                    return $repo->createIsActiveQueryBuilder();
                }
            ])
{{ form_start(userForm) }}
...
<h3>Courses</h3>
<div class="row js-user-course-wrapper"
     data-prototype="{{ form_widget(userForm.userCourses.vars.prototype)|e('html_attr') }}"
     data-index="{{ userForm.userCourses|length }}"
>
    {% for userCourseForm in userForm.userCourses %}
        <div class="col-xs-4 js-user-course-item">
            {{ form_errors(userCourseForm) }}
            {{ form_row(userCourseForm.course) }}
     </div>
    {% endfor %}
    <a href="#" class="js-user-course-add">
        <span class="fa fa-plus-circle"></span>
        Add Another Course
    </a>
</div>

<button type="submit" class="btn btn-primary" formnovalidate>Save</button>

{{ form_end(userForm) }}

添加课程的代码在另一个模板中,并通过表单定义原型创建一个空表单。

screenshot

是否可以解决这些问题?还是一种更好的方法来制作数据模型或表格以使其更无缝地工作?

1 个答案:

答案 0 :(得分:0)

使用后一种方法(ManyToOne / OneToMany),使用CSS将下拉框标记为已禁用(以嵌入式形式,使用'attr' => ['disabled' => true],然后使用javascript启用新呈现的select项目。您可能还需要在UserFormType中标记'allowDelete' => false,否则在提交表单后可能需要重新启用所有select项。