Yii2 requirement selection one or more checkboxes FormBuilder - forms

I have a registration form created in the "Yii2 krajee FormBuilder". It contains two checkboxes. At least one of them must be selected. Validation must be carried out on the client side, in order not to overload the page. Everything would be easy if the Yii2 contain the option to assign the rules required and whenClient to checkboxes - unfortunately that is not possible. For other fields(textboxes, selectboxes, you can for example use this code:
Model:
$public $module1;
$public $module2;
'module1'=>[
'type'=>Form::INPUT_CHECKBOX,
'name'=>'ak1',
'label'=>'<b>'.Yii::t('app','register.module1').'</b>' ],
'module2'=>[
'type'=>Form::INPUT_CHECKBOX,
'name'=>'ak2',
'label'=>'<b>'.Yii::t('app','register.module2').'</b>' ]
'textbox1'=>[
'type'=>Form::INPUT_TEXTBOX,
'name'=>'tx1',
'label'=>'<b>'.Yii::t('app','register.tx1').'</b>' ]
[...]
[[ 'textbox1', 'texbox2', ],'required','whenClient'=> "function (attribute, value) { return $('#registerform-textbox1').is(':checked') == false && $('#registerform-textbox2').is(':checked') == false;}"
],
It works ..but for texboxes. Checbox can not be assigned to required
I used this but in this case, the page is reloaded
['module1',function ($attribute, $params) {
if ($this->module1 == 0 && $this->module2 == 0) {
$this->addError($attribute, 'you have to select at least one option');
}
}],
Typically checkboxes validation is carried out by this
public function rules ()
     {
         array ['checboxname', 'compare', 'compareValue' => true,
               'message' => 'You must agree to the terms and conditions'],
         ...
     }
but in this case you can not combine rule compare with the rule whenClient - which is responsible for the function-specifed validation on the client side.
How can I solve this problem?

I'm not pretty sure what you are trying, but I think that you would do:
['checkbox1', 'required', 'when' => function($model) {
return $model->checkbox2 == false;
}
],
['checkbox2', 'required', 'when' => function($model) {
return $model->checkbox1 == false;
}
],

Related

Codeigniter - Form validation not works

I already try to googling but not solve, my code below is to check duplicate before insert, when "tagnumber" field already exists will go to specific page and not inserted to table, it works but the problem is although not insert to the table but it wont go to specific page I want.
below is my problem on conditional statements:
if data exists on form validation will execute not insert the data.
if data not exists form validation will execute insert data but go to wrong page (same page with exists data page).
my controoler :
function tambahSubmit()
{
$tagnumber = $this->input->post("tagnumber");
$this->myigniter_model->addData($tagnumber);
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('tagnumber', 'tagnumber', 'trim|required|is_unique[inventorytag.tagnumber]');
$this->form_validation->set_rules('date', 'date', 'trim|required');
$this->form_validation->set_rules('employee', 'employee', 'trim|required');
$this->form_validation->set_rules('semnumber', 'semnumber', 'trim|required');
$this->form_validation->set_rules('quantity', 'quantity', 'required');
$this->form_validation->set_rules('area', 'area', 'trim|required');
if($this->form_validation->run() == false)
{
$this->load->view('YearEndStock/tampilan_input_gagal');
}
else
{
$this->myigniter_model->addData($tagnumber);
$this->load->view('YearEndStock/tampilan_input_sukses');
}
}
my model :
function addData($tagnumber)
{
// Added $this->db->escape() and limit 1 for Performance
$query = $this->db->query("SELECT tagnumber FROM inventorytag WHERE tagnumber = ".$this->db->escape($tagnumber)." limit 1");
$data = array(
'tagnumber' => $this->input->post('tagnumber'),
'date'=> date('Y-m-d H:i:s'),
'employee' => $this->input->post('employee'),
'semnumber' => $this->input->post('semnumber'),
'quantity' => $this->input->post('quantity'),
'area' => $this->input->post('area')
);
return $query->num_rows() == 0 ? $this->db->insert('inventorytag', $data) : false;
}
Then you just need to separate your true statement. Remove your is_unique validation.
if($this->form_validation->run() == false)
{
SHOW ERRORS
$this->load->view('YearEndStock/tampilan_input_gagal');
}
else
{
$row = $this->db->get_where('inventorytag', array('tagnumber' => $tagnumber))->row();
if (empty($row)) {
//insert
$this->myigniter_model->addData($tagnumber);
} else {
//row exists
}
$this->load->view('YearEndStock/tampilan_input_sukses');
}

Conditional validation using scenarios in yii2

I am trying to validate my form in edit scenario where if CandidateResumeName is not filled, I want to require this field. This is how I am trying, but it's not working.
[['CandidateResumeName'], 'required', 'when' => function($model) {
if($model->HRMS_CandidateResumeName == "")
return true;
},'on' => 'edit'],
Please help!
You should remove the inner array
['CandidateResumeName', 'required', 'when' => function($model) {
if($model->HRMS_CandidateResumeName == "")
return true;
},'on' => 'edit'],
Remember to define and set the edit scenario properly
Your rule should look like this
['CandidateResumeName', 'required', 'on' => 'edit'],
Custom Scenario:
In your model
public function scenarios(){
$scenarios = parent::scenarios();
$scenarios['edit'] = ['CandidateResumeName'];
return $scenarios;
}
Controller
public function actionCreate(){
---
$model->scenario = 'edit';
---
}

Yii framework: access rules not working properly

I have problem with access control. I have rule:
array('deny',
'actions'=>array('index'),
'expression'=>'Yii::app()->user->isRegistered()',
'deniedCallback' => array(
$this->render('//site/info',array(
'message'=>'You must activate your account.'
)
),Yii::app()->end()),
),
function:
public function isRegistered()
{
return (Yii::app()->user->isGuest) ? FALSE : $this->level == 1;
}
If I login as admin and i have level 3, isRegistered() return false, but deniedCalback runs.
How to change this to run callback only when expression is true?
You need to specify the callback as callable. The way you wrote it, it will always execute the code you have in that array. You should better write a dedicated method in the controller.
array('deny',
'actions'=>array('index'),
'expression'=>'Yii::app()->user->isRegistered()',
'deniedCallback' => array($this, 'accessDenied'),
),
// ...
public function accessDenied()
{
$this->render('//site/info', array(
'message' => 'You must activate your account.'
));
Yii::app()->end(); // not really neccessary
}

How to use form validation in Drupal 7

I am trying to edit the checkout form in Drupal Commerce, to require a user to enter their email address twice. When they submit their form, Drupal should check to see if the emails match, and call form_set_error() if they don't. For now, I am just trying to attach a custom validation function to the form, which I can't get to work. (My module is called checkout_confirm_email. This module is only for our own use, so I didn't put much effort into the name).
function checkout_confirm_email_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'commerce_checkout_form_checkout') {
$form['#validate'][] = 'checkout_confirm_email_form_validate';
dprint_r($form['#validate']);
dsm("I printed");
}
}
function checkout_confirm_email_form_validate($form, &$form_state) {
dsm("Never prints...");
}
The dprint_r statment outputs Array ([0] => checkout_confirm_email_form_validate). So the function is part of the form array, but the dsm statement in the validation function never prints.
I've actually been stuck for a while. I've looked up examples, and I can't see what I'm doing wrong. Anyone?
You need to attach the #validate property to the form submit button like this:
$form['submit']['#validate'][] = 'checkout_confirm_email_form_validate'
And it'll work then it's not necessary that my example is identical match to your form tree you should search for the submit button array and apply this example to it
Instead of form_set_error() I would use form_error($form, t('Error message.'));
function checkout_confirm_email_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'commerce_checkout_form_checkout') {
$form['#validate'][] = 'checkout_confirm_email_form_validate';
dpm($form['#validate']);
dsm("I printed");
}
}
function checkout_confirm_email_form_validate(&$form, &$form_state) {
// Not sure the exact email field
if(empty($form['submitted']['mail']['#value'])){
dsm("Should see me now and return to the form for re-submission.");
form_error($form, t('Username or email address already in use.'));
}
}
You could use any validate function here
https://api.drupal.org/api/drupal/includes!form.inc/7
The listed validations would be
date_validate - Validates the date type to prevent invalid dates
(e.g., February 30, 2006).
element_validate_integer -Form element validation handler for
integer elements.
element_validate_integer_positive - Form element validation handler
for integer elements that must be positive
element_validate_number - Form element validation handler for
number elements.
password_confirm_validate - Validates a password_confirm element.
Ex of usage
$form['my_number_field'] = array(
'#type' => 'textfield',
'#title' => t('Number'),
'#default_value' => 0,
'#size' => 20,
'#maxlength' => 128,
'#required' => TRUE,
'#element_validate' => array('element_validate_number')
);
You can use _form_validate().
function my_form_form_validate($form, &$form_state) {
if ((valid_email_address($form_state['values']['field_candid_email'])) === FALSE) {
form_set_error('field_candid_email', t('The email address is not valid.'));
}
if (!(is_numeric($form_state ['values']['field_candid_montant']))) {
form_set_error('field_candid_montant', t('The field value must be numeric.'));
}
}
I changed this line:
$form['submit']['#validate'][] = 'checkout_confirm_email_form_validate'
to this:
$form['actions']['submit']['#validate'][] = 'checkout_confirm_email_form_validate';
And it's works !
Use the following code:
$form['submit']['#validate'][] = 'checkout_confirm_email_form_validate'

