yii2: get relation data in kartik editable widget - yii2

I am using kartik yii2 editable extension to edit inline in gridview.
The extension is working fine.
Please refer this screen-shot link [http://awesomescreenshot.com/00753dvb73][1]
In this screen-shot the source field is a dropdown and I want the value of source instead id its id
My View
use kartik\editable\Editable;
[
'attribute'=>'source',
'format'=>'raw',
'value'=> function($data){
//$s = $data->getBacklog_source();//var_dump($s);exit;
return Editable::widget([
'name'=>'source',
'model'=>$data,
'value'=>$data->source,
'header' => 'Source',
'type'=>'primary',
'size'=> 'sm',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=>$data->getSource(), // any list of values
'options' => ['class'=>'form-control', 'prompt'=>'Select Source'],
'editableValueOptions'=>['class'=>'text-danger'],
'afterInput' => Html::hiddenInput('id',$data->id),
]);
}
],
The relation I made is:
public function getSource()
{
$source = BacklogSource::find()->all();
return ArrayHelper::map($source, 'id', 'Source');
}
public function getBacklog_complexity()
{
return $this->hasOne(BacklogComplexity::className(), [
'id' => 'complexity'
]);
}
Thanks for help in advance

I got the solution something like this:
[
'attribute'=>'status',
'format'=>'raw',
'value'=> function($data){
$s = BacklogStatus::findOne($data->status);
return Editable::widget([
'name'=>'status',
'model'=>$data,
'value'=>$s->Status,
'header' => 'Status',
'type'=>'primary',
'size'=> 'sm',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=>$data->getStatus(), // any list of values
'options' => ['class'=>'form-control', 'prompt'=>'Select Source'],
'editableValueOptions'=>['class'=>'text-danger'],
'afterInput' => Html::hiddenInput('id',$data->id),
]);
}
],

Related

Listview pagination and GET parameters on the next page

I have this UrlManager rule:
'<pageSlug>-pa<pageId:\d+>' => 'page/page',
Then I have page with url like this domain.com/blog-pa54
In this example I have
pageSlug = blog and pageId = 54
In my view I have ListView with my blog posts.
I set my dataprovider like this:
$dataProvider = new ActiveDataProvider([
'query' => BlogPost::find()
->where([
'active' => 1
]),
'pagination' => [
'defaultPageSize' => 3,
//'params' => [], when I set this, it only shows get param "page"
'pageParam' => 'page',
'route' => $pageURL, // this variable is equal to "blog-pa54"
],
]);
My route is current url slug - blog-pa54
When I go to next page I recieve this url: blog-pa54?pageSlug=blog&pageId=54&page=2
How can I remove $_GET params pageSlug and pageId from url?
I try to set pagination > params = [] and it remove this get param, but when I go to other page it doesn't change items in my ListView
Here is also my ListView and LinkPager
<div class="blog-post-wrapper">
<?= ListView::widget([
'dataProvider' => $blogPostsDataprovider,
'itemOptions' => ['tag' => null],
'options' => [
'tag' => false,
],
'layout' => "{summary}<div class='row'>{items}</div>",
'itemView' => function ($model, $key, $index, $widget) use ($page) {
return $this->render('//blog-post/_blogPostList', [
'page' => $page,
'model' => $model
]);
},
]); ?>
</div>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $blogPostsDataprovider->pagination,
'linkContainerOptions' => [
'class' => 'page-item',
],
'linkOptions' => [
'class' => 'page-link',
],
]); ?>
Okay, I figured it out.
params attribute must not be empty.
You can set it like this:
'params' => [
'page' => isset($_GET['page']) ? $_GET['page'] : 1,
]
Or if you have another get params like get filters:
$getParams = [];
if(isset($_GET)){
foreach($_GET as $getKey => $getValue){
if(in_array($getKey, ['pageSlug', 'pageId'])){ //here I skip my params from UrlManager rule
continue;
}
$getParams[$getKey] = $getValue;
}
}
.....
'params' => $getParams

