Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Assign parent to belongsTo relation in create context

0
by mjauvin, last modified on July 11th, 2025

Let's say you have a Client model with hasMany relation to an Invoice model and you would like to automatically assign the client relation widget when creating an Invoice for the Client in the create form.

The Invoice model has this relation:

$belongsTo = [
    'client' => [Client::class],
];

The Invoice form fields.yaml has a "client field" like below:

client:
    type: relation
    label: Client
    emptyOption: -- Select Client --

Add this to your Invoice model:

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    $this->bindEvent('model.form.filterFields', function ($formWidget, $fields, $context) {
        $model = $formWidget->model;
        if ($context === 'create' && $model) {
            $model->client = $client = $formWidget->getController()->relationObject->getParent();
            $fields->client->value = $client->id;
        }
    });
}

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?