CodeIgniter - adding comments to a post - php

I'd like some help please. I have a post page that has the full post and below the post a small form for adding comments. The uri of the post page is: site/posts/1, so it is in posts controller, and the form action is form_open(site_url('comments/add/'.$post->post_id)).
This is my add() function inside comments controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
and this is the add() function inside the comment model
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
What I'm trying to do is if the $result = $this->comment_model->add($post_id); fails the validation to display the validation errors in my post view, else insert the comment and redirect to the same post page (site/posts/1).
The problem is that when I hit submit the form action goes in the comments/add/1, as expected, but doesn't do any these above.
Any ideas how can I fix this??
EDIT
I did a small change to the code without the 'confusing' validate() function. Maybe this is more helpful.
Comment controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
Comment model:
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}

You need away of passing validation_errors() back to your Posts controller. At the minute, when you perform the redirect in your add function (when the validation fails), you loose the validation errors thrown.
I would consider using flashdata (http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) to pass a success/error message from your Comments controller back to your Posts controller. Something similar to the below:
Comments Controller:
public function add($post_id) {
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
// Store the success message in flash data
$this->session->set_flashdata('message', 'Ok! TODO save the comment.');
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
} else {
// Store the error message in flash data
$this->session->set_flashdata('message', validation_errors());
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
}
}
Posts Controller:
public function index($post_id) {
$this->data['message'] = $this->session->flashdata('message');
$this->load->view('posts', $this->data);
}
Posts View:
echo $message;
Might not be perfect but hope it helps...

Related

Data not insert into codeigniter