Yii2 - Dropdownlist to load other attributes

I have this Model Class
public function attributeLabels()
{
return [
'id' => Yii::t('course', 'ID'),
'course_code' => Yii::t('course', 'Course Code'),
'course_type' => Yii::t('course', 'Course Type'),
'course_title' => Yii::t('course', 'Course Title'),
'course_unit' => Yii::t('course', 'Course Unit'),
];
}
On Dropdownlist change, I want to load and display course_code, course_type, course_title, and course_unit. But should only save course_title. The other should only be displayed and not save, except course_title.
Am ableto display only course_title. This is my view for the dropdown list.
<?= $form->field($modelDetail, "course_id")->widget(Select2::classname(), [
'data' => ArrayHelper::map(app\modules\course\models\CourseMaster::find()->where(['is_status'=>0])->all(),'id','course_title'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Course ---',
],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
This is what I have done.
But I want to achieve this.
How do I display other attributes as textInput() or label without saving in database. Thanks
Controller
public function actionCreate()
{
$modelDetail = new CourseMaster();
if (Yii::$app->request->isAjax && $modelDetail->load(Yii::$app->request->post())) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($modelDetail);
}
if ($modelDetail->load(Yii::$app->request->post())) {
$modelDetail->attributes = $_POST['CourseMaster'];
if($modelDetail->save())
return $this->redirect(['index']);
else
return $this->render('create', ['modelDetail' => $modelDetail,]);
} else {
return $this->render('create', [
'modelDetail' => $modelDetail,
]);
}
}
If you want to only display other fields without sending it on form submit, you can mark field as disabled:
<?= $form->field($modelDetail, 'course_code')->textInput([
'disabled' => true,
]) ?>
This will render input which cannot be edited directly and it will not be sent on form submit.
Well You can concat the data in the label of dropdown itself, will be an easier option. Use closure on the third argument in ArrayHelper::map($array, $from, $to, $group = null) as follows.
ArrayHelper::map(
app\modules\course\models\CourseMaster::find()->where(['is_status'=>0])->all(),
'id',
function($model){
return $model['course_title']." - ".$model['course_code'];
}
)

kartik DynaGrid select2 filter not render

my setup column using kartik DynaGrid Widget to display data on yii2. but filter (FILTER_SELECT2) not render on my table. Can someone help me? Please.
'class' => 'kartik\grid\DataColumn',
'attribute' => 'city_id',
'label' => 'City',
'hAlign' => 'center',
'vAlign' => 'middle',
'width' => '70px',
'filterType' => GridView::FILTER_SELECT2,
'filter' => [
1 => 'filter 1',
2 => 'filter 2',
],
'format' => 'html',
'value' => function($data){
$cities = \app\models\City::getData();
if(isset($cities[$data->city_id])){
return $cities[$data->city_id];
}
return $data->city_id;
}
Post your grid config. Maybe you turn off filter in config. Default config is this
....
'gridOptions'=>[
'dataProvider'=>$dataProvider,
'filterModel'=>$searchModel,
....
],

Yii2: Kartik's DetailView and Select2 loading id's not text

So I'm loading Kartik's Select2 widget in Kartik's DetailView using multiple input:
[
'attribute' => 'characters',
'format' => 'raw',
'type' => DetailView::INPUT_SELECT2,
'value' => function($form, $widget) {
<my_stuff_in_VIEW_mode>
},
'widgetOptions' => [
'options' => ['multiple' => true, 'placeholder' => Yii::t('app', 'Select...')],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'maximumInputLength' => 20,
'language' => Yii::$app->language,
'ajax' => [
'url' => \yii\helpers\Url::to(['myAjaxServer']),
'dataType' => 'json',
'delay' => 250,
'data' => new JsExpression('function(params) { return {q:params.term, p:params.page}; }'),
'cache' => true,
],
'escapeMarkup' => new JsExpression("function (markup) { return markup; }"),
'templateResult' => new JsExpression("function (characters) { return '<b>' + characters.text + '</b>'; }"),
'templateSelection' => new JsExpression("function (characters) { return characters.text; }"),
],
],
],
When it comes to Kartik's DetailView, VIEW mode correctly shows my list of characters given by value, but when entering EDIT mode I got this:
which obviously is not what I expected: I want my characters' names rather than their IDs. However if I select new characters from this very same input dropdown, new tags are added which properly show the new names (thus this issue happens when updating data). After I confirm the new data and then try to update, new characters are shown with their IDs again.
JSON data is as follows:
{"results":[{"id":"8","text":"Character8"},{"id":"5","text":"Character5"}],"pagination":{"more":true}}
Any ideas?
UPDATED WITH SOLUTION BY KARTIK BELOW:
Add initValueText as an array of desired attribute values:
'initValueText' => ArrayHelper::getColumn($model->characters, 'name'),
You need to set Select2::initValueText when using Select2 with ajax to show the displayed name instead of id. For multiple select this needs to be setup as an array.

