I was trying to make a blog with YII2, my framework is confusing to call data from database.
For example when I call "username" from "user" table,
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'user.fullname', --->> Yii2 is thinking that this is a category and not a user table
'title',
'description',
'content:html',
'count_view',
'status',
'created_at',
],
]) ?>
I am getting this error: -->> unknown property: app\models\Category::fullname
please could you help me to solve this issue, where I did make a mistake?
and here is my post model contains:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "post".
*
* #property integer $id
* #property integer $user_id
* #property string $title
* #property string $description
* #property string $content
* #property integer $count_view
* #property string $status
* #property string $created_at
*
* #property User $user
* #property TagAssign[] $tagAssigns
*/
class Post extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'count_view','category_id'], 'integer'],
[['content', 'status'], 'string'],
[['created_at'], 'safe'],
[['count_view'], 'default','value'=>0],
[['user_id'], 'default','value'=>Yii::$app->user->id],
[['title', 'description'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'title' => 'Title',
'description' => 'Description',
'content' => 'Content',
'category' => 'Category',
'count_view' => 'Count View',
'status' => 'Status',
'created_at' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}
public function getCategory()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getTagAssigns()
{
return $this->hasMany(TagAssign::className(), ['post_id' => 'id']);
}
}
and here user Model:
<?php
namespace app\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $fullname
* #property string $status
* #property string $role
* #property string $created_At
*
* #property Post[] $posts
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
public $current_password;
public $new_password;
public $confirm_password;
public $authKey;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['status', 'role'], 'string'],
[['created_At'], 'safe'],
[['username', 'password', 'fullname'], 'string', 'max' => 45],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'username',
'password' => 'password',
'fullname' => 'fullname',
'status' => 'Status',
'role' => 'Role',
'created_At' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token,$type=null)
{
return static::findOne(['access_token'=>$token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey == $authKey;
}
public static function findByUsername($username)
{
return static::findOne(['username'=>$username]);
}
public function validatePassword($password)
{
if(Yii::$app->security->validatePassword($password,$this->password))
{
return true;
} else {
return false;
}
}
}
Change to this in Post model.
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}
Related
I have users table containing : PK - id, username, password.
i have three tables ( laptop, display, phone) - id - FK, series, model
I have userequipmentmapping table containing : id - PK , user_id - FK( id from users table), laptop_id - FK (id from laptop table), phone_id - FK (id from phone table), display_id(id from dislpay table), start_date, end_date.
I want to search by user in my gridview from UserEquipmentMapping, but don't know where should i implement the search model, considering the username is passed from the users table by foreign key.
If you have any suggestions are appreciated. Thank You in advance !
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
ModelSearch :
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\UserEquipmentMapping;
/**
* UserequipmentmappingSearch represents the model behind the search form of `app\models\UserEquipmentMapping`.
*/
class UserequipmentmappingSearch extends UserEquipmentMapping
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = UserEquipmentMapping::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'laptop_id' => $this->laptop_id,
'phone_id' => $this->phone_id,
'display_id' => $this->display_id,
'start_date' => $this->start_date,
'stop_date' => $this->stop_date,
]);
return $dataProvider;
}
}
Index :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
#'id',
'user.username',
#'laptop.laptop_model',
'laptop.laptop_series',
#'laptop_id',
#'phone.phone_model',
'phone.phone_series',
#'phone_id',
#'display.display_model',
'display.display_series',
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Uncomment in your index view _search view. There are all fields from UserequipmentmappingSearch model. You can replace input fields with select fields for user, laptop and etc. Search model will do the other thing, all is in search function that fills your dataprovider
I'm new in StackOverflow and also new using the framework Yii 2, and I need to get session data and put in a create and update form using the _form.php from a view called Planficacion, but when I try to use this line of code in the form:
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?>
Return this error: PHP Warning – yii\base\ErrorException. Invalid argument supplied for foreach()
I need to get the value of 'nombreProfesor' from a model called Profesor, and the relation of both Planificacion and Profesor is 'rutProfesor' and I want to show in the dropDownList only the 'nombreProfesor' of the actual session.
There are the codes from:
Profesor Model (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 Model (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 Model (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 Controller (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.');
}
}
}
First, why you getting the error, is because ArrayHelper::getValue() require an array as first parameter, as it's purpose is to
Retrieves the value of an array element or object property with the
given key or property name.
And Yii::$app->user->identity->rutProfesor wouldn't yield an array, no, it would yield an single string, which is current rutProfessor in the session.
Then, on how you create the dropDownList you wanted, i suggest using an ArrayHelper::map() which is more straightfoward.
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([
'rutProfesor' => Yii::$app->user->identity->rutProfesor
])->all(), 'rutProfesor', 'nombreProfesor'); ?>
I beleive that code will do you good.
Happy coding. :)
I have 2 tables:User and Posts. User can have many posts,post can't have many users. How to build relations in that models and how to make Join in ActiveDataProvider I have user_id in my Posts table and want to show data in my gridview like Posts(id,title,text) and User(name) how can I do that?I need to make relations in my model and how can I use it?;
Posts model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "posts".
*
* #property integer $id
* #property integer $user_id
* #property string $post_title
* #property string $post_text
*/
class Posts extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'posts';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'integer'],
[['post_title'], 'string', 'max' => 50],
[['post_text'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'post_title' => 'Post Title',
'post_text' => 'Post Text',
];
}
public function insertPost()
{
$userId = \Yii::$app->user->identity->id;
$posts = new Posts();
$posts->user_id = $userId;
$posts->post_title = $this->post_title;
$posts->post_text = $this->post_text;
return $posts->save();
}
public function getUser()
{
return $this->hasOne(User::classname(),['user_id'=>'id']);
}
}
User model:
* #property integer $id
* #property string $email
* #property string $password
* #property string $name
*/
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['email'], 'string', 'max' => 100],
[['password'], 'string', 'max' => 255],
[['name'], 'string', 'max' => 25],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
'password' => 'Password',
'name' => 'Name',
];
}
public function setPassword($password)
{
$this->password = sha1($password);
}
public function validatePassword($password)
{
return $this->password === sha1($password);
}
public static function findIdentity($id)
{
return self::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
}
public function validateAuthKey($authKey)
{
}
public function getPost()
{
return $this->hasMany(Posts::classname(),['id'=>'user_id']);
}
}
You already have a relation (your function getPost ) in User model between User and Post
you can access the the value of Post eg:
$userModel = User::find()->where([ 'id' => $id])->one();
$myUserPost = $userModel->post;
$myUserPostAttribute = $userModel->post->attribute;
for ActiveDataProvider you can use
$dataProvider = User::find()->where([ 'id' => $id]);
and eventually add getter for single attribute in User Model eg:
getMyPostAttribute1()
{
return $this->post->attribute1
}
so you can easly use this getter in a gridview
<?= GridView::widget([
'dataProvider' => $dataProvider,
......
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'myPostAttribute1',
....
I have user, role tables and a junction table role_user for many to many relationship between these tables.
Timestamp and Blameable behaviours works fine for user and role tables but i want to add these behaviours to my junction table too.
My models are;
User.php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $auth_key
* #property string $password_hash
* #property string $password_reset_token
* #property string $email
* #property integer $status
* #property integer $created_at
* #property integer $updated_at
* #property string $name
* #property string $surname
* #property integer $role_id
*/
class User extends ActiveRecord {
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public static function getStates() {
return ArrayHelper::map([
['id' => User::STATUS_ACTIVE, 'name' => 'Active'],
['id' => User::STATUS_DELETED, 'name' => 'Deleted'],
], 'id', 'name');
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['username', 'auth_key', 'password_hash', 'email'], 'required'],
[['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email', 'name', 'surname'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
[['username'], 'unique']
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'name' => 'Name',
'surname' => 'Surname',
'roles' => 'Roles',
];
}
/**
* #return ActiveQuery
*/
public function getRoles() {
return $this->hasMany(Role::className(), ['id' => 'role_id'])
->viaTable(RoleUser::tableName(), ['user_id' => 'id']);
}
}
Role.php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "role".
*
* #property integer $id
* #property string $name
* #property integer $status
* #property string $created_at
* #property string $updated_at
*
* #property User[] $users
*/
class Role extends ActiveRecord {
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public static function getStates() {
return ArrayHelper::map([
['id' => Role::STATUS_ACTIVE, 'name' => 'Active'],
['id' => Role::STATUS_DELETED, 'name' => 'Deleted'],
], 'id', 'name');
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'role';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
[['name'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
];
}
/**
* #return ActiveQuery
*/
public function getUsers() {
return $this->hasMany(User::className(), ['role_id' => 'id']);
}
}
RoleUser.php
<?php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* This is the model class for table "role_user".
*
* #property integer $id
* #property integer $user_id
* #property integer $role_id
*
* #property Role $role
* #property User $user
*/
class RoleUser extends ActiveRecord {
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'role_user';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['user_id', 'role_id'], 'required'],
[['user_id', 'role_id', 'status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'user_id' => 'User ID',
'role_id' => 'Role ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
];
}
/**
* #return ActiveQuery
*/
public function getRole() {
return $this->hasOne(Role::className(), ['id' => 'role_id']);
}
/**
* #return ActiveQuery
*/
public function getUser() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
While i am linking a role to user iam using link method of ActiveRecord:
$user->link('roles', Role::findOne($role_id));
Is there a better way to link these models with these behaviours or should i do the linking via creating an instance from RoleUser model?
Thanks in advance.
If you want Yii to work with your RoleUser class inside link method then you should define relation using via not viaTable.
Declare additional relation:
User.php
public function getRoleLinks()
{
return $this->hasMany(UserRole::className(), ['user_id' => 'id']);
}
And modify your user->role relation:
public function getRoles() {
return $this->hasMany(Role::className(), ['id' => 'role_id'])
->via('roleLinks');
}
If you are using viaTable then yii will directly insert new record into user_role without instantiating of UserRole class.
p.s. and vice versa if you want to call $role->link('users', $user)
I try to make login from DB.As I understand for this i just need to replace default model User. So i try it two times but in both cases Yii::$app->user->isGuest is true but must be false
LoginForm.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return false;
}
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username); //default
# $this->_user = Users::findByUsername($this->username);//my try 1
# $this->_user = Users2::findByUsername($this->username); // my trey 2
}
return $this->_user;
}
}
Users.php
<?php
namespace app\models;
use Yii;
class Users extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public $authKey;
public $accessToken;
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['name', 'surname', 'login', 'password', 'email'], 'required'],
[['name', 'surname'], 'string', 'max' => 50],
[['login'], 'string', 'max' => 20],
[['password'], 'string', 'max' => 16],
[['email'], 'string', 'max' => 250]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'surname' => 'Surname',
'login' => 'Login',
'password' => 'Password',
'email' => 'Email',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getOrders()
{
return $this->hasMany(Orders::className(), ['user_id' => 'id']);
}
public static function findIdentity($id) {
$user = self::find()
->where([
"id" => $id
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$user = self::find()
->where(["accessToken" => $token])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$user = self::find()
->where([
"login" => $username
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return $this->password === $password;
}
}
Users2.php
<?php
namespace app\models;
use Yii;
class Users2 extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '2sers';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['authKey', 'accessToken', 'name', 'surname', 'login', 'password', 'email'], 'required'],
[['authKey', 'accessToken'], 'string'],
[['name', 'surname'], 'string', 'max' => 50],
[['login'], 'string', 'max' => 20],
[['password'], 'string', 'max' => 16],
[['email'], 'string', 'max' => 250]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'authKey' => 'Auth Key',
'accessToken' => 'Access Token',
'name' => 'Name',
'surname' => 'Surname',
'login' => 'Login',
'password' => 'Password',
'email' => 'Email',
];
}
public static function findIdentity($id) {
$user = self::find()
->where([
"id" => $id
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$user = self::find()
->where(["accessToken" => $token])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$user = self::find()
->where([
"login" => $username
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return $this->password === $password;
}
}
In your config change
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
To
'user' => [
'identityClass' => 'app\models\Users',//or Users2
'enableAutoLogin' => true,
You should also implement \yii\web\IdentityInterface. This is how Yii knows to log you in using this class.
When this is properly done...
Yii::$app->user will be an instance of yii\web\User, while
Yii::$app->user->identity would be an instance of app\models\User2
... as it should be.
P.S.:
Also make sure to implement the necessary methods from the \yii\web\IdentityInterface in your model class, app\models\User2