Yii Framework Forum: [SOLVED] Chapter 8, page 210 Add user to project - Yii Framework Forum

Jump to content

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

[SOLVED] Chapter 8, page 210 Add user to project

#1 User is offline   pantopita 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 5
  • Joined: 19-September 10

Posted 01 October 2010 - 05:12 AM

Hello everybody. recently I switched from CakePHP to Yii and I must say I'm more than satisfied with Yii.
I followed the book until chapter 8 page 210 and I'm stuck there. If someone can help it will be apreciated.
On page 210 we have snippet of code so we can access form for adding user to project

The following line was 
added to the project show.php view fle's list of link options:
[<?php echo CHtml::link('Add User To Project',array('adduser','id'=>$m
odel->projectId)); ?>]


My question is were exactly to put link above in menu array. I folowed instruction till en of this chapter and
when I try to access page to add user to project I got the message:

PHP Error
Description

Missing argument 1 for ProjectController::loadModel(), called in C:\htdocs\trackstar\protected\controllers\ProjectController.php on line 192 and defined
Source File

C:\htdocs\trackstar\protected\controllers\ProjectController.php(168)

00156:             $model->attributes=$_GET['Project'];
00157: 
00158:         $this->render('admin',array(
00159:             'model'=>$model,
00160:         ));
00161:     }
00162: 
00163:     /**
00164:      * Returns the data model based on the primary key given in the GET variable.
00165:      * If the data model is not found, an HTTP exception will be raised.
00166:      * @param integer the ID of the model to be loaded
00167:      */
00168: public function loadModel($id)
00169:     {
00170:         $model=Project::model()->findByPk((int)$id);
00171:         if($model===null)
00172:             throw new CHttpException(404,'The requested page does not exist.');
00173:         return $model;
00174:     }
00175: 
00176:     /**
00177:      * Performs the AJAX validation.
00178:      * @param CModel the model to be validated
00179:      */
00180:     protected function performAjaxValidation($model)



Here is my ProjectController.php

<?php

class ProjectController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * 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', 'adduser'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	       
        $issueDataProvider = new CActiveDataProvider('Issue', array(
            'criteria' => array(
                'condition' =>'project_id=:projectId',
                'params' => array(':projectId' => $this->loadModel($id)->id),
                ),
                'pagination' => array(
                    'pageSize' => 1,
                    ),
                    ));
       
		$this->render('view',array(
			'model'=>$this->loadModel($id),
            'issueDataProvider' => $issueDataProvider,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Project;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * 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);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Project');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Project('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Project']))
			$model->attributes=$_GET['Project'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Project::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='project-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
    
    public function actionAdduser() 
    {
         
         $project = $this->loadModel();
		if(!Yii::app()->user->checkAccess('createUser', array('project'=>$project)))
	    {
			throw new CHttpException(403,'You are not authorized to per-form this action.');
		} 
	    $form=new ProjectUserForm; 
	    // collect user input data
		if(isset($_POST['ProjectUserForm']))
		{
			$form->attributes=$_POST['ProjectUserForm'];
			$form->project = $project;
			// validate user input and set a sucessfull flassh message if valid   
			if($form->validate())  
			{
				Yii::app()->user->setFlash('success',$form->username . " has been added to the project." ); 
				$form=new ProjectUserForm;
			}
		}
		// display the add user form
		$users = User::model()->findAll();
		$usernames=array();
		foreach($users as $user)
		{
			$usernames[]=$user->username;
		}
		$form->project = $project;
		$this->render('adduser',array('model'=>$form, 'usernames'=>$usernames));
         
}


}


And protected/project/view/view.php file

<?php
$this->breadcrumbs=array(
	'Projects'=>array('index'),
	$model->name,
);

$this->menu=array(
	array('label'=>'List Project', 'url'=>array('index')),
	array('label'=>'Create Project', 'url'=>array('create')),
	array('label'=>'Update Project', 'url'=>array('update', 'id'=>$model->id)),
	array('label'=>'Delete Project', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage Project', 'url'=>array('admin')),
        array('label'=>'Create Issue', 'url'=>array('issue/create', 'pid'=>$model->id)),
        
);
	
 


?>


<h1>View Project #<?php echo $model->id; ?></h1>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(
		'id',
		'name',
		'description',
		'create_time',
		'create_user_id',
		'update_time',
		'update_user_id',
	),
)); 
?>
<br />

<h1>Project Issue</h1>

<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider' => $issueDataProvider,
    'itemView' => '/issue/_view',
    )); ?>


0

#2 User is offline   jefftulsa 

  • Advanced Member
  • Yii
  • Group: Yii Dev Team
  • Posts: 168
  • Joined: 06-October 08
  • Location:Austin, TX

