Welcome Guest, Not a member yet? Register   Sign In
Passing a view as a variable.
#1

[eluser]ellipsis[/eluser]
Hi. I'm new to PHP and CodeIgniter so please bear with me.

I have a basic set of views for my header, content (includes both a sidebar and a content area) and a footer. In the content area I'm simply echoing a variable $page_content where I want the view to be. ATM I'm working on the registration page. Now.. everything seems fine so far, it's just that I don't really know how to store the view as an array element in order to pass it along to the list because I've been having some real issues with this. Here's the code so you can hopefully get a better understanding of what my problem is.


Code:
// CONTROLLERS/REGISTRATION.PHP

<?php

class Registration extends Controller {

    function Registration()
    {
        parent::Controller();    
    }
    

    function index()
    {
        
        $this->validation->set_rules($rules);*/
        
        //re-populating the forms after a registration error has occurred
        if(isset($_POST['ln']))
        {
                $trans=    $_POST['ln'];    
                $fields['ln'] = $trans;
        }
        else
        {
                $fields['ln'] = NULL;
        }
        
        if(isset($_POST['site']))
        {
                $trans=    $_POST['site'];    
                $fields['site'] = $trans;
        }
        else
        {
                $fields['site'] = NULL;
        }
        
        if(isset($_POST['city']))
        {
                $trans=    $_POST['city'];    
                $fields['city'] = $trans;
        }
        else
        {
                $fields['city'] = NULL;
        }
            
        //setting the form rules
        $this->form_validation->set_rules('fn', 'First Name', 'required');
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]|callback_username_check');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[50]|matches[passconf]');
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
        $this->form_validation->set_rules('country', 'Country', 'required');
        
        //getting shit from db
        $fields['query']=$this->db->get('users');
            
        //running form validation and loading the appropriate page                
        if ($this->form_validation->run() == FALSE)
        {
            $data['page_content']=$this->load->view('register', $fields, true);
        }
        else
        {
            $data['page_content']=$this->load->view('regsuccess', "", true);
        }
        
        //loading the views
        $this->load->vars($data, $fields);
        $this->load->view('header');
        $this->load->view('content');
        $this->load->view('footer');
        

    }
    
        //checking the username against a predefined set of rules
    function username_check($str)
    {
                
        if ($this->db->where('username', $str))
        {
            $this->form_validation->set_message('username_check', 'The username is already taken');
            return FALSE;
        }
        elseif ($str == 'administrator')
        {
            $this->form_validation->set_message('username_check', 'That username is reserved');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    //checking the e-mail address against a predefined set of rules
    function email_check($str)
    {
        if ($this->db->where('email', $str) || $str == '[email protected]')
        {
            $this->form_validation->set_message('email_check', 'That e-mail address is already in use');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }    


}
/* End of file registration.php */
/* Location: ./frontend/controllers/registration.php */
?>

Here's content.php as well, for reference.

Code:
// VIEWS/CONTENT.PHP

<div id="wrapper">
    
  <div id="sidebar">
        <ul>
            <li><a href="/app/" class="menu">Home</a></li>
            <li><a href="bookmarks" class="menu">Bookmarks</a></li>
            <li><a href="notes" class="menu">Notes</a></li>
            <li><a href="files" class="menu">Files</a></li>
            <li><a href="pictures" class="menu">Pictures</a></li>
            <li><a href="videos" class="menu">Videos</a></li>
        </ul>
  &lt;!-- / #sidebar --&gt;</div>

  <div id="content">
    &lt;?php echo $page_content; ?&gt;
    
    
  &lt;!-- / #content --&gt;</div>
  
&lt;!-- / #wrapper --&gt;</div>

Any help or suggestions on how to better the code would be greatly appreciated.
#2

[eluser]jedd[/eluser]
Hi ellipsis and welcome to the CI forums.

I like posts when I'm invited to nit-pick other people's code .. so much easier than writing my own code Wink

Initial glance - the way you're loading views into a variable, using the TRUE (as third parameter) - why don't you continue with that approach for your header, footer, and so on? Consistency is the hobgoblin (etc) but it also makes for easier to understand code.

And I was so hoping you were going to have a model function called get_shit_from_db() .. oh well.
#3

[eluser]Dam1an[/eluser]
To assign a view as a variable, just set the 3rd parameter to true, it will then return the contents of that view as a string which you can assign to a variable

Edit, Darn it, beat by Jedd
Jedd, seeing as you like nitpicking other people code, I was wondering if you could loook over this function for me

Code:
function get_shit_from_db() {
  $this->db->where('user', 'jedd');
  $query = $this->db->get('posts');

  return $query->num_rows() == 0 ? false : $query->results();
}

Too harsh? Tongue
#4

[eluser]jedd[/eluser]
Oh .. and you can replace this:
Quote:
Code:
//re-populating the forms after a registration error has occurred
        if(isset($_POST['ln']))
        {
                $trans=    $_POST['ln'];    
                $fields['ln'] = $trans;
        }
        else
        {
                $fields['ln'] = NULL;
        }
        
        if(isset($_POST['site']))
        {
                $trans=    $_POST['site'];    
                $fields['site'] = $trans;
        }
        else
        {
                $fields['site'] = NULL;
        }
        
        if(isset($_POST['city']))
        {
                $trans=    $_POST['city'];    
                $fields['city'] = $trans;
        }
        else
        {
                $fields['city'] = NULL;
        }

With this:
Code:
$fieldnames = array ("ln", "site", "city");
foreach ($fieldnames as $fn)
    $fields[$fn] = (isset ($_POST[$fn])) ?  $_POST[$fn] : NULL;
#5

[eluser]ellipsis[/eluser]
Thanks for the quick replies.
By reading the user guide (which I've been doing quite a lot lately), I somehow got the impression that passing the view as a string would somehow limit the view's functionality as in... uhm... well, I don't really know what I mean by that myself so I'll just ask. Is there any downside to using the TRUE parameter?
@Dam1an - I actually did do that, it's just that I've been getting some weird results. Meaning that even if atm you see both $data and $fields passed through vars(), $fields doesn't seem to be passed at all. I had to add it as the second parameter when loading the view. Any idea what that is?

Edit: @jedd... you lost me at the last line :lol:
#6

[eluser]jedd[/eluser]
Quote:Too harsh? Tongue

A little. I did four major re-writes of that message before posting, so you had plenty of time to sneak in there. Smile

Besides, I'm out of practice - my typing speed is down to about 70wpm these days. So that's like two head starts you had there.

I was going to suggest the outright TRUE thing on the view load, but then noticed that they'd actually done this already in one of their view calls. Hence I suggested to stick with that approach, as I think it's far more elegant and might negate the other problems.

I'm quite jealous - I didn't discover that feature (or the joy it brought to my code) for months - it's not spectacularly well documented, or at least it wasn't a year ago.
#7

[eluser]Dam1an[/eluser]
I may have had 2 head starts, but I also had 43 other tabs I was dealing with
And i just glossed over the code and saw the last 3 views loaded, didn't notice the one a few lines up with the 3rd param

And if it's any consolation, I didn;t discover that feature for a while at first
#8

[eluser]jedd[/eluser]
[quote author="ellipsis" date="1245369329"]
Is there any downside to using the TRUE parameter?[/quote]

I don't think so, and I don't think anyone else will assert that it's bad - it's just one way of achieving the same net result.

Some people like to load views from within other views - which is the third broad approach. (First two are: 1) load views sequentially, and 2) this one you're doing is where you load each of your sub-view, or component bits of HTML, into a variable and then feed them into your 'whole page' view - which usually ends up just being a few DIV's, maybe some JS preamble, and a handful of echos).

Quote:@Dam1an - I actually did do that, it's just that I've been getting some weird results. Meaning that even if atm you see both $data and $fields passed through

Okay, don't use vars() anymore - just use your load->view approach and feed things into it.

I think you might just want to do this:
Code:
$data['fields'] = $fields;

I also think you might be about to get bitten on the proverbial by getting confused with the distinction between $this->data and $data - but you may be fully aware of what you're doing (in an OO sense) and not be about to get bitten at all.

Quote:Edit: @jedd... you lost me at the last line :lol:

Ahh, the ternary operator. I was vaguely aware of it for a few years, but xwero on here really made me feel the love for it. It's insanely powerful for stripping otherwise lengthy code snippets into much shorter, albeit somewhat alarming at first glance, code.

EDIT - Two things - first, you can start using load->vars() later - some people really love it but I find it .. unnecessary. I think the problem here is that you're using both approaches, and that's probably going to confuse you. Second, of the three broad approaches I find the views-from-views approach to be ugly, and I find the views(,,TRUE) approach to be more elegant and much easier to track than calling each of my dozen or so mini-views to push output directly. I don't think there's much of a performance hit in double-handling the views by loading them into a variable, but I may be wrong there.
#9

[eluser]ellipsis[/eluser]
[quote author="jedd" date="1245370150"][quote author="ellipsis" date="1245369329"]
Is there any downside to using the TRUE parameter?[/quote]

I don't think so, and I don't think anyone else will assert that it's bad - it's just one way of achieving the same net result.

Some people like to load views from within other views - which is the third broad approach. (First two are: 1) load views sequentially, and 2) this one you're doing is where you load each of your sub-view, or component bits of HTML, into a variable and then feed them into your 'whole page' view - which usually ends up just being a few DIV's, maybe some JS preamble, and a handful of echos).
[/quote]
That's reassuring.

