yii2 foreign key dropdown - php

I am trying to display a dropdown with a category list in yii2 framework.
The tables in my database are setup with foreign key and used Model and Crud generator to generate the code.
I am trying to edit the code now to change the textfield into a dropdown with the values from the category table.
<?php $categoryArray = ArrayHelper::map(\app\models\Category::find()->orderBy('name')->all(), 'id', 'name') ?>
<?= $form->field($model, 'category_id')->dropDownList($categoryArray, ['prompt' => '---- Select category ----'])->label('category') ?>
This comes back with the error "2.yii\base\ErrorHandler::handleFatalError()"
Most related post to my problem refer to version 1 of the framework but can't find a good example how to do this with version 2.

use yii\helpers\ArrayHelper;
use backend\models\Model_name;
<?= $form->field($model, 'Field_id')->dropDownList(
ArrayHelper::map(<Model_name>::find()->all(),'Field_id','Field_name'),
['prompt'=>'Select XYZ']
)?>

I overlooked the error on top saying 'Class ArrayHelper not Found' this has been resolved by adding the following line on top:
use yii\helpers\ArrayHelper;

Add ->asArray() to your find query:
$categoryArray = ArrayHelper::map(\app\models\Category::find()->orderBy('name')->asArray()->all(), 'id', 'name');

Related

Yii2 Pjax Pagination On multiple Gridview not working

Have One Page 2 Gridview Table . Pagination Does not work properly ,
Here is the Code :
// table 1
<?php Pjax::begin(['id'=>'table_1']); ?>
<?= GridView::widget([
//
]); ?>
<?php Pjax::end(); ?>
// Table 2
<?php Pjax::begin(['id'=>'table_2']); ?>
<?= GridView::widget([
//
]); ?>
<?php Pjax::end(); ?>
It is already explained in the guide and here I quote.
You can use more than one GridView on a single page but some additional configuration is needed so that they do not interfere with each other. When using multiple instances of GridView you have to configure different parameter names for the generated sort and pagination links so that each GridView has its own individual sorting and pagination. You do so by setting the sortParam and pageParam of the dataProvider's sort and pagination instances.
In your case:
use yii\grid\GridView;
$tbl1Provider->pagination->pageParam = 'tbl1_page';
$tbl2Provider->pagination->pageParam = 'tbl2_page';
echo GridView::widget([
'dataProvider' => $tbl1Provider,
]);
echo GridView::widget([
'dataProvider' => $tbl2Provider,
]);

How do I get a list of key, value pairs from the database for a select list in Yii?

How do I get a list of key/value pairs to populate the options to a relation in a select list in Yii?
Similar to the following in Rails:
= f.select :age_group_id, AgeGroup.order(:name).pluck(:name, :id)
Get the list of values, perhaps in the controller
$campaigns = Campaign::find()->select('name')->indexBy('id')->column();
Display the list
<?= $form->field($model, 'campaign_id')->dropDownList($campaigns) ?>
Could be useful somethings like his
<?= $form->field($model, 'your_field')->listBox( ArrayHelper::map(Country::find()->all(), 'country_id', 'Country_description'),['prompt'=>'']) ?>
or for dropdown
<?= $form->field($model, 'your_field')->dropDownList( ArrayHelper::map(Country::find()->all(), 'country_id', 'Country_description'),['prompt'=>'']) ?>
change country_id, your_field and country_description for your need

Basic Hidden field in yii

I'm trying to place data in hidden text in yii, but I don't know how.
I need a similar code to a regular php syntax:
<input type="hidden" name="field_name" value="a"/>
It's supposed to be a field with static value of a. I just need it to go with my $_POST variables for error checking.
Is it possible to avoid modifying the models and controllers just to put the field in?I cant use gii cause I only have snippets of code with me.Sorry as well as I have little understanding of yii so I have no clue if what I'm saying about the last 2 sentences is correct.
in views
hidden field with model and form:
<?php echo $form->hiddenField($model, 'name'); ?>
or without model
<?php echo CHtml::hiddenField('name' , 'value', array('id' => 'hiddenInput')); ?>
Yii hidden input :
<?php echo $form->hiddenField($model,'fieldName',array('value'=>'foo bar')); ?>
In Yii2 this has changed too:
<?= Html::activeHiddenInput($model, 'name') ;?>
References:
http://www.yiiframework.com/forum/index.php/topic/49225-activeform-how-do-you-call-label-input-and-errors-individually/
https://github.com/yiisoft/yii2/issues/735
if data from database and value or size field:
echo $form->hiddenField($experience,'job_title',array('size'=>'50','value'=>$experience_data['job_title'])); ?>
Yii 1
<?php echo $form->hiddenField($model, 'name'); ?>
Yii2
<?= Html::activeHiddenInput($model, 'attribute', ['value' => 'Some Value']) ?>
Also, worth noting for Yii2, the array parameter works different to a normal form field.
E.G. A normal input would look more like this.
<?= $form->field($model, 'attribute', ['inputOptions' => ['placeholder' => 'Some Placeholder', 'value' => 'Some Input Value']]) ?>
Hope this helps.
for yii2 you can try this
<?= $form->field($model, 'user_type',['inputOptions' => ['value' => '2']])->hiddenInput()->label(false) ?>
It worked for me
Alternatively,
echo CHtml::activeHiddenField($model,"[$i]id", array("value" => $model->id));
This would set hidden field value as the id from model. The [$i] is useful for multiple record update.
Here are two ways to do that...
without model
echo CHtml::hiddenField('name' , 'value', array('id' => 'name'));
with model
echo $form->hiddenField($model, 'name');

