Yii gridview CHTML::dropdown as value doesn't work - php

I'am trying to implement a dropdownlist inside the gridview, but it is not working.
Here's my code
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->roadies_search(),
'filter' =>$model,
'columns'=>array(
array(
'name'=>'hname_search',
'header'=>'Hospital Name',
'value'=>'($data->AssociatedHospitals) ? $data->AssociatedHospitals : ""',
),
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function(){
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
$html = '<select name="user" style="width:100%;">
<option selected>Select User</option>
';
foreach ($res as $key) {
$html.='<option value="'.$key['id'].'">'.$key['name'].'</option>
';
}
$html.='</select>';
return $html;
},
),
)
));
I have tried it using the following function too:
public function getUsername(){
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
return CHtml::dropDownList('usersselectlist'.$this->id,'user_id',CHtml::listData($res, 'id', 'name'));
}
I want to show all the users as a dropdown, for every row in the gridview.
EDIT
I figured out that the dropdown works fine for firefox, but the problem is with chrome. It is not showing the selected values.
Here's an example
Chrome: http://i.imgur.com/eAvBRwO.png
Firefox: http://i.imgur.com/7wBc1GX.png

$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->roadies_search(),
'filter' =>$model,
'columns'=>array(
array(
'name'=>'hname_search',
'header'=>'Hospital Name',
'value'=>'($data->AssociatedHospitals) ? $data->AssociatedHospitals : ""',
),
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function(){
// but better prepare data in model and set here from controller
$dataReader = Yii::app()
->db
->createCommand("SELECT name,id FROM med_user WHERE rank>3")
->query();
$dropList = array();
foreach ($dataReader as $row) {
$id = $row['id'];
$dropList[$id] = $row['name'];
}
return CHtml::dropDownList('my', null/* or selected id */, $dropList);
},
),
)
));

It's really bad way. You will do SQL query for each row, why not use it outside of grid?
$res=Yii::app()->db->createCommand("SELECT name,id FROM med_user WHERE rank>3")->queryAll();
$select_data = CHtml::listData($res, 'id', 'name');
......
array(
'type'=>'raw',
'header'=>'Users',
'id' => 'test',
'value'=>function($data) use ($select_data){
return CHtml::dropDownList('usersselectlist'.$data->id','',$select_data);
},
),
.......
Something like this should work.

Related

Yii Framework - Using CCheckBoxColumn to delete multiple

I'm just trying to wrap my head around the yii framework at the moment and I've created a function to delete multiple database records at once. In the view I've got a grid with a reference to each item and a checkbox next to it
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'htmlOptions'=>array(
'class'=>''
),
'columns'=>array(
...
array(
'class'=>'CLinkColumn',
'header'=>'Handle',
'labelExpression'=>'$data->handle',
'urlExpression'=>'Yii::app()->createUrl(".../item/view", array("id"=>$data->id))',
),
array(
'class'=>'CCheckBoxColumn',
'header'=>'Select',
'selectableRows'=>'2',
),
),
Then further down the page I want a button (delete selected) which sends an array of all of the items to a delete function. My thoughts were it would be something akin to this:
<a href="
<?php echo Yii::app()->createUrl('.../item/bulkDelete','array("id" => $data->id)')?>"
class="btn">Delete Selected</a>
But I don't understand how to get a reference for each checked item instead of :
"id" => $data->id
as I used to call pass an item to the view function earlier. If anyone can help it will be greatly appreciated.
Edit:
View:
$form = $this->beginWidget('CActiveForm', array(
'id' => 'itemForm',
'action' => array('.../item/bulkDelete'),
));
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'htmlOptions'=>array(
'class'=>''
),
array(
'class'=>'CLinkColumn',
'header'=>'Handle',
'labelExpression'=>'$data->handle',
'urlExpression'=>'Yii::app()->createUrl(".../item/view", array("id"=>$data->id))',
),
array(
'class'=>'CCheckBoxColumn',
'header'=>'Select',
'selectableRows'=>'2',
),
... //More Columns
), //End of Grid
...
echo CHtml::SubmitButton('Delete Multiple');
$this->endWidget();
Controller:
public function actionBulkDelete()
{
if(isset($_POST['id'])&& !empty($_POST['id']))
{
Yii::app()->user->setFlash('success', 'Delete Items');
$this->redirect(array('.../item/index'));
}
else
{
Yii::app()->user->setFlash('success', 'No Items Selected');
$this->redirect(array('.../item/index'));
}
}
Wrap the grid view inside a form, and do the following changes in your columns array:
$form = $this->beginWidget('CActiveForm', array(
'id' => 'some-grid-form',
'action' => array('myController/myAction'),
));
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'selectableRows' => 2,
'columns'=>array(
array(
'id' => 'id',
'class' => 'CCheckBoxColumn',
),
//... rest of your columns
),
array(
'class'=>'CButtonColumn',
),
),
));
echo CHtml::SubmitButton('Multiple Delete');
$this->endWidget(); // end form
And in your Controller's myAction:
public function actionmyAction()
{
if(isset($_POST['id']) && !empty($_POST['id'])) { //you'll get all the ids in an array
//print_r($_POST['id']);
//your delete function here, also add a few validation here to authenticate deletion
$ids = $_POST['id'];
$criteria = new CDbCriteria;
$criteria->addInCondition('id',$ids);
MyModel::model()->deleteAll($criteria);
//.... render with success flash message etc.
}
}