Posted 01 October 2010 - 08:35 AM

Please read through this other thread and see if the information contained there is of any help:

http://www.yiiframew...ntroller-issue/
0

#3 User is offline   pantopita 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 5
  • Joined: 19-September 10

Posted 03 October 2010 - 04:04 AM

I'm sorry for my late replay. Thank for your answer. I followed instructions in post you give me and I were able to get past my original issue (It's important to say that I'm on Yii 1.1.4 ).

Now I have following error:

Description

Object of class CAutoComplete could not be converted to string
Source File

C:\htdocs\trackstar\protected\views\project\adduser.php(34)

00022:     
00023:     <p class="note">Fields with <span class="required">*</span>are required.</p>
00024:     
00025:     <div class="row">
00026:     
00027:         <?php echo $form->labelEx($model, 'username'); ?>
00028:         <?php echo $this->widget('CAutoComplete', array(
00029:                 'model' => $model,
00030:                 'attribute' => 'username',
00031:                 'data' => $usernames,
00032:                 'multiple' => false,
00033:                 'htmlOptions' => array('size' => 25),
00034: )); ?>
00035:                 
00036:         <?php echo $form->error($model, 'username'); ?>
00037:     
00038:     </div>
00039:     
00040:     <div class="row">
00041:         <?php echo $form->labelEx($model, 'role'); ?>
00042:         <?php echo $form->dropDownList($model, 'role', Project::getUserRoleOptions()); ?>
00043:         <?php echo $form->error($model, 'role'); ?>
00044:     </div>
00045:     
00046:     <div class="row buttons">




If anyone have idea what is problem please let me know. Thanks in advance
0

#4 User is offline   thammu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 55
  • Joined: 04-October 09

Posted 19 December 2010 - 03:52 AM

I got stuck at the same point. It's a serious error in the book, as there is no show.php file in the project.

What I did was to add the following code in .../protected/views/project/view.php file:


$this->menu=array(
array('label'=>'List Project', 'url'=>array('index')),
array('label'=>'Create Project', 'url'=>array('create')),
array('label'=>'Update Project', 'url'=>array('update', 'id'=>$model->id)),
array('label'=>'Delete Project', 'url'=>'#',
'linkOptions'=>array('submit'=>array('delete',
'id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Project', 'url'=>array('admin')),
array('label'=>'Create Issue', 'url'=>array('issue/create','pid'=>$model->id)),
array('label'=>'Add User To Project', 'url'=>array('adduser', 'id'=>$model->id)),
);

The last line "array('label'=>'Add User To Project', 'url'=>array('adduser', 'id'=>$model->id)), " adds a new link to the right. Clicking this takes you to the page displayed on Page 210.
0

#5 User is offline   chuntley 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 67
  • Joined: 23-April 10

Posted 20 December 2010 - 01:14 PM

I believe this issue is because of the difference of versions we are using. To fix this, go to the bottom of your ProjectController.php file and change:

$project = $this->loadModel();


to

$project = $this->loadModel($id);

0

#6 User is offline   Alexandre Carmo 

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

Posted 15 January 2011 - 02:42 PM

Hello friends.

I have the same problem on page 210 (It's important to say that I'm on Yii 1.1.4 ).
I saw this post: Chapter 6 But not solved my problem
Here is my project controller:

<?php

class ProjectController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
       
private $_model;


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * 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','adduser'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	/*public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}*/
        public function actionView($id)
        {
           
                $issueDataProvider = new CActiveDataProvider('Issue', array(
                                'criteria' => array(
                                        'condition' => 'project_id=:projectId',
                                        'params'=> array(':projectId'=>$this->loadModel($id)->id),
                                ),
                                'pagination'=>array(
                                        'pageSize' => 1,
                                ),
                        ));


                $this->render('view', array(
                         'model' => $this->loadModel($id),
                        'issueDataProvider' => $issueDataProvider,
                ));
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Project;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * 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);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Project');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Project('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Project']))
			$model->attributes=$_GET['Project'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Project::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='project-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

        public function actionAdduser()
        {
            $form=new ProjectUserForm();
            $project = $this->loadModel($id);
            //collect user input data
            if(isset($_POST['ProjectUserForm']))
            {
                $form->attributes=$_POST['ProjectUserForm'];
                $form->project = $project;
                //validate user input and set a sucessfull flassh message if valid
                if($form->validate())
                {
                    Yii::app()->user->setFlash('success',$form->username. "has been added to the project");
                    $form=new ProjectUserForm();
                }
            }
            //display the add user form
            $user = User::model()->findAll();
            $usernames=array();
            foreach($users as $user)
            {
                $usernames[]=$user->username;
            }
            $form->project = $project;
            $this->render('adduser',array('model'=>$form,'usernames'=>$usernames));
        }
}



here is the view:
<?php
$this->breadcrumbs=array(
	'Projects'=>array('index'),
	$model->name,
);

$this->menu=array(
	array('label'=>'List Project', 'url'=>array('index')),
	array('label'=>'Create Project', 'url'=>array('create')),
	array('label'=>'Update Project', 'url'=>array('update', 'id'=>$model->id)),
	array('label'=>'Delete Project', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage Project', 'url'=>array('admin')),
        array('label'=>'Create Issue', 'url'=>array('issue/create','pid'=>$model->id)), //a varia pid siginfica project ID
        array('label'=>'Add User To Project', 'url'=>array('adduser', 'id'=>$model->id)),
);
?>

<h1>View Project #<?php echo $model->id; ?></h1>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(
		'id',
		'name',
		'description',
		'create_time',
		'create_user_id',
		'update_time',
		'update_user_id',
	),
)); ?>
<br />
<h1>Project Issues</h1>