Creating dropdown list from related table yii

I have two tables: product and product_type (related to the models resp. Product and Product_type):
product : product_id, product_type_id, name, etc...
product_type : product_type_id, name, desc, etc...
Both are related with key "product_type_id".
I have created the crud for both tables using gii crud generator. Now on Product form page I want to display the listing of all product_type name in dropdown field using Yii ActiveRecord. I have added this line in views/product/_form.php script:
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'id', 'id');
echo $form->dropDownList($model, 'product_type_id', $list);
?>
But it's showing blank dropdown field :(
How can I do this?
Solved MySelf :)
By just providing product_type_name.
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'product_type_id', 'product_type_name');
echo $form->dropDownList($model, 'product_type_id', $list);
?>
In Yii2 the class CHtml does not exist anymore.
Below is a solution, based on the following assumptions:
The Yii2 framework is used;
The table product_type is associated with the model Product_type;
The product_type table has a field called "type-name".
<?php
// get all product types from the corresponding table:
$productTypes = Product_type::find()->orderBy('type-name')->asArray()->all();
// create an array of pairs ('id', 'type-name'):
$productTypeList = ArrayHelper::map($productTypes, 'id', 'type-name');
// finally create the drop-down list:
$form->field($model, 'product_type_id')->dropDownList($productTypeList)
?>
Change your code like bellow
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'table_col_name1', 'table_col_name2'); //table_col_name1 is value of option, table_col_name2 is label of option
// echo $form->dropDownList($model, 'product_type_id', $list);
echo CHtml::dropDownList('name_of_the_dropdown', $model, $list);
?>

Need help to create CRUD screen with dropdown (relation) using yii-framework

I need to create CRUD screen using yii-framework. Simple CRUD screen using one table is working perfectly fine. I'm facing problem/issue while using dropdown (linking table).
I have installed giix extension which is suppose to create CRUD with dropdown if FK is specified but I dnt have MySql Engine InnoDB on my hosting provider, so I'm not able to use that extension. I need to do it manually.
I have two tables
main:-
id
store_id
prefix
store:-
id
name
Now store_id of main is FK to id of store table. And I want to create CRUD for main table.
So that Add Screen should show:-
Store Name:- Dropdown
prefix:- Textbox
View screen should use name column of store table instead of showing store_id
Thanks in anticipation.
Generate CRUD using Gii, then read my blog. http://jmmurphy.blogspot.com/2013/05/using-yii-model-relations.html
Basically you will have something like this for your store_id field after Gii Generation
<?php echo $form->labelEx($model,'store_id'); ?>
<?php echo $form->textField($model, 'store_id', array('size'=>60,'maxlength'=>255));?>
<?php echo $form->error($model,'store_id'); ?>
The textField line is replaced by:
<?php $list = CHtml::listData(Store::model()->findAll(), 'id', 'name'); ?>
<?php echo $form->dropDownList($model, 'store_id', $list, array('empty'=>'(Select a Store)')); ?>
You also need to define relations in your Main model so that you can access related tables (even if your database does not support foreign keys) like this:
public function relations()
{
return array(
'store'=>array(self::BELONGS_TO, 'Store', 'store_id'),
);
}
And to complete this relation, you should also add the following relation to your Store model:
public function relations()
{
return array(
'main'=>array(self::HAS_MANY, 'Main', 'store_id'),
);
}
These relations define a One to Many relation between Store and Main where store is the parent, and Main is the Child. To make it a One to One relationship change HAS_MANY to HAS_ONE. The HAS_* goes in the parent model and points to the foreign key attribute in the child table. The BELONGS_TO goes in the child and tells the attribute in the child table that points to the primary key in the parent.
Now to see the store name in the view action, you need to change 'store_id' in your view.php to an array that looks like:
array(
'name' => 'store_id',
'value' => $model->store->name,
)
The admin view is slightly different. I am not sure exactly why, but to view the store name instead of the id in the admin view you will need to use an array that looks like:
array(
'name' => 'store_id',
'value' => '$data->store->name',
)
Note that Gii generates this so that $data is the model instead of $model, and also it does a funky double indirection thing so that you need to put the variable declaration in single quotes.
Thanks jmarkmurphy for your help. You helped me lot and I have marked your answer as correct only as you gave me guidance. Just posting exact code in detail.
I changed view.php with below code:-
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'store.name',
'prefix',
),
));
Also changed admin.php with below code:-
<?php echo CHtml::encode($data->store->name); ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'main-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'store.name',
'prefix',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Thanks once again jmarkmurphy. Thanks a lot . My application is now working and exactly the way I wanted.

Categories