Related
I want to search my data but the search is not working. I can't understand what's going wrong? please help to fix it... here is the code
payable controller
<?php
namespace app\controllers;
use Yii;
use app\models\Payable;
use app\models\PayableSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PayableController implements the CRUD actions for Payable model.
*/
class PayableController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Payable models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PayableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Payable model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Payable model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Payable();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Payable model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Payable model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Payable model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Payable the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Payable::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
PaybleSearch
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Payable;
/**
* PayableSearch represents the model behind the search form of `app\models\Payable`.
*/
class PayableSearch extends Payable
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'consumer_id', 'total_months_conservancy', 'water_arrears', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges'], 'integer'],
[['water_remarks', 'remarks', 'billing_months', 'issue_date', 'due_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Bill::find()->where('status=0');
// echo"<pre>";
// print_r($query);
// exit();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$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;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'consumer_id' => $this->consumer_id,
'total_months_conservancy' => $this->total_months_conservancy,
'water_arrears' => $this->water_arrears,
'conservancy_amount' => $this->conservancy_amount,
'total_water_and_conservancy_amount' => $this->total_water_and_conservancy_amount,
'tinure' => $this->tinure,
'dues_amount' => $this->dues_amount,
'per_month_charges' => $this->per_month_charges,
'no_of_months' => $this->no_of_months,
'total_amount_of_current_months' => $this->total_amount_of_current_months,
'advanced_pay' => $this->advanced_pay,
'arrears' => $this->arrears,
'arrears_period' => $this->arrears_period,
'total_bill' => $this->total_bill,
'after_due_date_charges' => $this->after_due_date_charges,
'total_after_due_date' => $this->total_after_due_date,
'balance_arears' => $this->balance_arears,
'water_charges_per_month' => $this->water_charges_per_month,
'conservancy_charges_per_month' => $this->conservancy_charges_per_month,
'four_months_water_charges' => $this->four_months_water_charges,
'four_months_conservancy_charges' => $this->four_months_conservancy_charges,
'issue_date' => $this->issue_date,
'due_date' => $this->due_date,
]);
$query->andFilterWhere(['like', 'water_remarks', $this->water_remarks])
->andFilterWhere(['like', 'remarks', $this->remarks])
->andFilterWhere(['like', 'billing_months', $this->billing_months]);
return $dataProvider;
}
}
Payable Model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "payable".
*
* #property int $id
* #property int $consumer_id
* #property int $total_months_conservancy
* #property int $water_arrears
* #property string $water_remarks
* #property int $conservancy_amount
* #property int $total_water_and_conservancy_amount
* #property int $tinure
* #property int $dues_amount
* #property int $per_month_charges
* #property int $no_of_months
* #property int $total_amount_of_current_months
* #property int $advanced_pay
* #property int $arrears
* #property int $arrears_period
* #property int $total_bill
* #property int $after_due_date_charges
* #property int $total_after_due_date
* #property int $balance_arears
* #property string $remarks
* #property int $water_charges_per_month
* #property int $conservancy_charges_per_month
* #property int $four_months_water_charges
* #property int $four_months_conservancy_charges
* #property string $billing_months
* #property string $issue_date
* #property string $due_date
*/
class Payable extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'payable';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['consumer_id', 'total_months_conservancy', 'water_arrears', 'water_remarks', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'remarks', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges', 'billing_months', 'issue_date', 'due_date'], 'required'],
[['consumer_id', 'total_months_conservancy', 'water_arrears', 'conservancy_amount', 'total_water_and_conservancy_amount', 'tinure', 'dues_amount', 'per_month_charges', 'no_of_months', 'total_amount_of_current_months', 'advanced_pay', 'arrears', 'arrears_period', 'total_bill', 'after_due_date_charges', 'total_after_due_date', 'balance_arears', 'water_charges_per_month', 'conservancy_charges_per_month', 'four_months_water_charges', 'four_months_conservancy_charges'], 'integer'],
[['issue_date', 'due_date'], 'safe'],
[['water_remarks'], 'string', 'max' => 250],
[['remarks'], 'string', 'max' => 350],
[['billing_months'], 'string', 'max' => 25],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'consumer_id' => 'Consumer ID',
'total_months_conservancy' => 'Total Months Conservancy',
'water_arrears' => 'Water Arrears',
'water_remarks' => 'Water Remarks',
'conservancy_amount' => 'Conservancy Amount',
'total_water_and_conservancy_amount' => 'Total Water And Conservancy Amount',
'tinure' => 'Tinure',
'dues_amount' => 'Dues Amount',
'per_month_charges' => 'Per Month Charges',
'no_of_months' => 'No Of Months',
'total_amount_of_current_months' => 'Total Amount Of Current Months',
'advanced_pay' => 'Advanced Pay',
'arrears' => 'Arrears',
'arrears_period' => 'Arrears Period',
'total_bill' => 'Total Bill',
'after_due_date_charges' => 'After Due Date Charges',
'total_after_due_date' => 'Total After Due Date',
'balance_arears' => 'Balance Arears',
'remarks' => 'Remarks',
'water_charges_per_month' => 'Water Charges Per Month',
'conservancy_charges_per_month' => 'Conservancy Charges Per Month',
'four_months_water_charges' => 'Four Months Water Charges',
'four_months_conservancy_charges' => 'Four Months Conservancy Charges',
'billing_months' => 'Billing Months',
'issue_date' => 'Issue Date',
'due_date' => 'Due Date',
];
}
public function getconsumerId()
{
return $this->hasOne(Plot::className(),['id' => 'consumer_id']);
}
}
View.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Payable */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Payables', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="payable-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'consumer_id',
'total_months_conservancy',
'water_arrears',
'water_remarks',
'conservancy_amount',
'total_water_and_conservancy_amount',
'tinure',
'dues_amount',
'per_month_charges',
'no_of_months',
'total_amount_of_current_months',
'advanced_pay',
'arrears',
'arrears_period',
'total_bill',
'after_due_date_charges',
'total_after_due_date',
'balance_arears',
'remarks',
'water_charges_per_month',
'conservancy_charges_per_month',
'four_months_water_charges',
'four_months_conservancy_charges',
'billing_months',
'issue_date',
'due_date',
],
]) ?>
</div>
Index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\PayableSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Payables';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="payable-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create Payable', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//
'id',
[ 'header'=> 'Consumer Name',
'attribute'=>'consumer_id',
'value'=>'consumerId.allottee_name',
],
// 'total_months_conservancy',
// 'water_arrears',
// 'water_remarks',
// 'conservancy_amount',
//'total_water_and_conservancy_amount',
//'tinure',
//'dues_amount',
//'per_month_charges',
//'no_of_months',
//'total_amount_of_current_months',
//'advanced_pay',
'arrears',
//'arrears_period',
'total_bill',
//'after_due_date_charges',
'total_after_due_date',
//'balance_arears',
//'remarks',
//'water_charges_per_month',
//'conservancy_charges_per_month',
//'four_months_water_charges',
//'four_months_conservancy_charges',
'billing_months',
//'issue_date',
'due_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I want to make a search but the search is not working. I tried but fails. I could not found any error.please help me in finding the issue
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.
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'],
basically. I have a problem with 2 things:
I'm using dynamic forms, the user can add as many as he needs to input all of the invoices at hand. I have a field (invoice_loadamount), i want to sum all of the invoice_loadamount fields. So if the user generates 3 forms i want it to sum dynamic form one(invoice_loadamount field 1) + dynamic form two.(invoice_loadamount field 2) + dynamic form three(invoice_loadamount field 3). How can i make this? Auto sum this field from every form he generated?
My second problem is that i want to then retrieve data from a table (vehicles, column vehicle_capacity) and then compare in such a way that it will validate if the sum is greater than the vehicle_maxcap and then give an error if so.
My form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Drivers;
use app\models\Vehicles;
use app\models\Invoices;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model app\models\Archive */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="archive-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese el numero de cedula...'],
'pluginOptions' => [
'allowClear' => true],
]); ?>
<div align="right"><?= Html::a('Add driver', ['/drivers/create'],
['target'=>'_blank']); ?>
</div>
<?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'),
'language' => 'en',
'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<div align="right"><?= Html::a('Add vehicle', ['/vehicles/create'],
['target'=>'_blank']); ?>
</div>
<div class="row"> <div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Facturas</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsInvoices[0],
'formId' => 'dynamic-form',
'formFields' => [
'invoice_number',
'invoice_loadamount',
'invoice_date',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsInvoices as $i => $modelInvoices): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Facturas</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelInvoices->isNewRecord) {
echo Html::activeHiddenInput($modelInvoices, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_date", ['enableAjaxValidation' => true])->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>',
'options' => ['class' => 'form-control picker'],
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-mm-yyyy'
]
]);?>
</div>
</div><!-- .row -->
<div class="row">
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</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>
My archive model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "archive".
*
* #property integer $id
* #property string $driver_identitynum
* #property string $vehicle_lp
* #property string $DateCreated
*
* #property Invoices[] $invoices
*/
class Archive extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'archive';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['driver_identitynum', 'vehicle_lp'], 'required'],
[['DateCreated'], 'safe'],
[['driver_identitynum', 'vehicle_lp'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'driver_identitynum' => 'Cedula del conductor:',
'vehicle_lp' => 'Placa del vehiculo:',
'DateCreated' => 'Date Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getInvoices()
{
return $this->hasMany(Invoices::className(), ['archive_id' => 'id']);
}
}
My vehicle model:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "vehicles".
*
* #property integer $vehicle_id
* #property string $vehicle_model
* #property string $vehicle_lp
* #property string $vehicle_maxcap
*/
class Vehicles extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'vehicles';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'required'],
[['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'string', 'max' => 100]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'vehicle_id' => 'Vehicle ID',
'vehicle_model' => 'Vehicle Model',
'vehicle_lp' => 'Vehicle Lp',
'vehicle_maxcap' => 'Vehicle Maxcap',
];
}
public function getfullTruck()
{
return $this->vehicle_lp.' - '.$this->vehicle_model.' - '.$this->vehicle_maxcap.'kgs';
}
}
My invoice model:
<?php
namespace app\models;
use Yii;
use yii\db\Query;
/**
* This is the model class for table "invoices".
*
* #property integer $id
* #property string $invoice_number
* #property string $invoice_loadamount
* #property string $invoice_date
* #property integer $archive_id
* #property string $DateProcessed
*
* #property Archive $archive
*/
class Invoices extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'invoices';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'required'],
[['archive_id'], 'integer'],
[['DateProcessed'], 'safe'],
//[['invoice_date'],'date','format'=>'dd-mm-yyyy','min'=>date('d-m-Y',time()-60*60*24*5)],
//Checks if invoice date put in is older than 5 days
[['invoice_date'], 'date', 'format'=>"dd-MM-yyyy", 'min'=>date("d-m-Y",strtotime('-5 days'))],
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'string', 'max' => 100]];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'invoice_number' => 'Numero de factura:',
'invoice_loadamount' => 'Carga de la factura(kgs):',
'invoice_date' => 'Fecha de emision de la factura:',
'archive_id' => 'Archive ID',
'DateProcessed' => 'Fecha de registro:'];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getArchive()
{
return $this->hasOne(Archive::className(), ['id' => 'archive_id']);
}
public function compareweight($attribute,$params)
{
$inputlp=($this->invoice_loadamount);
$row = (new \yii\db\Query())
->select('vehicle_lp')
->from('vehicles')
->where("vehicle_lp=$vehiclelp")
->all();
}
}
My controller:
<?php
namespace app\controllers;
use Yii;
use app\models\Vehicles;
use app\models\VehiclesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* VehiclesController implements the CRUD actions for Vehicles model.
*/
class VehiclesController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Vehicles models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new VehiclesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Vehicles model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Vehicles model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Vehicles();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->vehicle_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Vehicles 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->vehicle_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Vehicles 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 Vehicles model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Vehicles the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Vehicles::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
As you can see from the HTML <input type="text" id="invoices-0-invoice_loadamount" class="form-control" name="Invoices[0][invoice_loadamount]" maxlength="100"> the loadamount input field is like this. So on the controller side either create function or update function will receive post data as $_POST['Invoices'] as an array like
array(
"0"=>array("invoice_number" => "132412", "invoice_loadamount" =>"34.00", "invoice_date" =>"2015-03-04"),
"1"=>array("invoice_number" => "352223", "invoice_loadamount" =>"233.00", "invoice_date" =>"2016-03-04"),
...
);
where 0, 1 represents each form added. In your case form one, form two etc.
What you need to do is just loop through the array you get from the array. Like this:
if (Yii::$app->request->isPost) {
$data = Yii::$app->request->post();
$invoices = $data['Invoices'];
$total = 0;
if(sizeof($invoices) > 0){
foreach($invoices as $one_invoice){
$one_loadamount = floatval($one_invoice['invoice_loadamount']);
$total += $one_loadamount;
}
}
//then you get the total amount as $total
}
for problem 2, you can then (assume that you already have the vehicle_id).
$vehicle = Vehicles::find()->where(['id'=>$vehicle_id])->one();
if($total > $vehicle->maxcap){
\Yii::$app->getSession()->setFlash('danger', 'Total is larger than max cap');
}
Since the second problem depends on a specific vehicles, you need to get its id first.
When I'm selecting First Category - I can see the data in firebug that should populate in the secon level but it's instead populating 0,1,2,3,4 and I'm unable to select it.
My _form is
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\View;
use frontend\assets\XyzAsset;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\Productnames;
use kartik\depdrop\DepDrop;
use yii\helpers\Json;
//XyzAsset::register($this);
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->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,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'cat-id'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Controller -
<?php
namespace frontend\modules\production\controllers;
use Yii;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\ProductbatchSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
/**
* ProductbatchController implements the CRUD actions for Productbatch model.
*/
class ProductbatchController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Productbatch models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new ProductbatchSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Productbatch model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Productbatch model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Productbatch();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->itemid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Productbatch 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->itemid]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Productbatch 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 actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = Productbatch::getBatchNo($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
/**
* Finds the Productbatch model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Productbatch the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Productbatch::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Model
<?php
namespace frontend\modules\production\models;
use Yii;
/**
* This is the model class for table "productbatch".
*
* #property integer $itemid
* #property string $productname
* #property string $batchno
* #property string $mfgdate
* #property string $expdate
* #property double $mrp
* #property double $rate
*
* #property Productnames $productname0
*/
class Productbatch extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'productbatch';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['batchno'], 'string'],
[['mfgdate', 'expdate'], 'safe'],
[['mrp', 'rate'], 'number'],
[['productname'], 'string', 'max' => 25]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'itemid' => 'Itemid',
'productname' => 'Productname',
'batchno' => 'Batchno',
'mfgdate' => 'Mfgdate',
'expdate' => 'Expdate',
'mrp' => 'Mrp',
'rate' => 'Rate',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductname0()
{
return $this->hasOne(Productnames::className(), ['productnames_productname' => 'productname']);
}
public static function getBatchNo($cat_id)
{
$data = static::find()->where(['productname'=>$cat_id])->select(['batchno'])->asArray()->all();
$value = (count($data) == 0) ? ['' => ''] : $data;
return $value;
}
}
The output looks like -