Retreving specific row from database in yii - php

I am working on a job site,And want to show only the jobs posted by a particular user in cgridview.My actuall aim is to authenticate the user so that only jobs posted by him/her will be visible in cgridview.I have done the following stuff,but not working.
In controller:
public function actionViewJob() {
$user_id = Yii::app()->session['user_id'];
/* For User Authentication */
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
/* For User Authentication */
/* Have tried the following codes to filter */
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
// $model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
// $model = ViewJob::model()->findAll("user_id=$user_id");
$model = new Viewjob('search');
$params = array('model' => $model,
);
$this->render('viewjob', $params);
}
In view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model->search()
// 'filter' => $model, /* not using this option ,so commented it */
))
In model
// Do I really Need This Function //
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('user_id', $this->user_id, true);
return new CActiveDataProvider('viewjob', array(
'criteria'=>$criteria,
));
},,
What am I doing wrong here.It is still fetching all the available rows in table.

You define $model 3 times:
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
Then
$model = new Viewjob('search');
And
'dataProvider' =>$model->search()
Choose one that you need, better last. And add to controller
$model->user_id = $user_id
It will works.

Create new CDbCriteria object and add condition using it and pass it to model.
In Controller:
public function actionViewJob() {
$criteria = new CDbCriteria ();
$criteria->condition = 'user_id=' . Yii::app()->user->id;
$model = ViewJob::model()->findAll($criteria);
$params = array('model' => $model);
$this->render('viewjob', $params);
}
And in View, simply:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model
Also for use Authentication, in your controller you don't need to check, if user has the user id, simply add access rules, which will automatically redirect user to the login page to view the job and once they are logged-in, will return them to the same page. So, add this at the top of our controller..
class YourController extends Controller {
public function filters() {
return array(
'accessControl', // perform access control
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow authenticate user actions
'actions' => array('viewjob'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}

Related

How to show logged-in user name in input form field while creating in Yii1?

I have a form where one can upload his/her own CV files(docx/pdf).I have a drop down menu "employee name" in the from which shows only the login user name in the list.But now i want to show the login user name in the from input field.how can i do that.Can any one give me code example.As i am very poor at coding.
Here is my from code:
if($UserType == "employee")
{
$criteria=new CDbCriteria();
$criteria->condition = "status= 'active' and id = $ID";
echo $form->dropDownListGroup(
$model,
'user_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(User::model()->findAll($criteria), 'id', 'user_id'),
'htmlOptions' => array('prompt'=>'Select'),
)
)
);
}
user name input field
logged-in user name
This is the way I do:
First, in /protected/components, I set a session variable to store the logged-in user name:
public function authenticate()
{
$user = Users::model()->find('user = ? ', array($this->username)); //user entered when trying to log in
...
}
If authentication is correct:
public function authenticate()
{
...
$session = new CHttpSession;
$session->open(); //session_start
$session['user'] = $user; //$user is the logged-in username
...
}
In controller action create:
public function actionCreate(){
$session = new CHttpSession;
$session->open();
$user = $session['user'];
...
$this->render('create',array(
'user'=>$user,
'model'=>$model,
...
));
}
In view (in /_form, for example):
...
$model->user = $user;
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
...
echo $form->dropDownList($model,'user',...); //Here, the attribute 'user' of the model $model will have the logged-in user-name
...
This is assuming you have an attribute called 'user' in your model. If not, then, in /model, create an auxiliary attribute 'user' in order to use this attribute in your /_form:
class YourModel extends CActiveRecord
{
public $user; //$variable used to set the logged-in username
...
}

Edit action in Yii framework

I am working on a web application that allow users to have video conferences. Users are allowed to create video conferences and I want them to be able to also edit the scheduled video conferences but I am having trouble implementing that. Please help.
Edit button in index.php view
$html .= CHtml::ajaxLink('Edit',
Yii::app()->createAbsoluteUrl('videoConference/update/'.$vc->id),
array(
'type'=>'post',
'data' => array('id' =>$vc->id,'type'=>'update'),
),
array( "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info")
);
Video conference Controller actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if (isset($_POST['VideoConference'])) {
$model->attributes = $_POST['VideoConference'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('edit', array(
'model' => $model,
));
}
The first step is to find where is problem(frontend / backend). You need call action without ajax(just from url with param id). Try my version:
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if ($model == null) {
throw new CHttpException(404, 'Model not exist.');
}
//if (isset($_POST['VideoConference'])) {
//$model->attributes = $_POST['VideoConference'];
$model->attributes = array('your_attr' => 'val', /* etc... */);
// or try to set 1 attribute $model->yourAttr = 'test';
if ($model->validate()) {
$model->update(); //better use update(), not save() for updating.
$this->redirect(array('view', 'id' => $model->id));
} else {
//check errors of validation
var_dump($model->getErrors());
die();
}
//}
$this->render('edit', array(
'model' => $model,
));
}
If on server side all working fine(row was updated) then check request params, console, tokens etc. Problem will be on frontend.
After troubleshooting a little I finally got it to work.
On the view I am calling the actionUpdate method like this:
$html .= CHtml::button('Edit', array('submit' => array('videoConference/update/'.$vc->id), "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info"));
On the controller just changed
$model->save() to $model->update()
and it works perfectly fine.

Getting a particular row from database in yii

I am working on a job site.And using Yii.I have gridview which list all the jobs posted by user,but I just want to show the jobs which are posted by a particular user.like if the user is logged in as admin then it should show only jobs posted by admin.I have tried the following things but not working.
In Controller.
//codes
public function actionViewJob() {
$user_id = Yii::app()->session['user_id'];
/* For User Authentication */
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
/* For User Authentication */
$model = ViewJob::model()->find(array(
'select' => array('*'), "condition" => "user_id= $user_id",
));
$params = array('model' => $model,
);
$this->render('viewjob', $params);
}
function as search() in model ViewJob.
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('key_skills','Admin',true);
return new CActiveDataProvider('viewjob', array(
// 'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'key_skills ASC',
),
));
}
What am I doing wrong here.?.Its still listing the whole data.
Try like
$model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
Try this
$model = ViewJob::model()->findAll("user_id=$user_id");
/*
1. find() can fetch first matched row, where as findAll() fetches all matched rows in the db table
2. "user_id=$user_id" is equals to WHERE user_id=$user_id
*/
Code improvements(Yii way)
Register user sessions as bellow
Yii::app()->user->setState('user_id',$value_variable); //Set the session
Yii::app()->user->getState('user_id'); //Get the session
You can use accessRules() for bellow code
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
Like
public function accessRules()
{
return array(
array('allow',
'actions' => array('viewJob'),
'users' => array('#'),
----
---

How to view data only made by the user?

I created a link and what it's supposed to do is take me to the page where it displays all the announcements that I posted but instead it shows me all of the announcements inside the database.
here is my link:
<a class="more" href="<?php echo Yii::app()->createUrl('announcement')?>" ><?php switch_lang('View Announcements', '查看更多', FALSE)?></a>
This is the controller for announcement for the actionView() :
public function actionView()
{
$post=$this->loadModel();
if(Persons::model()->compare_country(explode("|",$post->country)))
{
$post->view_count = $post->view_count + 1;
Yii::app()->db->createCommand("UPDATE content SET view_count = {$post->view_count} WHERE id = {$post->id}")->execute();
//$post->save();
$comment=$this->newComment($post, 'view');
if (!empty(Yii::app()->session['announcement_message']))
{
Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
Yii::app()->session['announcement_message'] = null;
}
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
'view'=>'view',
));
}
else
{
$this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
}
}
Yii supports the concept of the data owner in its access control implementation.
The first step to implementing this in your own application is to instruct the controller to enable this rule. This is done by overwriting the filters() function.
class ContentController extends Controller {
public function filters() {
return array(
'accessControl'
);
}
public function accessRules() {
}
}
The 'accessControl' flag specifies that access control is applied for data management. The actual business rules are defined in the accessRules() function, and specifying the access control expression that will be evaluated to provide the desired control. And example of the function implementation is.
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('view'),
'users' => array('*'),
),
array('allow', // allow authenticated user to perform 'add' action
'actions' => array('add'),
'users' => array('#'),
),
array('allow', // allow only the owner to perform 'modify' 'delete' actions
'actions' => array('modify', 'delete'),
'expression' => array('ContentController','isMyRecord')
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The isMyRecord is a method that will be run that returns true or false to indicate if the action should be allowed.
public function isMyRecord(){
$content_id = $_GET["content_id"];
$person = Example::model()->findByPk($content_id);
if ($example->owner_id === Yii::app()->user->id)
return true;
else
return false;
}

In YII Framework, the Captcha doesn't show(conflict with accessControl)

In my site, only when I remove the filters() method, the captcha can show up. other time the captcha doesn't work. and my php gd support is enable.
now I am using a custome WebUser, if I remove it from config, the captcha also works well.
by the way, if I access user/captcha directly, it only show a picture box, but not content, maybe can not load the picture..
here are some code segments in my UserController:
actions();
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'minLength' => 4,
'maxLength' => 4,
'testLimit' => 99999
)
);
}
filters():
public function filters()
{
// return the filter configuration for this controller, e.g.:
return array(
"accessControl",
);
}
accessRulse():
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','login','signup'),
'expression'=>'Yii::app()->user->isGuest',
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('cpassword','info','logout'),
'expression'=>'!Yii::app()->user->isGuest',
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'users'=>array('admin#example.com'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
My WebUsers.php
<?php
// this file must be stored in:
// protected/components/WebUser.php
class WebUser extends CWebUser {
// Store model to not repeat query.
private $_model;
// Return first name.
// access it by Yii::app()->user->first_name
public function getDisplayName(){
$user = $this->loadUser(Yii::app()->user->id);
if($user)
return $user->display_name;
}
public function getGroupId(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->group_id;
}
// This is a function that checks the field 'role'
// in the User model to be equal to 1, that means it's admin
// access it by Yii::app()->user->isAdmin()
public function isAdmin(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1;
}
public function isGroupAAS(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1001;
}
// Load user model.
protected function loadUser($id=null)
{
if($this->_model===null)
{
if($id!==null)
$this->_model=User::model()->findByPk($id);
}
return $this->_model;
}
protected function afterLogin($fromCookie){
$user = $this->loadUser($this->id);
$user->last_login_ip = Yii::app()->request->userHostAddress;
$user->last_login_time = new CDbExpression('NOW()');
$user->save();
}
}
?>
In your controller, make sure this is defined.
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
Then, allow the action as following.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
and in the form,
<?php $this->widget('CCaptcha'); ?><br>
<?php echo CHtml::textField('captcha'); ?>
if this doesnt work, try this way..
<?php $this->widget('CCaptcha', array('captchaAction' => 'site/captcha')); ?>
to validate the capthca, define it as following in your action
$captcha=Yii::app()->getController()->createAction("captcha");
$code = $captcha->verifyCode;
if($code === $_REQUEST['captcha']){
}
Your code looks fine and compare your code with this answer or please provide the source code to take a look at.
Give access to your captcha showing method ie actions
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('actions'),
'users'=>array('*'),
),
I have tested your code with one of my SiteController & it's (captcha action) working fine under contact action. Could you kindly post full UserController code to review & identify the exact cause?
Just add 'captcha' in the actions array like this
public function accessRules()
{
return array(array('allow', // allow admin user to perform these actions
'actions'=>array('index','view','add','captcha'),
'users'=>array('admin'),
), ...

Categories