如何在Yii1中创建时在输入表单字段中显示登录的用户名


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

我有一个表格,可以上传他/她自己的简历文件(docx/pdf)。我有一个下拉菜单"员工名称",从其中只显示在列表中的登录用户名。但是现在我想在from输入字段中显示登录用户名。我怎么能做到呢?谁能给我代码例子。因为我很不擅长编码。下面是我的from代码:

        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'),
                )
            )
        );
        }

用户名输入字段登录用户名

我就是这么做的:

首先,在/protected/components中,我设置一个会话变量来存储登录的用户名:
public function authenticate()
{
  $user = Users::model()->find('user = ? ', array($this->username)); //user entered when trying to log in
...
}

如果认证正确:

public function authenticate()
{
 ...
  $session = new CHttpSession;
  $session->open(); //session_start
  $session['user'] = $user; //$user is the logged-in username
 ...
}

在控制器操作中创建:

public function actionCreate(){
  $session = new CHttpSession;  
  $session->open();
  $user = $session['user'];
  ...
  $this->render('create',array(
    'user'=>$user,
    'model'=>$model,
    ...
  ));
}

In view(例如In/_form):

...
$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
...

这是假设你在你的模型中有一个名为'user'的属性。如果没有,那么,在/model中创建一个辅助属性'user',以便在/_form中使用该属性:

class YourModel extends CActiveRecord
{
  public $user; //$variable used to set the logged-in username
 ...
}