Im trying to pass a condition to my UserController in order to view certain Users whose Role matches to the page I'm trying to access.
For example:
/admin => User.admin
/student => User.student
I'm able to retrieve a list of all registered students using the find('all') function, but when I try to filter roles through setting conditions I'm getting an error that references my code and the role I'm trying to retrieve.
Here's my function in my controller:
public function index($role="admin") {
//debug($role);
$this->User->recursive = 0;
$this->request->data('users', $this->User->find('all',
array('conditions' => 'User.role')));
$this->set('users', $this->paginate());
}
Any tips?
conditions should be an array of conditions.
i.e. array('role' => 'role_value')
See documentation at http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
For adding conditions, use WHERE option with find().
Like:
public function index($role="admin") {
$this->User->recursive = 0;
$this->request->data('users',
$this->User->find()->where(['conditions' => 'User.role']));
$this->set('users', $this->paginate());
}
OR
If role is the DB table field name, the code is simple:
public function index($role="admin") {
$this->User->recursive = 0;
$this->request->data('users',
$this->User->findByRole());
$this->set('users', $this->paginate());
}
Related
I am trying to display table Users, and I want it to display the user with the role "Moderator" only.
public function moderators() {
$this->set('users', $this->paginate());
$this->User->find('all', array(
'conditions' => array('User.role' => 'moderator')
));
This is my controller, and it seems that it is still displaying all data in my table.
Try to use custom query for that:
$this->User->query("select * from users where role = 'moderator';");
I am trying to creating a STAT relation for a model that sums up the contents of a column provided that another column matches my conditional statement. In my particular case, I need to get the sum of all the file sizes of the pictures that a user has uploaded.
Code:
class User extends CActiveRecord {
public function relations() {
return array(
'pictureSpaceUsed'=>array(self::STAT, 'Picture', 'user_id', 'select' => 'SUM(size)','condition' => 'user_id=' . $this->id),
),
}
}
Problem is that Yii complains that it can't access the id of the model. $this->id doesn't seem to be working inside the relations function... It works if I replace $this->id with a number though, but that wouldn't be dynamic anymore.
Anybody know what's going on here?
Why do you want to insert that condition? It looks like you already state the condition when you say:
class User extends CActiveRecord {
public function relations() {
return array(
'pictureSpaceUsed'=>array(self::STAT, 'Picture', 'user_id', 'select' => 'SUM(size)'),
),
}
}
It will find the relation based on user_id
I just started cakephp following there tutorials
I'm able to grab the posts table in my post controller and spew it onto my index.ctp
In my view for the post controller i also want to list the User name that posted the article. My post table has a user_id, so i need to match it to my user table and pass it along
class PostsController extends AppController {
public function index() {
//passes values to the view
$this->set('posts', $this->Post->find('all'));
//is "Post" a post method? or is it the name of the table? i'm unsure of the syntax
$this->set('users', $this->Users->find('all')); //this does not work
}
}
thank you for your help with this basic question
You must use 'recursive'
$this->Post->find('all', array(
'recursive' => 2,
// ...
));
Of course, you first need to link models together
I assume that you have already set a belongsTo association (Post belongsTo User) and/or a hasMany association (User hasMany Post). If so, cake will automaticly brings the associated models (unless you put $recursive = -1 on your model).
Thus you'll have access to the users related to each post on the view: posts[i]['User']
You can also use this on your view to see the view variables:
debug($this->viewVars)
put this on your Post model if you don't:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
)
);
Make sure that you load models corretly (in case you want to load the User model inside PostsController).
So simply add this attribute inside your class controller.
public $uses = array('Post','User');
to link models together . u need to add the association inside your Post model .
public $belongsTo = array(
'User'=>array(
'className'=> 'User',
'foreignKey'=>'user_id'
)
);
and i you want to retrieve data from database you have to set your recursivity and there is two ways
first one :
$posts = $this->Post->find('all',array('recursive'=>2));
// or
$this->Post->recursive = 2;
$posts = $this->Post->find('all');
second one : use the Containable behavior
set the recursivity to -1 in the AppModel and include the behavior
public $recursive = -1;
public $actsAs = array('Containable');
so simply u can retieve posts with any other linked models like that
$posts = $this->Post->find('all',array(
'contain'=>array('User'),
// ...
)));
Using Laravel 4 and PHP I am able to query the database and populate an HTML selection box.
the magic happend with User::find(1)->lists('username', 'user_id')
And here is my code for the selection field.
<?php
echo Form::label("username", "Username", array('class' => 'col-lg-12 control-label')); }}
echo Form::select(
'user',
User::find(1)->lists('username', 'user_id'),
Input::get('user'),
array(
"placeholder" => "US",
'class' => 'form-control'
)
)
?>
I need to modify this to only populate the Form selection with Users who's status is not set to 0.
I think this is probably a simple fix but I have not found the solution yet>
This should also work:
User::where('status', '!=', '0')->lists('username', 'user_id')
But as J.T. Grimes mentions, you should move this code in to a method in your Users controller, or better yet your User model in a method called getActiveUsersList():
public function getActiveUsersList()
{
return $this->where('status', '!=', '0')->lists('username', 'user_id');
}
Don't forget to type hint your user model in your controllers __construct() method.
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
and assign it to a variable in your controller using:
$activeUsersList = $this->user->getActiveUsersList();
which you can then pass to the view using:
return View::make('users', compact('activeUsersList'))
I haven't seen lists() applied to a model instance before -- I'd assume that only returns one record?
I'd try
// warning: untested code...
...
DB::table('user')->where('status','<>',0)->lists('username','user_id'),
...
I'd also move that to the controller ($userList = DB::table('user')...) and pass that variable to the view. Making a database call within the view seems like suboptimal MVC.
I've a standard Gii created admin view, which use a CGridView, and it's showing my user table data.
the problem is that user with name 'root' must NOT BE VISIBLE.
Is there a way to add a static where condition " ... and username !='root' " ?
admin.php [view]
'columns'=>array(
'id',
'username',
'password',
'realname',
'email',
.....
user.php [model]
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('username',$this->username,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('realname',$this->realname,true);
$criteria->compare('email',$this->email,true);
......
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
You can use CDbCriteria's addCondition like this:
$criteria->addCondition("username !='root'");
Your best option would be to use Yii scopes which are essentially a saved where clause (or other modification of your existing criteria) that you can apply all over your app and only need to change in one place if your criteria ends up changing later.
What makes them even cooler is that you can string them together with other scopes / criteria changes (from users in grids for instance) without having to keep track of what criteria clause is getting changed by what.
A few examples that might apply to your situation. In your controller you probably have something like this:
$users = User::model()->search()->findAll();
Asgaroth's answer answers what you were asking on the surface. But there is so much more you can do (and do easily) using scopes.
If you add the below to your user model:
class User extends CActiveRecord
{
......
public function scopes()
{
return array(
'active'=>array(
'condition'=>'active=1',
),
'isAdmin'=>array(
'condition'=>'isAdmin=1',
),
);
}
}
then you can retrieve active users (with your users' filters still applied) like this in your controller:
$users = User::model()->active()->search()->findAll();
Or you can retrieve all active admin users (without being filtered by your gridview criteria) like this:
$users = User::model()->active()->isAdmin()->findAll();
Default scopes are just an extension of the same idea:
class User extends CActiveRecord
{
public function defaultScope()
{
return array(
'condition'=>"username != 'root'",
);
}
}
If before your isAdmin scope would return the root user, applying the default scope will eliminate the root user from the models returned, as it applies to every User::model() query you make.