Symfony2 Choice : Expected argument of type "scalar", "array" given

I'm making a form with a choice list. Here's the content of my FormType (only as a test):
$builder->add('regionUser');
$builder->add('roles' ,'choice' ,array('choices' => array(
"ROLE_ADMIN" => "ROLE_ADMIN",
"ROLE_USER" => "ROLE_USER",
),
'required' => true,
'multiple' => false,
));
When I execute this, I get the following error:
Expected argument of type "scalar", "array" given
What goes wrong? How to solve it?
There is 3 solutions:
Use a multiple choices field to show the roles field. Multiple
choices returns a array.
In your form, don't show the "roles" field.
Put a new field "role" only in your buildform, not in your entity.
(You can fill autmaticaly it with the role hierarchy if you want).
In the onSuccess method, get the "role" to set roles for your user.
$user->addRole( $role );
When you create your user class, don't use the UserInterface from
the FOSUserBundle. Copy it and change the prototype of the method.
// FOSUserBundle/UserInterface
function setRoles(array $roles);
// YourUserBundle/UserInterface
function setRoles($roles);
And change the method in your User Class
// FOSUserBundle/UserInterface
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
}
// YourUserBundle/UserInterface
public function setRoles($roles)
{
if (is_string()) {
$this->addRole($roles);
} else {
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
}
}
You can find more information here: https://groups.google.com/group/symfony2/browse_thread/thread/3dd0d26bcaae4f82/4e091567abe764f9
http://blog.aelius.fr/blog/2011/11/allow-user-to-choose-role-at-registration-in-symfony2-fosuserbundle-2/
https://github.com/FriendsOfSymfony/FOSUserBundle