[quote author="jedd" date="1245370150"]
Quote:@Dam1an - I actually did do that, it's just that I've been getting some weird results. Meaning that even if atm you see both $data and $fields passed through

Okay, don't use vars() anymore - just use your load->view approach and feed things into it.

I think you might just want to do this:
Code:
$data['fields'] = $fields;

I also think you might be about to get bitten on the proverbial by getting confused with the distinction between $this->data and $data - but you may be fully aware of what you're doing (in an OO sense) and not be about to get bitten at all.
[/quote]
I've all but given up on vars(), but why not use them at all? Also, you said I should just pass my variables in the views statement, but I don't think it's possible to pass more than one array in there; is it? Something like $this->load->view('hawtpage', $data, $more_data, $fatty_foods, TRUE);
or do you mean that I should just somehow store all my arrays in another array and then pass that array as the second arguemnt; like $allData=array($data, $more_data, $fatty_foods);
[quote author="jedd" date="1245370150"]
Quote:Edit: @jedd... you lost me at the last line :lol:

Ahh, the ternary operator. I was vaguely aware of it for a few years, but xwero on here really made me feel the love for it. It's insanely powerful for stripping otherwise lengthy code snippets into much shorter, albeit somewhat alarming at first glance, code.

EDIT - Two things - first, you can start using load->vars() later - some people really love it but I find it .. unnecessary. I think the problem here is that you're using both approaches, and that's probably going to confuse you. Second, of the three broad approaches I find the views-from-views approach to be ugly, and I find the views(,,TRUE) approach to be more elegant and much easier to track than calling each of my dozen or so mini-views to push output directly. I don't think there's much of a performance hit in double-handling the views by loading them into a variable, but I may be wrong there.[/quote][/quote]
Yeah, that confused me a bit, but I introduced it into the code and it works beautifully. Thank you.
#10

