Ok I am trying to use the Kartik Depdrop widget, all I am getting a white drop-down list that is values not showing in the dependent drop-down list.
I have a state model and a city model and I have it setup like this.
In _form.php
$catList=ArrayHelper::map(app\models\State::find()->all(), 'id', 'state_name' );
echo $form->field($model, 'state')->dropDownList($catList, ['id'=>'state_name']);
echo $form->field($model, 'district_city')->widget(DepDrop::classname(), [
'options'=>['id'=>'district_city'],
'pluginOptions'=>[
'depends'=>['state_name'], // the id for cat attribute
'placeholder'=>'Select...',
'url'=> \yii\helpers\Url::to(['patient-entry/subcat'])
]
]);
?>
Then in model
public static function getCity($city_id) {
$data=\app\models\City::find()
->where(['state_name'=>$city_id])
->select(['id','city_name'])->asArray()->all();
return $data;
}
Then in my controller
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = \app\models\PatientEntry::getCity($cat_id);
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
When I select the state field, the firebug console shows the data correctly like:
{"output":[{"id":"172","city_name":"Along"},{"id":"173","city_name":"Bomdila"},{"id":"174","city_name":"Itanagar"},{"id":"175","city_name":"Naharlagun"},{"id":"176","city_name":"Pasighat"}],"selected":""}
The city field drop-down is also shows as if it has been filled up with data, but only with white-spaces.
What I am doing wrong here?
Thanks.
Ok I found the solution, All the code is ok, actually the depdrop widget looks for the pair id and name like:
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
Accordingly I have changed the code in the model
->select(['id','city_name'])->asArray()->all();
with
->select(['id','city_name AS name'])->asArray()->all();
That's all and it is working fine now. Hope someone will find this useful.
Instead of changing the Select statement you could also:
echo $form->field($model, 'district_city')->widget(DepDrop::classname(), [
'options'=>['id'=>'district_city'],
'pluginOptions'=>[
//// change default 'nameParam'=>'name' to
'nameParam'=>'city_name',
'depends'=>['state_name'], // the id for cat attribute
'placeholder'=>'Select...',
'url'=> \yii\helpers\Url::to(['patient-entry/subcat'])
]
]);
?>
change the 'nameParam' to 'city_name'
Related
Model - Promo:
...
protected $table = 'promo';
...
public function locations()
{
return $this->belongsToMany(Cities::class, 'cities_promo');
}
Controller in laravel-admin
...
protected function form()
{
$location = Cities::pluck('name', 'id');
$form = new Form(new Promo);
$form->text('title', __('Title'));
$form->textarea('desc', __('Description'));
$form->multipleSelect('locations')->options($location);
return $form;
}
...
The bottom line is that it does not display the values that were previously selected and saved. An empty field is displayed there, where you can select values from the City model.
An intermediate solution was to use the attribute.
It is necessary that the format for multipleSelect (and others) was in array format [1,2,3 ... ,7].
In normal communication, an array of the form is transmitted:
{
['id' => 1,
'name' => 'Moscow',
...
],
['id' => 2,
'name' => 'Ekb',
...
],
}
Therefore, for formalization, I used a third-party attribute "Cities" to the model "Promo".
...
//Add extra attribute
//These attributes will be written to the database, if you do not want
//this, then do not advertise!
//protected $attributes = ['cities'];
//Make it available in the json response
protected $appends = ['cities'];
public function getCitiesAttribute()
{
return $this->locations->pluck('id');
}
public function setCitiesAttribute($value)
{
$this->locations()->sync($value);
}
If there are other suggestions, I am ready to listen.
Thank.
change $location to
$location = Cities::All()->pluck('name', 'id');
you can return $location to know it has value or not
also you can set options manually
$form->multipleSelect('locations')->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);
to know it works
I have a function in my controller file that get the persons who lives in a city.
My controller file:
public function actionGetPersons($id_city)
{
$model = Persons::find()->where(['id_city' => $id_city])->all();
return $this->render('persons-city', [
'model' => $model,
]);
}
Then I have my model file that have to show a form with text inputs: one text input per persons and its attribute name have to be the name of the person.
My view file:
<?
foreach ($model as $person) {
$form->field($person, $person->person_name)->textInput();
}
?>
But the browser shows this error:
Unknown Property – yii\base\UnknownPropertyException Getting unknown
property: app\models\Persons::John
Try to change your view to be like this:
<?php
foreach ($model as $key=>$person) {
echo $form->field($person, "[{$key}]person_name")->textInput(['value' => $person->person_name]);
}
?>
second param for field() method should be field name, not current field value
in your example:
<?
foreach ($model as $person) {
$form->field($person, 'person_name')->textInput();
}
?>
docs: https://www.yiiframework.com/doc/guide/2.0/en/input-forms
I set up editable column for the GridView in Yii2 with Kartik Editable extension. The problem I am facing is that I cannot find a way to update multiple table cell from one editable column.
The things I did:
GridView column
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'post_title',
'editableOptions'=> function ($model, $key, $index) {
return [
'inputType' => \kartik\editable\Editable::INPUT_TEXT,
'size'=>'sm',
'afterInput'=>function ($form, $widget) use ($model, $index) {
return $form->field($model, 'post_description')->textInput(['placeholder'=>'Enter post title']);
}
];
}
],
By clicking edit post title column it shows edit fields for title and description
PostsController action
public function actionIndex()
{
$searchModel = new PostsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (Yii::$app->request->post('hasEditable')) {
$postId = Yii::$app->request->post('editableKey');
$model = Posts::findOne($postId);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['Posts']);
$post['Posts'] = $posted;
if ($model->load($post)) {
$output = '';
$out = Json::encode(['output'=>$output, 'message'=>'']);
$model->save();
}
echo $out;
return;
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
So, when I edit post title and description only post title is saved into database.
I think it is because current saves only one value
$posted = current($_POST['Posts']);
What is the proper way to save both
$model->post_title and $model->post_description ?
This is an Ajax editable column. At a time only one value would be sent to the controller.
So the class of post_title and post_description column must be editable in the view.
This should work everytime you edit those columns.
Also change this
if ($model->load($post)) {
if (isset($model->post_title)){
// here you can format the value of the attribute
and display on the screen
$output = $model->post_title;
}
if (isset($model->post_description)){
$output = $model->post_description;
}
$model->save();
// Here you send a message that the value has been saved
$out = Json::encode(['output'=>$output, 'message'=>'Saved']);
}
I have one temporary model as viewModel. In my CRUD actions (for example actionCreate) I want to get this viewModel data and assign that to a ActiveRecord model. I used below code but my model object atrribute always show NULL value for attributes:
$model = new _Users();
if ($model->load(Yii::$app->request->post())) {
Yii::info($model->attributes,'test'); // NULL
$attributesValue =[
'title' => $_POST['_Users']['title'],
'type' => $_POST['_Users']['type'],
];
$model->attributes = $attributesValue;
Yii::info($model->attributes,'test'); // NULL
$dbModel = new Users();
$dbModel->title = $model->title;
$dbModel->type = $model->type . ' CYC'; // CYC is static type code
Yii::info($dbModel->attributes,'test'); // NULL
if ($dbModel->save()) {
return $this->redirect(['view', 'id' => $dbModel->id]); // Page redirect to blank page
}
}
else {
return $this->render('create', [
'model' => $model,
]);
}
I think $model->load(Yii::$app->request->post()) not working and object attribute being NULL. Is it Yii2 bug or my code is incorrect??
If there is no rule for your attribute the $model->load() will ignore those not in the rules of the model.
Add your attributes to the rules function
public function rules()
{
return [
...
[['attribute_name'], 'type'],
...
];
}
To fetch data for an individually attributes(db-fields) in yii2.0 then you should just do as:
echo $yourModel->getAttribute('email');
ActiveRecord $attributes is a private property
Use $model->getAttribute(string)
You can use following codes:
$model = new _Users();
$model->attributes=Yii::$app->request->post('_Users');
$model->title= $model->title
$model->type = $model->type . ' CYC'; // CYC is static type code
#$model->sampleAttribute='Hello World';
Declare attribute as private then
echo $yourModel->attribute
work as expected
You must remove all public properties (title, type, etc.) in your _User model and $model->attributes = $post will work correctly.
I have also encountered the same problem, i Add my attributes to the rules function,but also error. And i found the reason for this problem. It is beause that the submit form's name in corresponding view file is not the same as the model's name which you use in controller
[controller file]:
$model=new SearchForm();
[view file]:
<input name="SearchForm[attribus]" ...
or
[view file]:
<?= $form->field($model,'atrribus')->textInput()?>
I have an issue with the CJuiAutoComplete in Yii and using it with a model. I've been able to run a query within the function and pass that back, but not with using a model. It just returns no results. Can anyone see where the issue is?
This is the code in the controller:
public function actionAutocompleteTest() {
$arr = array();
foreach($models as $model) {
$arr[] = array(
'label'=>$model->pID, // label for dropdown list
'value'=>$model->pID, // value for input field
'id'=>$model->pName, // return value from autocomplete
);
}
echo CJSON::encode($arr);
Yii::app()->end();
}
This is the code on the page:
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'model'=>'Players',
'attribute'=>array('pID', 'pName'),
'name'=>'test',
'source'=>$this->createUrl('jui/autocompleteTest'),
// additional javascript options for the autocomplete plugin
'options'=>array(
'showAnim'=>'fold',
'select'=>'alert("hello"); return true;'
),
));
?>
actionAutocompleteTest will get the data sent by CJuiAtoComplete via post. So, you have to use the data to filter the results from the post, run the query and return the results.