How to set default values for CodeIgniter Form Validation? - php

I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isnt submitted or its before a form submission?
public function index($uri = NULL)
{
$this->load->helper('form');
$this->load->library('form_validation');
//pull from DB or Session
$data = array(
'Status' => 'users_default_status',
'Order' => 'users_default_order',
'Asc' => 'users_default_asc'
);
$this->form_validation->set_data($data);
$this->form_validation->set_rules('Status', 'Status', 'numeric|trim|required|strtolower');
$this->form_validation->set_rules('Order', 'Order', 'trim|required');
$this->form_validation->set_rules('Asc', 'Asc', 'trim|required|strtolower');
if ($this->form_validation->run() === FALSE) // validation failed
{
// validation failed but maintain submitted values in form/feedback
}else{
// validation successful, do whatever
}
}
So that if there was a form submission it uses the POST values, and if not it uses defaults (but still validated). I would like the defaults to work on a variable by variable basis, so some can be defaults some can be user submitted.

I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isn't submitted or it's before a form submission?
Simply check if the value exists and use it as the default, otherwise it's blank (or a different default).
In the Controller, decide if you're going to load a blank form, if not, send the data for the fields....
$data['fieldname'] = "whatever"; // from the database
$this->load->view('yourpage', $data);
Then in your View, check for the existence of this data for each field. If the data was sent, use it. Otherwise, set a blank value.
<?php $value = isset($fieldname) ? $fieldname : ''; ?>
<input name="fieldname" value="<?php echo set_value('fieldname', $value); ?>" type="text" />
If you do not send the data from the Controller, the field will be blank (you could also set a default)
If you send the data from the Controller, the field will be filled out with this data from your Controller (database).
If you submit the form and validation fails, set_value() function will reload the field with the data from the most recent post array.

These are just some thoughts...
The validation rules act upon the posted data. So if you are using set_value('order',$default_order), when the form is submitted it will either take the new user entered value or the one you provided.
If the user empties a prefilled or default input, you can't have it set as "required" in the rules. What you would do is use a callback function to handle that case to check if it's empty and provide a default value and return TRUE.

Related

How to submit unchecked checkboxes to controller

Ok first I have a "settings" table on my database in which I have the fields "name" and "value" its a configuration kind of table where the value could be anything from string to boolean values etc.
Now on my blade, I have a form with various inputs "texts" "selects" "checkboxes" etc. When submitting the form on the controller I run a foreach where for each attribute of the $request I store its key as the name and its value as its value on the database.
$agency_id = Auth::user()->agency->id;
$settings = AgencySettings::whereAgencyId($agency_id)->get();
foreach ($request->except('_token') as $key => $value)
{
$setting = $settings->where('name','=',$key)->first();
if (boolval($setting))
{
$setting->value = $value;
$setting->update();
}else{
$setting = new AgencySettings;
$setting->agency_id = $agency_id;
$setting->name = $key;
$setting->value = $value;
$setting->save();
}
}
All works well except the unchecked checkboxes which are not inside the $request.
I know I can handle them like so $request->has('name_of_checkbox') but because of the dynamic nature of the table on the database, I don't want to have hardcoded on my Controller the name of a specific setting.
My goal is that the code on my Controller will be the same regardless the number of different settings I will use on my frontend (maybe in the future there will be a need to add more).
So my question, is there a way to handle those checkboxes serverside without having to refer to them specifically, or a way to always return the value of the checkboxes to the server despite its state?
My first thought is to go with javascript and hidden inputs, but maybe there is a better way.
You could add a hidden field with the same name before every checkbox you want to receive, like :
<input type="hidden" name="checkbox-1" value="0" />
<input type="checkbox" name="checkbox-1" value="1" /> My checbox 1
That will send the hidden field with the 0 value when the field is unchecked and send the proper truthy value when it's checked.
NOTE: Just make sure you're adding the hidden field first so you'll receive just the checked one when the field is checked.
Other solution is to simply check if value for "checkbox-1" is set in post array.
So you will set default to 0 on your controller side and check if value exists instead of checking if it is 0 or 1.
(M.)

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?
I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.
I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?
very simple:
let's say both the fields names are foo and bar respectively.
then:
// Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc
// if validation passes, add this (i.e. inside if($validator->passes()))
if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
{
$messages = new Illuminate\Support\MessageBag;
$messages->add('customError', 'both fields can not be no');
return Redirect::route('route.name')->withErrors($validator);
}
the error messge will appear while retrieving.
if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.
Obviously don't know what your form fields are called, but this should work.
This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.
$data = array(
'field1' => 'no',
'field2' => 'no'
);
$validator = Validator::make($data, array());
$validator->sometimes('field1', 'not_in:no', function($input) {
return $input->field2 == 'no';
});
$validator->sometimes('field2', 'not_in:no', function($input) {
return $input->field1 == 'no';
});
if ($validator->fails()) {
// will fail in this instance
// changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
}
Just to note, this will only work in Laravel 4.2+

Should I use set_value() to repopulate a form in CodeIgniter