I will try to insert & also update data using session in Codeigniter, but data not inserted into the database even its print save successfully.
Here is my controller:
public function save($user_id)
{
$this->load->model('Users');
$code=$this->input->post('code');
$name=$this->input->post('name');
$address=$this->input->post('address');
$user_data= array(
'code' =>$code,
'name'=>$name,
'address'=>$address,
'active'=>1
);
if($this->Users->save($user_data,$user_id))
{
$this->session->set_flashdata('msg',"save sucesss");
}else {
$this->session->set_flashdata('msg',"not save");
}
redirect('home');
}
& this is my model:
public function save($data,$id)
{
if (id=='') {
// code...
$this->db->insert('user',$data);
return true;
}else
{
$this->db->where('id',$id)
->update('user',$data);
return true;
}
return false;
}
Data insert if I removed if in model!
You have the model always returning true no matter the outcome of the database operation. You should use the return value from insert() or update() so the "message" reports what actually happens.
Note that the argument to save has a default value. Now you can call the save URL without an argument and it will automatically do an insert.
public function save($user_id = NULL)
{
$this->load->model('users');
$user_data = array(
'code' => $this->input->post('code'),
'name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'active' => 1
);
if($this->Users->save($user_data, $user_id))
{
$msg = "save sucesss";
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
redirect('home');
}
public function save($data, $id)
{
if(empty($id))
{
// code...
// insert returns TRUE on success, FALSE on failure
return $this->db->insert('user', $data);
}
// update() accepts a third argument, a "where" array
// and returns TRUE on success, FALSE on failure
return $this->db->update('user', $data, array('id' => $id));
}
Now have an accurate report on the database operations.
the first check is data is coming in save controller or not if it's not getting the data then fix it. If coming then pass it in a model in the correct format and it will definitely be inserted in the database.
use following printing data
echo $data;
var_dump($data);
print($data);
print_r($data);
First thing is to rename your model calling eg:
$this->load->model('users');
and use this to call your method:
$this->users->save($user_data,$user_id)
your model should look like this then:
public function save($data, $id) {
if ($id) {
$this->db->where('id', $id)
->update('user', $data);
return true;
}
$this->db->insert('user', $data);
return true;
}
if you want to use your flashdata on the next request, use this:
$this->session->keep_flashdata('item');
$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
because flashdata is only for the next request:
CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.

I get error when i login to my project and then go back to the base url

I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.

Code Igniter Validation on Error

I am pretty knew to code igniter / OOP but I am giving it a shot and a little stumped at this point.
I have 2 functions. One is the search which loads data from a model. The other is the save function.
My issue is, when running save() I am getting errors because its trying ti display the validation errors but we no longer have the data from the database that we got from the search() function.
I feel that it would be redundant to include all the details form the search back into this save function which is why I think I am doing something wrong.
public function search()
{
// Define some vars
$data['title'] = 'Submit Attrition';
$data['js_file'] = 'submit.js';
// Load our helper
$this->load->helper('form');
// Get the user and pass it to the model
$empQID = $this->input->post('empQID');
$data['userDetails'] = $this->submit_model->get_details($empQID);
$data['languages'] = $this->submit_model->get_languages();
$data['types'] = $this->submit_model->get_types();
$data['ratings'] = $this->submit_model->get_ratings();
$data['processes'] = $this->submit_model->get_processes();
// Send the data to the views
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
/**
* Validate & save attrition submission
*
* #author Carl
* #return void
*/
public function save()
{
$data['title'] = 'Submit Attrition';
$this->load->library('form_validation');
$this->form_validation->set_rules('language', 'Supporting Language', 'required');
// Validation failed, show form w/ validation errors
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
else
{
// Success : Send data to model
$this->submit_model->save_attrition();
$this->load->view('templates/header', $data);
$this->load->view('submit/success', $data);
$this->load->view('templates/footer', $data);
}
}
I'm not sure I entirely understand your question, but I think I understand what you're trying to do. In CodeIgniter, you do something like this:
class MyController
{
// this controller action will load whether the form is submitted or not
// $user_id is set by the router
public function save($username)
{
// if the users not in the database, throw a 404 error
$user = $this->db->get_where('users', ['username' => $username]);
if(!$user) {
return show_404();
}
// if it's not a post request, then the form hasn't been submitted
// so don't bother validating it
if($router->fetch_method() === 'POST' && $form_validation->run() === TRUE)
{
$user['name'] = $this->input->post('name');
$this->db->update('users', $user);
$this->load->view('success_page');
// return so we don't render the form again
return;
}
// this will happen in all cases, __except__ when the form was submitted
// with valid data
$this->load->view('form');
}
}
I've skipped on details for brevity (like loading the relevant libraries), and because I can't remember all the CI syntax.

Laravel form not getting any data on redirect (no errors no input)

I have a form for creating an organization. If I do not pass the name of the organization through, it fails validation as it should. In the store method I can see the proper errors in $this->validator->getErrors() and I pass those in, but NOTHING shows up in the form. I can dump errors and Input:old() from the view form yet nothing is there. What am I missing?
public function create()
{
$supportedStates = ['' => 'Choose'] + $this->us_states->supportedStates();
$procedures = $this->procedures->getList();
$phoneTypes = $this->phone_types->lists('phone_number_type', 'id');
return View::make('organizations.create', array('supportedStates' => $supportedStates, 'procedures' => $procedures, 'phoneTypes' => $phoneTypes, 'input' => Input::old()));
}
public function store()
{
$input = Input::all();
if($this->validator->passes())
{
$new_organization = $this->repository->create(['organization_name' => $input['organization_name']]);
if($input['logo_url'])
{
$new_organization->processImage($input, Request::root());
}
$new_organization->createRelated($input);
return Redirect::route('/')
->with('message', 'Organization Created.');
}
return Redirect::route('organizations.create')
->withInput()
->withErrors($this->validator->getErrors())
->with('message', 'There were validation errors.');
}
You need to show us how you are displaying the errors on ther form.
Are you using the below to get the errors
The errors are in messages.
//send this to your view from controller
$messages = $validator->messages();
//retrieve errors in view
foreach ($messages as $message)
{
//
}

Codeigniter form validation error message

I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error

Categories