Yii2 : Dynamic Form wbraganca - php

I want to use dynamic form widget (wbraganca). I tried it using the tutorial by 'doingItEasy' channel & also by github. And wrote following code :
controller code -
public function actionCreate()
{
$model = new Vendors();
$modelsSubCat = [new BusinessSubCategories];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
Model::loadMultiple($modelsSubCat, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSubCat) && $valid;
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsSubCat as $modelSubCat) {
$model->ven_sub_category_id = $modelSubCat->bsc_id;
if (! ($flag = $modelSubCat->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ven_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsSubCat' => (empty($modelsSubCat)) ? [new BusinessSubCategories] : $modelsSubCat
]);
}
}
'_form.php' code -
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<div class="vendors-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'ven_company_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_main_category_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_sub_category_id')->textInput() ?>
<div class="row">
<div class="panel panel-default">
<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' => $modelsSubCat[0],
'formId' => 'dynamic-form',
'formFields' => [
// 'bsc_id',
'bsc_name',
'bsc_image',
'bsc_description',
'bmc_id',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsSubCat as $i => $modelSubCat): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Sub Categories</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 (! $modelSubCat->isNewRecord) {
echo Html::activeHiddenInput($modelSubCat, "[{$i}]id");
}
?>
<?= $form->field($modelSubCat, "[{$i}]bsc_name")->textInput(['maxlength' => true]) ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelSubCat, "[{$i}]bsc_image")->fileInput(); ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelSubCat, "[{$i}]bsc_description")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<?= $form->field($model, 'ven_services_offered')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_business_logo')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_company_descr')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_established_date')->textInput() ?>
<?= $form->field($model, 'ven_noof_emp')->textInput() ?>
<?= $form->field($model, 'ven_branches_loc')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_market_area')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_website')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_specialized_in')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_contact_no')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_email_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_address')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_country_id')->textInput() ?>
<?= $form->field($model, 'ven_state_id')->textInput() ?>
<?= $form->field($model, 'ven_city_id')->textInput() ?>
<?= $form->field($model, 'ven_location_id')->textInput() ?>
<?= $form->field($model, 'ven_zip')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_contact_person_id')->textInput() ?>
<?= $form->field($model, 'ven_verified')->dropDownList([ 'Y' => 'Y', 'N' => 'N', ], ['prompt' => '']) ?>
<?= $form->field($model, 'ven_created')->textInput() ?>
<?= $form->field($model, 'ven_updated')->textInput() ?>
<?= $form->field($model, 'ven_deleted')->dropDownList([ 'Y' => 'Y', 'N' => 'N', ], ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
console.log("beforeInsert");
});
$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
console.log("afterInsert");
});
$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
if (! confirm("Are you sure you want to delete this item?")) {
return false;
}
return true;
});
$(".dynamicform_wrapper").on("afterDelete", function(e) {
console.log("Deleted item!");
});
$(".dynamicform_wrapper").on("limitReached", function(e, item) {
alert("Limit reached");
});
</script>
'create.php' code -
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Vendors */
$this->title = Yii::t('app', 'Create Vendors');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Vendors'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="vendors-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelsSubCat' => $modelsSubCat
]) ?>
</div>
But What happens is that the add/remove button is not working. I'm showing it's screenshot - Screenshot with Add/remove buttons

1)first add
$form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]);
instead your
2) delete 'bmc_id' from attributes of dynamic form or add textinput to dynamic form with bmc_id column
3) check if exist your model Model (...Model::loadMultiple($modelsSubCat, Yii::$app->request->post());)

I tried, but i can't reproduce this issue here. Can you try fix the following lines and see if the problem was there?
You are not closing the <div class="row"> after the dynamic form.
This could mess up the html code.
In your formFields, you don't need to add the 'bmc_id' if the
model have one. Remove it. By the way, you are using:
Html::activeHiddenInput($modelSubCat, "[{$i}]id");
Make sure this is the correct name of the attribute.
Non-related with your issue, you have a second:
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
After the loadMultiple method, making it useless.
EDIT
Just occurred to me: by any chance you have more than one DynamicForm in the same view? Or the code is the same as you posted?

Related

Yii2 dropdown list and array helper "Call to a member function isAttributeRequired() on array"

