Validation for form - php

Please help with setting rules (). The thing is, I have a form. Where 2 fields are present. If all fields are empty, the form cannot be submitted, but if at least ONE is not empty, then the form can be submitted. Can you help me please, I'm new at it?
Here's my form
<?php $form = ActiveForm::begin() ?>
$form->field($model, 'field1')->textInput();
$form->field($model, 'field2')->textInput();
<?php $form = ActiveForm::end() ?>
And this's my model, but this rule does not quite suit me. Because the rules require you to fill in all the fields. And the main thing for me is that at least one, but was filled, so i could send the form. If ALL fields are empty, then validation fails.
public function rules()
{
return [
[['field1', 'field1'], 'require'] ]}
Should I add something in controller maybe?

You have TYPO in rules: use required
public function rules()
{
return [
[['field1', 'field1'], 'required']
];
}

You can use yii\validators\Validator::when property to decide whether the rule should or shouldn't be applied.
public function rules()
{
return [
[['field1'], 'required', 'when' => function ($model) {
return empty($model->field2);
}]
[['field2'], 'required', 'when' => function ($model) {
return empty($model->field1);
}]
];
}
The when property is expecting a callable that returns true if the rule should be applied. If you are using a client side validation you might also need to set up the yii\validators\Validator::whenClient property.

You can use standalone validation:
public function rules()
{
return [
[['field1', 'field2'], MyValidator::className()],
];
}
And create a new class like follows:
namespace app\components;
use yii\validators\Validator;
class MyValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
if (empty($model->filed1) and empty($model->field2)) {
$this->addError($model, $attribute, 'some message');
}
}
}

Related

How to use Custom and Default Validation Together?

I have custom validation for validating data. The custom validation doesn't have unique rule as I need to ignore this on update, therefore I am using unique rule on store() method. But this is ignored, and it only works if I change the custom validation with default validation.
It works if I have the following:
public function store(Request $request)
{
if (!$this->user instanceof Employee) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$request->validate([
'name' => 'required|max:50|unique:centers'
]);
$center = Center::create($request->all());
return response()->json($center, 201);
}
But this doesn't work if I change the method signature to the following:
public function store(CustomValidation $request)
How can I use both together? I do not want to move the custom validation code inside the method as I have to repeat msyelf for update method then.
I think it will help you
use Illuminate\Contracts\Validation\Rule;
class CowbellValidationRule implements Rule
{
public function passes($attribute, $value)
{
return $value > 10;
}
public function message()
{
return ':attribute needs more cowbell!';
}
}
and
public function store()
{
// Validation message would be "song needs more cowbell!"
$this->validate(request(), [
'song' => [new CowbellValidationRule]
]);
}
or
public function store()
{
$this->validate(request(), [
'song' => [function ($attribute, $value, $fail) {
if ($value <= 10) {
$fail(':attribute needs more cowbell!');
}
}]
]);
}

Override Backpack validation roles

What I did:
I am trying to override backpack form validation roles (update request).
UserUpdateCrudRequest.php
use App\Http\Requests\Backpack\PermissionManager\UserUpdateCrudRequest as UpdateRequest;
class UserUpdateCrudRequest extends \Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest
{
function __construct()
{
parent::__construct();
}
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
}
public function rules()
{
$rules = [
'name' => 'required',
'password' => 'confirmed',
];
return $rules;
}
}
app/Http/Controllers/Admin/Backpack/PermissionManager/UserCrudController.php
public function update(UpdateRequest $request)
{
//code
}
What I expected to happen:
The email field is mandatory on create , and not mandatory on update.
What happened:
ErrorException in UserCrudController.php line 18:
Declaration of App\Http\Controllers\Admin\Backpack\PermissionManager\UserCrudController::update() should be compatible with Backpack\PermissionManager\app\Http\Controllers\UserCrudController::update(Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest $request)
If I'm right,
inside UserCrudController you have,
use Backpack\PermissionManager\app\Http\Requests\UserStoreCrudRequest as StoreRequest;
use Backpack\PermissionManager\app\Http\Requests\UserUpdateCrudRequest as UpdateRequest;
If you want to make the email field not mandatory on update you have to edit the UserUpdateCrudRequest.php inside your-project/vendor/backpack/permissionmanager/src/app/Http/Requests and remove the line
'email' => 'required',

Save value of checkboxlist to db in yii2

