I am new in yii. I want to search by attribute (field name) from my model and need to view in view page or another page by zii.widgets.grid.CGridView.
how can I create a search() function in model by findByAttribute()
so that we can show the results by attribute without any search
here is my model function but it is not working.. :: ERROR Undefined variable: pp_requisitionno
public function searchView()
{
$criteria=new CDbCriteria();
$criteria->select= 'pp_requisitionno';
$criteria->addSearchCondition('pp_requisitionno',$pp_requisitionno);
$criteria->compare('pp_requisitionno',$this->pp_requisitionno);
$criteria->condition = 'pp_requisitionno=:pp_requisitionno';
$criteria->params = array(':pp_requisitionno'=>Yii::app()->Request->Getpost('pp_requisitionno'));
$model = Requisitiondt::model()->find();
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Any help please...
It's probably going to be more useful to define a general search function that can be reused for different searches. This can be done in the following way:
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
$criteria = new CDbCriteria;
//Define all your searchable fields here
$criteria->compare('t.title', $this->title, true);
$criteria->compare('t.type', $this->type, true);
$criteria->compare('t.published', $this->published, true);
$criteria->compare('category.id', $this->category_id, true);
//Add any other criteria, like the default sort order etc.
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Then in your controller you can use the search like this;
pubic function actionSearch(){
$model = new Requisitiondt;
if (isset($_POST)){
$model->attributes = $_POST;
$dataProvider = $model->search();
$this->render('searchView', array('dataProvider' => $dataProvider));
}
}
The view 'searchView' then looks like this;
<?php
$this->widget('CGridView', array(
'dataProvider' => $dataProvider,
'columns' => array(
//Add in whatever columns you want the grid to show
)
));
?>
Obviously you'll need to replace your own model names and field names, but this is the general idea. This way will search for any attributes you include in the POST request,and is more reusable.
You need use Relations in your model, read here.
Then add 'filter' => $model, in your GridView Widget options array
Related
I have a user table in which i have multiple roles and i am showing different user on different action by using same model search function. By this
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
$model->userRole = UmsConfing::ADMIN;
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
I am using this function for different roles .This works well. but now i want to show admin and operation user in same list i tried
$model->userRole = UmsConfig::ADMIN || UmsConfig:: OPERATION
but i didn't work Please help.
Please you can try this below code:
public actionAdmin(){
$model = new User('search')
$model->unsetAttributes();
if(isset($_GET('User')))
$model->attributes = $_GET['User'];
$this->render('userlist',arary('model'=>$model));
}
Below codeadd in User Model Search Function:
model/User.php
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->addInCondition('userRole', array (UmsConfig::ADMIN,UmsConfig:: OPERATION));
$criteria->compare('status',$this->status);
$criteria->compare('is_deleted',$this->is_deleted);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => yii::app()->params->pagesize,
),
'sort'=>array(
'defaultOrder'=>array(
'id'=>CSort::SORT_DESC
),
),
));
}
wondering if anyone can help.
I have a two pages in my Yii application that use the same controller/model, but use different model functions. My initial page is pretty standard 'admin' page that uses the default search() as the model (this works fine - including filtering), but i've subsequently made a secondary view/action which looks at an altered search function - this has an ID passed into it (pulled from URL params). This works fine, but the filters in page don't work which is annoying.
I think it's because in the controller, i'm not passing the ID variable through correctly???
Here's some of my code;
Model:
public function searchByEvent($event_id) {
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id, true);
$criteria->compare('event_id', $this->event_id, true);
$criteria->compare('status_id', $this->status_id, true);
$criteria->compare('checkin_status_id', $this->checkin_status_id, true);
$criteria->compare('guest_of_user_id', $this->guest_of_user_id, true);
$criteria->compare('user_id', $this->user_id, true);
$criteria->compare('assign_group', $this->assign_group, true);
$criteria->with = 'user';
$criteria->compare('user.forename', $this->user_forename, true);
$criteria->compare('user.surname', $this->user_surname, true);
$criteria->compare('user.company', $this->user_company, true);
$criteria->order = 'user.surname ASC';
$criteria->condition = "event_id = :event_id";
$criteria->params=(array(':event_id'=>$event_id));
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination'=>array('pageSize'=>50),
));
}
Controller:
public function actionAdminByEvent() {
$model = new EventAttendees('searchByEvent');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['EventAttendees']))
$model->attributes = $_GET['EventAttendees'];
$this->render('webroot.themes.'.Yii::app()->name.'.views.adminEventAttend.adminByEvent', array(
'model' => $model,
));
}
View;
$event_id = Yii::app()->getRequest()->getParam('event_id');
this->widget('booster.widgets.TbGridView', array(
'id' => 'event-attendees-grid',
'dataProvider' => $model->searchByEvent($event_id),
'pager' => array(
'class' => 'booster.widgets.TbPager',
'displayFirstAndLast' => true,
),
'filter' => $model,
'template'=>'{summary}{pager}{items}{pager}',
'selectableRows' => 0,
'selectionChanged' => 'function(id){ location.href = "' . $this->createUrl('view') . '/id/"+$.fn.yiiGridView.getSelection(id);}',
'columns' => array(...
Can anyone see where i'm going wrong with the filters, or if im missing a step with search?
If I were to guess, it's because the attributes in your model are not declared as "safe" when it is under the "searchByEvent" scenario. If you used gii and looked at your model's rules method, you would find an entry there that marks all attributes as "safe" when using the "search" scenario. You are using a different scenario called "searchByEvent" in your controller action ($model = new EventAttendees('searchByEvent')) and if you did not create a new rule that flags your attributes as safe under this scenario, then your mass assignment line ($model->attributes = $_GET['EventAttendees']) will fail for any attributes without any scenario-less rules.
If that isn't the case though, another thing you might want to look at is changing the following:
$criteria->condition = "event_id = :event_id";
$criteria->params=(array(':event_id'=>$event_id));
to
$criteria->addColumnCondition(array('event_id' => $event_id))
Your params line might be overwriting all the other parameters that were set with all the previous compare statements because you are not merging your new parameters into the current set. Using the proper CDbCriteria methods helps get around this.
I'm working on a project in Yii where I would like the user to be able to update information on his mobile "accounts". The database I use has multiple accounts for each person (and, for that matter, has multiple individuals who will use the system). Now, when the user goes to "manage his account" he is able to manage all of the accounts of the database (not just his own).
Currently the code in the controller looks like this
public function actionAdmin()
{
$model =new Account('search');
$userId = Login::model()->getUserId();
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Account']))
{
$model->attributes=$_GET['Account'];
}
$this->render('admin',array(
'model'=>$model,
));
}
UserId is the the id that I would like to restrict that data to. Something along the lines of
$account = Account::model()->findAll(array("condition"=>"user_id = $userId"));
I'm not sure how exactly to go through with this. I've looked around and I know that there are "Criteria" that I could update in the model and there is also a "Filter function in the view". Should I be using one of these two to limit the accounts shown? Or can I do something directly from the controller?
Here is the code in the view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'account-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'user_id',
'name',
'mobile_comp',
'msisdn',
'pin',
'balance',
/*
'company',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
And the model
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
$criteria->compare('mobile_comp',$this->mobile_comp,true);
$criteria->compare('msisdn',$this->msisdn);
$criteria->compare('pin',$this->pin);
$criteria->compare('company',$this->company,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Change your actionAdmin to the following
public function actionAdmin()
{
$model =new Account('search');
$userId = Login::model()->getUserId();
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Account']))
{
$model->attributes=$_GET['Account'];
}
$model->user_id = $userId;
$this->render('admin',array(
'model'=>$model,
));
}
The above code will load only the current user record.
Just Solved - Different way than Think Different:
In my model I added a condition
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$userId = Login::model()->getUserId();
$criteria->addCondition(array("condtion"=>"user_id = $userId"));
$criteria->compare('name',$this->name,true);
$criteria->compare('mobile_comp',$this->mobile_comp,true);
$criteria->compare('msisdn',$this->msisdn);
$criteria->compare('pin',$this->pin);
$criteria->compare('company',$this->company,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
i got 2 models: Project and Users connected with (User.php):
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
"projects"=>array(self::MANY_MANY, 'Project','projects_users(user_id, project_id)'),
);
}
I want to show all users in CActiveDataProvider who are not connected with project. How can i do it?
I found solution:
$criteria=new CDbCriteria;
foreach($model->users as $cur) {
$criteria->addCondition("ID != ".$cur->ID);
}
$users=User::model()->findAll($criteria);
$dataProvider2=new CActiveDataProvider('User');
$dataProvider2->data = $users;
Try this:
$users = User::model()->with('projects')->findAll(array(
'together' => true,
'condition' => 'projects.id IS NULL',
));
I'm trying to work with a YII CGridview to display some data.
This is home my model search function looks like:
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('ip',$this->ip,true);
$criteria->compare('first_use',$this->first_use,true);
$criteria->compare('last_use',$this->last_use);
$criteria->compare('memberid',$this->memberid);
$criteria->compare('countryid',$this->countryid);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
));
}
And this is how my view looks like
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'iplog-grid',
'dataProvider'=>$oIPLog->search(),
'filter'=>$oIPLog,
'summaryText' => 'showing you {start} - {end} of {count} logged Ips',
'columns'=>array(
array(
'name'=>'ip',
'type'=>'raw',
),
array(
'name'=>'first_use',
'type'=>'datetime',
),
array(
'name'=>'last_use',
'type'=>'datetime',
),
),
));
Displaying the CGridview works, but I can't seem to get the filter on top of it to work. It sends the call and I don't get any error as reponse, it just returns the whole unfiltered data again..
Any clues?
And how exactly does your controller look like?
For the CGridview filter to work you need to check in your controller if there are any filters set and then return the filtered object.
To clarify, something like this should be placed into your controller action
$oObject = new Object('search');
if (isset($_GET['Object'])) {
$oObject->attributes = $_GET['Object'];
}
Hope this helps
You Have to apply these points:
1.Specify the global variable($_REQUEST) in function of your controller
for example
$model = new User('search');
$model->unsetAttributes(); // clear any default values
if (isset($_REQUEST['User'])){
$model->attributes = $_REQUEST['User'];
}
$this->render('admin', array(
'model' => $model,
));
Set method type in search form
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl('user/admin'),
'method'=>'POST',
)); ?>
3.In Cgrid view you have to define the url like
'ajaxUrl'=>Yii::app()->createUrl( 'controller/function' ),