octobercmsoctobercms-backendoctober-form-controller

OctoberCMS: Access parent model in relation form


I am creating an interface in the backend where the parent model has a belongsToMany relationship which is handled via a relation manager widget.

When creating the related model I need to be able to access the model (and relationships) of the model in the parent form in order to populate the child form correctly.

Unfortunately I was not able to find how to do this, can someone shed some light into this problem?


Solution

  • Managed to find out a way to pass the needed data to the form in the relation manager by extending the relation manager widget in the controller and passing the parrent model in the config of the widget making it accessible within the child form.

    Here is the code:

    public function relationExtendManageWidget($widget, $field, $model)
    {
        if($field === 'MyRelationName'
            && property_exists($widget->config, 'context')
        ) {
            $widget->config->parentModel = $model;
           
        }
    }
    

    You can also pass a value directly to the child Model like this:

    public function relationExtendManageWidget($widget, $field, $model)
    {
        if($field === 'MyRelationName'
            && property_exists($widget->config, 'context')
            && $widget->config->context === 'create'
        ) {
            $widget->config->model->customer_id = $model->customer_id;
           
        }
    }