Property "Alerts.alert_status_id" is not defined in Yii application - php

Here is my Alerts model:
<?php
/**
* This is the model class for table "alerts".
*
* The followings are the available columns in table 'alerts':
* #property string $id
* #property string $alert_status_id
* #property string $cmas_regions
* #property string $alert_type_id
* #property string $agency_id
* #property string $incident_at
* #property string $entered_by_given_name
* #property string $entered_by_surname
* #property integer $incident_location_state_reference_code
* #property string $incident_location_county
* #property string $incident_location_city
* #property string $incident_location_latitude
* #property string $incident_location_longitude
* #property string $incident_location_address1
* #property string $incident_location_address2
* #property string $incident_location_postal_code
* #property integer $cap_expiration_interval
* #property string $audio_url
* #property string $wordpress_post_id
* #property string $incident_summary
* #property string $ncic_case_number
* #property string $local_case_number
* #property string $information_provider_given_name
* #property string $information_provider_surname
* #property string $activation_authorization_officer_given_name
* #property integer $activation_authorization_officer_surname
* #property string $activation_authorization_officer_given_rank
* #property string $activation_authorization_officer_badge_number
* #property string $activated_at
* #property string $cancellation_authorization_officer_first_name
* #property string $cancellation_authorization_officer_surname
* #property string $cancellation_authorization_officer_rank
* #property string $cancellation_authorization_officer_badge_number
*
* The followings are the available model relations:
* #property AlertLog[] $alertLogs
* #property AlertPersons[] $alertPersons
* #property AlertVehicles[] $alertVehicles
* #property AlertTypes $alertType
* #property AlertStatuses $alertStatus
* #property StatesReference $incidentLocationStateReferenceCode
* #property Agencies $agency
* #property CapRegions[] $capRegions
* #property DistributionLists[] $distributionLists
* #property SharedAlertRequests[] $sharedAlertRequests
* #property SharedAlerts[] $sharedAlerts
*/
class Alerts extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Alerts the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'alerts';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('alert_status_id, alert_type_id, agency_id, incident_at, entered_by_given_name, entered_by_surname, incident_summary', 'required'),
array('incident_location_state_reference_code, cap_expiration_interval, activation_authorization_officer_surname', 'numerical', 'integerOnly'=>true),
array('alert_status_id, alert_type_id, agency_id, incident_location_postal_code, wordpress_post_id, ncic_case_number', 'length', 'max'=>10),
array('entered_by_given_name, entered_by_surname, incident_location_county, incident_location_city, incident_location_address1, incident_location_address2, information_provider_given_name, information_provider_surname, activation_authorization_officer_given_name, activation_authorization_officer_given_rank, activation_authorization_officer_badge_number, cancellation_authorization_officer_first_name, cancellation_authorization_officer_surname, cancellation_authorization_officer_rank, cancellation_authorization_officer_badge_number', 'length', 'max'=>63),
array('incident_location_latitude', 'length', 'max'=>11),
array('incident_location_longitude, local_case_number', 'length', 'max'=>12),
array('cmas_regions, audio_url', 'length', 'max'=>255),
array('activated_at', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, alert_status_id, alert_type_id, agency_id, incident_at, entered_by_given_name, entered_by_surname, incident_location_state_reference_code, incident_location_county, incident_location_city, incident_location_latitude, incident_location_longitude, incident_location_address1, incident_location_address2, incident_location_postal_code, cmas_regions, cap_expiration_interval, audio_url, wordpress_post_id, incident_summary, ncic_case_number, local_case_number, information_provider_given_name, information_provider_surname, activation_authorization_officer_given_name, activation_authorization_officer_surname, activation_authorization_officer_given_rank, activation_authorization_officer_badge_number, activated_at, cancellation_authorization_officer_first_name, cancellation_authorization_officer_surname, cancellation_authorization_officer_rank, cancellation_authorization_officer_badge_number', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'alertLogs' => array(self::HAS_MANY, 'AlertLog', 'alert_id'),
'alertPersons' => array(self::HAS_MANY, 'AlertPersons', 'alert_id'),
'alertVehicles' => array(self::HAS_MANY, 'AlertVehicles', 'alert_id'),
'alertType' => array(self::BELONGS_TO, 'AlertTypes', 'alert_type_id'),
'alertStatus' => array(self::BELONGS_TO, 'AlertStatuses', 'alert_status_id'),
'incidentLocationStateReferenceCode' => array(self::BELONGS_TO, 'StatesReference', 'incident_location_state_reference_code'),
'agency' => array(self::BELONGS_TO, 'Agencies', 'agency_id'),
'capRegions' => array(self::MANY_MANY, 'CapRegions', 'alerts_has_cap_regions(alerts_id, cap_regions_id)'),
'distributionLists' => array(self::MANY_MANY, 'DistributionLists', 'alerts_has_distribution_lists(alert_id, distribution_list_id)'),
'sharedAlertRequests' => array(self::HAS_MANY, 'SharedAlertRequests', 'alert_id'),
'sharedAlerts' => array(self::HAS_MANY, 'SharedAlerts', 'alert_id'),
);
}
public function getHour()
{
return date('H',strtotime($this->incident_at));
}
public function getMinute()
{
return date('i',strtotime($this->incident_at));
}
public function getDate()
{
return date('Y-m-d',strtotime($this->incident_at));
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'alert_status_id' => 'Alert Statuses',
'cmas_regions' => 'Cmas Regions',
'alert_type_id' => 'Alert Type',
'agency_id' => 'Agency',
'incident_at' => 'Incident At',
'entered_by_given_name' => 'First Name',
'entered_by_surname' => 'Last Name',
'incident_location_state_reference_code' => 'State',
'incident_location_county' => 'County',
'incident_location_city' => 'City',
'incident_location_latitude' => 'Latitude',
'incident_location_longitude' => 'Longitude',
'incident_location_address1' => 'Address1',
'incident_location_address2' => 'Address2',
'incident_location_postal_code' => 'Postal Code',
'min'=> 'Minute',
'cmas_regions' => 'Cmas Regions',
'cap_expiration_interval' => 'Cap Expiration Interval',
'audio_url' => 'Audio Url',
'wordpress_post_id' => 'Wordpress Post',
'incident_summary' => 'Incident Summary',
'ncic_case_number' => 'Ncic Case Number',
'local_case_number' => 'Local Case Number',
'information_provider_given_name' => 'First Name',
'information_provider_surname' => 'Last Name',
'activation_authorization_officer_given_name' => 'First Name',
'activation_authorization_officer_surname' => 'Last Name',
'activation_authorization_officer_given_rank' => 'Officer Rank',
'activation_authorization_officer_badge_number' => 'Officer Badge Number',
'activated_at' => 'Activated At',
'cancellation_authorization_officer_first_name' => 'First Name',
'cancellation_authorization_officer_surname' => 'Last Name',
'cancellation_authorization_officer_rank' => 'Officer Rank',
'cancellation_authorization_officer_badge_number' => 'Officer Badge Number',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('alert_status_id',$this->alert_status_id,true);
$criteria->compare('cmas_regions',$this->cmas_regions,true);
$criteria->compare('alert_type_id',$this->alert_type_id,true);
$criteria->compare('agency_id',$this->agency_id,true);
$criteria->compare('incident_at',$this->incident_at,true);
$criteria->compare('entered_by_given_name',$this->entered_by_given_name,true);
$criteria->compare('entered_by_surname',$this->entered_by_surname,true);
$criteria->compare('incident_location_state_reference_code',$this->incident_location_state_reference_code);
$criteria->compare('incident_location_county',$this->incident_location_county,true);
$criteria->compare('incident_location_city',$this->incident_location_city,true);
$criteria->compare('incident_location_latitude',$this->incident_location_latitude,true);
$criteria->compare('incident_location_longitude',$this->incident_location_longitude,true);
$criteria->compare('incident_location_address1',$this->incident_location_address1,true);
$criteria->compare('incident_location_address2',$this->incident_location_address2,true);
$criteria->compare('incident_location_postal_code',$this->incident_location_postal_code,true);
$criteria->compare('cmas_regions',$this->cmas_regions,true);
$criteria->compare('cap_expiration_interval',$this->cap_expiration_interval);
$criteria->compare('audio_url',$this->audio_url,true);
$criteria->compare('wordpress_post_id',$this->wordpress_post_id,true);
$criteria->compare('incident_summary',$this->incident_summary,true);
$criteria->compare('ncic_case_number',$this->ncic_case_number,true);
$criteria->compare('local_case_number',$this->local_case_number,true);
$criteria->compare('information_provider_given_name',$this->information_provider_given_name,true);
$criteria->compare('information_provider_surname',$this->information_provider_surname,true);
$criteria->compare('activation_authorization_officer_given_name',$this->activation_authorization_officer_given_name,true);
$criteria->compare('activation_authorization_officer_surname',$this->activation_authorization_officer_surname);
$criteria->compare('activation_authorization_officer_given_rank',$this->activation_authorization_officer_given_rank,true);
$criteria->compare('activation_authorization_officer_badge_number',$this->activation_authorization_officer_badge_number,true);
$criteria->compare('activated_at',$this->activated_at,true);
$criteria->compare('cancellation_authorization_officer_first_name',$this->cancellation_authorization_officer_first_name,true);
$criteria->compare('cancellation_authorization_officer_surname',$this->cancellation_authorization_officer_surname,true);
$criteria->compare('cancellation_authorization_officer_rank',$this->cancellation_authorization_officer_rank,true);
$criteria->compare('cancellation_authorization_officer_badge_number',$this->cancellation_authorization_officer_badge_number,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
I am calling it in controller by following line :
$alert_model = new Alerts;
$this->performAjaxValidation(array(
$alert_model, $agency_model, $victim_model, $suspect_model, $vehicle_model
));
$status = AlertStatuses::model()->find("name='created'");
$alert_model->alert_status_id = $status->id;
This is the error message:
Error: Property "Alerts.alert_status_id" is not defined.
Any help is much appreciated!

Check your alerts table, it most definitely does not contain alert_status_id column.

This "Property n is not defined" issue can also occur if you have set (text) type of a field and in your model while defining a property, you may have defined it as a boolean or integer.
For example: The below is wrong for text type property.
* #property boolean $billing_address
The right definition will be
* #property string $billing_address
Sometimes there is a small mistake that takes hours to be traced.

Related

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

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

Automatic filing of fields during registration in Laravel

Welcome.
I have been learning Laravela for a few days and stopped at registration.
I have migration:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 120);
$table->string('surname', 120);
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('counter')->default(0);
$table->string('url_address', 160);
$table->string('ip', 25);
$table->dateTime('date_of_registration');
$table->bigInteger('company_id')->unsigned();
$table->boolean('isCompany')->default(0);
$table->boolean('isMailing')->default(0);
$table->text('note');
$table->string('nip1', 12);
$table->string('business1', 120);
$table->string('phone1', 60);
$table->string('street1', 150);
$table->string('number1', 8);
$table->string('postal_code1', 12);
$table->string('city1', 100);
$table->bigInteger('country_id1')->default(0);
$table->bigInteger('provincial_id1')->default(0);
$table->string('nip2', 12);
$table->string('business2', 120);
$table->string('phone2', 60);
$table->string('street2', 150);
$table->string('number2', 8);
$table->string('postal_code2', 12);
$table->string('city2', 100);
$table->bigInteger('country_id2')->default(0);
$table->bigInteger('provincial_id2')->default(0);
$table->string('nip3', 12);
$table->string('business3', 120);
$table->string('phone3', 60);
$table->string('street3', 150);
$table->string('number3', 8);
$table->string('postal_code3', 12);
$table->string('city3', 100);
$table->bigInteger('country_id3')->default(0);
$table->bigInteger('provincial_id3')->default(0);
$table->decimal('cash', 9, 2)->default(0);
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
});
and functions:
function generateSeoUrl(string $string): string
{
$string = preg_replace("/ +/", "-", trim($string));
$string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
return $string;
}
The above table uses Laravel's default authorization (I use Laravel 5.8).
How can I add during registration:
- ip - IP address of the user who registered
- date_of_registration - current date
- url_address - here I would like to save the generatedSeoUrl result ($ email)
Please help. I've been sitting here for hours and I do not know how to deal with it :(
Step: 1 :
Add the extra Fileds to the users table migration
You have done already
Step: 2
Add the fileds to the fillable model of User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* #property integer $id
* #property string $name
* #property string $surname
* #property string $email
* #property string $email_verified_at
* #property string $password
* #property integer $counter
* #property string $url_address
* #property string $ip
* #property string $date_of_registration
* #property integer $company_id
* #property boolean $isCompany
* #property boolean $isMailing
* #property string $note
* #property string $nip1
* #property string $business1
* #property string $phone1
* #property string $street1
* #property string $number1
* #property string $postal_code1
* #property string $city1
* #property integer $country_id1
* #property integer $provincial_id1
* #property string $nip2
* #property string $business2
* #property string $phone2
* #property string $street2
* #property string $number2
* #property string $postal_code2
* #property string $city2
* #property integer $country_id2
* #property integer $provincial_id2
* #property string $nip3
* #property string $business3
* #property string $phone3
* #property string $street3
* #property string $number3
* #property string $postal_code3
* #property string $city3
* #property integer $country_id3
* #property integer $provincial_id3
* #property float $cash
* #property string $remember_token
* #property string $created_at
* #property string $updated_at
*/
class User extends Authenticatable
{
use Notifiable;
/**
* #var array
*/
protected $fillable = ['name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address', 'ip', 'date_of_registration', 'company_id', 'isCompany', 'isMailing', 'note', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'remember_token', 'created_at', 'updated_at'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Step:3
Add the fileds in the registration form can be found in projectname\resources\views\auth\register.blade.php
Add the required filed to the form
Step: 4
Now the Logic part
Open the file project\app\Http\Controllers\Auth\RegisterController.php
Now You will find the validator and create method
Add your method to the RegisterController.php
function generateSeoUrl(string $string): string
{
$string = preg_replace("/ +/", "-", trim($string));
$string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
return $string;
}
Add your validation logic in validator method
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
Now we need to manually add some fileds while storing
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$newArray = [
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'ip' => RequestFacade::ip(),
'date_of_registration' => now(),
'url_address' => $this->generateSeoUrl($data['email']),
];
return User::create($newArray);
}
Finally Your RegisterController will look like
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\Request as RequestFacade;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$newArray = [
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'ip' => RequestFacade::ip(),
'date_of_registration' => now(),
'url_address' => $this->generateSeoUrl($data['email']),
];
return User::create($newArray);
}
function generateSeoUrl(string $string): string
{
$string = preg_replace("/ +/", "-", trim($string));
$string = mb_strtolower(preg_replace('/[^A-Za-z0-9-]+/', '', $string), 'UTF-8');
return $string;
}
}
Please do comment if there is any issue
In App\Http\Controllers\Auth\RegisterController.php update your create() function and put all your extra fields there.
By the way, you don't need date_of_registration as the created_at field is already managed by Laravel.
Also, instead of your generateSeoUrl you can use Str::slug function from Laravel.
#trafficker
I will be assuming that you are using the default laravel registration controller in "App\Http\Controllers\Auth\RegisterController"
So in your RegisterController, there is a protected create method which accepts an array of data (data from the form submitted)
To get the ip address, laravel has provided a method for that on its Request Object
So you have $ip = Request::ip()
As for the date, you can use carbon which comes by default $date = \Carbon\Carbon::now()
As for getting the seoUrl, you make that function a private function in the RegisterController class and call it passing the string you want, (maybe the full name).
So In effect, your create method will look like this
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'seoUrl' => $this->generateSeoUrl($data['name']),
'ip' => Request::ip(),
'data_of_registration' => \Carbon\Carbon::now(),
... /*Other form fields continue*/
'password' => Hash::make($data['password']),
]);
}