My question is whether I should use set_value() at all to re-populate a form. It might seem odd to say that, however I am creating a shared controller function and view which can be used to either add a new record or edit an existing one. It seems to make sense to do this since the functionality is so incredibly alike.
As such, if we call up an existing record to edit I do this:
$data['fields'] = $this->customer_model->get_customer($id);
If the form is submitted to save the record, or if we're adding a record for the first time, the form has the potential to reload if the user makes a mistake so I populate $data['fields'] this way instead:
$data['fields'] = array(
'company' => $this->input->post('company') ?: '',
'website' => $this->input->post('website') ?: '',
'credit_limit' => $this->input->post('credit_limit') ?: ''
);
My form element looks like this:
<input type="text" name="company" value="<?php echo set_value('company', $fields['company']); ?>" />
But I'm thinking it may as well look like this:
<input type="text" name="company" value="<?php echo escape_html($fields['company']); ?>" />
Since the form data could come from either user input (when adding or saving) or from the database (when retrieving a record to edit) I cannot rely entirely on post() or set_value() without the 2nd parameter. Furthermore, the second parameter for set_value() will always exist ($fields['company'] in this example) because it's initialized from the start, which is why I am thinking of just using it directly.
Is there a problem with this approach?
If you want to populate form fields on FALSE return of Form Validation or insert data for editing operations, I suggest you to use following helper:
Usage
<input type="text" name="last_name" value="<?=vset_value('last_name','',$rs);?>">
Explanation
$rs here is the $db data for record (if you are sending it to view). To stay at the safe side please include $this->data['rs'] = false; at your controller. If $rs is set and true, helper take results from it and display it. Otherwise it displays if the key exist in $_POST. If both don't exists, it display default value.
Helper
/**
* vayes_helper::vset_value
*
* Retains state of INPUT text after Form Validation
*
* #access public
* #param string name of INPUT tag
* #param string default value for INPUT tag
* #param mixed DB Result (array or object)
* #return string
*/
if(!function_exists('vset_value')) {
function vset_value ($name_of_input,$default_state='',$db_result_array='') {
$CI = &get_instance();
$render_state = $default_state;
if($CI->input->post()) {
$render_state = $CI->input->post($name_of_input);
} else {
if(is_object($db_result_array) && isset($db_result_array->$name_of_input)) {
$render_state = (isset($db_result_array->$name_of_input)) ? $db_result_array->$name_of_input : $default_state;
} else if($db_result_array != '' && array_key_exists($name_of_input,$db_result_array)) {
$render_state = (isset($db_result_array[$name_of_input])) ? $db_result_array[$name_of_input] : $default_state;
}
}
return $render_state;
}
}
If you like the way, let me know. I can supply for more form input type like select, checkbox, etc.
The approach is correct, as mentioned in the CodeIgniter docs. In fact, you don't need to include the second parameter in set_value.
set_value definition:
string set_value(string $field = '', string $default = '')
//$field: If there is a submitted field with this name, its value is returned.
//$default: If there is no matching submitted field, this value is returned.
Yes,You should.
set_value() is used to re-populate a form has failed validation.
There is no additional filtering on it, so it faster.
But, I prefer some times to use $this->input->post() for the secure.

Change form value before Codeignighter Form Validation

I have form data posted by client, I want to manipulate one of the forms value before I run it through $this->form_validation->run().
Is this possible
i.e something like;
//Get user form inputs
$input = $this->input->post();
//generate slug - my custom code
$input['slug'] = sf_generate_slug($input['slug']);
if ($this->form_validation->run()) {
...
You can reassign any post value before $this->form_validation->run() like
$_POST['slug'] = sf_generate_slug($_POST['slug']);
While if you use your above method it will validate because it didn't overrides the $_POST values
Hope it makes sense

Codeigniter - How to populate form from database?

I have a small site which allows a user to enter values in a form and then either submit it directly or store the field values in a template to later submit it. To submit the form later, he can load the previously saved template. For that there are three buttons Load Template / Save Template / Submit form.
Because i am using the form validation built-in functionality from Codeigniter i run into problems when i want to populate the form with a template, which had been previously stored.
The form fields are all set up like
$name = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name', $form_field_values['name'])
);
The variable $form_field_values holds the values from either a loaded template in the case when a template has been loaded or the default values when the form is first loaded.
Initially the form is loaded with the default values. When i click on Load Template the values from the template are not chosen by set_value() because there were the default values in there before. What i want is to replace the values of the form fields with the ones from the template.
Do you have any idea how to do that in a clean approach? What i have done is to introduce a variable to skip the call to set_value() completely like:
$name= array(
'name' => 'name',
'id' => 'name',
'value' => $skip_form_validation ? $form_field_values['name'] : set_value('name', $form_field_values['name'])
);
Where $skip_form_validation is a variable set in the controller, based on what button was pressed. Form validation is skipped for saving/loading a template.
Codeigniter's set_value() function is a simple function which finds value in $_POST if value found then return else returns second argument, you can remove set_value() and write your own code for it. you can write $_POST['field_name'] if you want to populate value of POST data or add whatever value you want to add
Just use like this
$name = array(
'name' => 'name',
'id' => 'name',
'value' => $valueFromYourTemplate
);
You don't need to use set_value() function if you don't want to set POST values in the form
Assuming you retrieve the database fields and pass them to a data array in your controller.
$record = $this->data_model->get_record(array('uid' => $user_id), 'users');
if (!is_null($record)) {
$data['uname'] = $record->username;
$data['loc'] = $record->location;
}
where 'users' is the database table, and the uid is the id field of the table users.
In your form, do something like this
Hope it helps!

Categories