I am working on already built codeigniter application. I am working on enhancements. One of the enhancement is to change the validation messages. So I checked the validation messages are drive through CI_Form_validation library in codeigniter. I want manage to set the custom messages using the "set_message".
$this->form_validation->set_message('required', 'Please enter %s.');
This is triggering for all fields where the values is empty. Which is good. But I have few select fields and radio buttons the application. For those message should change from "Please enter %s" to "Please select %s". I tried callback methods mentioned in the " How can I setup custom error messages for each form field in Codeigniter? "
And also I have tried the method mentioned in the following links
1) " https://github.com/EllisLab/CodeIgniter/wiki/Custom-Validation-Errors-per-Field ".
2) " http://www.witheringtree.com/2011/09/custom-codeigniter-validation-methods/ ".
Is there any way to set the different custom messages for different fields? If so please give me the suggestion. There is already a file called MY_Form_validation in the application (which is mentioned in the second link) with some custom functions. Custom validations are triggering in that file except the custom function written by me. (I know you think may be I have written an faulty code! But there is only simple echo statement in that function. Just for testing only I have put an echo statement).
You wouldn't be able to create a generic function to do this as codeigniter has no way of knowing how the information was posted as it just receives it as an array.
What you could do is create MY_Form_validation.php in application/libraries
class MY_Form_validation extends CI_Form_validation
{
public function required_select($val)
{
if ($this->required($val) === FALSE) {
$this->set_message('required_select', 'Please select %s');
return FALSE;
}
return TRUE;
}
}
then when creating the rules for form validation
$this->form_validation->set_rules('dropdown', 'Dropdown', 'required_select');
Obviously, replace dropdown with the name of the element.
Hope this helps!
Related
I'm writing my own custom form validation class which extends from CI_Form_validation.
I'm curious how CodeIgniter sets its own form validation error messages. I don't see set_message in CI_Form_validation.
Let me know you need more clarification?
I think I got it. Will post the answer here in case someone else is asking...
Create a form_validation_lang.php inside the
application/language/english folder.
Then add a $lang associative array who index is the name of your
validation function prefixed with form_validation_. E.g. if
validation function is valid_date, it will look like this:
$lang['form_validation_valid_date'] = 'The {field} field must
contain a valid date.';
The lang file will be loaded automatically by CodeIgniter if you extend from CI_Form_validation.
I have a question about enabling the is_unique() rule for form validation in CodeIgniter.
In another explanation (link), they don't include the model query builder for standard usage of is_unique()
I need to use the rule is_unique(table.field) for my id field.
What should I do for making this function work on my model file to initiate table.field from my database? Because at documentation, I didn't see an explanation for enabling the is_unique rule.
My current code is still use matching data manually, but I need to know how to use this rules
$this->form_validation->set_rules('siteid', 'Site ID', 'trim|required|max_length[100]|is_unique[site_tower.site_id_tlp]');
I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.
With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.
For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.
How do we fix this? We run our own callback in which we specify the logic.
You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
This will then look for a method in your controller called 'username_check'
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.
more information can be found on Ci3 documentation.
LINK
Use CTRL + F and search for callback or is_unique
You might have missed this?
$this->load->library('database');
works instantly after adding database lib.
I've inherited a website built using Codeigniter (v2.1.4). The client has asked for a change, and I'm not sure of the best way to achieve it.
I have the following method in the Main controller that powers a new vans page.
public function new_vans($slug = null){
$this->load->view('inc/header_view');
if($slug === NULL){
//If no slug is provided, show all new vans
$this->load->view('new_vans_view');
}else{
//If there is a slug, just show the selected van, or redirect if nothing returned
$data['new_van'] = $this->Database->getSingle('new_vans', array('slug' => $slug));
if(!empty($data['new_van'])){
$this->load->view('new_van_details_view',$data);
}else{
redirect('/new-vans');
}
}
$this->load->view('inc/footer_view');
}
The client has asked for a contact form to be added to a couple of pages including this one, and my question is, should I create a new method that just handles the contact form submissions? If so, how would I handle sending validation errors back to the page? The contact forms will all have the same fields, so I would guess creating a new method is the way to go?
Partial Views(forms)
Partial views are good for forms, they can be re-used
like your client has requested.
Returning views as data
There is a third optional parameter lets you change the behavior
of the function so that it returns data as a
string rather than sending it to your browser.
This can be useful if you want to process the data in some way.
If you set the parameter to true (boolean) it will return data.
The default behavior is false, which sends it to your browser.
Remember to assign it to a variable if you want the data returned:
$string = $this->load->view('myfile', '', true);
Master layouts
To create a Master layout so you can wrap your views
create a new file inside your views directory
views/master/layout.php
<body>
<?php $this->load->view($view); ?>
</body>
Controller
class someController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->template = 'master/layout';
}
public function index()
{
return $this->load->view($this->template, array(
'view' => 'somecontrollerview',
'contact_form' => $this->load->view('partials/forms/contact', array(), true)
));
}
}
somecontrollerview
Echo out the contact form(string)
<?php echo $contact_form; ?>
Contact Controller
Create a new Controller to handle your form validation
The client has asked for a contact form to be added to a couple of pages including this one, and my question is, should I create a new method that just handles the contact form submissions?
create a new controller and new methods
If so, how would I handle sending validation errors back to the page?
look through the codeigniter documentation for form validation. basically if they have an error you are going to show them a view with the form again. it does not matter which page they came "from".
The contact forms will all have the same fields, so I would guess creating a new method is the way to go?
you need to validate the form fields, hopefully capture the contact info to a database, send an email confirmation to the customer, and send an email to the sales person unless its being done directly from the database, and then show a view with a thank you.
each one of those steps is a separate method.
optionally you can show the email address on the thank you page saying 'we have sent you a copy to the email address: something#gmail.com -- that way if the customer messed up the email address they can go back and correct it.
I am building a prestashop site
The corporate buyers cannot register for an account to view the products unless they can enter a valid EIN number or a valid Duns & Brandstreet number in registration.
How to make it possible?
Also any other e-commerce software that can help me solve this by switching to it?
All you really need to do is add the field to the template and then override the AuthController with additional code to handle you new field. e.g.
<?php
class AuthController extends AuthControllerCore
{
public function preProcess()
{
// Additional pre-processing for the new form field
if (Tools::isSubmit('submitAccount'))
{
if (!MyDBNumberValidationClass::verifyvalidnumber(Tools::getValue('db_number_field', 0)))
$this->errors[] = Tools::displayError('The Dun and Bradstreet number you entered is invalid.');
}
parent::preProcess();
}
}
I'm assuming that you're doing complex verification of the number which is why the static call to MyDBNumberValidationClass::verifyvalidnumber() is in the above, but it could equally by any simple test or an additional function in your AuthController override class definition above that validates. If you add two fields (i.e. the EIN number too) then just alter the logic to handle generating an error only if both are invalid; success of the form validation is based on $this->errors being empty.
This is only part of a general solution since it only handles validating the extra fields. If you need to actually do something with the data entered then the best way is to write a little handler module that installs itself on hookCreateAccount e.g.
public function hookCreateAccount($params)
{
// Get the field data entered on the form
$DB_number = $params['_POST']['db_number_field'];
// Your custom processing...
}
Note that there's no way to back out of the account creation from here so you will want to add code to email the store owner should there be a problem.
My validation is working as it stands, but I want to display the validation error prior to the search controller. I understand this might not be possible within the CakePHP framework.
I have a model plan.php. And in the plans_controller.php, I have a function called search().
My form calls search() as expected (because there is no search model):
echo $this->Form->create('Plan', array('action' => 'search'));
As it stands, when I submit my search, the errors are displayed and the url changes to .../search, so no results are displayed ("There are 0 results for that search criteria", but the correct validation errors are displayed below required form fields.
I do not want the .../search url to be displayed. I want the form to "halt" and just display the validation errors w/out changing the url to the search function.
I am calling the search form within an element because the search form displays on several different pages.
To sum this up: The search form should validate w/out changing the url path to the controller action name of the search. Of course, the validation is done IN the search() and plan.php model, so I just don't know how to work around this and wondering if its even possible.
You can use the validates() method of the model to check whether it validates and then redirect back.
Assuming your model is called Plan, this would be your controller
$errors = array();
if (!$this->Plan->validates($this->data)) {
//errors occured
$errors = $this->Plan->invalidFields();
$this->Session->save('Plan.errors', $errors);
$this->redirect('/plans');
}
And in your view.
if ($this->Session->check('Plan.errors')) {
$errors = $this->Session->read('Plan.errors');
$this->Session->delete('Plan.errors'); //don't want it again
}
In both cases, make sure Session helper/component is actually assigned to your view and controller
OK. Cracked out a working solution w/ implode, but now my errors are only displayed in the default layout and no longer under the form fields where that belong.. So now I need to know how to get the errors back below the form fields..
Working code:
...else {
$errors = $this->Plan->invalidFields();
$error_messages = implode(' ',$errors);
$this->Session->setFlash($error_messages);
$this->redirect('/');
}...