how to solve "Object of class Closure could not be converted to int"

I was going to call the data from model in gridview. I installed advanced grid view via composer and I am using \yiister\grid\widgets\ProgressColumn. but the prolem ProgressColumn widget is not taking
'value'=>function($model){
return $model->paxtashart;
},
as int value, it gives me error: Object of class Closure could not be converted to int
is there any possiblity that I can convert it to int or any other alternative?
here let me present you my entire code:
[
'class' => \yiister\grid\widgets\ProgressColumn::className(),
'attribute' => 'paxta_given',
'size' => \yiister\grid\widgets\ProgressColumn::SIZE_LARGE,
'isAnimated' => true,
'value'=>function($model){
$model->paxtashart;
},
// 'maxValue'=> $fermercha->paxtashart,
// 'minValue'=> $fermercha->paxta_given,
'progressBarClass' => function ($model, $column) {
return $model->{$column->attribute} > 60
? \yiister\grid\widgets\ProgressColumn::STYLE_SUCCESS
: \yiister\grid\widgets\ProgressColumn::STYLE_WARNING;
},
],
I tried this way:
$model->paxtashart
but it is jsut giving me 1 value for all attributes, it is not helping
here is what my model looks like:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "fermer".
*
* #property integer $id
* #property string $FIO
* #property integer $tuman_id
* #property string $Massiv
* #property integer $ferhojalik
* #property integer $maydoni
* #property integer $paxtamay
* #property integer $paxtashart
* #property integer $gallamay
* #property integer $gallashart
* #property integer $bog
* #property integer $uzum
* #property integer $poliz
* #property integer $sabzavot
* #property integer $chorva
*/
class Fermer extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'fermer';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['tuman_id', 'ferhojalik', 'maydoni', 'paxtamay', 'paxtashart', 'gallamay', 'gallashart', 'paxta_given', 'poliz', 'sabzavot', 'chorva','paxta_done'], 'integer'],
[['FIO', 'Massiv'], 'string', 'max' => 255],
[['image'], 'file', 'extensions' => ['png','jpg','jpeg']],
];
}
public function upload()
{
if ($this->validate() and $this->image->baseName) {
$this->image->saveAs(Yii::$app->basePath.'/web/uploads/' . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
return false;
}
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'FIO' => 'ФИО',
'tuman_id' => 'Туман номи',
'Massiv' => 'Массив номи',
'ferhojalik' => 'Фермер хўжалиги номи',
'maydoni' => 'Майдони',
'paxtamay' => 'Пахта майдони',
'paxtashart' => 'Пахта майдони шартнома режаси (тонна)',
'gallamay' => 'Ғалла майдони',
'gallashart' => 'Ғалла майдони шартнома режаси (тонна)',
'paxta_given' => 'Пахта шартнома бўйича топширилган тонна',
'image' => 'Расм',
'poliz' => 'Полизчилик',
'sabzavot' => 'Сабзавотчилик',
'chorva' => 'Чорвачилик',
];
}
// return $this->hasone(Extraagri::className(), ['id' => 'po_item_no']);
public function getDone()
{
return $this->hasone(done::classname(),['id'=>'paxta_done']);
}
/* public function getPoitem()
{
return $this->hasMany(Poitem::className(), ['id' => 'po_item_no']);
}*/
/* public function getExtraagri()
{
return $this->hasMany(Extraagri::className(), ['id' => 'id']);
}
*/
}
An anonymous function is an instance of Class closure. Try following variation
//assign the closure to variable
$value = function($model){
return $model->paxtashart;
}
$progressBarClass = function ($model, $column) {
return $model->{$column->attribute} > 60
? \yiister\grid\widgets\ProgressColumn::STYLE_SUCCESS
: \yiister\grid\widgets\ProgressColumn::STYLE_WARNING;
}
[
'class' => \yiister\grid\widgets\ProgressColumn::className(),
'attribute' => 'paxta_given',
'size' => \yiister\grid\widgets\ProgressColumn::SIZE_LARGE,
'isAnimated' => true,
'value'=>(int)$value($model), //invoke the closure and cast as integer
'progressBarClass' =>(string)$progressBarClass($model, $column), //invoke the closure and cast as string
],

