I've tried for created form update using modal in yii2. The problem is every I change one field with the other value, the result form update with modal closed and redirect to index. And message update can't display in index. I don't know why, maybe wrong in code controller.
Code actionUpdate in controller
public function actionUpdate($id)
{
$model = CalonKeluargaAsuh::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', 'Data berhasil diubah!');
return $this->redirect(['index']);
return $this->refresh();
} else {
if (Yii::$app->request->isAjax) {
return $this->renderAjax('update', ['model' => $model]);
}
else{
return $this->render('update', ['model' => $model]);
}
}
}
Code form in view
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
?>
<h2 align="center">Ubah Data Calon Keluarga Asuh</h2>
<?php
echo " ";
echo " ";
?>
<?php $form = ActiveForm::begin(['layout' => 'horizontal', 'enableAjaxValidation' => true,
'id' => 'update-form',
]); ?>
<?= $form->field($model, 'kode_calon_keluarga_asuh')->textInput(['readOnly' => true, 'style' => 'width:350px' ]) ?>
<?= $form->field($model, 'nama')->textInput(['style' => 'width:350px']) ?>
<?= $form->field($model, 'jenis_kelamin')->dropDownList(['Laki-laki' => 'Laki-laki', 'Perempuan' => 'Perempuan'],
['prompt'=>'--Pilih--', 'style' => 'width:350px']) ?>
<?= $form->field($model, 'pekerjaan')->textInput(['style' => 'width:350px']) ?>
<?= $form->field($model, 'alamat')->textArea(['rows' => 3, 'style' => 'width:350px']) ?>
<?= $form->field($model, 'telepon')->textInput(['style' => 'width:350px']) ?>
<div class="form-group">
<div class="col-sm-offset-4">
<?= Html::submitButton('Ubah', ['class' => 'btn btn-primary']) ?>
<?php
echo " ";
echo " ";
echo Html::a('Keluar', ['index'],[
'class'=>'btn btn-success',
'onclick' =>'$("#calonModal").modal("hide");
return false;'
]);
?>
<?php ActiveForm::end();?>
Code index.php in view
<?php \yii\widgets\Pjax::begin(['timeout' => false, 'id' => 'pjax-gridview']); ?>
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $searchModel app\models\SearchDonatur */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Data Calon Keluarga Asuh';
?>
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Informasi!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('delete')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Informasi!</h4>
<?= Yii::$app->session->getFlash('delete') ?>
</div>
<?php endif; ?>
<div class="calon-keluarga-asuh-index">
<?php Pjax::begin(['timeout'=>false,'id'=>'pjax-gridview']); ?>
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Tambah Data', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'emptyCell' => '-',
'summary' => '',
'columns' => [
[
'attribute' => 'kode_calon_keluarga_asuh',
'value' => 'kode_calon_keluarga_asuh',
'contentOptions' => ['style' => 'width: 100px;']
],
[
'attribute' => 'nama',
'value' => 'nama',
'contentOptions' => ['style' => 'width: 250px;']
],
[
'attribute' => 'jenis_kelamin',
'value' => 'jenis_kelamin',
'contentOptions' => ['style' => 'width: 100px;']
],
[
'attribute' => 'pekerjaan',
'value' => 'pekerjaan',
'contentOptions' => ['style' => 'width: 200px;']
],
[
'attribute' => 'alamat',
'value' => 'alamat',
'contentOptions' => ['style' => 'width: 210px;']
],
[
'attribute' => 'telepon',
'value' => 'telepon',
'contentOptions' => ['style' => 'width: 100px;']
],
[
'class' => \yii\grid\ActionColumn::className(),
'header' => 'Aksi',
'template' => '{update} {delete}',
'buttons' => [
'update' => function($url, $model) {
$icon = '<span class="glyphicon glyphicon-pencil"></span>';
return Html::a($icon, $url,[
'data-toggle' => "modal",
'data-target' => "#calonModal",
]);
},
'delete' => function($url, $model) {
$icon = '<span class="glyphicon glyphicon-trash"></span>';
return Html::a($icon, $url,
[
'data-confirm' => "Apakah yakin dihapus ?",
'data-method' => 'post',
]);
},
]
],
],
]); ?>
<?php \yii\widgets\Pjax::end() ?>
<?php Pjax::end(); ?>
</div>
<?php
Modal::begin(['id' => 'calonModal']);
Pjax::begin(['id'=>'pjax-modal', 'timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,]);
Pjax::end();
Modal::end();
?>
<?php
$this->registerJs('
$("#calonModal").on("shown.bs.modal", function (event) {
var button = $(event.relatedTarget)
var href = button.attr("href")
$.pjax.reload("#pjax-modal", {
"timeout":false,
"url":href,
"replace":false,
});
})
');
?>
Related
I am trying to use Yii2's conditional validator within DynamicModel clas, but the validator when is not working:
Controller
private function createFormModel(){
$model = new DynamicModel([
'indicador',
'departamento',
'mes'
]);
$model->addRule(['indicador'],'required',['message' => 'Este campo es obligatorio']);
$model->addRule(['departamento'], 'required', ['when' => function ($model) {
return $model->indicador == 'Semana';
}]);
return $model;
}
public function actionCuatrimestre()
{
$model = $this->createFormModel();
return $this->render('cuatrimestre',[
'model' => $model,
]);
}
Whether I select or not the "indicador" field which is a select field, the "departamento" field alwasys returns as required. I have algo try this way but with no results:
$model->addRule(['departamento'], 'required', ['when' => function ($model) {
return $model->indicador == 'Semana';
}], ['whenClient' => "function (attribute, value) {
return $('#indicador').val() == 'Semana';
}"]);
What I am missing here?
EDIT
My view code cuatrimestre.php
<?php $form = ActiveForm::begin(); ?>
<div class="form-group">
<?= $form->field($model, 'indicador')->widget(Select2::class, [
'options' => ['id'=>'indicador'],
'data' => ['Semana','Día','Resumen'],
]); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'departamento')->widget(Select2::class, [
'options' => ['id'=>'departamento'],
'data' => Departamentos::getDepartamentosByUser(),
]); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'curso')->widget(DepDrop::class, [
'type' => DepDrop::TYPE_SELECT2,
'options' => ['id' => 'curso-id'],
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['departamento-id'],
'placeholder'=>'Seleccionar curso',
'url' => Url::to(['/campus-actividad/subcursos']),
'loadingText' => 'Cargando ...',
'initialize' => true,
]
]);?>
</div>
<div>
<?= Html::submitButton('Aplicar filtros', ['class' => 'btn btn-block btn-default']) ?>
<?php ActiveForm::end(); ?>
</div>
The model is Booking.php. I need to get data from another model called ServiceCategory.php and add a filter to it in Gridview on my index.php. I created filter on view/index.php as below.
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(app\models\Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
This is my index.php
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\models\Servicecategory;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BookingSerach */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bookings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="list-booking">
<h1 class=""><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p class="form-inline text-right">
<label>Client:</label>
<?= Html::dropDownList('client', null, ArrayHelper::map($clients, 'id', 'fullname'), ['prompt' => 'Please Select', 'class' => 'form-control']) ?>
<?= Html::a('+ New Booking', ['booking/create/'], ['class' => 'btn btn-primary client-create']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'value' => 'user.client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
//'numberOfDays',
//'date',
//'followUpEmail:email',
// 'followUpEmailSent:ckeckbox',
//'Status',
['attribute' => 'status', 'value' => 'Status', 'filter' => array_filter(\app\models\Booking::$statuses)],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp(this, "' . $url . '")', 'checked' => false, 'id' => 'followup'];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:15%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
},
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
},
],
],
],
]);
?>
</div>
<?php
$script = <<< JS
$('.client-create').on('click', function () {
select = $(this).prev();
if(select.val()){
location.href = $(this).attr('href')+"/"+select.val();
} else {
$(this).parent().addClass('has-error');
}
return false;
});
JS;
$this->registerJs($script);
$this->registerJs("
function followUp(e, url){
$('#modal').modal('show').find('#modalContent').load(url);
}", yii\web\View::POS_END);
?>
I can get the data to the column on gridview but the filter is not working. Can anyone help me with this?
I solved it myself. For your information I post it here. I changed the attribute as the model contains and added the value as category.name
['attribute' => 'categoryID', 'value' => 'category.name','filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
I want to use pagination in my view, but I can't figure out how to do it in conjunction with the find() method.
Getting the numbers of pages works correctly, but it always displays all values from the database. I want to see 15 comments per page.
Here is my ViewAction controller:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'pagination'=> $pagination
]);
}
And this is how I get the comments:
public static function findComment($id)
{
if (($model = UrUser::findOne($id)) !== null) {
$Id=$model->Id;
$comment = UrComment::find()->where(['Rel_User' => $Id])->all();
return $comment;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
I tried to use this:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
$comment= UrComment::findComment($id);
$comment->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' =>$comment,
'pagination'=> $pagination
]);
}
But I get this error:
Call to a member function offset() on array
Then I display it in the view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php foreach ($comment as $comm): ?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comm->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comm->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comm->Text ?></p>
<hr>
<?php endforeach; ?>
<?php
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]);
?>
</div>
</div>
</div>
How can I limit the UrComment::findComment($id) using the pagination?
EDIT:
I think I understand you, and I think I've done everything you told me in your answer, but now I have another problem. I need to display under view comments only that which is id view only this one person not all comments.
Here is what I have now:
ActionView:
public function actionView($id) {
$searchModel = new CommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
CommentSearch:
<?php
namespace backend\modules\users\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UrComment;
class CommentSearch extends UrComment
{
public function rules() {
return [
[['Id'], 'integer'],
[['Text'], 'safe'],
];
}
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params) {
$query = UrComment::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'Id' => $this->Id,
'Text' => $this->Text,
]);
$query->andFilterWhere(['like', 'Text', $this->Text]);
return $dataProvider;
}
}
View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'comments',
'viewParams' => ['comment' => $comment, 'model'=>$model],
]);
?>
</div>
</div>
</div>
And my item comments:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comment->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comment->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comment->Text ?></p>
<hr>
Using that code, now I have error that in this item in button edit:
$comment->Id], ['class' => 'btn btn-primary']) ?>
Trying to get property of non-object
And I can't use foreach there because I have duplicate comments. Should change something in comment Search or in my function findComment(id) inquiry?
There is my actual item 'comments' where I want to display text of comments and buttons to edit and delete comment. But this does not work for me. I have:
Use of undefined constant Id - assumed 'Id'
and
Use of undefined constant Text - assumed 'Text';
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= Text ?></p>
<hr>
If you use model and foreach in not easy, use pagination because pagination if base on dataProvider and not directly for model ..
Essentially finding the model like you did mean work direclty on the data while pagination don't work directly on the data but rather use the a sql query for retrive information from db a let these available to widgets .. this is what the dataProvider perform .. .. then I suggest you of use a widget like ListView and change your query based on a find with a dataProvider based on a modelSearch ..
public function actionView($id) {
$searchModel = new UrCommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
and for view.php
<?php
echo ' <h1>User : ' . $model->userName . '</h1>';
echo '<h2>Comments</h2'>,
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_comment',
]);
where _comment is a partial view of you comment layout .,.
then in _comment.php you can simply
<?=$model->id;?>
<?=$model->text;?>
I generated a model,controller and a view by Gii,And I enabled the actionColumn in index.php.
I have delete button to delete the records.The buttons are working good but,It doesn't shows me the Alert box to confirm my action.
I am attaching my code here.
Can anyone tell what I am missing?
Index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
$this->title = 'Cities';
$this->params['breadcrumbs'][] = '/ '.$this->title;
?>
<div class="cities-index">
<h2><?= Html::encode($this->title) ?>
<?php //echo $this->render('_search', ['model' => $searchModel]); ?>
<?= Html::a('Create Cities', ['create'], ['class' => 'btn btn-success','style'=>'float:right']) ?>
</h2>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
// 'country_id',
[
'attribute'=>'country_id',
'value'=>'country.country_name',
],
'city_name',
'city_tax',
[ 'class' => 'yii\grid\ActionColumn',
'header'=>'Action',
'template'=>'{view}{update}{delete}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="btn btn-xs btn-success icon-search bigger-120" style="margin-left:5px;"></span>', $url, [
'title' => Yii::t('app', 'View'),
]);
},
'update' => function ($url, $model) {
return Html::a('<span class="btn btn-xs btn-info icon-pencil blue bigger-120" style="margin-left: 5px;"></span>', $url, [
'title' => Yii::t('app', 'Update'),'<span class="glyphicon glyphicon-search"></span>'
]);
},
'delete' => function ($url, $model) {
return Html::a('<span class="btn btn-xs btn-danger icon-trash bigger-120" style="margin-left: 5px;" ></span>',
$url, [
'title' => Yii::t('app', 'Remove'),'<span class="glyphicon glyphicon-search"></span>',
'data-confirm' => 'Are You sure',
'data-method' => 'post'
]);
},
],
],
],
]); ?>
</div>
Recently I installed the multiSelect check box extension.
my _form.php looks like this:
<? = $ Form-> field ($ model_detail, 'product_id') ->
widget (MultiSelect :: className (),
['id' => "multiXX",
"options" => ['multiple' => "multiple"],
'data' => $ rows,
'attribute' => 'product_id',
'model' => $ models ,
"clientOptions" =>
[
"includeSelectAllOption" => true, 'numberDisplayed' => 2,
],
]);
How can I extract the data chosen by the user in actionCreate of anther model?
how can I get the options that the user selected?
(I tried the $_post[] and it didn't worked.)
this is the whole form:
div class="customer-order2-form">
<?php $form = ActiveForm::begin(['action' => ['create']]); ?>
<?= $form->field($model, 'customer_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'customer_phone')->widget(\yii\widgets\MaskedInput::className(),
[
'mask' => '999-9999999',
'clientOptions' => ['alias' => '972']
]) ?>
<?php /* $form->field($model, 'customer_phone')->textInput(['maxlength' => 255]) **/?>
<?= $form->field($model, 'order_date')->widget(
DatePicker::className(), [
'inline' => false,
// 'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-m-d'
]
]);?>
<?php $model_detail = new OrderDetails2(); /* -------- כאן הוספתי נתונים ממודל
$rows=ArrayHelper::map(ProductFamily::find()->all(), 'id', 'name'); //--- אין צורך בשאילתא, עכשיו גם מציג את מה שנבחר למעלה
?>
<?= $form->field($model_detail, 'product_id')->widget(
MultiSelect::className(), [
'id'=>"multiXX",
"options" => ['multiple'=>"multiple"], // for the actual multiselect
'name' =>'multicheck',
'data' =>$rows,
'attribute' => 'product_id', // if preselected
'model' => $models,
"clientOptions" =>
[
"includeSelectAllOption" => true,
'numberDisplayed' => 2,
],
]);
?>
<?php
echo $form->field($model, 'description')->textarea(['rows' => 6]);
echo /*$form->field($model, 'totalprice')->textInput();*/
$form->field($model, 'totalprice')->widget(MaskMoney::classname(), [
'pluginOptions' => [
'prefix' => '₪ ',
'allowNegative' => false
]
]);
echo $form->field($model, 'status_id')->dropDownList(ArrayHelper::map(Status::find()->select('*')->all(), 'id', 'name'));
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'יצירה' : 'עדכון', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
what i tried is saving to different table in DB with a default Array,
and it worked.
it looks like this:
public function actionCreate()
{
$model = new CustomerOrder2();
$model_details= new OrderDetails2();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
if (isset($_POST['product_id'])){
$model_details->attributes = $_POST['product_id'];
$model_details->attributes=array();
echo
$model_details->attributes;
}
echo $_POST['description'];
$values = Array('1'=>'1','2'=>'2');
$model_details->attributes = $_POST['product_id'];
$array=$model_details->attributes;
//$data=OrderDetails2::->request->post();
//$values= Array(Yii::$app->request->post()['multiXX']);
//$values=Array($model_details->attributes);
foreach($values as $value)
{
$command = Yii::$app->db->createCommand();
$command->insert('order_details',array('Order_id'=>$model->id,
'product_id'=> $value,
'quantityOrdered'=> '1',
));
$command->execute();
}
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}