Reputation: 2206
I have two models in a form. One model is a master, and one model is representated as junction table (model).
Desc :
request_table : $model,
link_req_tipe : $modelLinkReqTipe;
My goal is,
I batch insert to link_req_item
id_request = $model->id and id_tipe = modelLinkReqTipe->id_tipe
Here it is the php :
_form.php (just example, because a lot of many input form)
<?= $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"])
];
}
Now, validation is in trouble, it always return false in submit. Please Advise.
Upvotes: 0
Views: 751
Reputation: 820
There are many ways to resolve this issue. I think the best way to make sure that $modelLinkReqTipe
's attribute id_request
is not taken into account upon validation is to provide validate()
function with array of attributes you want to validate: validate(['id_tipe'])
Upvotes: 1