[eluser]jedd[/eluser]
Quote:I've all but given up on vars(), but why not use them at all?

Oh, hopefully someone will pop up and defend their good name. I think Fuzzy is a fan of them, so can probably provide something more compelling than my dissing of them. Wink

Quote:Also, you said I should just pass my variables in the views statement, but I don't think it's possible to pass more than one array in there; is it? Something like $this->load->view('hawtpage', $data, $more_data, $fatty_foods, TRUE);
or do you mean that I should just somehow store all my arrays in another array and then pass that array as the second arguemnt; like $allData=array($data, $more_data, $fatty_foods);

Kinda sorta.
Code:
// controller
$data['fields'] = array ("bob", "ted", "carol", "alice");
$data['menu'] = $this->load->view ('main_menu', $data, TRUE);
$data['other_stuff'] = $heres_an_array_i_prepared_earlier;

Code:
// view
echo "At the party we had: ";
foreach ($fields as $field)
     echo $field . ", ";
?&gt;
<div id="menu">
     &lt;?php  echo $menu; ?&gt;
</div>

&lt;?
    // Do something with $other_stuff[] array ...
?&gt;


Quote:Yeah, that confused me a bit, but I introduced it into the code and it works beautifully. Thank you.

Close your eyes and learn how to [url="http://uk3.php.net/ternary"]use the ternary force[/url]. You'll never look back. But you will start looking sideways more often.




Theme © iAndrew 2016 - Forum software by © MyBB