Getting unknown property: app\models\AlumnyS2::alumniintegrasi - php

I want to display data relation by making a relation between table alumniintegrasi with alumnys2, but when I made it with gridview, there was an error.
it said '
getting unknown property: app\models\AlumnyS2::alumniintegrasi.
here is the code
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use app\models\AlumniIntegrasi;
/* #var $this yii\web\View */
/* #var $searchModel app\models\AlumnyS2Search */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Alumny S2s');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="alumny-s2-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Alumny S2'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'NRP',
//'NamaMahasiswa',
[
'attribute' => 'NamaMahasiswa',
'value' => function($data) {
return $data->alumniintegrasi->NamaMahasiswa;
},
/*'filter' => Html::activeDropDownList($searchModel, 'orang_ID', ArrayHelper::map(Orang::find()->asArray()->all(), 'ID', 'Nama'),['class'=>'form-control','prompt' => 'Select Category']),
*/
],
'ProgramStudi',
'Tanggal_Masuk',
'Tanggal_Lulus',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
and here is the model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "alumnys2".
*
* #property string $NRP
* #property string $NamaMahasiswa
* #property string $ProgramStudi
* #property string $Tanggal_Masuk
* #property string $Tanggal_Lulus
*
* #property AlumniIntegrasi $nRP
*/
class AlumnyS2 extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'alumnys2';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['NRP', 'NamaMahasiswa'], 'required'],
[['NRP'], 'string', 'max' => 15],
[['NamaMahasiswa'], 'string', 'max' => 50],
[['ProgramStudi'], 'string', 'max' => 5],
[['Tanggal_Masuk', 'Tanggal_Lulus'], 'string', 'max' => 30],
[['NRP'], 'exist', 'skipOnError' => true, 'targetClass' => AlumniIntegrasi::className(), 'targetAttribute' => ['NRP' => 'NRP']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'NRP' => Yii::t('app', 'Nrp'),
'NamaMahasiswa' => Yii::t('app', 'Nama Mahasiswa'),
'ProgramStudi' => Yii::t('app', 'Program Studi'),
'Tanggal_Masuk' => Yii::t('app', 'Tanggal Masuk'),
'Tanggal_Lulus' => Yii::t('app', 'Tanggal Lulus'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getNRP()
{
return $this->hasOne(AlumniIntegrasi::className(), ['NRP' => 'NRP']);
}
}
I want to display NamaMahasiswa in table alumniintegrasi. how can I fix that?

You should use a proper getter for the field NamaMahasiswa
in your model
change the name of model getter (aviding case convention problem for name
/**
* #return \yii\db\ActiveQuery
*/
public function getNrp()
{
return $this->hasOne(AlumniIntegrasi::className(), ['NRP' => 'NRP']);
}
and add the getter simply use the attribute name (based on getter)
/* Getter for NamaMahasiswa */
public function getNamaMahasiswa() {
return $this->Nrp->NamaMahasiswa;
}
in the view
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'namaMahasiswa',
],
'ProgramStudi',
'Tanggal_Masuk',
'Tanggal_Lulus',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
NB using UpperCamleCase ( Pascal Notation) for database name is not the best choice .. for database is better use underscore notattion ..

Related

Unknown Property – yii\base\UnknownPropertyException

I got the error in the title when trying to display a relational field in the gridview.
I have the problem with statuscode.statusname.
What do I miss?
Thanks in advance!
My Projectsearch model:
<?php namespace frontend\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Project;
class ProjectSearch extends Project
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'client_id', 'status_id'], 'integer'],
[['number', 'name'], 'safe'],
[['client.name'], 'safe'],
[['statuscode.statusname'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['client.name']);
return array_merge(parent::attributes(), ['statuscode.statusname']);
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Project::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['client.name'] = [
'asc' => ['client.name' => SORT_ASC],
'desc' => ['client.name' => SORT_DESC],
];
$dataProvider->sort->attributes['statuscode.statusname'] = [
'asc' => ['statuscode.statusname' => SORT_ASC],
'desc' => ['statuscode.statusname' => SORT_DESC],
];
$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;
}
$query->joinWith(['client' => function($query) {
$query->from(['client' => 'clients']); }]);
$query->joinWith(['statuscode' => function($query) { $query->from(['statuscode' => 'statuses']); }]);
// grid filtering conditions
$query->andFilterWhere(['like', 'project.number', $this->number])
->andFilterWhere(['like', 'project.name', $this->name])
->andFilterWhere(['LIKE', 'client.name', $this->getAttribute('client.name')])
->andFilterWhere(['LIKE', 'statuscode.statusname', $this->getAttribute('statuscode.statusname')]);
return $dataProvider;
}
}
My view:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = 'Projects';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="project-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p><?= Html::a('Create Project', ['create'], ['class' => 'btn btn-success']) ?></p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'number',
'client.name',
'name',
[
'attribute' => 'statuscode.statusname',
'label' => 'Projectstatus',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
Nevermind, i got it! :)
return array_merge(parent::attributes(), ['client.name', 'statuscode.statusname']);
instead of:
return array_merge(parent::attributes(), ['client.name']);
return array_merge(parent::attributes(), ['statuscode.statusname']);
LOL

