Related
The connection between the modules does not work, and because of this, the data in the table is not displayed. I can not understand why
Code in the controller
public function actionIndex()
{
$searchModel = new SuggestedNewsSearch();
$dataProvider = $searchModel->getAllNews(Yii::$app->request->queryParams);
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
code in suggestedNewsSearch.php
class SuggestedNewsSearch extends SuggestedNews
{
public function getAllNews($params)
{
$query = $this::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if ($this->validate() AND !($this->load($params))) {
return $dataProvider;
}
if (!empty($this->getAttribute('title'))) {
$query->andFilterWhere(['LIKE', 'title', $this->getAttribute('title')]);
}
if (!empty($this->getAttribute('category'))) {
$query->andFilterWhere(['LIKE', 'category', $this->getAttribute('category')]);
}
if (!empty($this->getAttribute('status'))) {
switch (mb_strtolower($this->getAttribute('status'))) {
case $this::APPROVED:
$status = $this::ACTIVE_STATUS;
break;
case $this::NOT_APPROVED:
$status = $this::DEACTIVATED_STATUS;
break;
}
$query->andFilterWhere(['=', 'status', $status]);
}
return $dataProvider;
}
}
code on SuggestedNews.php
class SuggestedNews extends \yii\db\ActiveRecord
{
CONST ACTIVE_NEWS = 1;
CONST ACTIVE_STATUS = 1;
CONST DEACTIVATED_STATUS = 0;
CONST APPROVED = 'одобренно';
CONST NOT_APPROVED = 'не одобренно';
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'suggested_news';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['news'], 'string'],
[['category', 'status'], 'integer'],
[['date'], 'safe'],
[['title', 'news_source'], 'string', 'max' => 255],
[['category'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'news' => 'News',
'category' => 'Category',
'status' => 'Status',
'date' => 'Date',
'news_source' => 'News Source',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category']);
}
public function deleteNewsById($id)
{
$customer = $this::findOne($id);
if ($customer->delete()) return true;
else return false;
}
public function getNewsByIdWithCategory($id){
return $this::find()->where(['id' => $id])->with('category')->one();
}
}
code on Category.php
class Category extends \yii\db\ActiveRecord
{
CONST STATUS_CATEGORY_OFF = 0;
CONST STATUS_CATEGORY_ON = 1;
CONST NEW_CATEGORY_INTEGER = 01;
CONST NEW_CATEGORY_NAME = 'New Category';
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'category';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['name', 'status_category'], 'required'],
[['status_category'], 'integer'],
[['name'], 'string', 'max' => 255],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'status_category' => 'Status Category',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSuggestedNews()
{
return $this->hasMany(SuggestedNews::className(), ['category' => 'id']);
}
public function getAllCategories(){
return $this::find()->where(['status_category' => $this::STATUS_CATEGORY_ON])->all();
}
}
my index.php file(view)
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'attribute' => 'title',
'format' => 'text',
'label' => 'title',
'filter' => true,
],
[
'attribute' => 'category.Category',
'format' => 'text',
'label' => 'Category',
],
[
'attribute' => 'status',
'filter' => true,
'value' => function($model) {
if($model->status == 1){
return $model::APPROVED;
}else{
return $model::NOT_APPROVED;
}
}
],
'date',
[
'class' => 'yii\grid\ActionColumn',
],
],
]);
?>
and on result i have this:result table
enter image description here
table category
table suggested_news
You field name and relation are the same, so You have to change Category relation name like this:
/**
* #return \yii\db\ActiveQuery
*/
public function getCategory1()
{
return $this->hasOne(Category::className(), ['id' => 'category']);
}
//Gridview
//...
[
'attribute' => 'category',
'label' => 'Category',
'value' => function($model){
return $model->category1->name;
}
],
//...
//or
//...
[
'attribute' => 'category1.name',
'format' => 'text',
'label' => 'Category',
],
Hope it will helps.
I'm trying to save a field from another table in update action. Here is my update action.
public function actionUpdateResumo($id)
{
$model = $this->findModel($id);
$model->situacao = $model->nginAgentDetail->situacao;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$nginAgentDet = NginAgentDetail::find()
->where(['CLIENT_ID'=>$id])->one();
$nginAgentDet->situacao = Yii::$app->request->post()['EtuLoja']['situacao'];
if ($model->save() && $nginAgentDet->save()) {
return $this->redirect(['view', 'id' => $model->ID]);
} else {
var_dump($nginAgentDet->getErrors());die;
}
} else {
return $this->render('update-resumo', [
'model' => $model,
]);
}
}
When i click update it displays the message:
Client ID is invalid.
Client ID is a field from the other table (NginAgentDetail)
In my model i have this relation:
public function getNginAgentDetail()
{
return $this->hasOne(NginAgentDetail::className(),['CLIENT_ID' => 'ID']);
}
and in the other table i have this relation:
public function getEtuLojas()
{
return $this->hasMany(EtuLoja::className(), ['ID' => 'CLIENT_ID']);
}
NginAgentDetail model:
class NginAgentDetail extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'ngin_agent_detail';
}
public function rules()
{
return [
[['situacao'], 'string'],
// [['valMoeda'], 'number'],
[['CLIENT_ID'], 'integer'],
[['OPERATION_DATE', 'CATEGORY', 'MOV_TYPE', 'VALUE', 'COMMISSION', 'AFTER_BALANCE', 'ORIGIN_DESTINY', 'VALUES', 'USER'], 'string', 'max' => 100],
[['CLIENT_ID'], 'exist', 'skipOnError' => true, 'targetClass' => MasterLoja::className(), 'targetAttribute' => ['CLIENT_ID' => 'id']],
];
}
public function attributeLabels()
{
return [
'id_pk' => 'Id Pk',
'OPERATION_DATE' => 'Operation Date',
'CLIENT_ID' => 'Client ID',
'CATEGORY' => 'Category',
'MOV_TYPE' => 'Mov Type',
'VALUE' => 'Value',
'COMMISSION' => 'Commission',
'AFTER_BALANCE' => 'After Balance',
'ORIGIN_DESTINY' => 'Origin Destiny',
'VALUES' => 'Values',
'USER' => 'User',
'situacao' => 'Status',
];
}
public function getEtuLojas()
{
return $this->hasMany(EtuLoja::className(), ['ID' => 'CLIENT_ID']);
}
public function getMasterLoja()
{
return $this->hasMany(MasterLoja::className(), ['id' => 'ORIGIN_DESTINY']);
}
}
FindModel function:
protected function findModel($id)
{
if (($model = EtuLoja::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
EDIT
I found what was causing te invalid Client ID message. It was this validation rule in NginAgentDetail model:
[['CLIENT_ID'], 'exist', 'skipOnError' => true, 'targetClass' => MasterLoja::className(), 'targetAttribute' => ['CLIENT_ID' => 'id']],
The problem now is that it appears to be saving to the database but when i return to the gridview the attribute situacao stays the same, i mean it doesn't update.
So let's say I've got a custom request called CreateReviewRequest.
In this request, I've got this method:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required_if(auth->logged)',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
As you can see in the name key, I want from the client to be required to fill the name field if he's not logged in.
So my question is, how can I exactly require my client to fill the name when he's a guest?
You can use check() method:
public function rules()
{
return [
'name' => auth()->check() ? 'required' : '',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
Can't you make a simple check?
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
if (auth()->check()) {
return [
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
return [
'name' => 'required',
'comments' => 'required|max:255',
'stars' => 'required|min:1|max:5',
];
}
Member only:
$validator = Validator::make($request->all(), [
'email' => auth()->check() ? '' : 'required|min:5|max:60|email',
]);
Guest only:
$validator = Validator::make($request->all(), [
'user_id' => auth()->check() ? 'required|integer|min:1' : '',
]);
Both:
$validator = Validator::make($request->all(), [
'message' => 'required|min:10|max:1000'
]);
Combined:
$validator = Validator::make($request->all(), [
'email' => auth()->check() ? '' : 'required|min:5|max:60|email',
'user_id' => auth()->check() ? 'required|integer|min:1' : '',
'message' => 'required|min:10|max:1000'
]);
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 ActiveDataProvider sort using count in relational ?
I've 3 tables, bellow :
And I displaying data from table inventory_device_type, here is the code :
Controller :
<?php
namespace app\controllers\inventory;
use Yii;
use yii\base\Action;
use app\models\tables\InventoryDeviceType;
class DeviceInventory extends Action
{
public function run()
{
$model = new InventoryDeviceType();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->controller->render('device-inventory',[
'dataProvider' => $dataProvider,
]);
}
}
Model :
<?php
namespace app\models\tables;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
class InventoryDeviceType extends ActiveRecord
{
public static function tableName()
{
return 'inventory_device_type';
}
public function rules()
{
return [
[['name','id_device_vendor'],'required'],
['name','unique']
];
}
public function attributeLabels()
{
return [
'id_device_vendor' => 'Device Vendor',
];
}
/** queries **/
public function findData($id)
{
if(($data = self::findOne($id)) == null){
throw new NotFoundHttpException;
}else{
return $data;
}
}
public function getNormal()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'normal'])->count();
}
public function getBroken()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'broken'])->count();
}
public function getSold()
{
return $this->getList()->where(['inventory_device_list.device_condition' => 'sold'])->count();
}
public function getTotal()
{
return $this->getList()->where(['!=','inventory_device_list.device_condition',''])->count();
}
public static function getVendorList($sort=[])
{
return InventoryDeviceVendor::find()->orderBy($sort)->all();
}
public function search($params, $spesific=[],$sort=[])
{
$query = self::find();
$query->where($spesific);
$query->joinWith(['list']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => $sort]
]);
$dataProvider->sort->attributes['vendor_name'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];
/** sort on page device-inventory **/
$dataProvider->sort->attributes['device_vendor'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];
/** sort on page device-inventory end **/
return $dataProvider;
}
/** queries end **/
/** relation **/
public function getListLeft()
{
return InventoryDeviceList::find();
}
public function getList()
{
return $this->hasMany(InventoryDeviceList::className(),['id_device_type' => 'id']);
}
public function getVendorLeft()
{
return InventoryDeviceVendor::find();
}
public function getVendor()
{
return $this->hasOne(InventoryDeviceVendor::className(),['id' => 'id_device_vendor']);
}
/** relation end **/
}
and here is the view :
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'layout' => '<div class="table-responsive">{items}</div> {summary} {pager}',
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'headerOptions' => ['width' => 50]
],
'name',
[
'attribute' => 'device_vendor',
'class' => 'yii\grid\DataColumn',
'value' => function($data){
return $data->vendor->name;
}
],
[
'attribute' => 'normal',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getNormal(),'#',['class' => 'label label-success']);
},
],
[
'attribute' => 'sold',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getSold(),'#',['class' => 'label label-warning']);
},
],
[
'attribute' => 'broken',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getBroken(),'#',['class' => 'label label-danger']);
},
],
[
'attribute' => 'Total',
'class' => 'yii\grid\DataColumn',
'format' => 'html',
'value' => function($data){
return Html::a($data->getTotal(),'#',['class' => 'label label-primary']);
},
],
],
]);
?>
and how to sort it, like normal, broken, and, sold ?
here is : the result view :
the header normal, sold, broke and all not sortable, i can sort by relation if not using count like this code (like Device Vendor):
$dataProvider->sort->attributes['device_vendor'] = [
'asc' => ['inventory_device_vendor.name' => SORT_ASC],
'desc' => ['inventory_device_vendor.name' => SORT_DESC],
];