I made a custom function for my form validation in Codeigniter.
Its hooked to the URL Helper, i achieved this by making a MY_url_helper.
The helper modification:
function valid_url($str) {
$pattern = "/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if (preg_match($pattern, $str)) return TRUE;
else return FALSE;
}
/* End of file MY_url_helper.php */
/* Location: ./application/helpers/MY_url_helper.php */
How i call the validation:
$this->form_validation->set_rules('image', 'Image path', 'valid_url');
The language file:
$lang['valid_url'] = "The %s field must contain a valid URL.";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */
But it doesn't show any error message when submitting the form.
If i change the valid_url function to echo something on true and false, it will execute that. So it runs the function.
How can i make the error message appear?
Are you printing validation errors to your view? Add this line above your form in your view and see if it prints then.
<?php echo validation_errors(); ?>
Edit:
A few things based on your reply...I've never actually used a "helper" function as a callback for validation...I've always defined the callback in the controller where the validation occurs. Someone else may be able to elaborate on whether you can use a helper function as a callback. You may have to declare your validation function in the controller. You could also return the helper function from a callback you declare in the controller as well to keep from having to re-write your helper in two places. That may work.
I assume you are loading the 'url' helper in your controller?
Also..per CodeIgniter's documentation...I believe you are supposed to append 'callback_' to the beginning of your function name in your 'set_rules' declaration.
$this->form_validation->set_rules('image', 'Image path', 'callback_valid_url');
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
Related
After logout, I tried to redirect for the home page. I tried to few ways, but not redirected.
class User extends BaseController
{
public function __construct()
{
helper('url');
}
for the logout function. I used three ways
redirect('/');
or
header("Location:".base_url());
or
route_to('/');
as per CI 4
use
return redirect()->to('url');
if you are using route then use
return redirect()->route('named_route');
I use this and it works
return redirect()->to(site_url());
In codeigniter 4 redirect()->to() returns a RedirectResponse object, which you need to return from your controller to do the redirect.
for ex.
class Home extends BaseController {
public function index() {
return redirect()->to('https://example.com');
}
}
I am new to CI4. In my case, I had to properly set $baseURL in App.php. For example, if the port is set incorrectly in your local development, it will just hang.
eg. public $baseURL = 'http://localhost:8888/';
Its worth saying that unlike the former CI3 redirect() function this one must be called from within a Controller. It won't work for example within a Library.
Update 2021
It is in fact possible to do this! Simply check that the returned response is an object and return it instead. So if a library returns a RedirectResponse, check it using the following code and return if applicable.
if (!empty($log) && is_object($log)){
return $log;
}
You could of course do get_class() to make sure the object is a type of RedirectResponse if there is any possibility of another object being returned.
If you using unnamed route:
$this->response->redirect(site_url('/user'));
'/user': It is my controller name. You can also used controller/function name.
Please look at the documentation
// Go back to the previous page
return redirect()->back();
// Go to specific URI
return redirect()->to('/admin');
// Go to a named route
return redirect()->route('named_route');
// Keep the old input values upon redirect so they can be used by the old() function
return redirect()->back()->withInput();
// Set a flash message
return redirect()->back()->with('foo', 'message');
// Copies all cookies from global response instance
return redirect()->back()->withCookies();
// Copies all headers from the global response instance
return redirect()->back()->withHeaders();
If you find:
{0, string} route cannot be found while reverse-routing
This error:
Please Go to system\HTTP\RedirectResponse Line no 91 :
Change:
throw HTTPException::forInvalidRedirectRoute($route);
To:
return $this->redirect(site_url('/Home'));
(dashboard after login)
The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
Original Answer: https://stackoverflow.com/a/725200/5700401
In my application I am using multiple forms, the forms submission points to another
action but redirects back to the previous action. In the form submission action I handle
the form input / validation. To return an error or success message I use the FlashMessenger.
My point of problem is that it's not clear how I set a namespace for the FlashMessenger. I have serval forms on the same page where I would like to use FlashMessenger messenges.
if ($this->flashMessenger()->hasMessages()) {
$messages = $this->flashMessenger()->getMessages();
foreach($messages as $message) {
echo $message;
}
}
I am guessing I should do something with '$this->flashMessenger('namespace').. In my controller action? But I didn't figure out how exactly make this work. If anyone has an example.. that would be great :)
You can add a message into a particular namespace by using these built-in methods in your action controller:
// in your controller
$this->flashMessenger()->addInfoMessage('info message');
$this->flashMessenger()->addSuccessMessage('success message');
$this->flashMessenger()->addErrorMessage('error message');
// in your view script
$this->flashMessenger()->getInfoMessages();
$this->flashMessenger()->getSuccessMessages();
$this->flashMessenger()->getErrorMessages();
Or if you want to specify your own namespace, you can use something like:
// in your action controller
$defaultNamespace = $this->getNamespace();
$this->setNamespace('yournamespace');
$this->addMessage($message);
$this->setNamespace($defaultNamespace);
// in your view script
$this->flashMessenger()->getMessagesFromNamespace('yournamespace');
For more information, you can see the documentation:
http://framework.zend.com/manual/2.3/en/modules/zend.mvc.plugins.html#flashmessenger-plugin
http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.flash-messenger.html#basic-usage
The namespace of the flash messenger controller plugin can be manual set using the setNamespace($namespace) method.
$this->flashMessenger()->setNamespace('foo')->addMessage($message);
However there are also convenience functions that will set a different namespace and message at the same time.
For example, if you want to add a success message then you can use:
$this->flashMessenger()->addSuccessMessage($message);
Internally the plugin will set the namespace as success and add the message to it (and then reset the namespace to allow for the next message to be set (defaults to default))
public function addSuccessMessage($message)
{
$namespace = $this->getNamespace();
$this->setNamespace(self::NAMESPACE_SUCCESS);
$this->addMessage($message);
$this->setNamespace($namespace);
return $this;
}
I am working in codeigniter and Iam looking to make my own custom validation class using "Validation_form" library and my custom rule where I will place my own validation rules and use that from everywhere in my project, but this seems impossible, I tried in couples ways to handle this but nothing.
Codeigniter kindle force me to make my callback methods in my controller but I need them in my library or "method" or wherever else!!!
My question is, can I build an specific library where I'll place my validation rules and other functions I need to handle that?
you could create a new library in application/libriries and name the file MY_Form_validation
What you are doing here is extending the form_validation class so that you will not need to mess with the core files.
The MY_ is what is set on your config, be sure to check it if you changed yours.
sample MY_Form_validation.php
class MY_Form_validation Extends CI_Form_validation
{
//this is mandatory for this class
//do not forget this or it will not work
public function __construct($rules = array(){
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
public function method1($str){
return $str == '' ? FALSE : TRUE;
}
pulic function method2($str)
{
//if you want a validation from database
//you can load it here
// or check the `form_validation` file on `system/libraries/form_validation`
}
public function check_something_with_post($tr)
{
return $this->CI->input->post('some_post') == FALSE ? FALSE : TRUE;
}
}
Basically, when you call a rule sample method1|method2 the value of your post field will be the parameter of the method. if you want to check other post you can do it by using $this->CI->input->post('name of the post');
when you want to pass a parameter just look at the form validation is_unique or unique code on system/libraries/form_validation you will have an idea.
To create a error message that goes with it go to application/language/english/MY_Form_validation_lang
Sample MY_form_validation_lang.php
$lang['method1'] = "error error error.";
$lang['method2'] = "this is an error message.";
if english does not exist on your application/language just create it.
check more atCreating libraries
NOTE:
On some linux or debian server you may want to change the file name from MY_Form_validation to
MY_form_validation note the small f on the word form.
I have one question.. How to validate fields data with custom error messages? I use codeigniter, and grocery crud with twitter bootstrap theme, and do some field required, for example:
$crud->set_rules('first_name', 'NAME', 'required'); OR $crud->required_fields('first_name');
Validation work fine, but if validation unsuccessfull - we see just alert with standart message - "An error has occurred on insert\update". How to display custom message that field are required or etc. ? Thanks.
Although this is old topic, but i thing someone can get this error as me just get it.
We can't use CI set_message function for CroceryCrud validation.
Because CroceryCrud use its validation object.
You can edit libraries/Grocery_CRUD.php, find line "protected function form_validation()",
at under this function, you can copy it, rename and edit access modifiler to public :
public function get_form_validation(){
if($this->form_validation === null)
{
$this->form_validation = new grocery_CRUD_Form_validation();
$ci = &get_instance();
$ci->load->library('form_validation');
$ci->form_validation = $this->form_validation;
}
return $this->form_validation;
}
Now, you can call it in your controller :
$crud-> get_form_validation()->set_message('check_city',"invail %s");
Take a look at function set_message in form_validation library:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#settingerrors
A function in the controller User loads the signup form, eg:
public function signup()
{
$this->load->view('form_view');
}
So the signup form url will be like root/user/signup (ignore index.php)
The form_view has a form, which is submitted to another method in the same controller, lets say process(), eg.
<? echo form_open('user/process') ?>
Once the form is submitted, it goes to the user/process, which contains the validation code. If there is any validation error, It would load the form_view again and pass the error data to display on the form.
if ( $this -> form_validation -> run() === FALSE )
{
//$this -> load -> vars( $data );
$this -> load -> view( 'form_view' );
}
Everything works fine. But now since the same form_view is loaded from the user/process function, the url of the form will change from:
root/user/signup
to
root/user/process
Because the form was submitted to the url user/process and the form_view is being called from the process(). Is it possible to somehow redirect or maintain the original form url(root/user/signup) when the form_view is loaded from the process function in case of errors?
Thanks.
Using the same method to for and validation you can try something like
if( count($this->input->post()) > 0 )
{ // do validation
if ($this->form_validation->run())
{
// initilize and
redirect('logged');
}
}
$this->load->view( 'form_view' );
you always get the same method, as you asked
I've done this a different way. I actually have one controller to do all this.
if ( $this -> form_validation -> run() === TRUE )
{
code
code
redirect('ANOTHER_URL_WITH_VALIDATION_CODE_DISPLAY');
}
$this -> load -> view( 'form_view' );
Sorry about that, I meant to say one controller NOT one method. If you're just looking for form validation, then throw it all into one controller. Have CI's built-in form_validation function do the validation for you. IF you require backend validation (i.e. username check), you can create a custom validation rule called a "callback" and have the form validate against that as well.
Ideally your controller will check all fields, if it passes, it should redirect to onward to the next page w/ any information you want to display (i.e. "Thank's for registering!"). If it fails the check, it should load the view page again; you'll need to repopulate the fields obviously.
See my response here for a detailed explanation of how/why the Codeigniter form validation should be called:
Question about how redirects should work