Not able to access application param from model

248 Views Asked by At

There are two models, User and UserProfile. When saving a new user, a single form is used to save data to both model/tables.Here's the controller action.

public function actionCreate($role)
{
    $User = new User;
    $UserProfile = new UserProfile;
    Yii::app()->params['u_role'] = $role;
    if(isset($_POST['User'], $_POST['UserProfile']))
        {
            $User->attributes=$_POST['User'];
            $UserProfile->attributes=$_POST['UserProfile'];
            $valid=$User->validate(); 
            if($valid)  
                {
                    if($User->save(false))  
                    {
                        $UserProfile->user_id = $User->id;  
                        if ($UserProfile->save()) 
                            {
                                $model=User::model()->with('userProfiles')->findByPk($User->id);
                                $this->redirect(array('manage/list'));
                            }
                    }
                }
        }
        $this->render('create', array(
            'User'=>$User,
            'UserProfile'=>$UserProfile,
        ));     
}

The model, relations,views and the create action seems to be working fine, I can save the new user with data to both the tables. The problem is there's a field in the User model, 'role' which is not supplied from the form but pre-set, depending on the param passed to the controller action ($role). I am setting this $role value as an application param in the create action itself

Yii::app()->params['u_role'] = $role;

And in the User model, I am using a function to determine the value of the field based on the value of this app param. Here's the function,

public function fixUrole()
    {
        $returnUrole;
        if (Yii::app()->params['u_role']=='adm')
        {
            $returnUrole=1;

        }
        else if (Yii::app()->params['u_role']=='mgr')
        {
            $returnUrole=2;
        }
        return $returnUrole;
    }

Which is called from beforeValidate(), like below.

$this->role = $this->fixUrole();

Problem is, there's something going wrong in getting the value by using application params. If I hardcode a value in the function fixUrole(), it saves/works correctly. But otherwise the function return 'blank'. What is going wrong here? Also, I am not entirely sure if I am doing what I want in the correct way, so is there any better way to do this?

Edit:Here's the config main.php

<?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'MY APP NAME',

    // preloading 'log' component
    'preload'=>array(
        'log',
        'bootstrap'),

    // autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
    ),

    'modules'=>array(
        // uncomment the following to enable the Gii tool
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'enter',
            // If removed, Gii defaults to localhost only. Edit carefully to taste.
            'ipFilters'=>array('127.0.0.1','::1'),
            'generatorPaths' => array(
            'bootstrap.gii'
        ),
        ),/**/
    ),

    // application components
    'components'=>array(
        'user'=>array(
            //'allowAutoLogin'=>true,
              'class' => 'WebUser',
        ),
        'bootstrap' => array(
        'class' => 'ext.bootstrap.components.Bootstrap',
        'responsiveCss' => true,
        ),

        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=testdb1',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ),
        'errorHandler'=>array(
            // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
                // uncomment the following to show log messages on web pages

                array(
                    'class'=>'CWebLogRoute',
                ),
                /**/
            ),
        ),
    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'[email protected]',
         'u_role'=>'', 
    ),
);
2

There are 2 best solutions below

0
On

You can try Yii::app()->session('u_role') and this tutorial may help you also.

2
On

I don't think you can set/change the params during runtime (in your controller).

Note that this method is for static configuration parameters - it's doesn't provide for dynamic parameters changed (or persisted) at runtime, or per-user settings.

Do check this article for proper usage: http://www.yiiframework.com/wiki/126/setting-and-getting-systemwide-static-parameters/