2017-02-16 2 views
1

Я новичок в StackOverflow, а также новый, используя фреймворк Yii 2, и мне нужно получить данные сеанса и поместить в форму для создания и обновления с помощью _form.php из вида Planficacion, но когда я попытаюсь использовать эту строка кода в форме:Как получить данные сеанса и положить в dropDownList в Yii 2?

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

Вернуть эту ошибку: Предупреждение PHP - yii \ base \ ErrorException. Недействительный аргумент для Еогеаспа()

Мне нужно получить значение «nombreProfesor» из модели под названием Profesor, а отношение как Planificacion и Profesor является «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

Я спросил о том, как получить данные сеанса и поместить в dropDownList в Yii 2. Извините, если вопрос плохо описан. Я просто не знаю, как задать лучший вопрос. Только у меня есть эта проблема получить и поместить определенное значение из данных сеанса в 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 кольцо, которое является текущим rutProfessor в сеансе.

Затем, как вы создаете 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

Смежные вопросы