CodeIgniter Forums

Full Version: Calling one method from another within the same controller
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Unknown[/eluser]
I'm trying to add error messages and prompts at the top of pages, rather than redirecting to new pages.

For instance, when I link to 'user/delete', I tell my controller to load an alert variable, and then run the usual 'user/view' method:

Code:
function delete()
{
    $this->load->vars('alert','Are you sure?');
    $this->view();
    return;

    [...]

(I'm "paraphrasing" my code here, there's more to it than that.)

Note that I have use 'return' to keep CI from continuing through the delete function. This works, but it really doesn't feel like the best way of doing this.

I was using $this->session->set_flashdata() for the alert and then redirecting to 'user/view', but that seems even worse since it requires a redirect that slows things down (right?).

Thanks for any advice.

El Forum

[eluser]Pedro Luz[/eluser]
Hi,
Im currently working on a project, and since i dont like the flashdata.. because.. it usualy doesnt work the way i wanted, and i needed to pass messages to the user.. (success, fail, etc), what i did has... in all the methods in the controller i have something like this... i add a $params = array()

Code:
class User extends CI_Controller
{
/**
* Controller default welcome msg
* @var array
*/
private $_cMsg;

function __construct()
{
parent::__construct();
        
$this->_cMsg = array(
    array("type" => "info", "text" => "Welcome to the Users.")
);
}

function edit($params = array())
{
$this->_cMsg = array(
array("type" => "info", "text" => "Edit Users.")
);

// put together all the incoming messages
$data["msg"] = isset($params["msg"]) ? array_merge($this->_cMsg, $params["msg"]) : $this->_cMsg;

// then you load the views and pass
$this->load->view('something.php', $data);
}

then what i have in a little view that loads on top of the page
is something like this

Code:
$count = 0;
echo "<table class='msg-list'>";
    
    foreach($msg as $m)
    {    
        $msgBox  = "<tr class='msg ".$m['type']."'>";
        $msgBox .= "<td class='icn'></td>";
        $msgBox .= "<td class='msg-text'>".$m['text']."</td>";
        $msgBox .= "<td id='".$count."' class='msg-close'></td>";
        $msgBox .= "</tr>";
        
        echo $msgBox;
        
        $count++;
    }
    
    echo "</table>";

and with this you generate a table with multiple rows.. each with a message


if you want to pass a message to that method, i do somehting like
Code:
array_push($msgBag["msg"], array("text" => "Added width success", "type" => "success"));
array_push($msgBag["msg"], array("text" => "Still need to change the users permissions", "type" => "info"));
$this->edit($msgBag);

where im passing 2 messages to the edit method

is not the most accurate way, or the most guru way... but it works for me.