Multiple validation on one attribute in Yii - validation

I want to validate an attribute on multiple CValidator classes.
To be more specific, I want an email address to be validated by the email validator, but I also want it to be required.
I can of course define two separate rules, like so:
array('email', 'email'),
array('email', 'required'),
But when I leave the input blank the validation only returns an error saying the field is required, but it doesn't return an error saying it has to be an email address. When I fill in a non-email string, it then returns the email validation error.
I tried to combine the validators in an array, and a comma separated string but that doesn't work. So I guess the only option is to use a custom validation method.
But how can I use the built-in CValidator validators in this method? And how can I build it, that the two rules are validated together at once instead of one at a time?

If I am getting you right you have an issue with error message. I think you can use following approach to show message.
array('email', 'email', 'message' => 'Please provide valid email.'),
array('email', 'required', 'message' => 'Email is required. Please provide valid email.'),
Hope this will help you....

User interface wise this makes little sense to specify that an email is invalid when left empty. You tell them that the email is required when empty or invalid when it isn't empty but not an email. Doing both seems very confusing to me.
I personally just use:
array('email', 'email', 'allowEmpty' => FALSE),

Use the errorsummary() method:
EDIT:
Changed reference to CHTML
http://www.yiiframework.com/doc/api/1.1/CHtml#errorSummary-detail
In your view, add
<?php echo CHtml::errorSummary($model, NULL, NULL, array ('firstError' => false));
...
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
From the documentation
additional HTML attributes to be rendered in the container div tag. A
special option named 'firstError' is recognized, which when set true,
will make the error summary to show only the first error message of
each attribute. If this is not set or is false, all error messages
will be displayed. This option has been available since version 1.1.3.
Note that if you are using Ajax validation then you will get the first error only, next to the fields

Actually model validation returns all errors of validation, but CActiveForm::error method shows only first one for selected attribute. I guess you use now something like this:
<?php echo $form->error($model,'attr'); ?>
but instead should use
<?php if ($model->hasErrors('attr')) : ?>
<?php $errorList = $model->getErrors('attr'); ?>
<?php foreach ($errorList as $error) : ?>
// display error
<?php endforeach ?>
<?php endif ?>
Also you can write your own helper method for displaying all errors for single attribute.

You can use skipOnError property of the validator.
array('email', 'email', 'skipOnError' => false),
array('email', 'required', 'skipOnError' => false),

Related

yii2 not rendering to view just refreshing the page

view.php code part:
View Picture
viewgood.php
<?php
echo 'hello';
GoodsController.php
public function viewgood($id = null) {
}
After clicking on button View Picture my page just refreshing instead of going to viewgood.php
What am I doing incorrectly?
I am a begginer in Yii2
Try use
View Picture
in a anchor tag html your need use the complete route, for use shortcut you try use
<?= Html::a('View Picture', ['/goods/viewgood/', 'id' => $good['GoodGallery'][0]['id']], ['class' => 'btn btn-primary']) ?>
view.php
You can use Html:a(), or in your example use Url helper to() function to generate the proper route for your anchor tag.
View Picture
GoodsController.php
public function actionViewgood($id=null){
//fetch the data e.g.
$model = Good::findOne(id);
//Do some extra code checking when no record is found like throw an exception or set a flash error message, etc.
//render the viewgood and pass the data (if needed)
return $this->render('viewgood', [
'model' => $model
]);
}
viewgood.php
<?php
//do what you want with the data passed by the controller. E.g. print the name of the good (if applicable)
echo $model->name;
//your other code ...
?>

Ckeditor getdata() function is not working in laravel

I used withinput() function to return back with form values but it's not working for ckeditor, that's why I tried getting value with Ckeditor getdata() function but it's also didn't work.
Ckeditor Form is like:
<?php echo Form::text("PageLanguage[description][$language>id]",
old("PageLanguage[description][$language->id]"),
array('id' =>"description-$language->id",'class' => 'form-control'));
?>
Any ideas?
I used textarea and it worked in my code
If you use Form::text it can't get value that's why it will save null value, you must change Form::text to Form::textarea like that:
<?php echo Form::textarea("PageLanguage[description][$language->id]",
old("PageLanguage[description][$language->id]"),
array('id' =>"description-$language->id",'class' => 'form-control'));?>

How to implement model validation on autocomplete field in yii2?

