Add a relation manager widget to a form
15
Given are the following models (adapt the class names and namespaces to your usecase):
- Post: This is the base model, a simple blog post. We want to add the relation manager to this model's form.
- Comment: This is the related model. A blog post has many comments.
<?php
namespace Acme\Blog\Models;
class Post extends Model
{
// The relation manager works for any relation type, use whatever you need.
public $hasMany = ['comments' => \Acme\Blog\Models\Comment::class];
}
Implementing and configuring the relation controller
In your PostsController
add the following lines:
<?php
namespace Acme\Blog\Controllers;
class Posts extends Controller
{
public $implement = [
'Backend.Behaviors.FormController',
'Backend.Behaviors.RelationController', // Add this!
];
public $formConfig = 'config_form.yaml';
public $relationConfig = 'config_relation.yaml'; // Add this!
}
Next, create the config_relation.yaml
file in plugins/acme/blog/controllers/posts/config_relation.yaml
.
Paste the contents below (in case of a hasMany
relation) into the yaml file.
You can find more examples for different relationship types (hasOne
, belongsToMany
, etc)
in the official docs.
comments:
label: Comment
deferredBinding: true
view:
list: $/acme/blog/models/comment/columns.yaml
toolbarButtons: create|delete
manage:
form: $/acme/blog/models/comment/fields.yaml
recordsPerPage: 10
Displaying the relation manager
Create a new file in plugins/acme/blog/controllers/posts/_comments.htm
. Paste the following contents:
<?= $this->relationRender('comments'); ?>
The comments
key corresponds to the base key in your config_relation.yaml
.
Now you can include this partial in your model's form definition to display the relation manager.
# in plugins/acme/blog/models/post/fields.yaml
comments:
type: partial
path: comments # includes _comments.htm from the current controller's path.
Thanks
I want to know, how can we update a field from the parent model when updating the relation
i didn't find the solution,any idéa please ? Thanks.
Can anyone help, why it takes to much time to load the popup modal after u click to update any row after first time before u refresh the page. E.g. first time after u refresh the page the modal opens instantly but in 2nd time it takes time to loda th emodal, third time much more time and so on.