Home > Mobile >  Why do I have this error when I try to submit a comment without adding Name and/or body?
Why do I have this error when I try to submit a comment without adding Name and/or body?

Time:04-01

I am facing this problem(please check the picture). I want when I click on "Submit" without typing body and/or email, to show that those fields are required. I am currently a beginner, and I've tried to deal with the error, but I couldn't. Please Help.

ERROR

This is my model:

             <?php 
  class Comment_model extends CI_Model {
public function __construct() {
    $this->load->database(); //database library loaded
}

public function create_comment($post_id) {
    $data = array(
        'post_id' => $post_id,
        'name' => $this->input->post('name'),
        'body' => $this->input->post('body')

    );

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

public function get_comments($post_id){
    $query = $this->db->get_where('comments', array('post_id' => $post_id));
    return $query->result_array();
}

}

This is my comment controller:

                          <?php 
  class Comments extends CI_Controller {
  public function create($post_id) {
    $slug = $this->input->post('slug');
    $data['post'] = $this->post_model->get_posts($slug);

    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('body', 'Body', 'required');

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


    }
    else {
        $this->comment_model->create_comment($post_id);
        redirect('posts/'.$slug);
    }
}

}

Post controller:

       public function view($slug = NULL) {
       $data['post'] = $this->post_model->get_posts($slug);

    $post_id = $data['post']['id'];
    $data['comments'] = $this->comment_model->get_comments($post_id);
    
    if(empty($data['post'])){
        show_404();
    }

    $data['title'] = $data['post']['title'];
    $this->load->view('templates/header');
    $this->load->view('posts/view', $data);
    $this->load->view('templates/footer');
}

And view: code

              <h3>Comments</h3>
<?php if($comments) : ?>
    <?php foreach($comments as $comment) : ?>
        <div >
            <h5><?php echo $comment['body']; ?> [by <strong><?php echo $comment['name']; ?></strong>]</h5>
        </div>
    <?php endforeach; ?>

<?php else : ?>
    <p>No Comments to Display</p>
<?php endif; ?> 

CodePudding user response:

In your view try like this

<?php if(!empty($comments)) : ?>

instead of

<?php if($comments) : ?>

CodePudding user response:

Your comments from $data is missing in your Comment controller. Use empty() to check if a variable is present or not in your view

  • Related