<?php
$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$issueDataProvider,
    'itemView'=>'/issue/_view',
));
?>



here is the error:

Quote

Description

Undefined variable: id
Source File

/var/www/trackstar/protected/controllers/ProjectController.php(207)

00195: protected function performAjaxValidation($model)
00196: {
00197: if(isset($_POST['ajax']) && $_POST['ajax']==='project-form')
00198: {
00199: echo CActiveForm::validate($model);
00200: Yii::app()->end();
00201: }
00202: }
00203:
00204: public function actionAdduser()
00205: {
00206: $form=new ProjectUserForm();
00207: $project = $this->loadModel($id);
00208: //collect user input data
00209: if(isset($_POST['ProjectUserForm']))
00210: {
00211: $form->attributes=$_POST['ProjectUserForm'];
00212: $form->project = $project;
00213: //validate user input and set a sucessfull flassh message if valid
00214: if($form->validate())
00215: {
00216: Yii::app()->user->setFlash('success',$form->username. "has been added to the project");
00217: $form=new ProjectUserForm();
00218: }
00219: }

Stack Trace

#0 /var/www/yii/framework/web/actions/CInlineAction.php(50): ProjectController->actionAdduser()
#1 /var/www/yii/framework/web/CController.php(300): CInlineAction->run()
#2 /var/www/yii/framework/web/filters/CFilterChain.php(133): ProjectController->runAction()
#3 /var/www/yii/framework/web/filters/CFilter.php(41): CFilterChain->run()
#4 /var/www/yii/framework/web/CController.php(1049): CAccessControlFilter->filter()
#5 /var/www/yii/framework/web/filters/CInlineFilter.php(59): ProjectController->filterAccessControl()
#6 /var/www/yii/framework/web/filters/CFilterChain.php(130): CInlineFilter->filter()
#7 /var/www/yii/framework/web/CController.php(283): CFilterChain->run()
#8 /var/www/yii/framework/web/CController.php(257): ProjectController->runActionWithFilters()
#9 /var/www/yii/framework/web/CWebApplication.php(324): ProjectController->run()
#10 /var/www/yii/framework/web/CWebApplication.php(121): CWebApplication->runController()
#11 /var/www/yii/framework/base/CApplication.php(135): CWebApplication->processRequest()
#12 /var/www/trackstar/index.php(13): CWebApplication->run()


In the method actionAdduser() I change this:
$project = $this->loadModel();

to
$project = $this->loadModel($id);


But not solved the problem. Where is the error?
0

#7 User is offline   yiiter 

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

Posted 15 January 2011 - 03:37 PM

when you call index.php?r=project/addUser&id=1 you are calling the addUser function with the Id number 1. So essentially you are calling addUser(1) but in your controller the actionAddUser is not expecting a parameter therefore it is complaining. Go ahead and make the changes to your code and that should fix your problem...
public function actionAdduser($id)	
 {
    $project = $this->loadModel($id);
...
..
.
 }
...
..
.
public function loadModel($id)
 {
...
..
.
 }

0

#8 User is offline   Alexandre Carmo 

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

Posted 15 January 2011 - 04:07 PM

Thanks for help. I get it. This solved my problem
0

#9 User is offline   st3v3 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 28-February 11

Posted 28 February 2011 - 03:41 AM

I am having a similar issue. When I try to access index.php?r=project/adduser&id=1 -- I just get a blank page. No php error. No errors in the application.log either.

ProjectController.php

<?php

class ProjectController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

  /**
   * @var CActiveRecord the currently loaded data movel instance
   */
  private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * 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','adduser'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
    $issueDataProvider = new CActiveDataProvider('Issue', array(
      'criteria'  => array(
        'condition' => 'project_id=:projectId',
        'params' => array(':projectId' => $this->loadModel()->id),
      ),
      'pagination' => array(
        'pageSize' => 1,
      ),
    ));

		$this->render('view',array(
			'model'=>$this->loadModel($id),
      'issueDataProvider'=>$issueDataProvider,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Project;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * 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);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Project']))
		{
			$model->attributes=$_POST['Project'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Project');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Project('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Project']))
			$model->attributes=$_GET['Project'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
  public function loadModel()
    {
      if($this->_model===null)
      {
        if(isset($_GET['id']))
          $this->_model=Project::model()->findbyPk($_GET['id']);
        if($this->_model===null)
          throw new CHttpException(404,'The requested page does not exist.');
      }
      return $this->_model;
    }


	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='project-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

  /**
   * Handles display of the form for adding a new user to a project 
   * (ProjectUserForm)
   */
  public function actionAdduser()
  {
    $form = new ProjectUserForm;
    $project = $this->loadModel();
    // collect user input data
    if(isset($_POST['ProjectUserForm']))
    {
      $form->attributes = $_POST['ProjectUserForm'];
      $form->project = $project;
      // validate user input and set a successful flash message if valid
      if($form->validate())
      {
        Yii::app()->user->setFlash('success', $form->username . "has been added to the project.");
        $form = new ProjectUserForm;
      }
    }
    // display the add user form 
    $users = User::model()->findAll();
    $usernames = array();
    foreach($users as $user)
    {
      $usernames[] = $user->username;
    }
    $form->project = $project;
    $this->render('adduser', array('model' => $form, 'usernames' => $usernames));
  }
}


adduser.php

<?php
$this->pageTitle = Yii::app()->name . ' - Add User to Project';
$this->breadcrumbs = array(
  $model->project->name => array('view', 'id'=>$model->project->id),
  'Add User',
);
$this->menu = array(
  array(
    'label' => 'Back to Project',
    'url'->array('view', 'id'=>$model->project->id)
  ),
);
?>

<h1>Add User To <?php echo $model->project->name; ?></h1>

<?php if(Yii::app()->user->hasFlash('success')): ?>
<div class="successMessage">
  <?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>

<div class="form">
<?php $form = $this->beginWidget('CActiveForm'); ?>

  <p class="note">Fields with <span class="required">*</span> are required.</p>

  <div class="row">
    <?php echo $form->labelEx($model, 'username'); ?>
    <?php $this->widget('CAutoComplete', array(
      'model' => $model,
      'attribute' => 'username',
      'data' => $usernames,
      'multiple' => false,
      'htmlOptions' => array('size' => 25),
    )); ?>
    <?php echo $form->error($model, 'username'); ?>
  </div>

  <div class="row">
    <?php echo $form->labelEx($model, 'role'); ?>
    <?php echo $form->dropDownList($model, 'role', Project::getUserRoleOptions()); ?>
    <?php echo $form->error($model, 'role'); ?>
  </div>

  <div class="row buttons">
    <?php echo CHtml::submitButton('Add User'); ?>
  </div>

<?php $this->endWidget(); ?>
</div>


I'm using Yii 1.4 but have made it this far. Can anyone help? Tough to debug when I'm not getting any errors.
0

#10 User is offline   stutteringp0et 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 9
  • Joined: 14-February 11

Posted 01 March 2011 - 10:57 PM

You should tail your apache error log. When Yii doesn't give any output (errors or otherwise) I look in my apache error log for a hint. 99.99% of the time, there is enough of a hint that I can find the problem (mostly missing punctuation)
0

#11 User is offline   EmilioMedia 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 14-October 12

Posted 17 October 2012 - 07:02 PM

View Postthammu, on 19 December 2010 - 03:52 AM, said:

I got stuck at the same point. It's a serious error in the book, as there is no show.php file in the project.

What I did was to add the following code in .../protected/views/project/view.php file:


$this->menu=array(
array('label'=>'List Project', 'url'=>array('index')),
array('label'=>'Create Project', 'url'=>array('create')),
array('label'=>'Update Project', 'url'=>array('update', 'id'=>$model->id)),
array('label'=>'Delete Project', 'url'=>'#',
'linkOptions'=>array('submit'=>array('delete',
'id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Project', 'url'=>array('admin')),
array('label'=>'Create Issue', 'url'=>array('issue/create','pid'=>$model->id)),
array('label'=>'Add User To Project', 'url'=>array('adduser', 'id'=>$model->id)),
);

The last line "array('label'=>'Add User To Project', 'url'=>array('adduser', 'id'=>$model->id)), " adds a new link to the right. Clicking this takes you to the page displayed on Page 210.

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