I am trying to understand why my drop down list is not working. I recieve the following error messages when I try to run the custom view related to this model/view/controller.
Please forgive any of my ignorance as I am completely new to PHP and PHP frameworks by proxy.
Site Controller Code:
public function actionStudentcentrequiz()
{
$model = new GameId();
$qnamodel = new Questions();
$listData = ArrayHelper::map(Gameid::find()->all(), 'gameid','gamename');
if ($qnamodel->load(Yii::$app->request->post())) {
//PK FK relation
$model->gameid = $qnamodel->gameid;
if ($qnamodel->validate()) {
//var_dump($qnamodel); die;
//then save.
$qnamodel->save();
}
//form inputs are valid, do something here
return;
}
return $this->render('studentcentrequiz', [
'model' => $model,
'qnamodel' => $qnamodel,
'listData' => $listData,
]);
}
view/questions/_form.PHP
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Questions */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="questions-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Question')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Answer1')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Answer2')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Answer3')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Answer4')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'gameid')->dropDownList($listData,['prompt'=>'ChooseGameID']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
view/questions/_create.PHP
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Questions */
$this->title = 'Create Questions';
$this->params['breadcrumbs'][] = ['label' => 'Questions', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="questions-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', ['model' => $model, 'listData' => $listData,
]) ?>
</div>
view/questions/_update.PHP
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Questions */
$this->title = 'Update Questions: ' . $model->questionID;
$this->params['breadcrumbs'][] = ['label' => 'Questions', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->questionID, 'url' => ['view', 'id' => $model->questionID]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="questions-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', ['model' => $model, 'listData' => $listData,]) ?>
</div>
Well, after 2 hours with the same problem
View:
$form->field($model[0], 'gameid')->dropDownList($listData,['prompt'=>'ChooseGameID'])
Why? i dont know, I would like to someone explain, I have 41 records and both appear the same way in the dropdownlist [0][1][2]...

YII2 Validation for several forms in one action

Hellow i'm making several forms and their validation on YII with ajax and i have some problems
Here the view code:
<?
$form = ActiveForm::begin([
'id' => 'test-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($model, 'name')->textInput(['placeholder' => "Имя"])->label('Имя'); ?>
<?= $form->field($model, 'lastname')->textInput(['placeholder' => "Фамилия"])->label('Фамилия'); ?>
<?= $form->field($model, 'country')->textInput(['placeholder' => "Страна"])->label('Страна'); ?>
<?= $form->field($model, 'pindex')->textInput(['placeholder' => "Индекс"])->label('Индекс'); ?>
<?= $form->field($model, 'card') ->textInput(['placeholder' => "Ваш номер карты xxxx xxxx xxxx xxxx"])->label('Номер карты');?>
<?= $form->field($model, 'form_name')->hiddenInput(['value' => 'Form']) ?>
<div class="form-group">
<div class="">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
<?
$form = ActiveForm::begin([
'id' => 'mobile-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($model2, 'name')->textInput(['placeholder' => "Имя"])->label('Имя'); ?>
<?= $form->field($model2, 'lastname')->textInput(['placeholder' => "Фамилия"])->label('Фамилия'); ?>
<?= $form->field($model2, 'country')->textInput(['placeholder' => "Страна"])->label('Страна'); ?>
<?= $form->field($model2, 'pindex')->textInput(['placeholder' => "Индекс"])->label('Индекс'); ?>
<?= $form->field($model2, 'phone') ->textInput(['placeholder' => "Ваш телефон"])->label('Ваш телефон');?>
<?= $form->field($model2, 'form_name')->hiddenInput(['value' => 'Mobile']) ?>
<div class="form-group">
<div class="">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
Then im sending data with ajax to controller, code:
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\MainForm;
use app\models\EntryForm;
use app\models\EntryMobile;
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public function actionEntry(){
$model = new EntryForm;
$model2 = new EntryMobile;
if(Yii::$app->request->isAjax) {
$model->load(Yii::$app->request->post());
$model2->load(Yii::$app->request->post());
if($model->validate() || $model2->validate()){
$json['ok'] = "";
}else{
$json['error'] = " ";
}
Yii::$app->response->format = Response::FORMAT_JSON;
return $json;
} else {
return $this->render('entry', ['model' => $model,'model2' => $model2]);
}
}
In models i have MainForm , and EntryForm and EntryMobile that extends MainForm with their own rules.
Here is a question:
How to make $model->validation() and $model2->validation() in one method? Or how to make the controller method width on model for two forms. Scenarios doesnt work cause they made me make the same. Two object and etc. Please help
You can use bitwise and for testing both models validations. Like:
$model->validate() & $model2->validate()
Which will then proceed only if both conditions are true but will test both of them anyway (which should throw the validation errors you expect to see).

How to create a dynamic list of the same form on Yii2?

How do I create a dynamic list of the same form and show it on the view on Yii2 (it can be viewed as a list of the same object with different information) Thanks.
I have the following form on /frontend/views/site/example.php
That form I want to put it on a list.
<div class="site-example">
<h1><?= Html::encode($this->title) ?></h1>
<p>Example of a list:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-example']); ?>
<?= $form->field($model, 'email')->textInput(['readonly' => true, 'value' => $email]) ?>
<?= $form->field($model, 'lastname')->textInput(['readonly' => true, 'value' => $lastname]) ?>
<?= $form->field($model, 'phone')->textInput(['readonly' => true, 'value' => $phone]) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Assuming this is your controller.
<?php
namespace frontend\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use frontend\models\YourForm;
class SiteController extends Controller
{
public function actionYourAction()
{
$forms = [new YourForm, new YourForm, new YourForm];
return $this->render('example', [
'forms' => $forms
]);
}
}
Then your view could be below
<div class="site-example">
<h1><?= Html::encode($this->title) ?></h1>
<p>Example of a list:</p>
<div class="row">
<div class="col-lg-5">
<?php foreach ($forms as $index => $form): ?>
<?php $form = ActiveForm::begin(['options' => ['id' => "form-example-$index"]]); ?>
<?= $form->field($form, "[$index]email")->textInput(['readonly' => true, 'value' => $form->email]) ?>
<?= $form->field($form, "[$index]lastname")->textInput(['readonly' => true, 'value' => $form->lastname]) ?>
<?= $form->field($form, "[$index]phone")->textInput(['readonly' => true, 'value' => $form->phone]) ?>
<?php ActiveForm::end(); ?>
<?php endforeach; ?>
</div>
</div>
</div>

Yii2: Updating Grid-view using Pjax

Following this Wiki Yii 2.0: Pjax on ActiveForm and GridView - Yii2
I have tried to use my gridview to update on Ajax without page-reload, but couldn't succeed.
code of my _form.php
<?php
$this->registerJs(
'$("document").ready(function(){
$("#new_medicine").on("pjax:end", function() {
$.pjax.reload({container:"#medicine"}); //Reload GridView
});
});'
);
?>
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
//use yii\grid\Gridview;
use yii\data\ActiveDataProvider;
/* #var $this yii\web\View */
/* #var $model app\models\Medicine */
/* #var $form yii\widgets\ActiveForm */
?>
<!-- <div class="row">
<div class="col-lg-6 col-lg-offset-3"> -->
<div class="medicine-form">
<?php yii\widgets\Pjax::begin(['id' => 'new_medicine']) ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>
<?= $form->field($model, 'medicine_id')->textInput(['maxlength' => 10]) ?>
<?= $form->field($model, 'medicine_name')->textInput(['maxlength' => 50]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?= Html::submitButton($model->isNewRecord ? 'Save & New' : '',$option=['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','name'=>'save_and_new']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
</div>
Code in my controller
public function actionIndex()
{
$model = new Medicine();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
$model = new Medicine(); //reset model
}
$searchModel = new MedicineSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
code in index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\MedicineSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Medicines';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="medicine-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Medicine', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php \yii\widgets\Pjax::begin(['id' => 'medicine']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'medicine_id',
'medicine_name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>
I think I have followed the instructions very carefully, but surely I am missing something as the grid-view is not showing the new records added without page-reload.
Any help will be greatly appreciated.
Thanks.
try to explain how to do it as a widget; it's a generic solution, so contact me in case of troubles:
Controller (#your-alias/controllers/yourController):
...
public function actionManage($param=''){
$model = new YourModel();
if (Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && $model->save())
{
$model = new YourModel(); //reset model
}
$model->paramId = $param;
$queryParams = Yii::$app->request->getQueryParams();
$queryParams['YourModelSearch']['param'] = $param;
$searchModel = new YourModelSearch();
$dataProvider = $searchModel->search($queryParams);
return $this->renderAjax('#your-alias/widgets/views/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}...
widgets (#your-alias/widgets/) [form, view]:
_form:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
/**
* #var yii\web\View $this
* #var yourModule/models/YourModel $model
* #var yii\widgets\ActiveForm $form
*/
?>
<?php
$js = <<<JS
// get the form id and set the event
$('form#{$model->formName()}').on('beforeSubmit', function(e) {
var \$form = $(this);
// do whatever here, see the parameter \$form? is a jQuery Element to your form
console.log(\$form);
console.log("MODEL CODE = " + $("#yourmodel-code").val());
}).on('submit', function(e){
e.preventDefault();
});
JS;
//$this->registerJs($js);
$this->registerJs(
'$("#new-your-model").on("pjax:end", function() {
commonLib.divAction("#div_new_model", "hide"); //hide form
$.pjax.reload({container:"#models"}); //Reload GridView
});', \yii\web\View::POS_READY
);
?>
<div class="model-form">
<?php Pjax::begin(['id' => 'new-model', 'timeout' => false, 'enablePushState' => false]) ?>
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
//'method' => 'post',
'action' => ['/module/controller/manage?param='.$model->code],
'options' => ['data-pjax' => true ],
//'layout' => 'default',
]); ?>
<?= $form->field($model, 'code')->textInput(['maxlength' => 255]) ?>
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
</div>
index view (grid view):
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/**
* #var yii\web\View $this
* #var yii\data\ActiveDataProvider $dataProvider
* #var yourModule\models\search\YourModelSearch $searchModel
*/
?>
<div class="model-index">
<!--h1><!--?= Html::encode($this->title) ?></h1-->
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::button(Yii::t('bp', 'Add ...'), [
'class' => 'btn btn-success',
'onclick'=>'js:commonLib.divAction("#div_new_model", "show")'
])?>
</p>
<div id="div_new_model" style="display:none">
<?= Html::button(Yii::t('common', 'Cancel'), [
'class' => 'btn btn-success',
'onclick'=>'js:commonLib.divAction("#div_new_model", "hide")'
])?>
<!-- Render create form -->
<?= $this->render('_formModel', [
'model' => $model,
]) ?>
</div>
<?php Pjax::begin(['id' => 'models', 'timeout' => false, 'enablePushState' => false]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
...
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end() ?>
</div>
widget call (in view):
echo #your-alias\widgets\YourWidget::widget([
'param' => $model->param,]);
$.pjax.reload('#my-grid-pjax' , {timeout : false});
To update GridView table without page reload using pjax:
use yii\grid\GridView;
use yii\widgets\Pjax;
Pjax::begin(['id' => 'todaysactivity', 'timeout' => false, 'enablePushState' => false])
Use jQuery/JavaScript as follows:
var url = baseurl + '/activity/logging'; // url where the gridview table need to update
$.pjax.reload({container: "#todaysactivity", url: url}); // refresh the grid
I couldn't find a suitable solution to update the grid-view widget using pjax.
I resolved by using a auto-refresh method for the grid-view page. I understand that this is not the best solution and I am still looking for a suitable solution.
The method I have used is like this:
<script>
function autoRefresh()
{
window.location.reload();
}
setInterval('autoRefresh()', 60000); // this will reload page after every 1 minute.
</script>
What you're looking for is
<script type="text/javascript">
$.pjax.defaults.timeout = false;
</script>
The default pjax timeout setting doesn't give the page time to do anything so it reloads.
Reference

Yii2 Multiple instances of the same model

I want to get multiplie instance of the same model in my controller. I saw this wiki for Yii 1.1 and tried like that but in my code only last instance in form was acceble from controller my code is here (I commented code with error and variable values):
$model = new Person(['scenario' => 'create_update']);
$contractDate = new DatePart(); // DatePart is my own class
$contractExpirationDate = new DatePart(); // DatePart is my own class
if ($model->load(Yii::$app->request->post()) &&
$contractDate->load(Yii::$app->request->post()) &&
$contractExpirationDate->load(Yii::$app->request->post())){
Yii::info(Yii::$app->request->post(),'test'); // only one instance of Person and one instance of DatePart are available here
Yii::info($_POST['DatePart'],'test'); // only last instance of DatePart (contractExpirationDate in html form) is available here
Yii::info($_POST['DatePart'][0],'test'); // Error: Undefined offset: 0
Yii::info($_POST['DatePart'][1],'test'); // Error: Undefined offset: 1
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'contractDate' => $contractDate,
'contractExpirationDate' => $contractExpirationDate,
]);
}
It is my form view in _form.php:
<?php
use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\widgets\ActiveForm;
use common\models\DataOperations;
/* #var $this yii\web\View */
/* #var $model app\models\Person */
/* #var $contractDate backend\viewModels\DatePart */
/* #var $contractExpirationDate backend\viewModels\DatePart */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="user-form">
<?php
$form = kartik\widgets\ActiveForm::begin(
[
'id' => $model->isNewRecord ? 'user-form-create' : 'user-form-update',
'type' => ActiveForm::TYPE_VERTICAL,
//'enableAjaxValidation' => true,
'fieldConfig' => [
//'autoPlaceholder'=>true
]
]);
?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 60]) ?>
<?= $form->field($model, 'family')->textInput(['maxlength' => 60]) ?>
<?= $form->field($model, 'mobile')->textInput() ?>
<?= $form->field($contractDate, 'year')->textInput() ?>
<?= $form->field($contractDate, 'month')->textInput() ?>
<?= $form->field($contractDate, 'day')->textInput() ?>
<?= $form->field($contractExpirationDate, 'year')->textInput() ?>
<?= $form->field($contractExpirationDate, 'month')->textInput() ?>
<?= $form->field($contractExpirationDate, 'day')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
It is log result for:
Yii::info(Yii::$app->request->post(),'test')
in debugger as you seen only last DatePart available but I have two DatePart model instance (contractDate and contractExpirationDate):
[
'_csrf' => 'Vl81R0ZvMk1hD1oELT9aDzkIe3EPHFgiIBJTBhA9RD8GbFM.AhlVBw==',
'Person' => [
'name' => 'test name',
'family' => 'test family',
'mobile' => '09121212123',
],
'DatePart' => [
'year' => '2015',
'month' => 'Jun',
'day' => 'Mon',
],
]
Controller:
$model = new Person(['scenario' => 'create_update']);
$dates = [
'contractDate' => new DatePart(),
'contractExpirationDate' => new DatePart()
];
if ($model->load(Yii::$app->request->post())) {
if (Model::loadMultiple($dates, Yii::$app->request->post()) && Model::validateMultiple($dates)) {
foreach ($dates as $date) {
$date->save();
}
// or
$contractDate = $dates['contractDate'];
$contractExpirationDate = $dates['contractExpirationDate'];
// ...... some logic
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
else {
return $this->render('create', [
'model' => $model,
'dates' => $dates
]);
}
View Form:
<?= $form->field($dates, '[contractDate]year')->textInput() ?>
<?= $form->field($dates, '[contractDate]month')->textInput() ?>
<?= $form->field($dates, '[contractDate]day')->textInput() ?>
<?= $form->field($dates, '[contractExpirationDate]year')->textInput() ?>
<?= $form->field($dates, '[contractExpirationDate]month')->textInput() ?>
<?= $form->field($dates, '[contractExpirationDate]day')->textInput() ?>
To complement b24 answer.
// In View Form add foreach:
<?php foreach ($dates as $index => $date): ?>
<?= $form->field($date, '[contractDate]year')->textInput() ?>
<?= $form->field($date, '[contractDate]month')->textInput() ?>
<?= $form->field($date, '[contractDate]day')->textInput() ?>
<?= $form->field($date, '[contractExpirationDate]year')->textInput() ?>
<?= $form->field($date, '[contractExpirationDate]month')->textInput() ?>
<?= $form->field($date, '[contractExpirationDate]day')->textInput() ?>
<?php endforeach; ?>
// - or - add index
<?= $form->field($dates['contractDate'], '[contractDate]year')->textInput() ?>
<?= $form->field($dates['contractDate'], '[contractDate]month')->textInput() ?>
<?= $form->field($dates['contractDate'], '[contractDate]day')->textInput() ?>
<?= $form->field($dates['contractExpirationDate'], '[contractExpirationDate]year')->textInput() ?>
<?= $form->field($dates['contractExpirationDate'], '[contractExpirationDate]month')->textInput() ?>
<?= $form->field($dates['contractExpirationDate'], '[contractExpirationDate]day')->textInput() ?>
This can be is solution for this problem :
http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184#entry248184

Categories