October CMS resources and help articles

Simple and to the point. Optimized by the community.

Add a relation manager widget to a form

12
by OFFLINE, last modified on August 12th, 2019

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
{
    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.

Discussion

3 comments

0
ridha
Post on June 11th, 2019 1:52 PM

Thanks

I want to know, how can we update a field from the parent model when updating the relation

-1
ridha
Post on October 2nd, 2019 1:10 PM

i didn't find the solution,any idéa please ? Thanks.

0
fiskydeagle
Post on August 20th, 2020 8:32 AM

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.

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