I would like to create a plugin where to create Posts
, each post belong to 1 Category
.
And there is a dropdown menu at the backend where you can choose which category the post belongs to when you are creating a post.
However, I want the the options in such dropdown depend on the model Category
where the Value
is category.name
and Key
is category.id
instead of me typing the string into it.
Please help! Thanks
I already have my relationship set as followings:
in /models/Category.php
public $hasMany = [
'posts' => ['stephenli\plugin\Models\Posts']
];
in /models/Post.php
public $belongsTo = [
'category' => ['stephenli\plugin\Models\Category', 'key' => 'category_id']
]; /* I tried with or without 'key' => 'category_id'*/
and used relation widget at the Builder
Plugin,
in /models/post/field.yaml
category_id:
label: 'stephenli.postgod::lang.plugin.categorypick_label'
oc.commentPosition: ''
nameFrom: name
descriptionFrom: description
emptyOption: 'No categories found'
span: auto
type: relation
where in /models/post/columns.yaml
category_id:
label: 'stephenli.plugin::lang.plugin.categorypick_label'
type: text
searchable: true
sortable: true
When I access to my Post
Plugin and click the Create
button or try to amend any existing record in list
, the following error shows:
Model 'plugin\Models\Post' does not contain a definition for 'category_id'.
To sum up everything for any other people who encounter the same issue in the future, there are two methods to solve the problem
You can either
Dropdown
widget and change the options with detailed solution here provided by @Mittul At TechnoBraveRelation
widget as provided in the suggested solution by @dragontreeThere are several ways to define the dropdown options.
But in this case its sounds like you should be using the relation
widget instead on a normal dropdown:
category:
label: Category
type: relation
nameFrom: name
PS. This also requires you to define the relations in the Post
and Category
models. But you should do that anyway.
It is also worth noting that the field name (in fields.yaml) should match the name of the relation.