我在表单中有两个模型。 一个模型是主模型,一个模型表示为连接表(模型)。
描述:
request_table : $model,
link_req_tipe : $modelLinkReqTipe;
我的目标是,
我批量插入到link_req_item
id_request = $ model-> id 和 id_tipe = modelLinkReqTipe-> id_tipe
这是php:
_form.php (仅举例,因为很多输入形式)
<?= $form->field($model, 'karyawan_id')->dropDownList(
ArrayHelper::map(Karyawan::find()->all(), 'id', 'first_name'), ['prompt' => 'Select Karyawan'])
?>
<?= $form->field($modelLinkReqTipe, 'id_tipe')->checkBoxList(ArrayHelper::map(TipeRequest::find()->all(), 'id', 'nama_tipe'));
?>
RequestController
if ($model->load($request->post()) && $modelLinkReqTipe->load(Yii::$app->request->post())) {
$valid = $model->validate();
$valid = $modelLinkReqTipe->validate() && $valid;
if ($valid) { ## Check validate : true
$transaction = Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelLinkReqTipe as $index => $modelLinkReqTipe ) {
if ($flag === false) {
break;
}
$modelLinkReqTipe->id_request = $model->id;
if (!($flag = $modelLinkReqTipe->save(false))) {
break;
}
}
}
if ($flag) {
$transaction->commit();
} else {
$transaction->rollBack()
}
}
catch (\Exception $e) {
$transaction->rollBack();
}
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Request",
'content' => '<h1 class="text-success">Success</h1>,
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}else{ ## Check validate : false
return [
'title' => "Create New Request",
'content' => $this->renderAjax('create', [
'model' => $model,
'modelLinkReqTipe' => (empty($modelLinkReqTipe)) ? new LinkReqTipe() : $modelLinkReqTipe,
'modelLinkReqItem' => (empty($modelLinkReqItem)) ? [new LinkReqItem] : $modelLinkReqItem,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
答案 0 :(得分:1)
有很多方法可以解决此问题。我认为确保$modelLinkReqTipe
属性id_request
在验证时不考虑的最佳方法是为validate()
函数提供您要验证的属性数组: validate(['id_tipe'])