YII2 - Save user ID to work with it on other pages - php

I'm building a questionnaire site.
On this site the user enters his email to receive the result of his questionnaire. So this site has no authentication.
How do I store the user's email to the end of the questionnaire?
It is my User model:
<?php
namespace common\models;
use Yii;
use \yii\db\ActiveRecord;
// use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* #property int $id
* #property string $email
* #property string $name
* #property string $family
* #property string $major
* #property string $univercity
* #property int $education
* #property int $gender
* #property int $age
* #property int $income
* #property int $get_result
* #property int $created_at
*/
class User extends ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user';
}
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
// TimestampBehavior::className(),
];
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['email', 'created_at'], 'required'],
[['education', 'gender', 'age', 'income', 'get_result', 'created_at'], 'integer'],
[['email', 'name', 'family', 'major', 'univercity'], 'string', 'max' => 255],
[['email'], 'unique'],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
'name' => 'Name',
'family' => 'Family',
'major' => 'Major',
'univercity' => 'Univercity',
'education' => 'Education',
'gender' => 'Gender',
'age' => 'Age',
'income' => 'Income',
'get_result' => 'Get Result',
'created_at' => 'Created At',
];
}
}

There are many ways of achieving that, it mostly depends on your logic under the hood.
One of the easiest is to use session.
First store the email in session:
\Yii::$app->session->set('questionnaire-email', $usersEmail);
Then, when you want to use it:
$email = \Yii::$app->session->get('questionnaire-email');

Related

Yii: How to add a simple checkbox in a view

I want to do add a checkbox to a view using the Yii2 framework.
Using HTML, JavaScript or Angular is very easy but I don't understand how to do it with Yii2.
I have a username input in the view called _form.php:
<div class="col-md-6">
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
</div>
And now I need a checkbox.
Is there any Yii documentation showing all its components?
This is my model:
<?php
namespace app\models;
use Yii;
/**
* 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
*/
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
[['status', 'created_at', 'updated_at'], 'date','format' => 'd-M-yyyy H:m'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
[['username'], 'unique'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'Idadm',
'username' => 'Nombre de usuario',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Creado',
'updated_at' => 'Actualizado',
];
}
}
So the attributes are: username, status, auth_key, email and password_reset_token. But I want to use a new attribute called population but I don't know how to do it.
Use ->checkBox instead of textInput
<div class="col-md-6">
<?= $form->field($model, 'username')->checkBox(['label' => 'your_label']) ?>
</div>
http://www.bsourcecode.com/yiiframework2/yii2-0-activeform-input-fields/
http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html
http://www.yiiframework.com/doc-2.0/guide-helper-html.html

yii2 function issue called with null value