I have a yii2 form which contain a checkbox list items which i made like this:
<?php $CheckList = ["users" => 'Users', "attendance" => 'Attendance', "leave" => 'Leave', "payroll" => 'Payroll'];?>
<?= $form->field($model, 'MenuID')->checkboxList($CheckList,['separator'=>'<br/>']) ?>
Now what i need is to save the values in the database column as a comma separated value.
I tried to modify the create function in my controller in this way:
public function actionCreate()
{
$model = new Role();
if ($model->load(Yii::$app->request->post())) {
if ($model->MenuID != " ") {
$model->MenuID = implode(",", $model->MenuID);
}
$model->save();
return $this->redirect(['view', 'id' => $model->RoleID]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But the values are not being saved in the database
You need to set your model rules().
When you call $model->load(Yii::$app->request->post()); the framework call method setAttributes() with param $safeOnly = true. This method with param $safe = true check if attributes are safe or not according to the rules of model. If you haven't any rules on the model all attributes are considered unsafe so your model is not populated.
Add rules() on your model and your code works
class Role extends yii\db\ActiveRecord
{
...
public function rules()
{
return [
['MenuID', 'your-validation-rule'],
];
}
...
Some additional info
N.B. If you do not specify scenario in the rules the default scenario is 'default' and if during instantiate of model object you set scenario to another didn't work. My example:
You have the same rules as I wrote before and you run this code
...
$model = new Role(['scenario' => 'insert']);
if ($model->load(Yii::$app->request->post())) {
...
model is empty after load becouse any rules is founded in 'insert' scenario and your problem is back. So if you want a rule that work only in particular scenario you must add 'on' rules definition. Like this:
...
public function rules()
{
return [
['MenuID', 'your-validation-rule', 'on' => 'insert'],
];
}
...
For more example and explanations visit:
Declaring Rules
load()
setAttributes()
safeAttributes()

yii2 validation rules on update

I have a model and validation rules for it:
class User extends ActiveRecord implements IdentityInterface
{
...
public function rules()
{
return [
[['username', 'password', 'email'], 'required', 'on' => 'insert'],
[['password', 'email'], 'required', 'on' => 'update'],
]
}
Actually the code produces no validators. When I remove 'on' section, everything goes well.
Digging in official documentation and search thru The Web didn't help me to understand what is the issue, and why can't I have custom required fields sets for different actions.
The Scenario is not automaticaly setted by Yii2 ActiveReccoed. If you need a specific scenario you must create it and assign
E.g. for update ...
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['update'] = ['password', 'email'];//Scenario Values Only Accepted
return $scenarios;
}
Also you can set scenario in your actionUpdate
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
........
}

Textfield Mandatory On basis of radio button selection- Yii2

I'm having radio button with two value i.e, Individual and Firm.
I am looking for one scenario where if radio button having value Firm is selected, then CompanyName textinput should act as mandatory (required) field. And, when radio button having value Individual is selected, Then CompanyName textinput should act as Optional field.
I was not getting how to do it. I tried to add addAttribute in CompanyName textinput as mandatory. but it didn't worked as RegisterForm.php (model) is having few rules specified.
So, any idea how to do it. I'm not getting. Any help ?
register.php (view)
<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
.
.
.
<?= $form->field($model, 'AdminType')
->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company/Group of Employees'))
->label('Are You')?>
<?= $form->field($model, 'CompanyName')->textInput()->label('Company Name') ?>
<div class="form-group">
<?= Html::submitButton('Register', ['class' => 'btn btn-success', 'name' => 'register-button' ]) ?>
</div>
<?php ActiveForm::end(); ?>
<script>
$('input[type="radio"]').click(function()
{
if($(this).attr("value")=="Firm")
{
$('#registerform-companyname').addAttribute("required");
}
});
</script>
RegisterForm.php (model)
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;
class RegisterForm extends Model
{
public $fname;
public $lname;
public $email;
public $password;
public $confirmPassword;
public $AdminType;
public $CompanyName;
public $verifyCode;
public function rules()
{
return [
[['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
['email', 'email'],
['confirmPassword', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
];
}
First of all, having any kind of front end validation is BAD, as i can circumvent it by generating a post programmatically, and it will save the record without any problems, making a possibility of inconsistent records a reality.
What you want to do instead is create a custom validation rule function in your model, as well as add the rule to the validation array:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;
class RegisterForm extends Model
{
public $fname;
public $lname;
public $email;
public $password;
public $confirmPassword;
public $AdminType;
public $CompanyName;
public $verifyCode;
public function rules()
{
return [
[['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
['email', 'email'],
['confirmPassword', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
//add rule that uses the validator function
['AdminType','radioValidator'],
];
}
//implement the validator
public function radioValidator($attribute, $params)
{
if($this->$attribute === 'Firm' && empty($this->$attribute))
$this->addError('CompanyName', 'CompanyName cannot be blank');
}
}
?>
Now your field generating code should look like this
<?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
Hope this helps you
Edit: As I am used to working with AR classes(which generally, when generated with gii, have validation automatically ), it did not cross my mind that you are using just a form model ( the one that was given as an example in the basic app)
forget the ->error() in the field, also make sure you have the row
if ($model->load(Yii::$app->request->post()) && $model->validate()) {...}
in your action
At last I Got,
['company_name', 'required', 'when' => function($model){
return ($model->user_type == 'Firm' ? true : false);
}, 'whenClient' => "function (attribute, value) {
return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 'Firm';
}"],

Categories