Welcome Guest, Not a member yet? Register   Sign In
Model return TRUE or FALSE
#1

[eluser]someone Smile[/eluser]
Hello!

I'm working some script and I have few questions about returning if operation in model was successfully finished or there was a problem.

So I would like to create model function like:
Code:
function somefunc($id)
{
$check = $this->db->select('id')->where('id', $id)->get('sometable');
if ($check->row('id'))
{
  //then do something with this field in table
}
else
{
  //this id doesn't exist and we need to tell controller which will tells view there is something going wrong
}
}

What I need to do instead second comment to tell controller there's something wrong (if it's possible to set message or flashdata it would be great)?

Thanks! :-)
#2

[eluser]mast3rpyr0[/eluser]
Just return true or false.

Code:
return true;
return false;


To send a specific message:

Code:
return 'message';
#3

[eluser]meigwilym[/eluser]
You could even cut it down to
Code:
function somefunc($id)
{
return $this->db->select('id')
                 ->where('id', $id)
                 ->get('sometable')
                 ->row();

}

It will return FALSE if there are no records, or just the record itself.

Mei
#4

[eluser]someone Smile[/eluser]
In controller then I use just:
Code:
if ($this->Model->somefunc($id)) // do I need to add is equal to TRUE?
{
   //do something
}
else
{
   //show error
}

So what I have to use then?

Thanks! :-)

EDIT:
Can I also set " return 'error1'; " and then in controller:
Code:
if ($this->Model->somefunc($id) == "error1")
{
   //do something
}
else
{
   //show what's wrong
}
#5

[eluser]someone Smile[/eluser]
Anyone?
#6

[eluser]mast3rpyr0[/eluser]
You can send any variable or string back with return. If it works, send back return true; If not, then return false or a string with the error message.

And no you dont have to add == true in your if statement, as long as what you are returning is either true or false. if you dont send back true at all, then you will want to check for the specific string that you do return.
#7

[eluser]Aken[/eluser]
I usually throw exceptions, but then you'll want something to handle those, naturally.
#8

[eluser]someone Smile[/eluser]
How to use error message then to show it to user?

Something like that?
Code:
if ($this->Model->somefunc($id) == "error1")
{
   //do something
}
else
{
   //show what's wrong
}
#9

[eluser]InsiteFX[/eluser]
CodeIgniter User Guide - Error Handling
#10

[eluser]someone Smile[/eluser]
I see this already, but I would like to do:
1. Model return T/F (in this case F)
2. In return is string err1/err2/err3
3. Controller read string and if it's right set flashdata message to user after redirect.

So.. How to use model return string in controller checking with if?

Thanks! :-)




Theme © iAndrew 2016 - Forum software by © MyBB