Welcome Guest, Not a member yet? Register   Sign In
How do you deal with "Edit" pages?
#1

[eluser]KeyStroke[/eluser]
I have a controller "Post" which has a function "edit_post" for editing posts. However, I can't figure out how this would work.

Are you supposed to use two functions for edits? like one that initially loads the form and populates it with data from the database; and another to process it, show errors and re-populate it with the data the user enters? how would that work in my "View"?

I want the user to edit the post and see the errors on the same form.

Appreciate your help
#2

[eluser]GSV Sleeper Service[/eluser]
here's an 'edit_post' function that I use on my (not quite finished) blog.
Code:
// Handles New Posts and Editing Posts
function edit_post($post_id = false) {
    if(!$this->auth->try_session_login()){
        redirect('blog');
    }

    $data['title'] = '';
    $data['body'] = '';
    $data['post_id'] = '';

    if($post_id) {
        $query = $this->db->get_where('posts',array('id' => $post_id));
        if($query->num_rows() > 0) {
            $row = $query->row();
            $data['title'] = $row->title;
            $data['body'] = $row->body;
            $data['post_id'] = $row->id;
        }

    }

    $data['mode'] = $post_id ? 'Edit' : 'New';
    $data['target'] = 'blog/edit_post';

    $this->load->library('validation');
    $this->validation->set_error_delimiters('<div class="error">', '</div>');

    $rules['title'] = 'trim|required|min_length[3]|max_length[255]';
    $rules['body'] = 'trim|required';
    $this->validation->set_rules($rules);

    $fields['title'] = 'title';
    $fields['body'] = 'body';
    $this->validation->set_fields($fields);
    if ($this->validation->run()) {
        if($this->input->post('post_id')){
            // post_id sent, must be an update
            $update = array(
                    'title'=> $this->input->post('title'),
                    'slug' => url_title($this->input->post('title')),
                    'body' => $this->input->post('body')
                    );
            $this->db->update('posts', $update, array('id' => $this->input->post('post_id') ));
        } else {
            // no post_id, new post
            $this->load->helper('date');
            $insert = array(
                    'title' => $this->input->post('title'),
                    'slug' => url_title($this->input->post('title')),
                    'user_id' => $this->session->userdata('user_id'),
                    'body' => $this->input->post('body'),
                    'post_date' => date('Y-m-d H:i:s')
                    );
            $this->db->insert('posts', $insert);
        }
        redirect('blog');
    } else {
        $this->load->view('blog/edit_post',$data);
    }
}




Theme © iAndrew 2016 - Forum software by © MyBB