I have two tables; applicant_rating (AR) and applicant_rating_score (ARS). I have made a dropdown menu using the values in applicant_rating:
<?= $form->field($model,'rating_id')->dropDownList(Applicant::getApplicantRatingNames(),['prompt' => 'Please select']);?>
This is the function being called in the model:
public function getApplicantRatingNames() {
$rate = ApplicantRating::find()->all();
$listData = ArrayHelper::map($rate, 'id', 'name');
return $listData;
}
AR.id = ARS.rating_id
The chosen value from the dropdown menu on submission goes into rating_id in ARS table.
IN THE DROPDOWN MENU I ONLY WANT TO DISPLAY VALUES THAT ARE NOT IN rating_id. So in dropdown menu if for example id 1 was chosen, i want to only display values which are not id 1; where id != rating_id
Any help would be appreciated.
The syntax of not statement in ActiveQuery is ['not', [columnName => value]]
So I suppose you should do this like this:
Model::find()->where(['not', ['id', $rating_id]])->all();
Related
So I'm creating an application for clients to fill in an order to calculate the price. The client has to fill in a form, the form will be posted to a table in MySQL. When the order is complete the client gets an overview of his order with the calculated price. I'm having trouble with storing a variable (from tblPanel_Prices) which is related with a variable in tblPaneltypes. So after filling in the form data from column tblPaneltypes and tblPanel_Prices should be stored together in another table. Both tables (types and prices) are related.
The client has to select a type of panel. These types are stored in the table (tblPaneltypes). Every panel has a certain price-categorie (field price_id) which is needed to calculate the price. The prices of the paneltypes are stored in another table (tblPanel_Prices). There is a relation between the tblPaneltypes and tblPanel_Prices (both integer)
So the client fills in the form and selects a certain type of panel, this gets posted (controller) to the table with the function: this->input->post('paneltype').
After this I want to calculate the surface of the panel and make select the right price-category on the field price-id.
So in the form there is a type of panel choosen by the client. This already goes to my table, but I also want to pass the price_id tag in the form.
Then, I would like to get the price_id tag from the table tblPaneltypes to link this with the price_id tag in tblPanel_Prices. The value of the price_id isn't important for the client, so no need to select or show this value. I just need it to calculate the price of the panel (which depends on the type of panel filled in by the client)
Thanks in advance!
Store function in controller
public function store()
{
$this->load->model("orders/panels/Panels");
$this->form_validation->set_rules('amount', 'aantal', 'numeric|required|max_length[2]');
$this->form_validation->set_rules('dwidth', 'paneelbreedte', 'numeric|callback_check_width');
$this->form_validation->set_rules('dheight', 'paneelhoogte', 'numeric|callback_check_height');
$this->form_validation->set_rules('paneltype', 'paneeltype', 'required');
$this->form_validation->set_rules('ral_code', 'ral kleur', 'callback_check_double');
if ($this->auth()) {
if ($this->form_validation->run() == FALSE) {
$this->read_panel();
} else {
$panel = $this->Panels->create__entry(
$this->input->post('order_id'),
$this->input->post('amount'),
$this->input->post('dwidth'),
$this->input->post('dheight'),
$this->input->post('paneltype'),
$this->input->post('panelcategory'),
$this->input->post('color'),
$this->input->post('othercolor'),
$this->input->post('tubes'),
$this->input->post('colorswatch'),
$this->input->post('structurepaint'),
$this->input->post('uv'),
$this->input->post('window'),
$this->input->post('paintwindow'),
$this->input->post('windowsetup'),
$this->input->post('glastype'),
$this->input->post('door')
);
redirect("rail/read_rail?order=" . $this->input->post('order_id'));
}
} else {
login();
}
create__entry in model: at this moment I'm filling in the panelcategory manually in the model in. In the future it should filled in automaticly.
function create__entry($order_id, $amount, $dwidth,
$dheight, $paneltype, $panelcategory, $color,
$othercolor, $tubes,
$colorswatch, $structurepaint,
$uv, $windowtype, $paintwindow,
$windowsetup, $glastype, $door)
{
$this->order_id = $order_id;
$this->amount = $amount;
$this->dwidth = $dwidth;
$this->dheight = $dheight;
$this->paneltype = $paneltype;
$this->panelcategory = $panelcategory;
$this->color = $color;
$this->othercolor = $othercolor;
$this->tubes = $tubes;
$this->colorswatch = $colorswatch;
$this->structurepaint = $structurepaint;
$this->uv = $uv;
$this->windowtype = $windowtype;
$this->paintwindow = $paintwindow;
$this->windowsetup = $windowsetup;
$this->glastype = $glastype;
$this->door = $door;
$this->db->insert(self::TABLE_NAME, $this);
return $this->read__entry($this->db->insert_id());
}
I'm developing a dropdown list that gets the values and his related from the same table.
AssetType
asset_type_id
name
order
parent_asset_type (related to AssetType.asset_type_id) - the top type as value = NULL
<?= $form->field($model, 'asset_type_id')->dropDownList(
ArrayHelper::map(AssetType::find()->where("parent_asset_type IS NOT NULL")->all(), 'asset_type_id', 'name', 'parent_asset_type'),
['prompt'=>'Choose a Category']);?>
And with this Yii2 arrayHelper i can save 3 values, the id of the asset which is not null, his name and the parent_asset_type (Which shows the ID)
Basically:
DropDownList
Choose a Category
1
T-Shirts
Jeans
2
Computers
Cellphones
Instead of the group Id i would love to know how can i make it show the name of that Asset Type.
I hope this will help you...
I have created a function in the model modelname.php
public function getAssetType(){
return $this->name .'-'.$this->parent_asset_type;
}
view.php
<?php
$asset = ArrayHelper::map(AssetType::find()->all(),'id','AssetType');
echo $form->field($model, 'asset_type_id')->dropDownList($asset,
['prompt'=>'Choose a Category']);
?>
Thank You...
I have a Product model with a 'categories' column. This column should be able to contain data from a Checkboxlist.
Whenever a user creates a new Product I want the form to display the 'categories' Checkbox, with the items set as active from the user's last created Product.
So for instance: the 'categories' Checkboxlist contains items 'Movies' and 'Music'. When the user checks 'Movies' and creates the Product, the next time the user goes to create a Product, 'Movies' is already selected (because it saves the selection from the user's previous product creation).
I believe these are the most effective steps to code in order to achieve this goal:
When Product is created: checked items are saved to 'categories' column in Product Model & a 'categories' column in the User's 'Profile' model
User's last saved categories ('categories' column in Profile model) should be retrieved at the Product's Create form.
Code in Product model's _form view:
<?php echo $form->checkBoxList($model, 'categories', array('movies'=>'Movies','music'=>'Music')); ?>
(I'm unsure as to where to set an array for active values)
I'll need to convert the Array of the selected Checkboxes to a string using explode(",", $model->categories) so I can put it inside the 'categories' columns of the 'Product' and 'Profile' models by using the ProductController's actionCreate function.
Then to set the user's last selected Checkboxlist items as active in the Product _form view I need to convert the $model->categories data back to an array by imploding the column ie implode(",", $user->profile->categories).
How would you code this in Yii?
Use CHtml::ckeckboxList instead of activecheckbox.
It have selected parameter. Selected there is array of key=>value pairs. yiiframework.com/doc/api/1.1/CHtml#checkBoxList-detail
Or you can rewrite (extend) you CHtml helper to resolve your format.
For example:
public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
if(array_key_exists('explode_format',$htmlOptions))
{
$selection=explode($model->$attribute);
unset($htmlOptions['explode_format']);
}
else{
$selection=self::resolveValue($model,$attribute);
}
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$name=$htmlOptions['name'];
unset($htmlOptions['name']);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
$hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
}
Then just add 'explode_format'=>true to your htmloptions for activecheckboxlist. Something like this will work.
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);
?>
I have 3 tables in mysql
city in which I have Cityid Cityname
labels in which I have
labelid langid and text
language table in which I have langid,
langname and enabled
Now the 3 tables are interrelated as cityname=labelid
text will hold the actual name
language will hold the language name
eg
City Table will be `
cityid=1, cityname=3000
cityid=2, cityname=3001
`
Labels Table will be
labelid =3000, langid=1, text=New York
labelid =3000, langid=23, text=New York in Chinese
labelid= 3001, langid=1, text= Mumbai
Language Table will be
`langid=1, lagname=english, enabled=1
langid=23, langname=chinese, enabled=1`
Now what I have achieved is to display the data of city in grid view and show a dropdown of all the languages whose enabled=1
What I want to do is change the content of the grid according to the language we have selected from the drop down.
So when Chinese is selected in the drop down then all the city names should appear in Chinese.
my view code is
$Labelcriteria = new CDbCriteria;
$Labelcriteria->condition = ("enabled=1");
$langarray= Language::model()->findAll($Labelcriteria);
$i=-1;
foreach ($langarray as $lang)
{
$i=$i+1;
$langName[$i]=$lang->langname;
}
//echo CHtml::dropDownList('select_box_name','select_value',$langName,array('onchange' => 'alert(1)',));
echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php
$this->renderPartial('_search',array('model'=>$model,));
?>
</div><!-- search-form -->
<?php
echo CHtml::dropDownList('select_box_name','select_value',$langName, array(
'onchange'=>'alert(1)',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('cityController/dynamiccities'),
)
));
$this->widget('zii.widgets.grid.CGridView',
array('id'=>'city-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array('citycode', 'cityname',array('class'=>'CButtonColumn',),),));
?>
While my model is
public function search()
{
$criteria=new CDbCriteria;
$criteria->select = 't.citycode,lbl.text as cityname ';
$criteria->join = 'inner join labels lbl on t.cityname=lbl.labelid inner join language lng on lbl.langid=lng.langid';
$criteria->order = 'lbl.text ASC';
$criteria->condition=$someway_to_change_dynamically_using_dropdown;
$criteria->compare('citycode',$this->citycode,true);
$criteria->compare('cityname',$this->cityname,true);
// $criteria->compare('cityid',$this->cityid);
// $criteria->compare('seq_no',$this->seq_no);
// $criteria->compare('enable',$this->enable);
return new CActiveDataProvider($this, array('criteria'=>$criteria,));
}
Any help will be really appreciated
This is the controller action which renders the view file
public function Admin()
{
$model=new City();
$model->unsetAttributes(); // clear any default values
if(isset($_GET['City']))
$model->attributes=$_GET['City'];
$this->render('admin',array('model'=>$model));
}
OK I've tried to wrap my head around it and I think I have it.
You want to show all the city names in English by default, but have a drop down with all the available languages in. When the language is switched, show the city names in that language.
So what you need is to have the grid view filled with all the name pulled out using a parameter, specified by the drop down, but defaulting to English. Your most of the way there.
Your countries are pulled out here:
....dget('zii.widgets.grid.CGridView',
array('id'=>'city-grid',
'dataProvider'=>$model->search(),
....
I'm guessing you want to just show the code and the translated name within the grid view?
So the widget will become:
$this->widget('zii.widgets.grid.CGridView',
array('id'=>'city-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'citycode',
array(
'name'=>'Country',
'value'=>'$data->getLabel("'.$langId.'")',
),
array('class'=>'CButtonColumn')
),
));
On your city model you then need a method to get its langauge variant out based on the ID of the langauge, so place this into your model:
public function getLabel($id){
return $this->labels[$id]->text;
}
You'll also need the proper realationship for the labels for each cityname too. Because your below Yii 1.1.9 and your not pulling them down together (joining) we'll need a manual function to join a FK to a FK.
Add this to your city Model:
public function getLabels(){
return Labels::model()->findAll(array(
'condition'=>'labelid = :labelid',
'params'=>array(':labelid'=>$this->cityname)
));
}
and change its search function to:
public function search()
{
$criteria=new CDbCriteria;
$criteria->order = 'lbl.text ASC';
$criteria->compare('citycode',$this->citycode,true);
$criteria->compare('cityname',$this->cityname,true);
$criteria->compare('cityid',$this->cityid);
$criteria->compare('seq_no',$this->seq_no);
$criteria->compare('enable',$this->enable);
return new CActiveDataProvider($this, array('criteria'=>$criteria,));
}
Now you'll need to modify the action send the right variables into the view:
public function Admin($lang=1)
{
$model=new City();
//populate the filters
$model->attributes = $_GET['City'];
$this->render('admin',array('model'=>$model, 'langId'=>$lang));
}
Then the search form needs to show all the available countries, which you've got already pulled out here:
$Labelcriteria = new CDbCriteria;
$Labelcriteria->condition = ("enabled=1");
$langarray= Language::model()->findAll($Labelcriteria);
$i=-1;
foreach ($langarray as $lang)
{
$i=$i+1;
$langName[$i]=$lang->langname;
}
This could be replaced without any change to the results with:
$langarray = Language::model()->findAll(array('condition'=>'enabled=1','select'=>'langname'));
....I think
Either way, you have the countries there and are already popluating a drop down with them.
So all that should give you a view with the drop down of langauges and a grid view with the city names populated with English names by default, but if you pass the lang parameter with an ID it will show cities with that language.
How you implement the Javascript to actually update the grid view on Ajax will on the rest of your page layout, framework and splitting out some more views. But we can get into that another time.
You can use this for updating the content of a GridView with respect to the selection on a CHtml::dropDownList.
1)The js script is for capturing the onchange of the select:
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
//alert(this.value);
$.fn.yiiGridView.update('milestone-category-grid', {
data: $(this).serialize()
});
return false;
});
");
2)Code for the select:
$data = CHtml::listData(Status::model()->findAll('IsProcess=?',array(1)), 'ID', 'Description');
$select = key($data);
echo CHtml::dropDownList(
'dropDownStatus',
$select, // selected item from the $data
$data,
array(
'style'=>'margin-bottom:10px;',
'id'=>'selStatus',
)
);
3)For the gridview widget:
$this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'milestone-category-grid',
'afterAjaxUpdate' => 'installSortable',
'enableSorting' => false,
'dataProvider'=>$model->search($select),
'rowCssClassExpression'=>'"items[]_{$data->ID}"',
'columns'=>array(
'Description',
),
)); ?>
4)In the Search function of your corresponding model the following code needs to capture the GET variable that is being passed, in this case it is dropDownStatus, the name given to the select (use Firebug, if necessary, to get the name of the variable being passed):
public function search($status=false)
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
if ($status!==false) {
$criteria->condition='StatusID=:StatusID';
$criteria->params=array('StatusID'=>$status);
}
if (isset($_GET['dropDownStatus'])) {
$criteria->condition='StatusID=:StatusID';
$criteria->params=array('StatusID'=>$_GET['dropDownStatus']);
$criteria->order='Position ASC';
}
...
Reference