Yii2 How to auto register new user without using site/signup - yii2

I want to signup new user every time I add a new client. I do not want to manually register a new user using the web/site/signup form via the browser.
I am trying to auto register new users from ClientController and I am having no luck at all. No error returned, it is as if the code doesn't run at all.
I can easily register the same user through site controller at site/signup but can not at all auto register through another controller by calling SignupForm model. Please help
I have this in my client controller
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\helpers\Html;
use frontend\models\Client;
use frontend\models\SignupForm;
class ClientController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
public function actionCreate()
{
$model = new Client;
if ($model->load(Yii::$app->request->post()))
{
$model->save();
$useremail = $model->Email;
$signupForm = new SignupForm();
$signupForm->username = $useremail;
$signupForm->password = $useremail;
$signupForm->email = $useremail;
$signupForm->created_at = time();
$signupForm->picture = null;
$signupForm->created_by = Yii::$app->session->get('USER_ID');
$NewUser = $signupForm->signup();
print_r($NewUser);
exit;
}
else{
return $this->render('create', [
'model' => $model
]);
}
}
}
and this is my SignupForm code:
<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
use Yii;
/**
* Signup form
*/
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public $picture;
public $created_by;
/**
* #inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
[['picture'], 'string'],
[['picture'],'default', 'value'=>null],
[['created_by'], 'integer'],
[['created_by'], 'default', 'value'=>Yii::$app->session->get('USER_ID')],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
$this->created_by = Yii::$app->session->get('USER_ID');
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->created_by = $this->created_by;
$user->picture = $this->picture;
//Save user
$user->save(false);
return $user;
}
return null;
}
}

Related

How to insert multiple times the value of an attribute in single table in yii2

I have a model named Taluka. I am supposed to select District and enter as many talukas for that specific district. Every thing is working, but when I enter multiple talukas, only last taluka is getting saved in database table. I have also tried the solution given in Yii2 Insert multiple records of a same table
But the error I received is "Call to a member function isAttributeRequired() on array"
Model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "taluka".
*
*/
class Taluka extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public $talukas=[];
public static function tableName()
{
return 'taluka';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['DistrictId', 'Taluka'], 'required'],
[['DistrictId'], 'integer'],
[['talukas'], 'required'],
[['Taluka'], 'string', 'max' => 100],
[['DistrictId'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['DistrictId' => 'DistrictId']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'TalukaId' => 'Taluka ID',
'DistrictId' => 'District',
'talukas' => 'Taluka',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getDistrict()
{
return $this->hasOne(District::className(), ['DistrictId' => 'DistrictId']);
}
}
Controller:
<?php
namespace app\controllers;
use Yii;
use app\models\Taluka;
use app\models\TalukaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\District;
use app\models\Model;
/**
* TalukaController implements the CRUD actions for Taluka model.
*/
class TalukaController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Taluka models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new TalukaSearch();
$dataProvider = $searchModel->search(Yii::$app->request-`>queryParams);`
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Taluka model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Taluka model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Taluka();
if ($model->load(Yii::$app->request->post()) ) {
echo $model->DistrictId;
$talukalist = $model->talukas;
if(is_array($talukalist))
{
foreach($talukalist as $v)
{
}
}
foreach($talukalist as $talukalist)
{
//echo $talukalist;
$model->Taluka = $talukalist;
echo $model->Taluka;
$model->save(false);
}
//return $this->redirect(['view', 'id' => $model->TalukaId]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Taluka model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->TalukaId]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Taluka 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 Taluka model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Taluka the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Taluka::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
View:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use app\models\District;
use yii\helpers\ArrayHelper;
use unclead\multipleinput\MultipleInput;
/* #var $this yii\web\View */
/* #var $model app\models\Taluka */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="taluka-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form', 'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'horizontalCssClasses' => [
'label' => 'col-sm-5',
//'offset' => 'col-sm-offset-2',
//'wrapper' => 'col-sm-7',
'error' => '',
'hint' => '',
],
],]);?>
<div class="panel panel-primary " >
<div class="panel panel-heading"><font size="3"><b>Taluka</b></font></div>
<div class="row">
<div class="col-sm-5">
<?= $form->field($model, 'DistrictId')->dropDownList(ArrayHelper::map(District::find()->all(),'DistrictId','District'), ['prompt' => 'Select District']) ?>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<?php
echo $form->field($model, 'talukas')->widget(MultipleInput::className(), [
'max' => 500,
'min' => 1, // should be at least 2 rows
'allowEmptyList' => false,
//'enableGuessTitle' => true,
//'addButtonPosition' => MultipleInput::POS_HEADER // show add button in the header
]);
?>
</div>
</div>
</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>
At first, let’s understand why you have an error "Call to a member function isAttributeRequired() on array". The reason is in rules method:
public function rules()
{
return [
[['DistrictId', 'Taluka'], 'required'],
[['DistrictId'], 'integer'],
[['talukas'], 'required'],// <-- This line causes an error. Reqired filed in ActiveRecord model could not be an array.
[['Taluka'], 'string', 'max' => 100],
[['DistrictId'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['DistrictId' => 'DistrictId']],
];
}
So it's better to remove [['talukas'], 'required'] from rules(). It is a custom field so it is not checked by ActiveRecord logic.
Also, there is a strange logic in actionCreate(). Keep in mind, that you've added a custom field to your model and don't fill Taluka, which is required, according to you model rules(). So you can't just load $_POST into model, and need to iterate through talukas to create a new record for each:
public function actionCreate()
{
$model = new Taluka();
if ($model->load(Yii::$app->request->post())) {
$talukaList = $model->talukas;
if (is_array($talukaList)) {
foreach ($talukaList as $taluka) {
$talukaRecord = new Taluka();
$talukaRecord->DistrictId = $model->DistrictId;
$talukaRecord->Taluka = $taluka;
$talukaRecord->save();
}
}
return $this->redirect(['view', 'id' => $talukaRecord->TalukaId]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I assume, that TalukaId is an autoincrement primary key. After saving all records, it will redirect you to the last created taluka.

Insert checked rows from a gridview to a table in yii2

With reference to Insert multiple rows into table by checkboxcolumn in yii2 I'm asking this question. I'm trying to insert data into rawmaterial table. The data that will be inserted is coming from rmtemplate table. I've added a gridview that loads data from rmtemplate in the rawmaterial form. Along with the checked rows I have two more fields usedate, chargenumber which will be inserted with each row.
Bythe code below it only inserts a single row with no other data except chargenumber,usedate
_form.php
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
use yii\helpers\Json;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\models\Rawmaterial */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="rawmaterial-form">
<?php $form = ActiveForm::begin(); ?>
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-lg-6">
<?= $form->field($model, 'usedate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-6 col-sm-6 col-lg-6">
<?= $form->field($model, 'chargenumber')->textInput(['readOnly' => true]) ?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<?= GridView::widget([
'dataProvider' => $dataProvider2,
'filterModel' => $searchModel2,
//'id' => $mytable,
'columns' => [
[
'class' => 'kartik\grid\CheckboxColumn',
'name' => 'RawMaterialForm[rmtemplate_ids]',
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['value' => $model->id];
}
],
//'id',
//'productname',
[
'attribute'=>'productname',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Charge Name'],
],
'rmname',
'qty',
'cost',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','name' => 'submit', 'value' => 'create_update']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the chargeno */
$script = <<<EOD
$(window).load(function(){
$.get('index.php?r=rmprod/rawmaterial/get-for-chargeno',{ orderid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#rawmaterialform-chargenumber').attr('value',data.chargeno);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the chargeno */
?>
Rwmaterial model
<?php
namespace frontend\modules\rmprod\models;
use Yii;
/**
* This is the model class for table "rawmaterial".
*
* #property integer $id
* #property string $vname
* #property integer $rm_chid
* #property string $challan
* #property string $purchasedate
* #property string $purchaseqty
* #property string $rate
* #property string $rmname
* #property string $usedate
* #property string $useqty
* #property string $unitcost
* #property string $productname
* #property integer $chargenumber
*
* #property Pursum $rmCh
*/
class Rawmaterial extends \yii\db\ActiveRecord
{
public $mytable;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'rawmaterial';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rm_chid', 'chargenumber'], 'integer'],
[['purchasedate', 'usedate'], 'safe'],
[['vname', 'productname'], 'string', 'max' => 40],
[['challan'], 'string', 'max' => 20],
[['purchaseqty', 'rmname', 'useqty'], 'string', 'max' => 50],
[['rate', 'unitcost'], 'string', 'max' => 10],
[['rm_chid'], 'exist', 'skipOnError' => true, 'targetClass' => Pursum::className(), 'targetAttribute' => ['rm_chid' => 'ps_chid']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'vname' => 'Vname',
'rm_chid' => 'Rm Chid',
'challan' => 'Challan',
'purchasedate' => 'Purchasedate',
'purchaseqty' => 'Purchaseqty',
'rate' => 'Rate',
'rmname' => 'Rmname',
'usedate' => 'Usedate',
'useqty' => 'Useqty',
'unitcost' => 'Unitcost',
'productname' => 'Productname',
'chargenumber' => 'Chargenumber',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRmCh()
{
return $this->hasOne(Pursum::className(), ['ps_chid' => 'rm_chid']);
}
}
RawmaterialForm model
<?php
namespace frontend\modules\rmprod\models;
use Yii;
/**
* This is the model class for table "rawmaterial".
*
* #property integer $id
* #property string $vname
* #property string $challan
* #property string $purchasedate
* #property string $purchaseqty
* #property string $rate
* #property string $rmname
* #property string $usedate
* #property string $useqty
* #property string $unitcost
* #property string $productname
* #property integer $chargenumber
*/
class RawMaterialForm extends \yii\db\ActiveRecord
{
public $rmtemplate_ids;
public $mytable;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'rawmaterial';
}
/**
* #inheritdoc
*/
// public function rules()
// {
// return [
// [['purchasedate', 'usedate'], 'safe'],
// [['chargenumber'], 'integer'],
// [['vname', 'productname'], 'string', 'max' => 40],
// [['challan'], 'string', 'max' => 20],
// [['purchaseqty', 'rmname', 'useqty'], 'string', 'max' => 50],
// [['rate', 'unitcost'], 'string', 'max' => 10],
// ];
// }
public function rules()
{
return [
[['usedate'], 'safe'],
[['chargenumber'], 'integer'],
[['productname'], 'string', 'max' => 40],
[['rmname', 'useqty'], 'string', 'max' => 50],
[['unitcost'], 'string', 'max' => 10],
[['rmtemplate_ids'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'rmname' => 'Rmname',
'usedate' => 'Usedate',
'useqty' => 'Useqty',
'unitcost' => 'Unitcost',
'productname' => 'Productname',
'chargenumber' => 'Chargenumber',
];
}
}
Rawmaterial controller
<?php
namespace frontend\modules\rmprod\controllers;
use Yii;
use frontend\models\Rawmaterial;
use frontend\modules\rmprod\models\RawmaterialSearch;
use frontend\modules\rmprod\models\RmtemplateSearch;
use frontend\modules\rmprod\models\RawMaterialForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
/**
* RawmaterialController implements the CRUD actions for Rawmaterial model.
*/
class RawmaterialController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Rawmaterial models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new RawmaterialSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
/**
* Displays a single Rawmaterial model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Rawmaterial model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new RawMaterialForm();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
['create']
// redirect to where you want
);
}
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
/**
* Updates an existing Rawmaterial model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Rawmaterial 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']);
}
public function actionGetForChargeno($orderid)
{
$rates = Rawmaterial::find()->select('(max(chargenumber) + 1) as chargeno')->asArray()->one();
echo Json::encode($rates);
}
/**
* Finds the Rawmaterial model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Rawmaterial the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Rawmaterial::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function save()
{
try {
if ($this->validate()) {
// assuming Rmtemplate is the model used in RmtemplateSearch
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $this->rmtemplate_ids]);
foreach ($selectedRmtemplate->each() as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm->rmname;
$rawMaterial->usedate = $this->usedate;
$rawMaterial->useqty = $rm->qty;
$rawMaterial->unitcost = $rm->unitcost;
$rawMaterial->productname = $rm->productname;
$rawMaterial->chargenumber = $this->chargenumber;
if (!$rawMaterial->save()) {
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
}
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
return false;
}
}
The debug toolbar shows the following -
After moving save function to RawmaterialForm model
VarDump
public function actionCreate()
{
$model = new RawMaterialForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if($model->saveRawTemlate($model)) {
// success message
} else {
// failure message
}
return $this->redirect(['create']);
}
if ($rawMaterial->save()) { throw new \Exception('Error while saving rawMaterial!'); } else { var_dump($rawMaterial->getErrors());}
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
Vardump in Function
public function saveRawTemlate($model)
{
try {
// assuming Rmtemplate is the model used in RmtemplateSearch
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids]);
foreach ($selectedRmtemplate->each() as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm->rmname;
$rawMaterial->usedate = $model->usedate;
$rawMaterial->useqty = $rm->qty;
$rawMaterial->unitcost = $rm->unitcost;
$rawMaterial->productname = $rm->productname;
$rawMaterial->chargenumber = $model->chargenumber;
if (!$rawMaterial->save()) {
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
if ($rawMaterial->save()) { throw new \Exception('Error while saving rawMaterial!'); } else { var_dump($rawMaterial->getErrors());}
return false;
}
function saveRawTemlate
public function saveRawTemlate($model)
{
try {
// assuming Rmtemplate is the model used in RmtemplateSearch
//$selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids]);
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids])->all();
var_dump($selectedRmtemplate);
foreach ($selectedRmtemplate->each() as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm->rmname;
$rawMaterial->usedate = $model->usedate;
$rawMaterial->useqty = $rm->qty;
$rawMaterial->unitcost = $rm->unitcost;
$rawMaterial->productname = $rm->productname;
$rawMaterial->chargenumber = $model->chargenumber;
if (!$rawMaterial->save()) {
//var_dump($rawMaterial->getErrors()); exit;
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
return false;
}
Output
Controller
public function actionCreate()
{
$model = new RawMaterialForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if($model->saveRawTemlate($model)) {
// success message
} else {
// failure message
}
return $this->redirect(['create']);
}
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
Model
public function saveRawTemlate($model)
{
try {
// assuming Rmtemplate is the model used in RmtemplateSearch
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $model->rmtemplate_ids])->all();
foreach ($selectedRmtemplate as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm['rmname'];
$rawMaterial->usedate = $model->usedate;
$rawMaterial->useqty = $rm['qty'];
$rawMaterial->unitcost = $rm['unitcost'];
$rawMaterial->productname = $rm['productname'];
$rawMaterial->chargenumber = $model->chargenumber;
if (!$rawMaterial->save()) {
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
return false;
}

Insert multiple rows into table by checkboxcolumn in yii2

I have a table rawmaterial. The fields are - rmname, usedate, useqty, unitcost, productname, chargenumber. I've added a gridview (which comes from rmtemplate table) with a checkboxcolumn in the form. The gridview contains columns productname, rmname, qty, unitcost. How can I insert the checked rows along with usedate, chargenumber(which come from respective textboxes) in the table rawmaterial.
I've checked ActiveRecord batch insert (yii2) but not getting how to use it with checkbocolumn.
Checked How I can process a checkbox column from Yii2 gridview? - not quite sure with it.
Checked Yii2 How to properly create checkbox column in gridview for bulk actions? - I think it's not using activeform.
form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
/* #var $this yii\web\View */
/* #var $model frontend\models\Rawmaterial */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="rawmaterial-form">
<?php $form = ActiveForm::begin(); ?>
<div class="form-group">
<div class="col-xs-12 col-sm-12 col-lg-12">
<?= $form->field($model, 'usedate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<?= GridView::widget([
'dataProvider' => $dataProvider2,
'filterModel' => $searchModel2,
'columns' => [
['class' => 'kartik\grid\CheckboxColumn'],
//'id',
//'productname',
[
'attribute'=>'productname',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Charge Name'],
],
'rmname',
'qty',
[
'attribute' => 'unitcost',
'value' => 'unitcost.unitcost',
],
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<?= $form->field($model, 'chargenumber')->textInput()->hiddenInput()->label(false) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','name' => 'submit', 'value' => 'create_update']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the chargeno */
$script = <<<EOD
$(window).load(function(){
$.get('index.php?r=rmprod/rawmaterial/get-for-chargeno',{ orderid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#rawmaterial-chargenumber').attr('value',data.chargeno);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the chargeno */
?>
And it looks like below.
CreateAction looks like -
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if (isset($_POST['submit'])) {
if ($_POST('submit') == 'create_update' ) {
// then perform the insert
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
} else {
// no insert but render for filter ..
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
Update
RawMaterialForm.php
<?php
namespace frontend\modules\rmprod\models;
use Yii;
/**
* This is the model class for table "rawmaterial".
*
* #property integer $id
* #property string $vname
* #property string $challan
* #property string $purchasedate
* #property string $purchaseqty
* #property string $rate
* #property string $rmname
* #property string $usedate
* #property string $useqty
* #property string $unitcost
* #property string $productname
* #property integer $chargenumber
*/
class RawMaterialForm extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'rawmaterial';
}
/**
* #inheritdoc
*/
// public function rules()
// {
// return [
// [['purchasedate', 'usedate'], 'safe'],
// [['chargenumber'], 'integer'],
// [['vname', 'productname'], 'string', 'max' => 40],
// [['challan'], 'string', 'max' => 20],
// [['purchaseqty', 'rmname', 'useqty'], 'string', 'max' => 50],
// [['rate', 'unitcost'], 'string', 'max' => 10],
// ];
// }
public function rules()
{
return [
[['usedate'], 'safe'],
[['chargenumber'], 'integer'],
[['productname'], 'string', 'max' => 40],
[['rmname', 'useqty'], 'string', 'max' => 50],
[['unitcost'], 'string', 'max' => 10],
[['rmtemplate_ids'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'vname' => 'Vname',
'challan' => 'Challan',
'purchasedate' => 'Purchasedate',
'purchaseqty' => 'Purchaseqty',
'rate' => 'Rate',
'rmname' => 'Rmname',
'usedate' => 'Usedate',
'useqty' => 'Useqty',
'unitcost' => 'Unitcost',
'productname' => 'Productname',
'chargenumber' => 'Chargenumber',
];
}
}
RawmaterialController
<?php
namespace frontend\modules\rmprod\controllers;
use Yii;
use frontend\models\Rawmaterial;
use frontend\modules\rmprod\models\RawmaterialSearch;
use frontend\modules\rmprod\models\RmtemplateSearch;
use frontend\modules\rmprod\models\RawMaterialForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
/**
* RawmaterialController implements the CRUD actions for Rawmaterial model.
*/
class RawmaterialController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Rawmaterial models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new RawmaterialSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
/**
* Displays a single Rawmaterial model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Rawmaterial model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new RawMaterialForm();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
['create']
// redirect to where you want
);
}
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
/**
* Updates an existing Rawmaterial model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Rawmaterial 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']);
}
public function actionGetForChargeno($orderid)
{
$rates = Rawmaterial::find()->select('(max(chargenumber) + 1) as chargeno')->asArray()->one();
echo Json::encode($rates);
}
/**
* Finds the Rawmaterial model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Rawmaterial the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Rawmaterial::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function save()
{
try {
if ($this->validate()) {
// assuming Rmtemplate is the model used in RmtemplateSearch
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $this->rmtemplate_ids]);
foreach ($selectedRmtemplate->each() as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm->rmname;
$rawMaterial->usedate = $this->usedate;
$rawMaterial->useqty = $rm->qty;
$rawMaterial->unitcost = $rm->unitcost;
$rawMaterial->productname = $rm->productname;
$rawMaterial->chargenumber = $this->chargenumber;
if (!$rawMaterial->save()) {
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
}
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
return false;
}
}
Error
According to my understanding, you have to do two things.
Firstly, you have to grab all the checked rows data of the grid view as an array or object. You can see how to do that from Get Grid Data .
Secondly you have to change your create action for handling the data you fetch from that grid. You can take help from Batch Insert
Hope it helps...
Prepare additional model like RawMaterialForm with properties that will be taken from ActiveForm usedate, chargenumber and rmtemplate_ids. The last one is the array of GridView IDs. Remember to add rules() in the RawMaterialForm for the properties.
The view - just the GridView needs some tweaks. Extend the configuration for Checkbox column.
[
'class' => 'kartik\grid\CheckboxColumn',
'name' => 'RawMaterialForm[rmtemplate_ids]',
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['value' => $model->id];
}
],
The action:
public function actionCreate()
{
$model = new RawMaterialForm();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
// redirect to where you want
);
}
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
RawMaterialForm's save() method:
public function save()
{
try {
if ($this->validate()) {
// assuming Rmtemplate is the model used in RmtemplateSearch
$selectedRmtemplate = Rmtemplate::find()->where(['id' => $this->rmtemplate_ids]);
foreach ($selectedRmtemplate->each() as $rm) {
$rawMaterial = new Rawmaterial();
$rawMaterial->rmname = $rm->rmname;
$rawMaterial->usedate = $this->usedate;
$rawMaterial->useqty = $rm->qty;
$rawMaterial->unitcost = $rm->unitcost;
$rawMaterial->productname = $rm->productname;
$rawMaterial->chargenumber = $this->chargenumber;
if (!$rawMaterial->save()) {
throw new \Exception('Error while saving rawMaterial!');
}
}
return true;
}
} catch (\Exception $exc) {
\Yii::error($exc->getMessage());
}
return false;
}
This will copy every selected row into a new Rawmaterial row with additional inputs from ActiveForm.
In case of errors in $rawMaterial saving check $rawMaterial->errors property.
Fair warning - depending on the system performance this can be slow (or even fatal) in case of selecting many rows at once.

Yii2 Select2 - selected value on update - junction table (many to many)

I am successfully inserting new rows in my junction table (userlocations) on action create and I successfully update them on action update but the problem is on ation update the location_id field is always empty. It should retrieve the location_id's from userlocations table and populate the field on update but it doesnt.
Database: http://i.stack.imgur.com/JFjdz.png
UserController:
<?php
namespace backend\controllers;
use Yii;
use backend\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use backend\models\Locations;
use backend\models\Userlocations;
class UserController extends Controller
{
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();
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) ) {
$model->setPassword($model->password);
$model->generateAuthKey();
$userlocations->load(Yii::$app->request->post());
if ($model->save() && !empty($userlocations->location_id)){
foreach ($userlocations->location_id as $location_id) {
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
}
}
return $this->redirect(['user/index']);
} else {
return $this->render('create', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
}
}
/**
* 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 = $this->findModel($id);
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Userlocations::deleteAll(['user_id' => $id]);
$userlocations->load(Yii::$app->request->post());
if (!empty($userlocations->location_id)){
foreach ($userlocations->location_id as $location_id) {
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
}
}
return $this->redirect(['user/index']);
} else {
return $this->render('update', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
}
}
/**
* 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.');
}
}
}
User model:
class User extends \common\models\User
{
public $password;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'User';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique', 'message' => 'Username already taken!'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}
My form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use backend\models\Locations;
?>
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($userlocations, 'location_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'size' => Select2::MEDIUM,
'options' => ['placeholder' => 'Select a location ...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true,
],
]); ?>
<?= $form->field($model, 'status')->dropDownList(['10' => 'Active', '0' => 'Inactive']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
For multiple location select, use the plugin code as given below.
<?= Select2::widget([
'name' => 'Userlocations[location_id]',
'value' => $location_ids, // initial value
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'options' => ['placeholder' => 'Select your locations...', 'multiple' => true],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
]); ?>
$location_ids will be the location array you have previously selected during creation time.Also remember when you are making changes for more than one table,make sure you do it in a transaction.

Invalid validation rule: a rule must specify both attribute names and validator type, in Yii2

In my basic app project, I'm trying to integrate the signup form, I'm getting this error:
Invalid validation rule: a rule must specify both attribute names and validator type.
My code is here.
SignUpForm.php
<?php
namespace app\models;
use yii\base\Model;
use app\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $user_fname;
public $user_email;
public $user_password_hash;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_fname','user_email', 'user_password_hash'], 'required'],
// rememberMe must be a boolean value
['user_password_hash','match','pattern'=>'$\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '],
[['user_password_hash'],'string','min'=>6],
//email validation
['user_email','email']
[['user_email'], 'string', 'max' => 255],
[['user_fname'], 'string', 'max' => 45],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new SimUser();
$user->user_fname = $this->user_fname;
$user->user_email = $this->user_email;
$user->setPassword($this->user_password_hash);
$user->generateAuthKey();
$user->save();
return $user;
}
}
Site Controller.php/signup method
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,
]);
}
my view file
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'user_fname')->textInput() ?>
<?= $form->field($model, 'user_email')->textInput() ?>
<?= $form->field($model, 'user_password_hash')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
My User file, this s the file to which the data has to be posted.. I retrieve login details from here.
namespace app\models;
use Yii;
/**
* This is the model class for table "sim_user".
*
* #property integer $user_id
* #property string $user_email
* #property string $user_password_hash
* #property string $user_fname
* #property string $user_lname
* #property integer $user_company
* #property string $user_authcode
* #property integer $user_suspended
* #property string $user_created
* #property integer $user_deleted
* #property string $user_auth_key
* #property string $user_access_token
*/
class SimUser extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'sim_user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_email', 'user_password_hash']],
[['user_company', 'user_suspended', 'user_deleted'], 'integer'],
[['user_created'], 'safe'],
[['user_email'], 'string', 'max' => 255],
[['user_password_hash'], 'string', 'max' => 20],
[['user_fname', 'user_lname'], 'string', 'max' => 45],
[['user_auth_key'], 'string', 'max' => 32],
[['user_access_token'], 'string', 'max' => 100],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => Yii::t('app', 'User ID'),
'user_email' => Yii::t('app', 'User Email'),
'user_password_hash' => Yii::t('app', 'User Password Hash'),
'user_fname' => Yii::t('app', 'User Fname'),
'user_lname' => Yii::t('app', 'User Lname'),
'user_company' => Yii::t('app', 'User Company'),
'user_authcode' => Yii::t('app', 'User Authcode'),
'user_suspended' => Yii::t('app', 'User Suspended'),
'user_created' => Yii::t('app', 'User Created'),
'user_deleted' => Yii::t('app', 'User Deleted'),
'user_auth_key' => Yii::t('app', 'User Auth Key'),
'user_access_token' => Yii::t('app', 'User Access Token'),
];
}
public function getAuthKey() {
return $this->user_auth_key;
}
public function getId() {
return $this->user_id;
}
public function validateAuthKey($authKey) {
return $this->user_auth_key = $authkey;
}
public static function findIdentity($id) {
return self::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null) {
return $this->user_access_token;
}
public static function findByUsername($email){
return self::findOne(['user_email'=>$email]);
}
public function validatePassword($password){
return $this->user_password_hash === $password;
}
public function setPassword($password)
{
$this->user_password_hash = Yii::$app->security->generatePasswordHash($password);
}
public function generateAuthKey()
{
$this->user_auth_key = Yii::$app->security->generateRandomString();
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert))
{
if ($this->isNewRecord)
{
$this->user_auth_key = \Yii::$app->security->generateRandomString();
}
return true;
}
return false;
}
}
First rule in your SimUser class is probably causing this error.
return [
[['user_email', 'user_password_hash']],
...
];
Maybe you mean:
return [
[['user_email', 'user_password_hash'], 'required'],
...
];
In you code you have:
['user_email', 'email']
should be:
[['user_email', 'email'], 'email'],
or
[['user_email'], 'email'],