Get id of selected values in CAutoComplete in Yii

I am using CAutoComplete to select multiple comma separated values. Now I am able to pass only the selected values, I need to pass the id of selected values also when the form is submitted.
Can you please help me to send the id on submit as an array or comma separated.
In my form I am using:
<?php
$this->widget('CAutoComplete', array(
'model' => $model,
'attribute' => 'skills',
'url' => array('serviceRequest/Suggest'),
'multiple' => true,
'htmlOptions' => array('size' => 34),
));
?>
Controller:
public function actionSuggest()
{
if (isset($_GET['q']) && ($keyword = trim($_GET['q'])) !== '')
{
$tags = Skills::model()->suggest($keyword);
if ($tags !== array())
echo implode("\n", $tags);
}
}
Model:
public function suggest($keyword,$limit=20)
{
$tags=$this->findAll(array(
'condition'=>'skills LIKE :keyword',
// 'order'=>'Name',
'limit'=>$limit,
'params'=>array(
':keyword'=>'%'.strtr($keyword,array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')).'%',
),
));
$names=array();
foreach($tags as $tag)
$names[]=$tag->skills;
return $names;
}
you can pass any option that the JUI autocomplete widget supports by including an options array:
$this->widget('CAutoComplete', array(
// your other settings here
'options' => array(
'select' => new CJavaScriptExpression('function(e, ui) { alert("hi"); }')
),
));
Read here for more: http://www.yiiframework.com/doc/api/1.1/CAutoComplete

yii framework: how to make search result empty in search form?

Hello i created a separate search form having input box and button.
in my model i want to search products by category wise...
but problem is that when input box is empty and clicking on search buttons it displays all entries from the database table..
controller code is-
class AddController extends Controller
{
public function actionAddsearch()
{
$model_form = new Add("search");
$attributes = Yii::app()->getRequest()->getPost("Add");
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
model code--
class Add extends CActiveRecord
{
public function searchAdd()
{
$criteria = new CDbCriteria();
$criteria->compare("addname", $this->category, TRUE, "OR");
$criteria->compare("category", $this->category, TRUE, "OR");
return Add::model()->findAll($criteria);
}
view code- addsearch.php
<div class="search-bar">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
"action"=>$this->createUrl("add/addsearch"),
'type'=>'search',
)
);
echo $form->textFieldRow($model,'category');
echo "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
$this->widget('bootstrap.widgets.TbButton',array(
'buttonType'=>'submit',
'type'=>'success',
'size'=>'large',
'label'=>'Search For Products ',
));
$this->endWidget();
?>
</div>
searchResults.php
<?php
echo "<h4>Results for Your Search</h4>";
foreach($models as $model):
$this->beginWidget('bootstrap.widgets.TbDetailView',array(
'type'=>'bordered condensed',
'data' => array(
'Shop Name' =>CHtml::link(CHtml::encode($model->addname),array('add/view','id'=> $model->addid)),
'Category' => $model->category
),
'attributes' => array(array('name' => 'Shop Name', 'label' => 'Name of Shop','value'=>CHtml::link(CHtml::encode($model->addname),
array('add/view','id'=>$model->addid)),'type'=>'raw'),
array('name' => 'Category', 'label' => 'Category of Shop'),
),
)
);
echo "<br><hr><br>";
$this->endWidget();
endforeach;
?>
what is wrong in the code??
I want to display no any product when text box is empty..
thanks in advance
change this
if(!is_null($attributes))
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
}
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
To
if($attributes)
{
$model_form->setAttributes(Yii::app()->getRequest()->getPost("Add"));
$this->render("searchResults", array(
"model" => $model_form,
"models" => $model_form->searchAdd(),
));
}
1) Is the 'caterory' attribute safe on search scenario ? (in rules)
2) category is an attribute of the table schema ?

