ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Posting a form that is included in a page

November 16, 2009 8:50am

Subscribe [5]
  • #1 / Nov 16, 2009 8:50am

    JamieBarton

    98 posts

    Hi guys,

    Fairly new with CodeIgniter - hence the simple question (simple for most of you). Would appreciate it very much if you guys could give me some help.

    I have a controller for my Dashboard. The index() of the Dashboard includes my header, footer, sidebar, and a general div for some static text. Also included is a ‘wall’ view.

    The view is:

    <h1>Wall Posts</h1>
        Posts below have been made by your family:
        
        <?=form_open('wall/create')?>
            
            <?=form_error('message')?>
            <textarea name="message" rows="8" cols="40"><?=set_value('message');?></textarea><br >
            
            <input type="submit" name="submit" value="Post it" id="submit" />
            
        <?=form_close()?>
        
        <?php if ($recent_wall_posts->num_rows() > 0) { ?>
        
            <?php foreach($recent_wall_posts->result() as $p) {?>
    
                
                    <strong>
                        <a >member_id?>"><?=$p->member_forename?> <?=$p->member_surname?></a>
                    </strong>
                     <?=$p->wallPost_message?>
                
                
                    Posted <?=relative_time($p->wallPost_posted_on);?>
                
    
            <?php } ?>
        
        <? } else { ?>
            
            <strong>No wall posts to display</strong>
            
        <? } ?>

    As you can see it posts to wall/create - Controller/Function.

    The create function checks for validation and if it passes validation it will insert the form data into the Database.

    How, if there is an error, it takes me to wall/create and shows the error. I would like it to remain at /dashboard controller only and not forward to wall/create.

    What’s the best way to doing a form, I’m thinking perhaps have another function that uses the result of ‘create’ to do something.

    Could someone help me out here?


    Thank you very much,

    Jamie

  • #2 / Nov 16, 2009 9:36am

    Flemming

    270 posts

    Hi Jamie,

    there’s no reason why your dashboard controller can’t handle the posted form, in exactly the same way as your /wall/create controller does. It does mean code duplication but you can keep that to a minimum be reusing your views as much as possible. For instance, your controllers can set the form action so you can reuse the same form view in both wall/create and dashboard.

    dashboard controller:

    $data['form_action'] = '/dashboard';

    dashboard view:

    <?=form_open($form_action)?>

    So your dashboard can include the form view (with the form action dynamically set by the controller, in this case to /dashboard) ... on initial page load and validation failure you can display the form along with the rest of the data from the dashboard just as you are currently doing. Just copy your validation rules into /dashboard. On success you can redirect wherever you want.

    Alternatively you could use Javascript validation, so that the dashboard form won’t get posted to the wall/create method until it has passed client-side validation.

    Hope that helps!?!

  • #3 / Nov 16, 2009 9:45am

    JamieBarton

    98 posts

    Hey Flemming,

    Thanks for replying. I’m wanting to reduce code duplication much as possible. I’m new to this whole thing and even MVC.

    In the end I want to be able to post the form using AJAX/jQuery and make it submit without refreshing the page. As for validation - I was thinking of disabling the submit button until the validation is met.

    I’m just not 100% sure what goes in the M, V and C. Mainly the M and C.

    Could you kindly elaborate more what would go in each to reduce less use of code. Without AJAX/jQuery. I thought in the /create function I could put in a redirect, but, it won’t take the form validation errors back with it.


    Regards,

    Jamie

  • #4 / Nov 16, 2009 10:05am

    Flemming

    270 posts

    Hi Jamie,

    A quick and dirty summary of the MVC architecture:

    Model - all your database queries

    Contollers - logic, as much as possible of it

    Views - HTML, with as little logic as possible ideally


    A controller won’t send validation messages through a redirect, which is why I suggested you post the dashboard form to the dashboard controller. If it fails validation then you WILL get the validation error data sent back to the view in validation_errors().

    If you’re using AJAX though, it doesn’t matter where you post the data! So you can either start your AJAX work now (definitely use jQuery and it’s AJAX or $post features) ... or you can spend a bit of time getting more familiar with CI and MVC first (sounds like a good idea) and then move on to AJAX.

    Keep asking questions and I or someone else will be happy to answer them - but don’t forget to search the forums too for answers if you think your questions are obvious/common ones!

  • #5 / Nov 16, 2009 10:12am

    JamieBarton

    98 posts

    Thanks for that. I’ve always thought of MVC as View -> Controller -> Model, well in fact it’s like View <- Controller -> Model.

    I guess my question originally could be similar to this post. Look at the bottom of the post, the Fast Reply button. That fast reply box, where will the controller to submit a fast reply be? In the viewthread controller?


    Regards,

    Jamie

  • #6 / Nov 16, 2009 10:22am

    JamieBarton

    98 posts

    Forgot to mention that when the form fails validation, i’ve included the form again, but it doesn’t show the header i’ve included, it just shows the form that ive included.

    What would be a way around that?

  • #7 / Nov 16, 2009 10:37am

    Flemming

    270 posts

    If you post the form using AJAX you can post it to any controller you like. That controller will send back a success (or fail) status to Javascript. The path to the controller is irrelevant, but you might want to keep it in a logical place, like /wall/add

    You might want to post your controller here so we can have a look?

    here’s a basic controller that handles a form submission. It might help you, I don’t know?

    <?php
    
    class login extends Controller {
        
        function __construct()
        {
            parent::Controller();
            $this->load->model('administrators_model');
            $this->load->library('form_validation');
        }
    
        function index()
        {
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
    
            $this->form_validation->set_error_delimiters('<li>', '</li>');
    
            if($this->form_validation->run())
            {
                // validation passed, so do something with the data and then probably redirect
            }
            else 
            {
                $this->load->view('header_view',$data);
                $this->load->view('login_view');
                $this->load->view('footer_view');
            }
        }
    }
    ?>
  • #8 / Nov 16, 2009 10:41am

    JamieBarton

    98 posts

    Hi,

    That helps a lot. Thanks for that, however, my dashboard will have multiple forms, for status update and wall post.

    That’s what had me struggling to see how to do that.

    my controller: (I’ve moved the function from wall.php controller to the dashboard controller inside a function called post_to_wall() not sure if it was right to do that though.

    <?php
    
    class Dashboard extends Controller {
    
        function Dashboard()
        {
            parent::Controller();
            $this->load->helper('date');
            $this->load->model("modelwall", "wall");
        }
        
        function index()
        {
            
            $data['recent_wall_posts'] = $this->wall->get_wall_posts(5);
            
            $this->load->view('header');
            $this->load->view('dashboard/wall', $data);
            $this->load->view('footer');
        }
        
        function post_to_wall()
        {
                $this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[7]|xss_clean');
                
                if($this->form_validation->run() == TRUE) {
                    
                    $member_id = 1;
                    $family_id = 1;
                    $message = $this->input->post('message');
                
                    $this->wall->insert_wall_post($family_id, $member_id, $message);
                    
                } else {
                    
                    $data['recent_wall_posts'] = $this->wall->get_wall_posts(5);
                    $this->load->view('dashboard/wall', $data);
                    
                }
            
        }
        
    }
    
    /* End of file Dashboard.php */
    /* Location: ./application/controllers/Dashboard.php */


    Thanks again,

    Also, seeing your profile - Your website - You’re based in Gateshead, I live in Prudhoe, so not far from you. Small world!

  • #9 / Nov 16, 2009 10:45am

    JamieBarton

    98 posts

    and my Model:

    function insert_wall_post($family_id, $member_id, $message)
        {
            $data = array(
                'wallPost_family_id'    => $family_id,
                'wallPost_member_id'    => $member_id,
                'wallPost_message'        => $message
            );
            
            $this->db->insert('wallPosts', $data);
            return true;
        }
  • #10 / Nov 16, 2009 11:35am

    Flemming

    270 posts

    Hi James,

    yep small world indeed! Amazing!

    Your model looks fine. For your controller I had meant that your index method would handle the posted form ... but I realise now that you’re wanting to handle more than 1 form on a single view. Off the top of my head I think you’re going to have to use AJAX to achieve that ... maybe someone else has other suggestions???

    Or ... you can still have multiple forms posting to different controllers, just don’t let them post until they’ve passed validation client-side. That would get around the problem.

    Are you familiar with jQuery’s AJAX features?

  • #11 / Nov 24, 2009 12:24pm

    JamieBarton

    98 posts

    Hi again,

    Also forgot to ask.

    Say I have a form to create a message, the URL being /messages/new

    Instead of having two controllers, one to handle including the view, and one to post the actual content, such as /messages/create

    How would I go about putting it all in one controller? Like if the form is submitted ... Do this, if not, show this etc. I’m probably just being stupid here, as it seems very easy and could do it in Procedural PHP fine.


    Thanks for your help.

  • #12 / Nov 24, 2009 12:36pm

    Flemming

    270 posts

    Hi Jamie,

    the answer is above! But here it is again ...

    if($this->form_validation->run())
            {
                // validation passed, so do something with the data and then probably redirect
            }
            else
            {
                // validation failed OR form not posted yet
                $this->load->view('view',$data);
            }
  • #13 / Nov 24, 2009 12:37pm

    JamieBarton

    98 posts

    Ah, I thought so! I wasn’t sure if the form validation run() meant when the form was submitted. I’m stoopid!

  • #14 / Dec 10, 2009 8:46pm

    dhenoer

    6 posts

    Comment to post#7
    According your codes:

    function post_to_wall()
        {              
                //set validation rules
                
                if($this->form_validation->run() == TRUE) {
    
                    //save data to database                
                    
                } else {
                    
                    //I will make a comment about this
                    $data['recent_wall_posts'] = $this->wall->get_wall_posts(5);
                    $this->load->view('dashboard/wall', $data);
                    
                }
        }

    If you use set_value() function, passing $data into the view(‘dashboard/wall’, $data) will re-populate the form gotten from database again.. So user should miss where my text I’ve submitted is?

    :red: Oppsss sorry.. forget my comment.. I think you use initial value that retrieved from database for your form..

  • #15 / May 22, 2012 3:45pm

    InsiteFX

    6819 posts

    You can also create a Forms Library.

    class Forms {
    
        /**
         * -----------------------------------------------------------------------
         * Class variables - public, private, protected and static.
         * -----------------------------------------------------------------------
         */
    
        /**
         * The CI object
         */
        private $CI;
    
        // -----------------------------------------------------------------------
    
        /**
         * __construct()
         *
         * Constructor    PHP 5+    NOTE: Not needed if not setting values!
         *
         * @access    public
         * @return    void
         */
        public function __construct()
        {
            $this->CI = get_instance();
    
            $this->CI->load->helper(array('form', 'url', 'email'));
            $this->CI->load->library('form_validation');
    
            log_message('debug', 'Class Forms Initialized');
        }
    
        public function form_1()
        {
            // setup your form rules here!
    
            if ($this->CI->form_validation->run() == FALSE)
            {
                $this->form_view('your_form');
            }
            else
            {
                // process the form data
                $this->form_view('your_success_form');
            }
        }
    
        // -----------------------------------------------------------------------
    
        /**
         * form_view()
         *
         * Load a specific form view.
         *
         * @access    public
         * @param     string - $page
         * @param     mixed  - $params
         * @return    void
         */
        public function form_view($page, $params = NULL)
        {
            if ($params !== NULL)
            {
                $data['data'] = $params;
            }
    
            $data['page'] = $page;
    
            $this->CI->load->view('your_view', $data);
        }
    }

     

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases