2017-02-16 172 views
1

我是新的StackOverflow,也是新的使用框架Yii 2,我需要獲取會話數據,並使用_form.php從一個名爲Planficacion的視圖中創建和更新表單,但是當我嘗試使用此以下形式的代碼行:如何獲取會話數據並放入Yii 2中的dropDownList?

<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?> 

返回此錯誤:PHP警告 - yii \ base \ ErrorException。爲的foreach()

我需要的「nombreProfesor」從一個叫PROFESOR模型中的價值提供了無效的參數,都PlanificacionPROFESOR的關係是「rutProfesor」和我想在dropDownList中僅顯示實際會話的'nombreProfesor'

有從代碼:

PROFESOR模型Profesor.php

<?php 

namespace common\models; 

use Yii; 

class Profesor extends \yii\db\ActiveRecord 
{ 
    /** 
    * @inheritdoc 
    */ 
    public static function tableName() 
    { 
     return 'profesor'; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function rules() 
    { 
     return [ 
      [['rutProfesor'], 'required'], 
      [['nombreProfesor', 'apellidoProfesor', 'escuelaProfesor'], 'string', 'max' => 45], 
      [['rutProfesor', 'claveProfesor'], 'string', 'max' => 15], 
      [['rol'], 'string', 'max' => 2], 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function attributeLabels() 
    { 
     return [ 
      'nombreProfesor' => 'Nombre Profesor', 
      'apellidoProfesor' => 'Apellido Profesor', 
      'escuelaProfesor' => 'Escuela', 
      'rutProfesor' => 'Rut', 
      'claveProfesor' => 'Clave Profesor', 
      'rol' => 'Rol', 
     ]; 
    } 

    /** 
    * @return \yii\db\ActiveQuery 
    */ 
    public function getPlanificacions() 
    { 
     return $this->hasMany(Planificacion::className(), ['rutProfesor' => 'rutProfesor']); 
    } 
} 

Planificacion模型planificacion.php

<?php 

namespace common\models; 

use Yii; 

class Planificacion extends \yii\db\ActiveRecord 
{ 
    /** 
    * @inheritdoc 
    */ 
    public static function tableName() 
    { 
     return 'planificacion'; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function rules() 
    { 
     return [ 
      [['fecha', 'fechaRevision', 'fechaPlanificacion'], 'safe'], 
      [['objetivosPlanificacion', 'actividad1', 'actividad2', 'actividad3', 'actividad4', 'obsActividad1', 'obsActividad2', 'obsActividad3', 'obsActividad4', 'contenidoActividad1', 'contenidoActividad2', 'contenidoActividad3', 'contenidoActividad4'], 'string'], 
      [['rutProfesor'], 'string', 'max' => 15], 
      [['nombreSesion', 'recursosUtilizadosPlanificacion', 'estadoActividad1', 'estadoActividad2', 'estadoActividad3', 'estadoActividad4', 'evalActividad1', 'evalActividad2', 'evalActividad3', 'evalActividad4', 'nombreSupervisor', 'asistencia'], 'string', 'max' => 255], 
      [['estado', 'rutSupervisor'], 'string', 'max' => 30], 
      [['rutProfesor'], 'exist', 'skipOnError' => true, 'targetClass' => Profesor::className(), 'targetAttribute' => ['rutProfesor' => 'rutProfesor']], 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function attributeLabels() 
    { 
     return [ 
      'idPlanificacion' => 'Id Planificacion', 
      'rutProfesor' => 'Nombre Profesor', 
      'fecha' => 'Fecha', 
      'nombreSesion' => 'Nombre Sesion', 
      'objetivosPlanificacion' => 'Objetivos Planificacion', 
      'recursosUtilizadosPlanificacion' => 'Recursos Utilizados Planificacion', 
      'actividad1' => 'Actividad1', 
      'actividad2' => 'Actividad2', 
      'actividad3' => 'Actividad3', 
      'actividad4' => 'Actividad4', 
      'estadoActividad1' => 'Estado Actividad1', 
      'estadoActividad2' => 'Estado Actividad2', 
      'estadoActividad3' => 'Estado Actividad3', 
      'estadoActividad4' => 'Estado Actividad4', 
      'obsActividad1' => 'Obs Actividad1', 
      'obsActividad2' => 'Obs Actividad2', 
      'obsActividad3' => 'Obs Actividad3', 
      'obsActividad4' => 'Obs Actividad4', 
      'contenidoActividad1' => 'Contenido Actividad1', 
      'contenidoActividad2' => 'Contenido Actividad2', 
      'contenidoActividad3' => 'Contenido Actividad3', 
      'contenidoActividad4' => 'Contenido Actividad4', 
      'evalActividad1' => 'Eval Actividad1', 
      'evalActividad2' => 'Eval Actividad2', 
      'evalActividad3' => 'Eval Actividad3', 
      'evalActividad4' => 'Eval Actividad4', 
      'estado' => 'Estado', 
      'fechaRevision' => 'Fecha Revision', 
      'rutSupervisor' => 'Rut Supervisor', 
      'fechaPlanificacion' => 'Fecha Planificacion', 
      'nombreSupervisor' => 'Nombre Supervisor', 
      'asistencia' => 'Asistencia', 
     ]; 
    } 

    /** 
    * @return \yii\db\ActiveQuery 
    */ 
    public function getAsistencias() 
    { 
     return $this->hasMany(Asistencia::className(), ['idPlanificacion' => 'idPlanificacion']); 
    } 

    /** 
    * @return \yii\db\ActiveQuery 
    */ 
    public function getRutProfesor0() 
    { 
     return $this->hasOne(Profesor::className(), ['rutProfesor' => 'rutProfesor']); 
    } 
} 

用戶模型User.php

<?php 
namespace common\models; 

use Yii; 
use yii\base\NotSupportedException; 
use yii\behaviors\TimestampBehavior; 
use yii\db\ActiveRecord; 
use yii\helpers\Security; 
use yii\web\IdentityInterface; 

class User extends ActiveRecord implements IdentityInterface 
{ 
    const STATUS_DELETED = 0; 
    const STATUS_ACTIVE = 10; 

    const ROLE_SUPERVISOR = 1; 
    const ROL_PROFESOR = 2; 

    public $authKey; 

    /** @inheritdoc 
    /** 
    */ 
    public static function tableName() 
    { 
     return 'profesor'; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function behaviors() 
    { 
     return [ 
      TimestampBehavior::className(), 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function rules() 
    { 
     return [ 
      ['status', 'default', 'value' => self::STATUS_ACTIVE], 
      ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]], 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public static function findIdentity($rutProfesor) 
    { 
     return static::findOne(['rutProfesor' => $rutProfesor]); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public static function findIdentityByAccessToken($token, $type = null) 
    { 
     throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); 
    } 

    /** 
    * Finds user by username 
    * 
    * @param string $username 
    * @return static|null 
    */ 
    public static function findByUsername($rutProfesor) 
    { 
     return static::findOne(['rutProfesor' => $rutProfesor]); 
    } 

    /** 
    * Finds user by password reset token 
    * 
    * @param string $token password reset token 
    * @return static|null 
    */ 
    public static function findByPasswordResetToken($token) 
    { 
     if (!static::isPasswordResetTokenValid($token)) { 
      return null; 
     } 

     return static::findOne([ 
      'password_reset_token' => $token, 
      'status' => self::STATUS_ACTIVE, 
     ]); 
    } 

    /** 
    * Finds out if password reset token is valid 
    * 
    * @param string $token password reset token 
    * @return bool 
    */ 
    public static function isPasswordResetTokenValid($token) 
    { 
     if (empty($token)) { 
      return false; 
     } 

     $timestamp = (int) substr($token, strrpos($token, '_') + 1); 
     $expire = Yii::$app->params['user.passwordResetTokenExpire']; 
     return $timestamp + $expire >= time(); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function getId() 
    { 
     return $this->getPrimaryKey(); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function getAuthKey() 
    { 
     return $this->authKey; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function validateAuthKey($authKey) 
    { 
     return $this->getAuthKey() === $authKey; 
    } 

    /** 
    * Validates password 
    * 
    * @param string $password password to validate 
    * @return bool if password provided is valid for current user 
    */ 
    public function validatePassword($claveProfesor) 
    { 
     return $this->claveProfesor === $claveProfesor; 
    } 

    /** 
    * Generates password hash from password and sets it to the model 
    * 
    * @param string $password 
    */ 
    public function setPassword($password) 
    { 
     $this->password_hash = Yii::$app->security->generatePasswordHash($password); 
    } 

    /** 
    * Generates "remember me" authentication key 
    */ 
    public function generateAuthKey() 
    { 
     $this->auth_key = Yii::$app->security->generateRandomString(); 
    } 

    /** 
    * Generates new password reset token 
    */ 
    public function generatePasswordResetToken() 
    { 
     $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time(); 
    } 

    /** 
    * Removes password reset token 
    */ 
    public function removePasswordResetToken() 
    { 
     $this->password_reset_token = null; 
    } 

    public function isUserSimple($rutProfesor) 
    { 
     if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 2])) 
     { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public function isUserAdmin($rutProfesor) 
    { 
     if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 1])) 
     { 
      return true; 
     } else { 
      return false; 
     } 
    } 

} 

Planificacion控制器planificacionController.php

<?php 

namespace frontend\controllers; 

use Yii; 
use common\models\Planificacion; 
use common\models\PlanificacionSearch; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 

/** 
* PlanificacionController implements the CRUD actions for Planificacion model. 
*/ 
class PlanificacionController extends Controller 
{ 
    /** 
    * @inheritdoc 
    */ 
    public function behaviors() 
    { 
     return [ 
      'verbs' => [ 
       'class' => VerbFilter::className(), 
       'actions' => [ 
        'delete' => ['POST'], 
       ], 
      ], 
     ]; 
    } 

    /** 
    * Lists all Planificacion models. 
    * @return mixed 
    */ 
    public function actionIndex() 
    { 
     $searchModel = new PlanificacionSearch(); 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

     return $this->render('index', [ 
      'searchModel' => $searchModel, 
      'dataProvider' => $dataProvider, 
     ]); 
    } 

    /** 
    * Displays a single Planificacion model. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionView($id) 
    { 
     return $this->render('view', [ 
      'model' => $this->findModel($id), 
     ]); 
    } 

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

     if ($model->load(Yii::$app->request->post()) && $model->save()) { 
      return $this->redirect(['view', 'id' => $model->idPlanificacion]); 
     } else { 
      return $this->render('create', [ 
       'model' => $model, 
      ]); 
     } 
    } 

    /** 
    * Updates an existing Planificacion model. 
    * If update is successful, the browser will be redirected to the 'view' page. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionUpdate($id) 
    { 
     $model = $this->findModel($id); 

     if ($model->load(Yii::$app->request->post()) && $model->save()) { 
      return $this->redirect(['view', 'id' => $model->idPlanificacion]); 
     } else { 
      return $this->render('update', [ 
       'model' => $model, 
      ]); 
     } 
    } 

    /** 
    * Deletes an existing Planificacion model. 
    * If deletion is successful, the browser will be redirected to the 'index' page. 
    * @param integer $id 
    * @return mixed 
    */ 
    public function actionDelete($id) 
    { 
     $this->findModel($id)->delete(); 

     return $this->redirect(['index']); 
    } 

    /** 
    * Finds the Planificacion model based on its primary key value. 
    * If the model is not found, a 404 HTTP exception will be thrown. 
    * @param integer $id 
    * @return Planificacion the loaded model 
    * @throws NotFoundHttpException if the model cannot be found 
    */ 
    protected function findModel($id) 
    { 
     if (($model = Planificacion::findOne($id)) !== null) { 
      return $model; 
     } else { 
      throw new NotFoundHttpException('The requested page does not exist.'); 
     } 
    } 
} 
+0

歡迎來到StackOverflow。你發佈了很多代碼,但忘了問一個問題! – kloarubeek

+0

我問過如何獲取會話數據並將其放在Yii 2的dropDownList中。對不起,如果這個問題描述得不好。我只是不知道如何提出更好的問題。只有我有這樣的問題,從dropDownList的會話數據中獲取並放置了一定的值,但我不知道在這個問題中要添加什麼...... –

+0

對不起,我忽略了那一個! – kloarubeek

回答

1

首先,爲什麼你得到的錯誤,是因爲ArrayHelper::getValue()需要一個數組作爲第一個參數,因爲它的目的是爲了

Retrieves the value of an array element or object property with the given key or property name.

Yii::$app->user->identity->rutProfesor不會產生一個數組,它不會產生一個st環,這是當前rut教授在會議上。

然後,關於如何創建你想要的dropDownList,我建議使用更直接的ArrayHelper::map()

<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([ 
'rutProfesor' => Yii::$app->user->identity->rutProfesor 
])->all(), 'rutProfesor', 'nombreProfesor'); ?> 

我相信代碼會對你有好處。

快樂編碼。 :)

+0

非常感謝!它完美的工作! –

+0

不客氣!很高興幫助。 :) – MegaGrindStone