GrumpyCrouton
GrumpyCrouton

Reputation: 8621

CodeIgniter Redirection from form input

I've never used a PHP framework, but I wanted to learn how to use one so I could more easily program for my company, so I chose CodeIgniter.

I am following the code igniter tutorial for a news section so I could learn how things work - but I am having some issues/questions.

Now, I am to the point in the tutorial that I have a form that submits and takes me to a success page. In normal PHP this is where I would just redirect the page to the view page of the news item submitted. In CodeIgniter I have a view function in my controller here

        public function view($slug = NULL)
        {
                $data['news_item'] = $this->news_model->get_news($slug);

                if (empty($data['news_item']))
                {
                        show_404();
                }

                $data['title'] = $data['news_item']['title'];

                $this->load->view('templates/header', $data);
                $this->load->view('news/view', $data);
                $this->load->view('templates/footer');
        }

I'm not sure how to get the slug from the form when it is submitted.

Here is my create function (Basically the one that inserts the database info and redirects to news/success)

        public function create()
        {
            $this->load->helper('form');
            $this->load->library('form_validation');

            $data['title'] = 'Create a news item';

            $this->form_validation->set_rules('title', 'Title', 'required');
            $this->form_validation->set_rules('text', 'Text', 'required');

            if ($this->form_validation->run() === FALSE)
            {
                $this->load->view('templates/header', $data);
                $this->load->view('news/create');
                $this->load->view('templates/footer');

            }
            else
            {
                $this->news_model->set_news();
                $this->load->view('news/success');
            }
        }

But I want this to redirect to the view page. To do that I need to have the slug I believe. So it should redirect to news/view/$slug - but I'm not sure how to do this.

My set_news model:

        public function set_news()
        {
            $this->load->helper('url');

            $slug = url_title($this->input->post('title'), 'dash', TRUE);

            $data = array(
                'title' => $this->input->post('title'),
                'slug' => $slug,
                'text' => $this->input->post('text')
            );

            return $this->db->insert('news', $data);
        }

Upvotes: 0

Views: 1123

Answers (1)

phpawy
phpawy

Reputation: 76

You should use something like that:

redirect('news/view/'.url_title($this->input->post('title'), 'dash', TRUE));

Upvotes: 1

Related Questions