How to connect 3 tables in yii2 and display in Gridview then make sorting work correctly

I have used the gii tool to create crud application. I have 3 tables the tbl_targetcities, lib_cities, and lib_provinces. I was able to connect lib_cities to tbl_targetciteis but not the lib_provinces. And also the sorting of city / Municipality does not work. It seems that it sorts according ti the ID.
tbl_target_cities
lib_cities
lib_provinces
sample View
So far here is my relation in the model.
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
}
in my view file...
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'city_code',
'value'=>'cityName.city_name'
],
[
'attribute'=>'prov code',
'value'=>'cityName.city_name'
],
'kc_classification',
'cluster',
'grouping',
'priority',
'launch_year',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How to display the prov_name from lib_provinces???
EDIT to answer user2839376 question in the comment box
IN THE SEARCH MODEL CLASS
$query = TblSpBub::find();
$query->joinWith('brgyCode')->joinWith(['cityCode'])->joinWith(['cityCode.provCode']);
$covered= LibAreas::find()->where(['user_id'=>yii::$app->user->identity->id])->all();
$query->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
]);
$dataProvider->sort->attributes['city'] = [
'asc' => ['lib_Cities.city_name' => SORT_ASC],
'desc' => ['lib_Cities.city_name' => SORT_DESC],
];
$dataProvider->sort->attributes['province'] = [
'asc' => ['lib_provinces.prov_name' => SORT_ASC],
'desc' => ['lib_provinces.prov_name' => SORT_DESC],
];
In LibCities model add new relation:
public function getProvince()
{
return $this->hasOne(LibProvince::className(),['prov_code'=>'prov_code']);
}
And change getCityName relation. You should add with() for relation:
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
}
And in view correct your columnto this:
[
'attribute'=>'prov code',
'value'=>'cityName.province.prov_name'
],
You have to use the function relations() in models.
In tbl_target_cities model:
public function relations()
{
return array(
'city' => array(self::HAS_ONE, 'LibCities', 'city_code'),
);
}
In LibCities model :
public function relations()
{
return array(
'province' => array(self::HAS_ONE, 'LibProvinces', 'prov_code'),
'targets' => array(self::HAS_MANY, 'TargetCity', 'city_code',
);
}
This will allowed you to jump throw the LibCities model,
now you can simply acces to prov name like this :
$model->city->province->prov name;
Note : You need to have the 3 models defined.
EDIT
array(
'name' => 'province name',
'value' => $data->city->province->prov_name;
),
Done it, Heres how.
in addition to the above code (original post)
// in Model I added an additional function
public function getTaskowner()
{
return $this->hasOne(Tasks::className(), ['id' => 'task_id'])
->with(
['location','taskowner']
);
}
and in view i did this
....
'columns' => [
....
[
'class' => 'kartik\grid\DataColumn',
'value'=> 'tasks.location.taskowner.name',
.....
],
.....
and it worked
key points. used an array with the 'with->(..)' to include both then in the view added 'tasks.location.taskowner.name', to join them all