Search code examples
formsdoctrine-ormsymfony4

How to setup Symfony form for many to many relationship with add only, no edit or delete


I have a many to many relationships setup between 2 entities, User and Course. I have join table UserCourse for the relationship that has a extra fields for the start date and a expiry date. If I setup as a ManyToMany relationship in Doctrine I can create an EntityTypeform that allow adding and deleting courses from a user, but, I cannot get it to set the UserCourse expiry which needs to be set using the date the UserCourse record is created + a subScriptionExpiry term value from the Course entity (a string like "+1 year"). I tried via PrePersist but it isn't triggered when the collection is updated.

/**
 * 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

If I set it up as a OneToMany/ManyToOne I can create a CollectionType embedded form, but I need to disallow editing existing UserCourse records and the CollectionType displays the Course field of the UserCourse records as select fields where the course can be changed.

/**
 * 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) }}

The code for add course is in another template and creates an empty form via the form definition prototype.

screenshot

Is there a way to fix these issues? Or a better way to do the data model or forms to make this work more seamlessly?


Solution

  • Using your latter approach (ManyToOne/OneToMany), use css to mark the drop-down boxes as disabled (in the embedded form, use 'attr' => ['disabled' => true], then enable newly rendered select items using javascript. You may also want to mark 'allowDelete' => false in your UserFormType, otherwise you may need to re-enable all select items upon form submission.