How do you update a backend form after adding a relation using the relationRender in OctoberCMS?

914 Views Asked by At

I have 2 models Booking and Attendee with a Many to Many relation

I also have a BookingAttendee pivot model - so I can make use of the afterCreate methods that these have.

In the backend form for a Booking where I want to add attendees - I'm using a partial to render the relation with <?= $this->relationRender('attendees') ?> and everything is working fine.

A booking has some price attributes that I would like to update on the page everytime an attendee is added or removed.

Are there any sort of methods on the relationWidget that happens after a relation is created that would allow me to update a div on the page?

According to the docs, there are these 4 methods that I can use to extend on the RelationController

relationExtendViewWidget()
relationExtendManageWidget()
relationExtendPivotWidget()
relationExtendRefreshResults()

The problem is I don't know how to use these to update content on the page.

1

There are 1 best solutions below

5
On

You have to add a div with an unique ID to your relation render. For example:

<div id="delegates-relation">
    <?= $this->relationRender('delegates') ?>
</div>

Then in your controller you have to add the relationExtendRefreshResults($field) method and return your new html from the relation render with the id defined above.

/**
 * Update fields after a relation has changed
 *
 * @param $field the relation field that has changed.
 * @return array|null
 */
public function relationExtendRefreshResults($field):? array
{
    if ($field !== 'yourField') { // here you can check which field was updated.
        return null;
    }

    return [
        '#delegates-relation'=> $this->relationRender('delegates'),
    ];
}