Assign parent to belongsTo relation in create context
0
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;
}
});
}
There are no comments yet
Be the first one to comment