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
Thanks to Dragontree's suggestions: here is my 1st EDIT:
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'.
Final edit:
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
- Use
Dropdownwidget and change the options with detailed solution here provided by @Mittul At TechnoBrave - Or directly use
Relationwidget as provided in the suggested solution by @dragontree