Hi All,
I got problem while updating Dynamic Form .I am using wbraganca\dynamicform.
It is not updating but inserting data to the tables
[size="6"]My view[/size]
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\modules\surveyOwner\models\Survey;
use backend\models\Questionoptiontype;
use wbraganca\dynamicform\DynamicFormWidget;
/* @var $this yii\web\View */
/* @var $model backend\modules\surveyOwner\models\Surveyquestion */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="row">
<div class="col-sm-12">
<div class="captionWrapper">
<ul>
<li><h2 class="cur">Question</h2></li>
<li><h2>Question Option</h2></li>
</ul>
</div>
</div>
</div>
<div class="surveyquestion-form">
<?php $session = Yii::$app->session; ?>
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?=
$form->field($model, 'SurveyId')->dropDownList(
ArrayHelper::map(Survey::find()->all(), 'SurveyId', 'SurveyName'), [
'prompt' => 'Select Survey',
]
)
?>
<?= $form->field($model, 'Question')->textarea(['rows' => 3]) ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4>Question Options</h4></div>
<div class="panel-body">
<?php
DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsQuestionOption[0],
'formId' => 'dynamic-form',
'formFields' => [
'QuestionOption',
'QuestionOptionTypeId',
],
]);
?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsQuestionOption as $i => $val): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Question Option</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$val->isNewRecord) {
// echo Html::activeHiddenInput($val, "[{$i}]id");
echo Html::activeHiddenInput($val, "[{$i}]QuestionOptionId");
echo Html::activeHiddenInput($val, "[{$i}]SurveyQuestionId");
}
?>
<div class="row">
<div class="col-sm-6">
<?php
// if (isset($val[$i]['QuestionOptionId'])) {
// $form->field($val, "[{$i}]QuestionOptionId")->hiddenInput()->label(false);
// }
?>
<?= $form->field($val, "[{$i}]QuestionOption")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?=
$form->field($val, "[{$i}]QuestionOptionTypeId")->dropDownList(
ArrayHelper::map(Questionoptiontype::find()->all(), 'QuestionOptionTypeId', 'QuestionOptionType'), [
'prompt' => 'Select Option',
]
)
?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<?= $form->field($model, 'CreatedOn')->hiddenInput(['value' => date('Y-m-d h:i:s')])->label(false) ?>
<?= $form->field($model, 'ModifiedOn')->hiddenInput(['value' => date('Y-m-d h:i:s')])->label(false) ?>
<?= $form->field($model, 'SurveyQuestionStatus')->dropDownList([ '1' => 'Active', '0' => 'Inactive'], ['prompt' => 'Select']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My Controller
<?php
namespace backend\modules\surveyOwner\controllers;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use backend\modules\surveyOwner\models\Surveyquestion;
use backend\modules\surveyOwner\models\SurveyquestionSearch;
use backend\modules\surveyOwner\models\Questionoption;
use backend\modules\surveyOwner\models\Model;
/**
* SurveyquestionController implements the CRUD actions for Surveyquestion model.
*/
class SurveyquestionController extends Controller {
public $layout = 'main';
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Surveyquestion models.
* @return mixed
*/
public function actionIndex() {
$searchModel = new SurveyquestionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Surveyquestion model.
* @param integer $id
* @return mixed
*/
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Surveyquestion model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate() {
$model = new Surveyquestion();
$modelsQuestionOption = [new Questionoption];
if ($model->load(Yii::$app->request->post())) {
$modelsQuestionOption = Model::createMultiple(Questionoption::classname());
Model::loadMultiple($modelsQuestionOption, Yii::$app->request->post());
// ajax validation
// if (Yii::$app->request->isAjax) {
// Yii::$app->response->format = Response::FORMAT_JSON;
// return ArrayHelper::merge(
// ActiveForm::validateMultiple($modelsAddress), ActiveForm::validate($modelCustomer)
// );
// }
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsQuestionOption) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsQuestionOption as $val) {
$val->SurveyQuestionId = $model->SurveyQuestionId;
if (!($flag = $val->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->SurveyQuestionId]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
// if ($model->save()) {
// // return $this->redirect(['view', 'id' => $model->SurveyQuestionId]);
// return $this->redirect(['questionoption/create', 'id' => $model->SurveyQuestionId]);
// } else {
// echo '<script>alert("error in creating question");</script>';
// echo '<script>top.window.location.href="' . Url::toRoute('surveyOwner/questionoption/create') . '"</script>';
// }
// }
else {
return $this->render('create', [
'model' => $model,
'modelsQuestionOption' => (empty($modelsQuestionOption)) ? [new Questionoption] : $modelsQuestionOption
]);
}
}
/**
* Updates an existing Surveyquestion model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id) {
$modelQuestion = $this->findModel($id);
$modelsQuestionOption = $modelQuestion->questionoptions; //questionoption is the relation name with QuestionOption
// var_dump($modelsQuestionOption);
if ($modelQuestion->load(Yii::$app->request->post())) {
// var_dump($_POST);
// var_dump($_POST['Questionoption'][0]['SurveyQuestionId']);
$oldIDs = ArrayHelper::map($modelsQuestionOption, 'QuestionOptionId', 'QuestionOptionId');
// $oldIDs = ArrayHelper::map($modelsQuestionOption, 'id', 'id');
$modelsQuestionOption = Model::createMultiple(Questionoption::classname());
// $modelsQuestionOption = Model::createMultiple(Questionoption::classname(), $modelsQuestionOption);
Model::loadMultiple($modelsQuestionOption, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsQuestionOption, 'QuestionOptionId', 'QuestionOptionId')));
// validate all models
$valid = $modelQuestion->validate();
$valid = Model::validateMultiple($modelsQuestionOption) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $modelQuestion->save(false)) {
if (!empty($deletedIDs)) {
Questionoption::deleteAll(['SurveyQuestionId' => $deletedIDs]);
}
foreach ($modelsQuestionOption as $val) {
$val->SurveyQuestionId = $modelQuestion->SurveyQuestionId;
if (!($flag = $val->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
// return $this->redirect(['view', 'id' => $modelCustomer->id]);
return $this->redirect(['view', 'id' => $modelQuestion->SurveyQuestionId]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
// var_dump($modelsQuestionOption);
return $this->render('update', [
'model' => $modelQuestion,
'modelsQuestionOption' => (empty($modelsQuestionOption)) ? [new Questionoption] : $modelsQuestionOption
]);
}
}
public function actionUpdate2($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->SurveyQuestionId]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Surveyquestion model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id) {
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Surveyquestion model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Surveyquestion the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = Surveyquestion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
My Model
<?php
namespace backend\modules\surveyOwner\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* @param string $modelClass
* @param array $multipleModels
* @return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}