I'm new to PHP CodeIgniter and I'm creating my first app, I've created the controller, model and views to add records to my DB and so far so good,
The problem starts when I click 'submit' in my form,
as instead of redirecting to the same form again if there is an issue in the form or redirecting to the success page, it redirects to the same page but with the full path twice,
like this:
form page - localhost/index.php/news/create
expected results:
form data is valid ->localhost/index.php/news/success
form is invalid -> localhost/index.php/news/create (same page)
but instead it does this when I click submit:
localhost/index.php/news/localhost/index.php/news/create
as you can see, it takes the full path again and puts it afterwards the already existing url.
this is my code
routes.php
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['news/create'] = 'news/create';
main controller
public function view($page = 'home')
{
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
controller that has the function create of the form
class News extends CI_Controller {
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');
}
}
}
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);
}
Form
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
Thanks to #tobifasc for the answer,
The problem was in config.php
I replaced
$config['base_url'] = 'localhost';
to this:
$config['base_url'] = 'http://localhost/';
and everything is working properly now
It's happening because you have already view loaded and when your validation failed again you loaded your same view so you don't need to view again. Replace your News controller the create method by this code EX:
class News extends CI_Controller {
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)
{
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
}
Related
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);
}
You should use something like that:
redirect('news/view/'.url_title($this->input->post('title'), 'dash', TRUE));
This doesn't make sense to me with how MVC works in codeigniter.
I have a 'controller/Company.php' loads using example.com/company/
function index() {
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
This loads 'views/company.php' and displays form:
<h1 class="page-title"><?php echo $title; ?></h1>
<?php echo form_open('company/update', 'class="form-horizontal" role="form"'); ?>
<input name="company_name" type="text">
<?php echo form_error('company_name'); ?> //if empty display error
//rest of form and submit button
I then have an update function inside the Company controller:
function update() {
$this->form_validation->set_rules('company_name', 'Company Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('company');
} else {
//update db, load model, post data, success, etc
}
}
My issues are:
If I just load the form view again then I lose my header, nav, footer, etc.
If I redeclare all 4 of those views, I lose the original data variables: $title, $page
If I use redirect('company'); to load the controller again then I would lose the submitted data and the form_error('company_name'); would be empty
I hope I'm missing something big because I have been staring at this all day and search for answers but can't find a tutorial of how all of this is suppose to work in the "real world" Thanks
Yes of course. Controller method act as single function in your project.
if i explain it more
<?php
public function one()
{
echo '1';
}
public function two()
{
echo '2';
}
In here function one don't know what is function two. So both functions are acting as Independent.
According to your question
you load this views in index()
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
but in update() you load only
$this->load->view('company');
so in second function there are no header, navigation, and footer.
Answer for your Question is
<?php
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}
For question Two
you can use like this
<?php
if ($this->form_validation->run() == FALSE)
{
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}
I have been trying to learn CI and implement a blog content management system following a lightweight tutorial I found online today, but I'm currently experiencing some problems in the view.
Adding new entries "works", but I get the following errors on top of the add_new page:
http://pastebin.com/4UhMTqLj
CONTROLLER
function new_entry()
{
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//set validation rules
$this->form_validation->set_rules('entry_name', 'Title', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('entry_body', 'Body', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header', $data);
$this->load->view('admin/new_entry', $data);
$this->load->view('footer', $data);
}
else
{
//if valid
$name = $this->input->post('entry_name');
$body = $this->input->post('entry_body');
$this->articles_model->new_entry($name,$body);
$this->session->set_flashdata('message', '1 new entry added!');
redirect('articles/new_entry');
}
}
VIEW
<h2>Add new entry</h2>
<?php echo validation_errors(); ?>
<?php if($this->session->flashdata('message')){echo $this->session->flashdata('message');}?>
<?php echo form_open('articles/new_entry');?>
<p>Title:<br />
<input type="text" name="entry_name" />
</p>
<p>Body:<br />
<textarea name="entry_body" rows="5" cols="50" style="resize:none;"></textarea>
</p>
<input type="submit" value="Submit" />
<?php echo form_close();?>
MODEL
function new_entry($name,$body)
{
$data = array(
'entry_name' => $name,
'entry_body' => $body
);
$this->db->insert('entry',$data);
}
What can be the cause?
Edit: I'm using Codeigniter 3.
You must initiate the $data variable before passing in to the views.
eg.
$data = array();
put it on the new entry class
I completely agree with the answer from Cha Hernandez, however, another possibility would be:
To remove the $data variable altogether:
$this->load->view('header');
$this->load->view('admin/new_entry');
$this->load->view('footer');
This is mainly because you're not actually passing any information to the view, so there is no point in having it in the instance.
Hope this helps!
Change your CONTROLLER TO file below code where i removed variable $data since it is not assigned to any values and passing undefined variable $data is not necessary.
function new_entry()
{
$this->load->helper('form');
$this->load->library(array('form_validation','session'));
//set validation rules
$this->form_validation->set_rules('entry_name', 'Title', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('entry_body', 'Body', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header');
$this->load->view('admin/new_entry');
$this->load->view('footer');
}
else
{
//if valid
$name = $this->input->post('entry_name');
$body = $this->input->post('entry_body');
$this->articles_model->new_entry($name,$body);
$this->session->set_flashdata('message', '1 new entry added!');
redirect('articles/new_entry');
}
}
I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}
I was playing around with this code. http://programmersvoice.com/tag/code
And I noticed that the following line.
$this->load->model($this->models."pagemodel", 'pages');
I compare this with
$this->load->model("pagemodel", 'pages');
This is what codeigniter's document http://codeigniter.com/user_guide/general/models.html#loading suggest.
However method 2 takes longer time than the first one.
Could anyone explain what "$this->models." do please?
Thanks in advance.
The following is the whole code of pages.php in controllers/admin
<?php
class Pages extends Application
{
function Pages()
{
parent::Application();
$this->auth->restrict('editor'); // restrict this controller to editor and above
$this->load->model($this->models."pagemodel", 'pages'); // Load the page model
}
function manage()
{
$data = $this->pages->pages(); // List the pages
$this->table->set_heading('Title', 'Slug', 'Actions'); // Setting headings for the table
foreach($data as $value => $key)
{
$actions = anchor("admin/pages/edit/".$key['id']."/", "Edit") . anchor("admin/pages/delete/".$key['id']."/", "Delete"); // Build actions links
$this->table->add_row($key['title'], $key['slug'], $actions); // Adding row to table
}
$this->auth->view('pages/manage'); // Load the view
}
function delete($id)
{
$this->pages->delete($id);
$this->auth->view('pages/delete_success');
}
function add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$this->auth->view('pages/add');
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->add($data);
$this->auth->view('pages/add_success');
}
}
function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$data = $this->pages->page($id);
$this->auth->view('pages/edit', $data[0]);
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->edit($id, $data);
$this->auth->view('pages/edit_success');
}
}
}
?>
I'm not totally sure about the following, since the current version of Codeigniter doesn't seem to populate the $this->models variable, but I think that:
$this->models contained the full path to the application models directory, and therefore loading is faster, since CI doesn't have to look in different folders (global & application)