Yii Framework Forum: Error on database - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Error on database Chapter 8 Trying to get property of non-object

#1 User is offline   Alexandre Carmo 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 154
  • Joined: 22-December 09
  • Location:Brazil - SP

Posted 15 January 2011 - 04:40 PM

Hello friends

I have a error when I Submit information to save on database, this the error:

Quote

Description

Trying to get property of non-object
Source File

/var/www/trackstar/protected/models/Project.php(168)

00156: {
00157: return CHtml::listData(Yii::app()->authManager->getRoles(), 'name', 'name');
00158: }
00159:
00160: /*
00161: * makes as associantion betwaeen a user and a the project
00162: */
00163: public function associateUserToProject($user)
00164: {
00165: $sql = "insert into tbl_project_user_assignment(project_id, user_id)values(:projectId, :userId)";
00166: $command = Yii::app()->db->createCommand($sql);
00167: $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
00168: $command->bindValue(":userId", $user->id, PDO::PARAM_INT);
00169: return $command->execute();
00170: }
00171:
00172: /*
00173: * determines whether or not a user is already part of a project
00174: */
00175: public function isUserInProject($user)
00176: {
00177: $sql = "select user_id from tbl_project_user_assignment where project_id=:projectId and user_id=:userId";
00178: $command = Yii::app()->db->createCommand($sql);
00179: $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
00180: $command->bindValue(":userId", $user->id, PDO::PARAM_INT);

Stack Trace

#0 /var/www/trackstar/protected/models/ProjectUserForm.php(61): Project->associateUserToProject()
#1 /var/www/yii/framework/validators/CInlineValidator.php(39): ProjectUserForm->verify()
#2 /var/www/yii/framework/validators/CValidator.php(184): CInlineValidator->validateAttribute()
#3 /var/www/yii/framework/base/CModel.php(150): CInlineValidator->validate()
#4 /var/www/trackstar/protected/controllers/ProjectController.php(211): ProjectUserForm->validate()
#5 unknown(0): ProjectController->actionAdduser()
#6 /var/www/yii/framework/web/actions/CInlineAction.php(47): ReflectionMethod->invokeArgs()
#7 /var/www/yii/framework/web/CController.php(300): CInlineAction->run()
#8 /var/www/yii/framework/web/filters/CFilterChain.php(133): ProjectController->runAction()
#9 /var/www/yii/framework/web/filters/CFilter.php(41): CFilterChain->run()
#10 /var/www/yii/framework/web/CController.php(1049): CAccessControlFilter->filter()
#11 /var/www/yii/framework/web/filters/CInlineFilter.php(59): ProjectController->filterAccessControl()
#12 /var/www/yii/framework/web/filters/CFilterChain.php(130): CInlineFilter->filter()
#13 /var/www/yii/framework/web/CController.php(283): CFilterChain->run()
#14 /var/www/yii/framework/web/CController.php(257): ProjectController->runActionWithFilters()
#15 /var/www/yii/framework/web/CWebApplication.php(324): ProjectController->run()
#16 /var/www/yii/framework/web/CWebApplication.php(121): CWebApplication->runController()
#17 /var/www/yii/framework/base/CApplication.php(135): CWebApplication->processRequest()
#18 /var/www/trackstar/index.php(13): CWebApplication->run()


This is the class Project:
<?php

/**
 * This is the model class for table "tbl_project".
 *
 * The followings are the available columns in table 'tbl_project':
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property string $create_time
 * @property integer $create_user_id
 * @property string $update_time
 * @property integer $update_user_id
 *
 * The followings are the available model relations:
 */
class Project extends TrackStarActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Project the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_project';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>128),
			array('description, create_time, update_time', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, description, create_time, create_user_id, update_time, update_user_id', 'safe', 'on'=>'search'),
                        array('name, description','required'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	
        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(
			'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),
			'users' => array(self::MANY_MANY, 'User', 'tbl_project_user_assignment(project_id, user_id)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'description' => 'Description',
			'create_time' => 'Create Time',
			'create_user_id' => 'Create User',
			'update_time' => 'Update Time',
			'update_user_id' => 'Update User',
		);
	}

	/**
	 * 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()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('create_user_id',$this->create_user_id);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('update_user_id',$this->update_user_id);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

       
        public function getUserOptions()
        {
            $usersArray = CHtml::listData($this->users, 'id', 'username');
            return $usersArray;

        }

        /*
         * creartes an associantion between the project, the user and the user's role within the project
         */
        public function associateUserToRole($role,$userId)
        {
            $sql = "insert into tbl_project_user_role (project_id, user_id, role)values(:projectId, :userId, :role)";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", $userId, PDO::PARAM_INT);
            $command->bindValue(":role", $role, PDO::PARAM_STR);
            return $command->execute();
        }
        public function removeUserFromRole($role,$userId)
        {
            $sql = "delete from tbl_project_user_role where project_id=:projectId and user_id=:userId and role=:role";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", $userId, PDO::PARAM_INT);
            $command->bindValue(":role", $role, PDO::PARAM_STR);
            return $command->execute();
        }
        /*
         * @return boolean whether or not the current user is in the specified role within the context of this project
         *
         */

        public function isUserInRole($role)
        {
            $sql = "select role from tbl_project_user_role where project_id=:projectId and user_id=:userId and role=:role";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", Yii::app()->user->getId(), PDO::PARAM_INT);
            $command->bindValue(":role", $role, PDO::PARAM_STR);
            return $command->execute() == 1 ? true : false;
        }

        /*
         * returns an array of available roles in which a user can be placed when being added to a project
         */
        public static function getUserRoleOptions()
        {
            return CHtml::listData(Yii::app()->authManager->getRoles(), 'name', 'name');
        }

        /*
         * makes as associantion betwaeen a user and a the project
         */
        public function associateUserToProject($user)
        {
            $sql = "insert into tbl_project_user_assignment(project_id, user_id)values(:projectId, :userId)";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", $user->id, PDO::PARAM_INT);
            return $command->execute();
        }

        /*
         * determines whether or not a user is already part of a project
         */
        public function isUserInProject($user)
        {
            $sql = "select user_id from tbl_project_user_assignment where project_id=:projectId and user_id=:userId";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", $user->id, PDO::PARAM_INT);
            return $command->execute()==1 ? true : false;
        }
}


This is the class ProjectUserForm:
<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProjectUserForm
 *
 * @author alexandre
 */
class ProjectUserForm extends CFormModel
{
    /*
     * @var stgring usename of the user being added to the project
     */
    public $username;
    /*
     * var string the role to which the usedr will be associated
     */
    public $role;

    /*
     * @var object as instance of the project ar model class
     */
    public $project;

    /*
     * declares the validation rules
     * The rules state that username and password are required, and password needs to be authenticated using the verify() method
     */

    public function rules()
    {
        return array(
            //username and password are required
            array('username, role', 'required'),
            //password needs to be authenticated
            array('username', 'exist', 'className'=>'User'),
            array('username', 'verify'),
        );
    }

    /*
     * Authenticates the existence of the user in the system.
     * If valid, it will also make the association between the user, role and project
     * This is the 'verify' validator as declared in rules()
     */
    public function verify($attribute,$params)
    {
        if(!$this->hasErrors()) // we only want to authenticate when no other input erros are present
        {
            $user = User::model()->findByAttributes(array('username'=>$this->username));
            if($this->project->isUserInProject($user))
            {
                $this->addError('username', 'This user name has already been added to the project');
            }
            else
            {
                $this->project->associateUserToProject($user);
                $this->project->associateUserToProject($this->role, $user->id);
                $auth = Yii::app()->authManager;
                $bizRule='return isset($params["project"]) && $params["project"]->isUserInRole("'.$this->role.'");';
                $auth->assign($this->role,$user->id, $bizRule);
            }
        }
    }
}
?>
This is the line 168: [b]$command->bindValue(":userId", $user->id, PDO::PARAM_INT);[/b] But I believe is correct.

where I went wrong? Why?

0

#2 User is offline   yiiter 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 5
  • Joined: 03-January 11

Posted 15 January 2011 - 07:30 PM

in your verify() function inside ProjectUserForm class you are calling associateUserToProject twice, the second call should be associateUserToRole... like this:
public function verify($attribute,$params)
{
...
    else  
    {
      $this->project->associateUserToProject($user);  
      $this->project->associateUserToRole($this->role, $user->id); 
...

0

#3 User is offline   Alexandre Carmo 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 154
  • Joined: 22-December 09
  • Location:Brazil - SP

Posted 15 January 2011 - 08:06 PM

Thanks for help, I need to pay atention. I read this code several times and not noticed it

Thanks friend
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users