Field Declare Dynamically in PhpStorm Yii2?

I have a function in model
public static function updateDetail($model)
{
$model->username = $model->partnerApiDetail->username;
$model->password = $model->partnerApiDetail->password;
}
username and password are public properties in partner table
PatnerApiDetail is relation of Partner table with partner_api_detail
table.
Why phpstorm haven't find the relation both show the error
$model-username(field declared dynamically error)
$model->partnerApiDetail->username(field partnerAapiDetail not found)
What i have to do actually to override the error
<?php
namespace common\models;
use Yii;
use yii\db\Expression;
/**
* This is the model class for table "ad_partner_api_detail".
*
* #property int $id
* #property string $username
* #property string $password
* #property string $access_token
* #property bool $is_deleted
* #property int $is_active
* #property int $created_by
* #property int $updated_by
* #property string $created_at
* #property string $updated_at
* #property int $ad_partner_id
*
* #property Partner $Partner
*/
class PartnerApiDetail extends \yii\db\ActiveRecord
{
const statusDeleted = false;
const statusActive = 1;
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'ad_partner_api_detail';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['is_deleted'], 'boolean'],
[['is_active', 'created_by', 'updated_by', 'ad_partner_id'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
[['ad_partner_id'], 'required'],
[['username', 'password', 'access_token'], 'string', 'max' => 255],
[['ad_partner_id'], 'exist', 'skipOnError' => true, 'targetClass' => Partner::class, 'targetAttribute' => ['ad_partner_id' => 'id']],
['is_active', 'default', 'value' => self::statusActive],
['is_deleted', 'default', 'value' => self::statusDeleted],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'username' => Yii::t('app', 'Username'),
'password' => Yii::t('app', 'Password'),
'access_token' => Yii::t('app', 'Access Token'),
'is_deleted' => Yii::t('app', 'Is Deleted'),
'is_active' => Yii::t('app', 'Status'),
'created_by' => Yii::t('app', 'Created By'),
'updated_by' => Yii::t('app', 'Updated By'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
'ad_partner_id' => Yii::t('app', 'Partner Name'),
];
}
/**
* {#BlameableBehavior}
*/
public function behaviors()
{
return [
[
'class' => 'yii\behaviors\BlameableBehavior',
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => 'yii\behaviors\TimestampBehavior',
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPartner()
{
return $this->hasOne(Partner::class, ['id' => 'ad_partner_id']);
}
}
I have found the solution myself
Baically yii defined the property of relation with capital letter at the start
like here
* #property PartnerApiDetail[] $PartnerApiDetail
for this rlation
/**
* #return \yii\db\ActiveQuery
*/
public function getPartnerApiDetail()
{
return $this->hasOne(PartnerApiDetail::class, ['ad_partner_id' => 'id']);
}
You just need to small the first letter
* #property PartnerApiDetail[] $partnerApiDetail
Working like cham

Yii2 loginform doesn't work correctly

Loginform in yii2 doesn't validate password properly. I have typed right password but it says that password is wrong.
Here is my controller
use frontend\models\SignupForm;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\User;
use frontend\models\ContactForm;
use yii\widgets\ActiveForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup','language'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout','set-cookie','show-cookie'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Languages.
*/
public function actionLanguage()
{
if(isset($_POST['lang'])){
Yii::$app->language = $_POST['lang'];
$cookie = new \yii\web\Cookie([
'name' => 'lang',
'value' => $_POST['lang']
]);
Yii::$app->getResponse()->getCookies()->add($cookie);
}
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
And here is my model
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user;
/**
* #inheritdoc
*/
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'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
I have registration and user create pages. When I use data of registered user then all right and when I use data of created user then all is wrong.
this is UserController and I think the problem in generatePasswordHash() in actionCreate function of this controller
<?php
namespace frontend\controllers;
use Yii;
use frontend\models\User;
use frontend\models\UserSearch;
use frontend\models\Schedule;
use frontend\models\Photo;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\widgets\ActiveForm;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all User models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single User model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new User();
$schedule = new Schedule();
$pass = Yii::$app->request->post('password_hash');
if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post()) && $schedule->save()) {
$model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
$model->auth_key = Yii::$app->security->generateRandomString();
if ($model->save()) {
$photoList = $_FILES['files']['name'];
foreach ($photoList as $value) {
$newPhoto = new Photo;
$newPhoto->user_id = $model->id;
$newPhoto->photo = $value;
$newPhoto->save();
}
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'schedule' => $schedule,
]);
}
}
public function actionValidation()
{
$model = new User();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = User::findOne($id);
if (!$model) {
throw new NotFoundHttpException("The user was not found.");
}
$schedule = Schedule::findOne($model->id);
if (!$schedule) {
throw new NotFoundHttpException("Error");
}
if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post())) {
$isValid = $model->validate();
$isValid = $schedule->validate() && $isValid;
if ($isValid) {
$model->save(false);
$schedule->save(false);
return $this->redirect(['user/view', 'id' => $id]);
}
}
return $this->render('update', [
'model' => $model,
'schedule' => $schedule,
]);
}
/**
* Deletes an existing User 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 User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return User the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
view file
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Countries;
use kartik\date\DatePicker;
use kartik\time\TimePicker;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model frontend\models\User */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="user-form">
<?php $form = ActiveForm::begin(['id' => $model->formName(), 'enableAjaxValidation' => true, 'validationUrl' => Url::toRoute('user/validation')]); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'lastname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'phone')->textInput() ?>
<?= $form->field($model, 'notes')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'country')->dropDownList(ArrayHelper::map(Countries::find()->all(),'id','name'),
[
'prompt' => 'Страна',
'onchange' => '
$.post( "../states/lists?id='.'"+$(this).val(), function( data ) {
$( "select#user-state" ).html( data );
});'
]); ?>
<?= $form->field($model, 'state')->dropDownList([],
[
'prompt' => 'Регион',
'onchange' => '
$.post( "../cities/lists?id='.'"+$(this).val(), function( data ) {
$( "select#user-city" ).html( data );
});'
]); ?>
<?= $form->field($model, 'city')->dropDownList([],[ 'prompt' => 'Город' ]); ?>
<?= $form->field($model, 'salary')->textInput() ?>
<?= $form->field($model, 'hiredate')->widget(DatePicker::classname(), [
'options' => ['placeholder' => 'Enter hire date ...'],
'pluginOptions' => [
'autoclose'=>true,
'format'=> 'yyyy-mm-dd'
]
]); ?>
<?= $form->field($model, 'birthday')->widget(DatePicker::classname(), [
'options' => ['placeholder' => 'Enter birthday ...'],
'pluginOptions' => [
'autoclose'=>true,
'format'=> 'yyyy-mm-dd'
]
]); ?>
<?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
<?= $form->field($schedule, 'monday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'monday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'tuesday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'tuesday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'wednesday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'wednesday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'thursday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'thursday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'friday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'friday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'saturday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'saturday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'sunday_start')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($schedule, 'sunday_end')->widget(TimePicker::classname(), [
'name' => 't1',
'pluginOptions' => [
'showSeconds' => true,
'showMeridian' => false,
'minuteStep' => 1,
'secondStep' => 5,
]
]); ?>
<?= $form->field($model, 'dismission')->widget(DatePicker::classname(), [
'options' => ['placeholder' => 'Enter dismission date ...'],
'pluginOptions' => [
'autoclose'=>true,
'format'=> 'yyyy-mm-dd'
]
]); ?>
<div class="cont">
<div class="demo-gallery">
<ul id="lightgallery">
<li data-responsive="/bridalpro/frontend/web/uploads/dodge.jpg 375, /bridalpro/frontend/web/uploads/dodge.jpg 480, /frontend/web/uploads/dodge.jpg 800" data-src="/bridalpro/frontend/web/uploads/dodge.jpg"
data-sub-html="<h4>Fading Light</h4><p>Classic view from Rigwood Jetty on Coniston Water an old archive shot similar to an old post but a little later on.</p>">
<a href="">
<img class="img-responsive" src="/bridalpro/frontend/web/uploads/dodge.jpg">
<div class="demo-gallery-poster">
<img src="/bridalpro/frontend/web/img/zoom.png">
</div>
</a>
<div class="glyphicon glyphicon-trash gallery_delete" data-name="dodge.jpg"></div>
</li>
</ul>
</div>
</div>
<div id="content">
<input type="file" name="files[]" id="filer_input1" multiple="multiple">
</div>
<div id="content">
<input type="file" name="files[]" id="filer_input2" multiple="multiple">
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The issue, mainly, in your UserController. Look at the following lines in the actionCreate:
$pass = Yii::$app->request->post('password_hash');
if ($model->load(Yii::$app->request->post()) && $schedule->load(Yii::$app->request->post()) && $schedule->save()) {
$model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
.......
look again at the last line of the snippet:
$model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
It should not be like above, it should be:
$model->password_hash = Yii::$app->security->generatePasswordHash($pass);
In your user model, you should add a plain text for requesting password and then hash it in your controller.
here is the example.
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = date('Y-m-d h:i:s');
$model->setPassword($model->password);
$model->generateAuthKey();
$model->status = User::STATUS_ACTIVE;
$model->save();
return $this->redirect(['view', 'id' => $model->getPrimaryKey()]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
$model->password is the field you add manually in the user model.

Yii2 PHP Excel Error getAttributeLabel() on null

I have to implementing export excel using moonland PHP excel extension. When I implemented it, it throws the error:
"Call to a member function getAttributeLabel() on null".
Code
$dataProvider = new \app\models\Details;
\moonland\phpexcel\Excel::widget([
'models' => $dataProvider,
'mode' => 'export', //default value as 'export'
'columns' => ['id','name','address'], //without header working, because the header will be get label from attribute label.
//'header' => ['id' => 'Header Column 1','name' => 'Header Column 2', 'address' => 'Header Column 3'],
]);
My model
class Details extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'details';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id'], 'required'],
[['id'], 'integer'],
[['name', 'address'], 'string', 'max' => 50],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
/* return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'address' => Yii::t('app', 'Address'),
];*/
return [
'id' => 'ID',
'name' => 'Name',
'address' =>'Address',
];
}
}
Table
May i know what is the problem in that, thanks in advance for your idea