Getting unknown property Exception in yii2

here I have a model in yii2
<?php
namespace app\models;
/**
* This is the model class for table "car_ad".
*
* #property integer $id
* #property integer $brand_id
* #property integer $sub_brand_id
* #property integer $sell_type
* #property integer $year
* #property integer $the_function
* #property integer $fuel_type_id
* #property integer $gearbox
* #property integer $sell_mode
* #property integer $real_price
* #property integer $prepayment
* #property integer $installment_price
* #property integer $no_installments
* #property integer $delivery_time_id
* #property integer $installments_period
* #property integer $body_status_id
* #property integer $body_color_id
* #property integer $inside_color_id
* #property integer $number_type
* #property string $description
* #property integer $ad_type_id
* #property integer $provice_id
* #property integer $city_id
* #property string $address
* #property string $lang
* #property string $lat
* #property string $creation_date
* #property integer $user_id
*/
class CarAd extends \yii\db\ActiveRecord
{
public $imageFiles;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'car_ad';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['brand_id', 'sub_brand_id', 'sell_type', 'year', 'used_value', 'fuel_type_id', 'gearbox', 'body_status_id', 'body_color_id', 'number_type', 'ad_type_id', 'provice_id', 'city_id', 'address', 'lang', 'lat', 'creation_date', 'user_id'], 'required'],
[['brand_id', 'sub_brand_id', 'sell_type', 'year', 'fuel_type_id', 'used_value ', 'gearbox', 'sell_mode', 'real_price', 'prepayment', 'installment_price', 'no_installments', 'delivery_time_id', 'installments_period', 'body_status_id', 'body_color_id', 'inside_color_id', 'number_type', 'ad_type_id', 'provice_id', 'city_id', 'creation_date', 'user_id'], 'integer'],
[['description'], 'string'],
[['address', 'lang', 'lat'], 'string', 'max' => 512],
[['imageFiles'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg', 'maxFiles' => 10],
];
}
public function upload()
{
foreach ($this->imageFiles as $file) {
$image = New CarAdImage();
$image->image = $file->baseName . '.' . $file->extension;
$image->car_ad_id = $this->id;
$image->save();
$file->saveAs('img/car_ad/' . $file->baseName . '.' . $file->extension);
}
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'شناسه', 'brand_id' => 'برند', 'sub_brand_id' => 'مدل','sell_type' => 'فروش به صورت',
'year' => 'سال','used_value' => 'کارکرد','fuel_type_id' => 'سیستم سوخت','gearbox' => 'گیربکس',
'sell_mode' => 'نوع فروش','real_price' => 'قیمت نقدی','prepayment' => 'پیش پرداخت','installment_price' => 'مبلغ هر قسط','no_installments' => 'تعداد اقساط','delivery_time_id' => 'موعد تحویل',
'installments_period' => 'دوره پرداخت',
'body_status_id' => 'وضعیت بدنه',
'body_color_id' => 'رنگ بدنه',
'inside_color_id' => 'رنگ داخل',
'number_type' => 'نوع پلاک',
'description' => 'توضیحات اضافی',
'ad_type_id' => 'نوع آگهی',
'provice_id' => 'استان',
'city_id' => 'شهرستان',
'address' => 'آدرس',
'lang' => 'طول جغرافیایی',
'lat' => 'عرض جغرافیایی',
'creation_date' => 'تاریخ ایجاد',
'user_id' => 'کاربر ایجاد کننده',
'imageFiles' => 'تصاویر آگهی'
];
}
}
when I want to submit the form I face with this error.
Getting unknown property: app\models\CarAd::used_value
but as you see I have this field in my fields.
My table name is car_ad.
what is the problem with my code?
Because this field is not present in the #property comment I guess you have added it after the model has been generated. If you have got the DB schema cached new fields are not fetched until cache is updated. Try to remove the cache for DB.
Yii::$app->cache->flush(); worked for me too

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