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');
}
}
Related
I am facing problem in function profile(). In this method I am fetching data from email using session.
When I login, displaying current data. But when I click on profile it displays previous session data and after refresh it become current session data.
last session data
after refresh display current session
my controller file is admin.php.
admin.php
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
// Load form helper library
$this->load->helper('form');
//Load foam valodation library
$this->load->library('form_validation');
// Load the model
$this->load->model('adminmodel');
}
public function index(){
// Load our view to be displayed
$this->load->view('admin/login');
}
// Check for Admin login process
public function dashboard(){
// Validate the user can login
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) //checking validation
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/dashboard');
}
else
{
$this->load->view('admin/login');
}
}
else
{ //validation are true
if (isset($_POST['login']))
{
$email = $this->input->post('email');
$password =$this->input->post('password');
// Validate the admin can login
$result = $this->adminmodel->validate($email,$password);
if ($result) {//if the user credidential is validated
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => true
);
print_r($data);
}
// Add user data in session
$this->session->set_userdata($data);
//load dashboard and passing value
$this->load->view('admin/dashboard',$result);
}
}
} //end of dashboard
public function profile(){
if($this->session->userdata('is_logged_in')){
$email = $this->session->userdata('email');
$result = $this->adminmodel->fetchdata($email);
print_r($result);
$this->load->view('admin/profile',$result);
}
else
{
echo "failed profile";
}
} // end of profile
// Logout from admin page
public function logout() {
// Removing session data
$sess_array = array(
'email' => '',
'is_logged_in'=>false
);
$this->session->unset_userdata($sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('admin/login', $data);
}
}
?>
model file
adminmodel.php
<?php
class Adminmodel extends CI_Model{
public function validate($email,$password)
{
$query = $this->db->where(['email'=>$email,'password'=>$password])
->from('login')
->get();
$result = $query->row();
return $result;
}
public function fetchdata($email)
{
$query = $this->db->where(['email'=>$email])
->from('login')
->get();
$result = $query->row();
return $result;
}
}
profile.php
<?php
echo " I am in Profile " . $email;
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
</head>
<body>
<p>Name : <input type = "text" value="<?php echo $name; ?>" /><p>
<p>Mobile : <input type = "text" value="<?php echo $mobile; ?>" /> </p>
<p>Address : <input type = "text" value="<?php echo $address; ?>" /> </p>
<p>Email : <input type = "text" value=" <?php echo $email;?>" /> </p>
</body>
</html>
Try the following, after logount instead of unset data, destroy the session entirely
$this->session->sess_destroy();
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');
}
}
}
I created a new controller questions.php which is not the default controller. I have already loaded the form_validation library but it did not echo out the validation errors when I submitted empty fields from my form. Other questions in SO seems to be completely unrelated to my situation.
Below is my questions.php controller. BTW I have only posted the necessary bits of the class controller.
<?php
class Questions extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper(array('form'));
$this->load->library("form_validation");
}
public function user_logged_in(){
$this->load->library('../controllers/main');
$obj = new $this->main();
$status = $obj->logged_in();
if($status){
return true;
}else{
return false;
}
}
public function question_validation(){
if($this->user_logged_in() == false){
redirect('main/index');
} else{
$this->load->library('form_validation');
$this->form_validation->set_rules('input_title','Title','required');
$this->form_validation->set_rules('message','Question Details','required');
$this->form_validation->set_rules('vidya','Tags','required');
if($this->form_validation->run() == false){
$this->load->library('../controllers/main');
$obj = new $this->main();
$getUserData = $obj->getLogged_userData();
$userdata = array(
'uservalues' => $getUserData
);
$this->load->view('view_header');
$this->load->view('view_nav',$userdata);
$this->load->view('log_user/user_second_nav');
$this->load->view('question_posts/post_questions');
$this->load->view('view_footer');
} else{
echo "form has been submitted";
}
}
}
?>
The form page in view called post_questions.php which is shown below,
<?php
$this->load->helper("form");
echo validation_errors();
echo form_open('questions/question_validation');
?>
<p><h2>Question title</h2></p>
<p><input type="text" name="input_title" id="input_title"
placeholder="what is your question please be specific and clear"></p>
<p><h3>Now Describe in detail!</h3>
<p><textarea id="message" name="message" rows="10px" cols="86px"></textarea></p>
<p><h3>Tags</h3></p><p><input type="text" id="vidyagames" name="vidya"></p>
<p><input type="submit" name="post" value="Submit"></p>
</form>
Before this, the questions controller was giving me error like undefined property Questions::$form_validation so I added a __construct() and now it wont echo out the form validation errors.
Can you help me because probably the form isn't being submitted at all.
Thank You in Advance.
I am using form validation of CodeIgniter, it works fine but when, form validation fails, it does not display the validation errors, by using
<?php echo validation_errors();?>
I am using
function insertProduct(){
$this->load->library('form_validation');
$this->form_validation->set_rules('pname','ProductName','trimirequired');
if($this->form_validation->run()){
$this->addProduct();
}
else{
$this->load->model('inventory/stock');
}
In your view you should have something like (this example shows errors individually);
<?php echo form_error('p_name'); ?>
<label for="p_name">Product Name</label>
<input type="text" id="p_name" name="p_name" value="<?php echo set_value('p_name'); ?>" />
You need to tell the method in your controller to render a view on success/failure of the form validation.
If you change your insertProduct method to the following, it 'should' solve your issue.
function insertProduct(){
$this->load->library('form_validation');
$this->form_validation->set_rules('pname','ProductName','trimirequired');
if($this->form_validation->run()){
$this->addProduct();
$this->load->view('{name_of_your_view}');
} else{
$this->load->model('inventory/stock');
$this->load->view('{name_of_your_view}');
}
}
Where 'name_of_your_view' is the view that you've placed the validation_errors() code in.
This example from the CodeIgniter tutorial pages explains how to validated submitted data to display validation errors at the header of the form like you might expect:
http://codeigniter.com/user_guide/tutorial/create_news_items.html
The example code for the creation function looks like this:
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');
}
}
As others have said, though, you need to add a view to handle success and return them to the form to display errors on failure.
We can change the line containing following code:
$this->form_validation->set_rules('pname','ProductName','trimirequired');
to:
$this->form_validation->set_rules('pname','ProductName','trim|required');
if($this->form_validation->run($this) == false)
{
$this->addProduct();
}
I have a form for user to input some feedbacks, and this form has to be resided in a product detail page. I am required to print out some error validation on the detail page instead of having the form redirected to the feedback form page with the validation message.
The product detail page is located at 'index.php/product/view/1', while the feedback form is at 'index.php/product/add_feedback'.
How can I print out the error form validation message so that it shows on the product detail page, instead of redirection to the add_feedback. Thank you.
My controller:
class Product extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('mproduct');
$this->load->model('mfeedback');
}
public function index()
{
//get product details
$data['content'] = $this->mproduct->get_details();
$this->load->view('listing', $data);
}
public function add_feedback()
{
// feedback form
$this->form_validation->set_rules('name', 'Name', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('feedback', 'Feedback', 'required|xss_clean|max_length[200]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('feedback');
}
else
{
$pid = $this->input->post('pid');
$name = $this->input->post('name');
$feedback = $this->input->post('feedback');
$this->MFeedback->add($pid, $name, $feedback);
redirect('product/view/'.$pid);
}
}
}
Model:
class MFeedback extends CI_Model {
function add_feedback($name, $pid, $feedback)
{
$data = array(
'name' => $name,
'feedback' => $feedback,
'pid' => $pid,
);
$this->db->insert('feedback', $data);
}
}
view - feedback.php
<h1>Add Feedback</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('product/add_feedback'); ?>
<p>Name</p>
<input type="text" name="name" size="50" value="<?php echo set_value('name'); ?>" />
<p>Feedback</p>
<textarea type="text" name="feedback"><?php echo set_value('feedback'); ?></textarea>
<?php echo form_hidden('pid', $this->uri->segment(3, 0)); ?>
<div><input type="submit" value="Add Feedback" /></div>
</form>
Simple! Just add the validation to Product/index-method, like this:
class Product extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('mproduct');
$this->load->model('mfeedback');
}
public function index()
{
// feedback form validation
$this->form_validation->set_rules('name', 'Name', 'required|xss_clean|max_length[200]');
$this->form_validation->set_rules('feedback', 'Feedback', 'required|xss_clean|max_length[200]');
if ($this->form_validation->run() == TRUE)
{
// the validation passed, lets use the form data!
$pid = $this->input->post('pid');
$name = $this->input->post('name');
$feedback = $this->input->post('feedback');
$this->MFeedback->add($pid, $name, $feedback);
redirect('form/success'); // redirect to a page, where the user gets a "thanks" message - or redirect to the product page, and show a thanks there (but be sure to use redirect and nocht $this->load->view(..), because then the form data would be still in the header and a reload of the page would send another mail :)
}
// form did not pass the validation, lets get and show the product details
$data['content'] = $this->mproduct->get_details();
$this->load->view('listing', $data);
}
}
And in the file feedback.php you'll have to change the form target to something like this:
<?php echo form_open('product/'.$this->uri->segment(3, 0)); ?>
... or even better:
<?php echo form_open('product/'.$content->id); ?>
... depends on your product view.