YII2 SqlDataProvider doesn't work relation table value

This is my model Riders:
<?php
namespace backend\models;
use Yii;
class Riders extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'riders';
}
public function rules()
{
return [
[['cagories_category_id', 'rider_firstname', 'rider_no_tlpn', 'rider_ucinumber', 'countries_id', 'rider_province', 'rider_city', 'rider_dateofbirth', 'rider_gender'], 'required'],
[['user_id', 'countries_id'], 'integer'],
[['rider_dateofbirth', 'cagories_category_id'], 'safe'],
[['rider_gender', 'rider_status'], 'string'],
[['rider_firstname', 'rider_lastname', 'rider_nickname', 'rider_province', 'rider_city'], 'string', 'max' => 45],
[['rider_email', 'rider_sponsor', 'rider_birthcertificate_url', 'rider_parental_consent_url'], 'string', 'max' => 100],
[['rider_no_tlpn'], 'string', 'max' => 15],
[['rider_ucinumber'], 'string', 'max' => 11]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'rider_id' => 'rider_id',
'cagories_category_id' => 'Category Name',
'user_id' => 'User Team',
'rider_firstname' => 'Rider Firstname',
'rider_lastname' => 'Rider Lastname',
'rider_nickname' => 'Rider Nickname',
'rider_email' => 'Rider Email',
'rider_no_tlpn' => 'Rider No Tlpn',
'rider_ucinumber' => 'Rider Ucinumber',
'countries_id' => 'Country Name',
'rider_province' => 'Rider Province',
'rider_city' => 'Rider City',
'rider_sponsor' => 'Rider Sponsor',
'rider_dateofbirth' => 'Rider Dateofbirth',
'rider_gender' => 'Rider Gender',
'rider_birthcertificate_url' => 'Rider Birthcertificate Url',
'rider_parental_consent_url' => 'Rider Parental Consent Url',
'rider_status' => 'Rider Status',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRegistrations()
{
return $this->hasMany(Registrations::className(), ['riders_rider_id' => 'rider_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCagoriesCategory()
{
return $this->hasOne(Categories::className(), ['category_id' => 'cagories_category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']) -> from(user::tableName() . 'ud');
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserDesc()
{
return $this->hasOne(UserDesc::className(), ['desc_id' => 'user_id']) -> from(['ud' => userDesc::tableName()]);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCountries()
{
return $this->hasOne(Countries::className(), ['id' => 'countries_id']);
}
}
This my Controller actionIndex:
$searchModel = new RidersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM riders WHERE user_id = :user_id',
[':user_id' => Yii::$app->user->identity->id])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM riders WHERE user_id = :user_id',
'params' => [':user_id' => Yii::$app->user->identity->id],
'totalCount' => $totalCount,
'key' => 'rider_id',
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => [
'cagories_category_id',
'rider_id',
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
]
]
]);
$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
This is my view index:
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Category Name',
'attribute'=>'cagories_category_id',
'value' => 'cagoriesCategory.category_name', <---Can't work again
],
[
'label' => 'BIB',
'attribute'=>'rider_id',
],
'rider_firstname',
'rider_email:email',
'rider_no_tlpn',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Before I use sqldataprovider, it can call from model function have relation, after use sqldataprovider can't work. How to get relation table value???
then before use it, i can to merge rider_firstname and rider_lastname with return $model->rider_firstname . " " . rider_lastname; after use sqldataprovider can't work too??
SqlDataProvider returns data as an array so You can't able to access related object with $dataProvider->models()
either you have to use ActiveDataProvider or change your Sql of SqlDataProvider with join condition
sql='sql' => 'SELECT * FROM riders inner join '. Categories::tableName() .' as c on c.category_id=riders.cagories_category_id WHERE user_id = :user_id'

Categories