I am using a jui autocomplete widget in my form. Model validation is not working properly in here.
This is my view
<?php $form = ActiveForm::begin();?>
<div class="members-form">
<div class="col-md-5">
<?php
$data = FamilyName::find()
->select(['name as value', 'name as label','id as id'])
->asArray()
->all();
echo 'Family Name' .'<br>';
echo AutoComplete::widget([
'name' => 'family',
'id' => 'family_name',
'clientOptions' => [
'source' => $data,
// 'minLength'=>'3',
'autoFill'=>true,
'select' => new JsExpression("function( event, ui ) {
$('#members-family_name_id').val(ui.item.id);//#City-state_name is the id of hiddenInput.
}")],
]);
?>
<?= Html::activeHiddenInput($model, 'family_name_id')?>
<?= $form->field($model, 'remarks')->textInput() ?>
<?php ActiveForm::end(); ?>
</div>
</div>
my model code
public function rules()
{
return [
[['family_name_id', 'first_name',
'date_of_birth', 'relation_id', 'is_head','marital_status','remarks',
'gender','address_id'], 'required'],
];
}
Now if i try to create a new member with no data selected in any of the fields, then required fields will show like " ... cannot be blank" in red. But the family_name_id is not showing such validation. The data is not getting saved if leave the auto complete field empty but no validation message is being displayed. How can i show validation messages with jui auto complete ?
I believe you faced the same problem as I had few weeks ago. I experienced similar behavior: I saw autocomplete suggestions and could interact with them, but when I left the input field the client-site validation kept silent.
If you look at the html produced by your view, at the bottom you can see some javascript code, which is responsible for the client-side validation. It looks like:
jQuery(document).ready(function () {
....
jQuery('#app-new-form').yiiActiveForm(
[
{
"id":"application-familyname",
"name":" familyname ",
"container":".field-application-familyname",
"input":"#application-familyname",
"enableAjaxValidation":true,
"validate":function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {"message":"Field cannot be empty"});
}
}
], []);
.....
});
This code assigns an event handler to your autocomplete field to start the client-side validation. But you have to pay attention, which id is used for the field. Unfortunately, yii2 takes the id provided by you only to construct the <input> element in html. When it produces javascript code the id is always generated from few permanent parts. The most important two are the name of the model and the name of the attribute. In your case id should be something like 'your_modelname -family_name_id'.
Because your explanation is not complete, this is only a guess. So, look at your html source and be sure you have the same id for the input you try to validate and the id in the JavaScript (see above).
You are using Html Hidden Input .. You have to use ActiveForm HiddenInput to show error validation..
use
<?= $form->field($model, 'family_name_id')->hiddenInput()->label(false);>
Why don't you use the family_name_id instead of creating a new select?
<?= $form->field($model, "family_name_id")->dropDownList(
ArrayHelper::map(FamilyName::find()->all(), 'id', 'name'),
['prompt' => 'Select']
) ?>
And you can change the label by using ->label('Family Name'), but i would recommend changing in model (unless you need "Family Name Id" as a label elsewhere).
I know you didn't said anything about that, but can i recommend you to see this answer about using methods that perform sql queries inside your view?

CakePHP 3 belongsToMany Validation

I am struggling with how to do validation with belongsToMany relationships. Namely, the classic recipes/ingredients relationship. I would like a recipe to always have an ingredient on create or edit. What would my validation look like in my RecipesTable? I have tried:
$validator->requirePresence('ingredients')->notEmpty('ingredients')
As well as
$validator->requirePresence('ingredients._ids')->notEmpty('ingredients._ids')
The second one works in that my form doesn't validate, but it does not add the error class to the input. I am setting up the input with a field name of ingredients._ids.
I am also having trouble with creating the data to pass to $this->post in my tests in order to successfully add a record in my test. My data in my test looks like:
$data = [
'ingredients' => [
'_ids' => [
'2'
]
];
And of course I'm doing the post in my test with $this->post('/recipes/add', $data);
I'm not passing the required rules for ingredients in my test.
I solved how to set up the validators. In the recipe Table validator:
$validator->add('ingredients', 'custom', [
'rule' => function($value, $context) {
return (!empty($value['_ids']) && is_array($value['_ids']));
},
'message' => 'Please choose at least one ingredient'
]);
However, the validation message was not being displayed on the form, so I'm doing a isFieldError check:
<?php if ($this->Form->isFieldError('ingredients')): ?>
<?php echo $this->Form->error('ingredients'); ?>
<?php endif; ?>
I'm using multiple checkboxes in my view file versus a multi-select.
And with that, I'm getting my validation message on the form.
As I thought, my tests fell into place once I figured out the validator. What I show above is indeed correct for passing data in the test.
I will have desired to add this answer as a comment of Kris answer but I do not have enough reputation.
Alternatively, to solve the issue with validation message not being displayed on the form, you can add these two line in your controller.
if(empty($this->request->data['ingredients']['_ids']))
$yourentity->errors('ingredients', 'Please choose at least one ingredient');

Getting form data in Yii to a CActiveRecord model works for one model but not for another

I'm getting a submitted form in this way:
$resume->attributes = $_POST['ResumeModel'];
$profile->attributes = $_POST['UserProfile'];
Both CActiveRecord models are correctly populated before this from the corresponding tables, they have the correct data and all.
Both models' data is present on $_POST as modified by the form.
But it seems that the assignment to the attributes property works only for $profile and not for $resume.
If I check their values after that assignment, $profile doesn't get the edits from the form.
Is there something in the definition of the model that can cause that? As far as I can see, both models are similarly implemented
I don't understand why this happens, does anyone have a clue?
Thanks!
The problem is that some fields on the $resume model didn't have any validation rules and weren't declared as safe either, so they couldn't be safely mass assigned.
Reference:
http://www.yiiframework.com/doc/guide/form.model#securing-attribute-assignments
Have you checked the $_POST variables closely? For the mass "attributes" assignment to work the array should be of the form:
$_POST = (
'ResumeModel' => (
'data1' => 'something',
'data2' => 'something else',
),
'UserProfile' => (
'data3' => 'yo ho ho',
'data4' => 'bottle of rum',
)
)
If it looks like this it's wrong:
$_POST = (
'ResumeModel' => (
'data1' => 'something',
'data2' => 'something else',
'data3' => 'yo ho ho',
'data4' => 'bottle of rum',
)
)
To ensure that the form is building the correct $_POST array for each model, make sure that you are passing both the $resume and $profile model into your form View like this:
<?php
$resume=new ResumeModel;
$profile=new UserProfile;
$this->render('yourFormView', array('resume'=>$resume,'profile'=>$profile));
?>
Then, in "yourFormView", make sure that you are creating the form fields appropriately with each model, like so:
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->textField($resume,'data1'); ?>
<?php echo $form->textField($resume,'data2'); ?>
<?php echo $form->textField($profile,'data3'); ?>
<?php echo $form->textField($profile,'data4'); ?>
<?php $this->endWidget(); ?>

Resources