我创建了一个与另一个模型有关系的模型。我使用关系管理器小部件来处理关系。一切都很好。
现在,我需要根据父模型中字段的选择动态地向关系模型添加字段。我注意到有关于此的relationExtendManageWidget()函数。
但是,我不知道如何使用它,文档没有提供任何示例。我试着这样做:
public function relationExtendManageWidget($widget, $field, $model)
{
// Make sure the field is the expected one
if ($field != 'references') return;
$widget->addFields([
'test' => [
'label' => 'Test',
'span' => 'left',
'type' => 'text',
],
]);
return $widget;
}
但是当我转到我的表单时,我收到以下错误:
在null /modules/backend/widgets/Form.php第569行调用成员函数addField()
$ widget对象(addFields
)上不存在Widget Base documentation方法。为了实现您想要做的事情,我建议使用extendFormFields方法扩展表单字段,或者创建部分字段。使用extendFormFields的示例如下所示(代码未经测试):
public function extendFormFields(function($form, $model, $context)
{
if (!$model instanceof MyModel) { //your related model
return;
}
$form->addFields([
'test' => [
'label' => 'Test',
'span' => 'left',
'type' => 'text',
],
]);
});
而不是使用$widget->addFields(...)
,将字段配置直接添加到$widget->fields
。这对我有用。
public function relationExtendManageWidget($widget, $field, $model)
{
// Make sure the field is the expected one
if ( $field != 'references') return;
$widget->fields += [
'test' => [
'label' => 'Test',
'span' => 'left',
'type' => 'text',
],
];
}
管理小部件没有明确记录,但它与Extending the view widget下的文档中解释的相同:
由于窗口小部件尚未在运行时周期的这一点完成初始化,因此无法调用$ widget-> removeColumn()。 ListController文档中描述的addColumns()方法将按预期工作,但要删除列,我们需要在relationExtendViewWidget()方法中侦听'list.extendColumns'事件。
要添加字段,我们需要监听form.extendFields事件:
public function relationExtendManageWidget($widget, $field, $model)
{
if ($field != 'references') return;
$widget->bindEvent('form.extendFields', function () use($widget) {
$widget->addFields([
'test' => [
'label' => 'test'
],
]);
});
}