Welcome Guest, Not a member yet? Register   Sign In
Variable Accessible In View, But Not Within View's Function?
#1

[eluser]Walter Coots[/eluser]
I'm stumped. I'm defining a function in my view which is trying to access a variable passed from the controller. The function itself returns an error as if the variable isn't defined. However if I print_r() the variable outside of that function, it shows up as expected.

In my controller:

Code:
function constructAndShowToolbar()
    {
        $toolbarLinks['new'] = Array();
        $toolbarLinks['edit'] = Array();
        $toolbarLinks['system'] = Array();
        $toolbarLinks['groupings'] = $this->TableOptions_model->getTableGroups();

        /* [...] Code to populate the empty arrays */

        $this->load->view('skins/admin/toolbar',$toolbarLinks);
    }

Then in my view:

Code:
function createTopLevelMenu($arr,$title='UNTITLED')
    {
        if($groupings != NULL) /* Returns, "PHP Error- undefined variable: "groupings"  */
        {
            print_r($groupings);
        }
    }
    
    print_r($groupings); /* Prints the array in its entirety */

    createTopLevelMenu($new,'New');
    createTopLevelMenu($edit,'Edit');
    createTopLevelMenu($system,'System');
}
#2

[eluser]samwilliamh[/eluser]
As a rule functions shouldn't really be in views. You could try putting the function in the controller/model, then populating some variables with the functions in the controller and echoing out the variables in the view. However, if you want to continue with the function in the view, try passing $groupings as a variable to the function.
#3

[eluser]Walter Coots[/eluser]
Thanks Sam. I thought that might have been the case. I'm sort-of new to the MVC design pattern, and sometimes the distinction between view and controller confuses me. Although the function is for generating a portion of the view, I suppose this would be along the lines of having a function in a model with the intention of cleaning up data for presentation. (Which makes more sense being done in the controller.)




Theme © iAndrew 2016 - Forum software by © MyBB