Yii dropdownlist saving value in ivar onclick

how can I save value as ivar from dropDownlist in yii? here my code, which doesn't work :/
declaration of ivar:
public $blaaa;
and my dropdownlist code:
echo CHtml::dropDownList(
'categoryDropDownList',
'',
CHtml::listData(Category::model()->findAll(), 'id', 'name'),
array(
'empty' => 'Select Category',
'onchange'=>function () {
$this->blaaa = 'js:this.value';
}
));
I tried also with ajax, but it also doesnt work:
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('category/actionBla'),
'data' => array('id' => 'js:this.value')
where
public function bla()
{
if (isset($_POST['id'])) {
$this->blaaa = $_POST['id'];
}
thanks in advance for help!
In ajax section, change url as below
'url' => CController::createUrl('category/bla'),
In controller, your function name should be
public function actionBla()
I solved my problem with echo'ing CHtml::dropDownList in form:
echo CHtml::form();
echo CHtml::dropDownList(
'categoryDropDownList',
'',
CHtml::listData(Category::model()->findAll(), 'id', 'name'),
array(
'empty' => 'Select Category'
));
echo CHtml::endForm();
and now activeForm bother about sending parameters via POST

Displaying data from two tables in Yii CGridView

I want to show 2 tables with a right join, but the code I wrote does not work as expected. Can anyone tell me what I am doing wrong ?
view : admin.php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'punish-grid',
'dataProvider' => $model->searchJoin(),
'type' => 'striped bordered condensed',
'filter' => $model,
'columns' => array(
array(
'header' => 'No',
'type'=>'raw',
'htmlOptions'=>array('style'=>'width: 25px'),
'value'=>'$this->grid->dataProvider->pagination->currentPage
*$this->grid->dataProvider->pagination->pageSize + $row+1',
),
// i want to display p.kode,p.status from table status
'berlaku_punish',
'nilai',
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
and my model : BasePunish.php
public function relations() {
return array(
'idStatus' => array(self::BELONGS_TO, 'Status', 'id_status'),
);
}
public function searchJoin() {
$criteria = new CDbCriteria;
$criteria->select = 'p.kode,p.status,t.nilai,t.berlaku_punish';
$criteria->join= 'RIGHT JOIN status p ON (t.id_status=p.id)';
$criteria->condition = 't.id_status IS NULL';
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort'=>array(
'defaultOrder'=>'kode ASC',
),
)
);
}
I might really did not understand what you are asking but still if nothing is working for you then you can try this
array(
'header'=>'Products',
'value'=>array($model,'gridCreateUser'),
),
In this, the value will try to find the function gridCreateUser in the class of which $model is the object. In your case i guess $model is the object of the BasePunish.
So in your BasePunish.php create a function gridCreateUser() and then you can return the value which you want to display in your widget.
eg:-
In your BasePunish.php
public function gridCreateUser($data)
{
// you can access the object $data here
// do what ever you want to do
$value='return whatever you want to return';
return $value;
// this $value will be displayed there
}

Categories