During user input validation I would like to compare an attribute with a value.
I have this code:
['ao_id', 'compare', 'when' => function($model) {
return $model->lqp_id == 24 || $model->lqp_id == 26 || $model->lqp_id == 46;
}, 'compareValue' => 50],
It works (however only when 'enableClientValidation' => false), but is it possible, to show rather the name of the foreign attribute somehow? Because it doesn't help much if the user is getting an error message that outer surface (ao_id) must be 50. Nobody has a clue what does it mean, because in the dropdown you see only the names and not the ids. Many thanks!
First of all, if you want your conditional validation to work on the client-side too (when enableClientValidation=>true), then add the whenClient property which contains the javascript code that will do the validation.
Second, you can use the message property to specify a custom validation error.
[
'ao_id',
'compare',
'when' => function ($model) {
return $model->lqp_id == 24 || $model->lqp_id == 26 || $model->lqp_id == 46;
},
'whenClient' => "function (attribute, value) {
return $('#lqp_id').val() == '24' || $('#lqp_id').val() == '26' || $('#lqp_id').val() == '46';
}",
'compareValue' => 50,
'message'=>'ao_id must be 50 when lqp_id is 24, 26 or 46'
]
Attention: be sure to check and change the id of the input field $('#lqp_id') as this is most likely different to my example.
Add message key where you define your own message that will be displayed instead of default one.
Related
So I have a structure like so:
{
documentGroup: {
Id: 000
Children: [
{
Id: 000
Status: 1
},
{
Id: 000
Status: 2
},...
]
},
},
Is there a way to write an ngIf statement to check if all Children elements have Status == 1?
EDIT:
When I try this
documentGroup.children.every(({status}) => status === 1)
I get the error:
Parser Error: Missing expected ) at column 41 in [documentGroup.children.every(({status}) => status === 1)
You will need add a new function into your component's .ts file which would do the check for you and you can then reference it in the template as follows (documentsObj is the object that contains the object in your example):
.ts:
isAllStatusOne(): boolean {
return this.documentsObj.documentGroup.Children.every(({Status}) => Status === 1);
}
.html:
*ngIf="isAllStatusOne()"
The above code should trigger change detection at the start and any time a property value changes in the documentsObj object which should then proceed to check if all Children have a Status property that is 1. If they all are 1 - every should return true and the nested elements/components should be rendered.
Alternatively you can use find which when using with Status !== 1 condition would return undefined when all Status properties are 1, hence coupled with ! at the start it will result in true:
isAllStatusOne(): boolean {
return !this.documentsObj.documentGroup.Children.find(({Status}) => Status !== 1);
}
you could also make use of an angular pipe, to check the status and return something else instead (in your case, you could check the status and return true or false).
Transforming Data Using Pipes
I am trying to import data from excel file into database tables in Laravel. I have successfully imported the data but If I mistakenly leave a field empty then I get error that column cannot be null. So I need check if the all necessary data is provided.
I use this code.
IndependentContractor::create(['staff_id' => $staff->id, 'address' => $excel_row['address'], 'longitude' => $excel_row['longitude'], 'latitude' => $excel_row['latitude'], 'tax_id' => $excel_row['tax_id'], 'business_name' => $excel_row['business_name'], 'person_incharge' => $excel_row['person_incharge'], 'phone_of_person_incharge' => $excel_row['phone_of_person_incharge'], 'general_manager' => $excel_row['general_manager'], 'phone_of_general_manager' => $excel_row['phone_of_general_manager']]);
I can use If() to check the data but I will have to repeat this in almost 7 places because there are 7 different tables in which data is being stored.
also if statement will look like this.
if(!empty($excel_row['address']) && !empty($excel_row['longitude']) && !empty($excel_row['latitude']) && !empty($excel_row['business_name']) and so on )
So is there any better way to achieve this?
Thanks.
you can try using looping, using the array_key, assumming database column name = excel column name
example :
$data = [];
foreach($excel_row as $key => $value){
if(!empty($excel_row[$key])){
$data[$key] = $excel_row[$key];
}else{
dd('empty column found'); //your code here
}
}
//if everything goes fine
IndependentContractor::create($data);
class UsersImport implements ToModel, WithUpserts
{
/**
* #return string|array
*/
public function uniqueBy()
{
return 'email';
}
if (!isset($row[0])) {
return null;
}
return new User([
'name' => $row[0],
]);
}
One of the two phone numbers phone_parent or phone_students must be provided AND they must be an integer. When combined, only atLeastValidator works, when I leave it out, the integer works. Out of ideas. Any hint?
[['phone_parent', 'phone_student'], 'integer'],
['phone_student', AtLeastValidator::class, 'in' => ['phone_student', 'phone_parent']],
['phone_parent', AtLeastValidator::class, 'in' => ['phone_student', 'phone_parent']],
update: I've just discovered that integer works when I try to submit (no request is sent yet, I remain on form page); However it should work on focus out - just like all the other validators; It's an instance of ActiveForm.
I don't think you need to have that custom AtLeastValidator, you can use when and whenClient in the following way to work the way you want.
Your rules should look like below
[
['phone_parent'],
'required',
'when' => function ($model) {
return ($model->phone_student == '');
},
'whenClient' => 'function(attribute,value){
return ($("#testform-phone_student").val()=="");
}',
'message' => 'Either Parent or Student Phone must be filled',
],
[
['phone_student'],
'required',
'when' => function ($model) {
return ($model->phone_parent == '');
},
'whenClient' => 'function(attribute,value){
return ($("#testform-phone_parent").val()=="");
}',
'message' => 'Either Parent or Student Phone must be filled',
],
[['phone_parent', 'phone_student'], 'integer'],
Above all i would use a regular expression in order to validate the phone number to be valid rather than just using integer that will allow 0 as a pone number or mobile number which isnt valid. using match validator with a regex in the pattern will make it solid.
I have a 'post' table with attribute 'user_id' in it to know who have posted that post. I run into a problem, when create a post, the 'user_id' didn't add into database, which can't be null, so I can't continue from there. So how can I add 'user_id' of the user that is currently logging in, automatically.
I'm using Yii2 basic template.
Thanks
Or you could have a look at Blameable Behavior
BlameableBehavior automatically fills the specified attributes with the current user ID.
I use this in alot of my projects (often combined with sluggable and timeable) and its easy to use, just put the following in your Post model:
use yii\behaviors\BlameableBehavior;
public function behaviors()
{
return [
[
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'user_id',
'updatedByAttribute' => false,
'attributes' => [
ActiveRecord::EVENT_BEFORE_VALIDATE => ['user_id'] // If usr_id is required
]
],
];
}
Referencing Behavior validation on validation behaviors.
If you want to do it manually like the other answers suggest, you need to change
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
to
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->user_id = \Yii::$app->user->identity->id
$model->save()
return $this->redirect(['view', 'id' => $model->id]);
}
Remember: when you validate before inputting the user id, the user_id can't be required in your model rules!
Apart from what Bloodhound suggest, you can also use the following code to get the currently logged in user ID:
$loggedInUserId = \Yii::$app->user->getId();
you can try this code
//To get whole logged user data
$user = \Yii::$app->user->identity;
//To get id of the logged user
$userId = \Yii::$app->user->identity->id
Look at the documentation for more details: doc .
I have written my own rule which must validate an array:
public function arrayValidation($attribute, $params)
{
(is_array($this -> $attribute)
&& isset($params['min']) ? count($this -> $attribute) >= $params['min'] : true
&& isset($params['max']) ? count($this -> $attribute) <= $params['max'] : true)
? NULL : $this -> addError($attribute, "$attribute must be array.");
}
and use it on the rules function:
['hashtags', 'arrayValidation', 'min' => 0, 'max' => 3],
but yii2 complain of
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\validators\InlineValidator::min
P.S. Sorry for my bad english.
You need to change your code like below:
['hashtags', 'arrayValidation','params'=>['min' => 0, 'max' => 3]],
In order to pass params to a custom validator, you should write it like above.