i'm trying to copy some values from a table that contain a column that relates to another table to copy too.
the problem is that if i call the function createNew() of the model Email.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "email".
*
* #property integer $id
* #property integer $provider_id
* #property integer $sender_id
* #property string $recipient
* #property string $name
* #property string $cc
* #property string $ccn
* #property string $subject
* #property string $body
* #property integer $type
* #property string $created
*
* #property Emailaccount $sender
* #property Provider $provider
*/
class Email extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'email';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['provider_id', 'sender_id', 'name', 'subject', 'body', 'type'], 'required'],
[['provider_id', 'sender_id', 'type'], 'integer'],
[['body'], 'string'],
[['created'], 'safe'],
[['recipient'], 'string', 'max' => 200],
[['name', 'cc', 'ccn', 'subject'], 'string', 'max' => 100],
[['sender_id'], 'exist', 'skipOnError' => true, 'targetClass' => Emailaccount::className(), 'targetAttribute' => ['sender_id' => 'id']],
[['provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => Provider::className(), 'targetAttribute' => ['provider_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'provider_id' => 'Provider ID',
'sender_id' => 'Sender ID',
'recipient' => 'Recipient',
'name' => 'Name',
'cc' => 'Cc',
'ccn' => 'Ccn',
'subject' => 'Subject',
'body' => 'Body',
'type' => 'Type',
'created' => 'Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSender()
{
return $this->hasOne(Emailaccount::className(), ['id' => 'sender_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProvider()
{
return $this->hasOne(Provider::className(), ['id' => 'provider_id']);
}
public function createNew ($id,$new_id){
$model = Email::findOne(['id'=>$id]);
$model->id = null;
$model->provider_id = $new_id;
$model->isNewRecord = true;
$model->save();
return $model->id;
}
}
from the model Service.php
namespace app\models;
use Yii;
use app\models\Email;
use app\models\Question;
/**
* This is the model class for table "service".
*
* #property integer $id
* #property integer $provider_id
* #property string $token
* #property string $name
* #property string $description
* #property integer $parent_id
* #property string $reference
* #property integer $reference_id
* #property integer $depth
* #property integer $isleaf
* #property string $color
* #property string $icon
* #property integer $type
* #property string $type_label
* #property integer $totem_reference_id
*
* #property Service $parent
* #property Service[] $services
*/
class Service extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'service';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['provider_id', 'token', 'name'], 'required'],
[['provider_id', 'parent_id', 'reference_id', 'depth', 'isleaf', 'type', 'totem_reference_id'], 'integer'],
[['reference', 'color'], 'string'],
[['token', 'type_label'], 'string', 'max' => 45],
[['name', 'description'], 'string', 'max' => 255],
[['icon'], 'string', 'max' => 30],
[['token'], 'unique'],
[['parent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Service::className(), 'targetAttribute' => ['parent_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'provider_id' => 'Provider ID',
'token' => 'Token',
'name' => 'Name',
'description' => 'Description',
'parent_id' => 'Parent ID',
'reference' => 'Reference',
'reference_id' => 'Reference ID',
'depth' => 'Depth',
'isleaf' => 'Isleaf',
'color' => 'Color',
'icon' => 'Icon',
'type' => 'Type',
'type_label' => 'Type Label',
'totem_reference_id' => 'Totem Reference ID',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getParent()
{
return $this->hasOne(Service::className(), ['id' => 'parent_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getServices()
{
return $this->hasMany(Service::className(), ['parent_id' => 'id']);
}
public function mostraService($id,$new_id){
$service = Service::find()
->where(['provider_id'=>$id])
->all();
foreach ($service as $s) {
if ($s->parent_id==NULL) {
$o_id= $s->id; //ID ORIGINALE
$s->id= null;
$s->token= Yii::$app->getSecurity()->generateRandomString(45);
$s->isNewRecord = true;
$s->provider_id = $new_id; //ID_NUOVO
$s->save();
$p_id=$s->id;
$copy = $this->recursiveCopy($o_id,$new_id,$p_id);
} else {
//do something
}
}
}
public function recursiveCopy ($id_s,$id_pr,$id_p){
$children = Service::find()
->where(['parent_id'=>$id_s])
->all();
foreach ($children as $c) {
if ($c->reference == null){
$o_id=$c->id;
$c->id= null;
$c->token= Yii::$app->getSecurity()->generateRandomString(45);
$c->isNewRecord = true;
$c->parent_id = $id_p;
$c->provider_id = $id_pr;
$c->save();
$c_id=$c->id;
$copy = $this->recursiveCopy($o_id,$id_pr,$c_id);
}else {
if ($c->reference =='email') {
$email = new Email();
$e_id=$email->createNew($c->reference_id, $id_pr);
$c->id= null;
$c->token = Yii::$app->getSecurity()->generateRandomString(45);
$c->reference_id = $e_id;
$c->provider_id = $id_pr;
$c->parent_id = $id_p;
$c->isNewRecord = true;
$c->save();
} else if ($c->reference =='question'){
$question = new Question();
$q_id = $question->createNew($c->reference_id, $id_pr);
} else {
$c->id= null;
$c->token = Yii::$app->getSecurity()->generateRandomString(45);
$c->reference_id = $id_p;
$c->provider_id = $id_pr;
$c->parent_id = $id_p;
$c->isNewRecord = true;
$c->save();
}
}
}
}
}
it work perfectly but if i call in the same way in the Question.php
namespace app\models;
use Yii;
use app\models\Email;
/**
* This is the model class for table "question".
*
* #property integer $id
*#property integer $provider_id
* #property string $title
* #property string $description
* #property string $children
* #property integer $parent_id
* #property string $reference
* #property integer $reference_id
* #property integer $depth
* #property integer $type
*
* #property Provider $provider
* #property Question $parent
* #property Question[] $questions
*/
class Question extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'question';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['provider_id', 'title'], 'required'],
[['provider_id', 'parent_id', 'reference_id', 'depth', 'type'], 'integer'],
[['reference'], 'string'],
[['title'], 'string', 'max' => 150],
[['description'], 'string', 'max' => 1000],
[['children'], 'string', 'max' => 300],
[['provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => Provider::className(), 'targetAttribute' => ['provider_id' => 'id']],
[['parent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Question::className(), 'targetAttribute' => ['parent_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'provider_id' => 'Provider ID',
'title' => 'Title',
'description' => 'Description',
'children' => 'Children',
'parent_id' => 'Parent ID',
'reference' => 'Reference',
'reference_id' => 'Reference ID',
'depth' => 'Depth',
'type' => 'Type',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProvider()
{
return $this->hasOne(Provider::className(), ['id' => 'provider_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getParent()
{
return $this->hasOne(Question::className(), ['id' => 'parent_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getQuestions()
{
return $this->hasMany(Question::className(), ['parent_id' => 'id']);
}
public function createNew ($id,$new_id){
$model = Question::findOne(['id'=>$id]);
$model->id= null;
$model->provider_id = $new_id;
$model->isNewRecord = true;
$model->save();
$child= explode(",", $model->children);
$sons= '';
foreach ($child as $c) {
$model_c = Question::findOne(['id'=>$c]);
$email = new Email();
$e_id=$email->createNew($model_c->reference_id,$new_id);
$model_c->id= null;
$model_c->provider_id = $new_id;
$model_c->parent_id = $model->id;
$model_c->isNewRecord = true;
$model_c->save();
$sons=$sons.$model_c->id.',';
}
$model->children =$sons;
}
}
it pass a null value and of course throw an exception.
exception 1 exception 2
i tried to echo the value before pass it to the function and it print the right value. i really don't understand, someone can help me?
The problem is you are not checking if Model::findOne() has actually returned a valid result model. It could be false / null if the record with $id doesn't exist.
The second error you are getting usually happens in following case:
$object = null;
$object->prop = 'a value';
aka whey you try to set a value of an object property which doesn't exist.
And your first error message is saying that above case is true.
app\models\Email::createNew(null, 51) <-- notice the null here
So when you are finding a model always check before using it. You can do following:
foreach ($child as $c) {
$model_c = Question::findOne(['id'=>$c]);
if( $model_c ) { // check the model is valid
$email = new Email();
$e_id=$email->createNew($model_c->reference_id,$new_id);
$model_c->id= null;
$model_c->provider_id = $new_id;
$model_c->parent_id = $model->id;
$model_c->isNewRecord = true;
$model_c->save();
$sons=$sons.$model_c->id.',';
}
}
Just showed you one, do the rest. :)

How to add behaviour to a junction table?

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)

Yii2 rest api join query with ActiveDataProvider

I have a custom action in ActiveController and need to fetch some data by joining two tables.
I have written following query .
$query = Item::find()->joinWith(['subcategory'])->select(['item.*', 'sub_category.name'])->where(['item.active' => 1])->addOrderBy(['item.id' => SORT_DESC]);
$pageSize = (isset($_GET["limit"]) ? $_GET["limit"] : 1) * 10;
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
$dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $pageSize, "page" => $page]]);
$formatter = new ResponseFormatter();
return $formatter->formatResponse("", $dataProvider->getTotalCount(), $dataProvider->getModels());
but it is throwing an exception
"message": "Setting unknown property: common\\models\\Item::name",
Here is the item Model with all the fields and relation.
<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\BaseActiveRecord;
use yii\db\Expression;
/**
* This is the model class for table "item".
*
* #property integer $id
* #property integer $subcategory_id
* #property string $title
* #property resource $description
* #property integer $created_by
* #property integer $updated_by
* #property string $created_at
* #property string $updated_at
* #property string $image
* #property integer $active
*
* #property SubCategory $subcategory
*/
class Item extends \yii\db\ActiveRecord
{
public $imageFile;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'item';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['created_by', 'updated_by'], 'required'],
[['subcategory_id', 'created_by', 'updated_by', 'active'], 'integer'],
[['description'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['title', 'image'], 'string', 'max' => 999],
[['title'], 'unique'],
[['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'subcategory_id' => 'Subcategory ID',
'title' => 'Title',
'description' => 'Description',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'image' => 'Image',
'active' => 'Active',
'imageFile' => 'Image',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSubcategory()
{
return $this->hasOne(SubCategory::className(), ['id' => 'subcategory_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCreatedBy()
{
return $this->hasOne(User::className(), ['id' => 'created_by']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUpdatedBy()
{
return $this->hasOne(User::className(), ['id' => 'updated_by']);
}
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => new Expression('NOW()'),
],
];
}
}
The joinWith makes a query using the joins requested, but result data are mapped in source model (in this case Item).
Since you have select(['item.*', 'sub_category.name']) , the framework will try to fill 'name' field of Item model, that does not exist and this generates the error.
According with documentation (http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#overriding-extra-fields) you should have db relation subcategory populated from db, by default, but I don't see subcategory relation in your model.
So you have only to create subcategory relation in your model, such as:
public function getSubcategory() { return $this->hasOne(Subcategory::className(), ['id' => 'subcategory_id']); }
So you should solve your problem.
Other solution to have custom fields from more models could be:
1) Create a sql View (and from that create the Model) with fields that you want and pass it to ActiveDataProvide
2) Override extraFields method of the model (http://www.yiiframework.com/doc-2.0/yii-base-arrayabletrait.html#extraFields%28%29-detail)
Again, I suggest you to read this good article:
http://www.yiiframework.com/wiki/834/relational-query-eager-loading-in-yii-2-0/

PHP Compile Error while creating Views and Controller using Gii in YII2

I have created Review model for the table. after that while creating views and controllers for the same table it shows PHP Compile error.
PHP Compile Error – yii\base\ErrorException
Declaration of app\models\Review::getRelation() must be compatible with yii\db\ActiveRecordInterface::getRelation($name, $throwException = true)
Here is the full error page
http://pastebin.com/kf8RFun8 .
I have created rest of the MVCs for my tables. I get error only for this.
My Model Class
app\models\Review
Search Model Class
app\models\ReviewSearch
Controller Class
app\controllers\ReviewController
Note: while creating this same in Yii2-Advanced It shows Error (#64) Internal Server Error
Review Model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "review".
*
* #property string $id
* #property string $title
* #property string $reviewer_id
* #property string $timestamp
* #property string $description
* #property string $organization_id
* #property integer $rating
* #property string $relation_id
* #property integer $send_msg
* #property string $org_contact_email
* #property string $org_contact_msg
*
* #property Answer[] $answers
* #property Reviewer $reviewer
* #property Organization $organization
* #property Relation $relation
*/
class Review extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'review';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['title', 'reviewer_id', 'organization_id', 'rating', 'relation_id'], 'required'],
[['reviewer_id', 'organization_id', 'rating', 'relation_id', 'send_msg'], 'integer'],
[['timestamp'], 'safe'],
[['title'], 'string', 'max' => 45],
[['description'], 'string', 'max' => 2000],
[['org_contact_email'], 'string', 'max' => 60],
[['org_contact_msg'], 'string', 'max' => 1000]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'reviewer_id' => 'Reviewer ID',
'timestamp' => 'Timestamp',
'description' => 'Description',
'organization_id' => 'Organization ID',
'rating' => 'Rating',
'relation_id' => 'Relation ID',
'send_msg' => 'Send Msg',
'org_contact_email' => 'Org Contact Email',
'org_contact_msg' => 'Org Contact Msg',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAnswers()
{
return $this->hasMany(Answer::className(), ['review_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getReviewer()
{
return $this->hasOne(Reviewer::className(), ['id' => 'reviewer_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getOrganization()
{
return $this->hasOne(Organization::className(), ['id' => 'organization_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRelation()
{
return $this->hasOne(Relation::className(), ['id' => 'relation_id']);
}
}
You need to rename your getRelation() method as, you are overriding yii\db\ActiveRecordInterface::getRelation($name, $throwException = true). So this will cause an exception that getRelation method has an invalid declaration.

Categories