If codeigniter model returns 0 rows, display custom error message. How to extend to a general case? - codeigniter

I have a variety of functions within my models which serve a different purpose.
One for example looks up the data for a given $_GET variable in the URL string.
I am trying to work out a way of displaying an error message if there is no matching row in the database due to url string manipulation for example.
My first idea was simply to return an error message (if there is an error) with each call to the function, then simply have an if statement whereby if there is an error, an error view is shown, and if not the normal view is shown..
Problem with this is that this function is called numerous times in my controller, and other similar functions are called throughout my code which need similar error handling..
I dont want millions of similar if/else statements all over my code to handle errors..
Anyone got any better ideas?
Cheers

Use the flashdata item of the session class. You can concatenate error messages and put them in the flashdata item to display.
my_function(){
// code that determines if there is an error returns => $error
if ($error)
{
// concat previous and current errors
$new_error = $this->session->flashdata('errors') . $error;
// replace 'errors' with newly concatenated errors
$this->session->set_flashdata('errors', $new_error);
}
}
This will keep track of all errors generated through each request and allow you to display a "list" of errors for that particular request.
echo $this->session->flashdata('errors');

Related

Dingo APi error message

I am trying to render my mailable in the browser in order to check the content. However I'm getting this message {"message":"sha1() expects parameter 1 to be string, object given","status_code":500}
My code snippet
I am running Dingo/Api on my page as well an I think it's somehow connected with it.
Can you please give me the suggestion why am I getting this message instead of rendering mailable?
Thank you
We got this to work by assigning the mailable to a var first and then directly calling the render function on it, like so:
$mailable = new YourMailableName();
return $mailable->render();

Custom filters - how do I make them fail?

I'm creating a package that allows users to use a custom filter.
So far I have a method called:
public function testFilter(){
return false;
}
In my filters file, in my main app I have I have:
Route::filter('test.test', MyPackage::testFilter());
And in my routes, in my main app I have:
'before'=>'test.test'
My question is, how do I do the filtering, I've done a return false to try and make the filter fail, do I need something else, like app abort?
According to Laravel filters documentation
If the filter returns a response, that response is considered the response to the request and the route will not execute. Any after filters on the route are also cancelled.
That means you do have to return a Response to cancel your route from proceeding.
It'll probably more logical for you have another view to be displayed to your visitor when the filter fails, and this is what Laravel is trying to do.
You can use App::abort() for that or App::abort(404) (with error codes) to show error page.

Codeigniter Form Validation - Is there a way to define multiple different %s when setting error messages?

Based on the documentation, %s will be replaced by field name when setting error messages.
If you include %s in your error string, it will be replaced with the
"human" name you used for your field when you set your rules.
Is there a way to have multiple %s in the string and define them differently?
This is the line in the form validation library that creates the error message:
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
$line: The error message template, for example "The % field is invalid"
$this->_translate_fieldname($row['label']): The field's label
$param: The parameter passed the the validation function, if any, max_length[5] would pass "5"
So that's the extent of what the form validation class does for you. If you need more flexibility you'll have to prepare the error message yourself <-- might be useful beforehand with the extra variables already populated.
It might be interesting to extend the form validation class via core/MY_form_validation.php and work this functionality in. Unfortunately this line is contained in the main function _execute which is very big and messy, and from looking at it now, you'd need to overload some other functions as well. I started to write an example but it actually looks like a chore. You might be better off using:
$this->form_validation->set_message('rule_name', 'Your custom message here');
More on setting error messages: http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html#settingerrors

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

How to get error messages from model

Say you have a User model. The controller is attempting to create a new User. Should the controller check that the username is valid, and the password is long enough, and the first and last name are filled out, etc? Or should you pass all that data straight to the User model via a Create method? The Create method would then return a true on success, or false on failure?
If it's the latter (and I think it is), how do the error messages get sent back to the controller (so they can be displayed in a view)? Should you pass an errors array to the Create method which the model augments? Or should the model keep an internal store of errors, with appropriate accessors? I don't like either method...is there a better way?
These errors don't seem exceptional, so I don't think exception handling is appropriate.
Edit: I'm using PHP for this project, but I use Python too.
For the first question, the model should do the verifications (and use some form of error handling to notify the controller and view that errors did or did not occur). For the second, it depends on what programming language / framework you are using... What are you using?

Resources