OctoberCMS: How to prefill a child form field based on a parent form field

166 views Asked by At

I'm just trying to set up a relation in OctoberCMS backend where a child form should get a value from the parent form as a suggestion (default).

In detail there are two models linked by a belongsTo relation (an attendee belongs to a tournament) 1st the parent model (field.yaml) covering a sports tournament:

tournament:
    # ... some other fields
    start_date:
        label: Start date
        type: date
    attendees:
        label: Attendees
        type: partial

2nd the child model for the attendees:

attendee:
    name:
        label: Name
        type: text
    start_date:
        label: Start date
        type: date
        # how to get the value from tournament->start_date as preset?

A parent form (on a sports tournament) has a start date as well as a related partial covering athletes attending the game. Each athlete also has an individual start date field which I would like to prefill with the start date of the game as soon this form is called by the parent tournament form. But it has to be editable, because not all attendees will start at the same day.

There is a built in function to preset a filed with a value from another field of the same form, but unfortunately I cannot find a solution how to get the value from a parent form.

Thanks in advance!

1

There are 1 answers

1
Hardik Satasiya On BEST ANSWER

You can add relationExtendManageWidget method into your Tournament controller and extend its behavior. you can now inject initial values for your new modal while creating new records.

// ..code
class Tournament extends Controller
{
    // ..code

    public function __construct()
    {
        // ..code
    }

    public function relationExtendManageWidget($widget, $field, $model)
    {
      // make sure we are doing on correct relation
      // also make sure our context is create so we only copy name on create
      if($field === 'attendees' 
          && property_exists($widget->config, 'context') 
          && $widget->config->context === 'create'
      ) {         
        $widget->config->model->start_date = $model->start_date;
        // this is attendee ^ model            ^ this is main tournament model
      }
    }
}

Now when your try to create a new attendee record from your Tournament record, your attendee's start_date will be pre-filled based on your tournament's start_date and it only happens on creating new records.

if any doubt please comment.