使用单一表单进行插入和更新功能,Codeigniter

Using a single form for insert and update function, Codeigniter

我正在尝试使用单一表单来插入新数据和更新现有数据的值 data.I 显示表单、获取数据和更新它没有问题,但是当我试图插入新数据时,表格没有出现。这是我的看法

     <div class="card-body">
           <small><?php echo validation_errors(); ?></small>
            <?php if (isset($packages)) { ?>
            <form action="<?= base_url('admin/update_package/' . $packages->id) ?>" method="POST" enctype="multipart/form-data">
            <div class="form-group">
           <label for="name" class="control-label">Package Name</label>
            <input type="text" class="form-control mb-3" name="title" placeholder="Enter Package Name" value="<?php echo !empty($packages->title) ? $packages->title : ''; ?>">
          </div>
         <div class="form-group">
           label for="short_name" class="control-label">Inclusions</label>
           <textarea id="compose-textarea" class="form-control" name="tour_location" style="height: 300px;"><?php echo !empty($packages->tour_location) ? $packages->tour_location : ''; ?></textarea>
        </div>
        <div class="form-group">
        <label for="short_name" class="control-label">Description</label>
         <textarea id="compose-textarea2" class="form-control" name="description" style="height: 300px;"><?php echo !empty($packages->description) ? $packages->description : ''; ?></textarea>
         </div>
         <div class="form-group">
         <label for="price" class="control-label">Price</label>
        <input type="number" step="any" class="form-control form" required name="cost" value="<?php echo !empty($packages->cost) ? $packages->cost : 0; ?>">
         </div>
         <div class="form-group">
         <label for="status" class="control-label">Status</label>
          <select name="status" id="status" class="custom-select select">
         <option value="1" <?php echo isset($status) && $status == 1 ? 'selected' : '- Select Status -' ?>>Active</option>
        <option value="0" <?php echo isset($status) && $status == 0 ? 'selected' : '- Select Status -' ?>>Inactive</option>
        </select>
        </div>
         <div class="form-group">
        <label for="short_name" class="control-label">Images</label>
         <div class="custom-file">
         <label class="btn custom-file-label text-light" for="customFile">Choose file
        <input type="hidden" name="current_image" value="<?php echo !empty($packages->upload_path) ? $packages->upload_path : ''; ?>">
        <input type="file" class="form-control custom-file-input" id="customFile" name="image" multiple accept="image/*"><small><?php if (isset($error)) {
        echo $error;} ?></small>
        </label>
        </div>
        </div>
        <?php 
         } ?>
         <!-- <div class="col-md-4">
        <img src="<?php echo base_url('images/' . $packages->upload_path) ?>" alt="Package Image" class="w-100 h-100">
        </div> -->
    
         <div class="card-footer">
          <input type="submit" name="packageData" class="btn btn-success " value="Save">
          <a class="btn btn-flat btn-default" href="<?php echo base_url('admin/packages'); ?>">Cancel</a>
            </div>
          </form>
          </div>
    
    
    
    
    My model
    
    
    
    <!-- language: lang-html -->
    
         public function insert($data = array())
            {
                if (!empty($data)) {
                    $this->db->insert('packages', $data);
    
                    return $this->db->insert_id();
                }
                return false;
            }
        public function edit($id)
            {
                $query = $this->db->get_where("packages", array('id' => $id));
    
                return $query->row();
            }
    
            public function update($data, $id)
            {
                return $this->db->update("packages", $data, array('id' => $id));
            }

然后是控制器

public function insert_package()
    {
        $packageData = array();

        // If add request is submitted
        if ($this->input->post('packageData')) {
            // Form field validation rules
            $this->form_validation->set_rules('title', 'Package Name', 'required');
            $this->form_validation->set_rules('tour_location', 'Inclusions', 'trim');
            $this->form_validation->set_rules('description', 'Description', 'trim|required');
            $this->form_validation->set_rules('cost', 'Price', 'required');
            $this->form_validation->set_rules('status', 'Status', 'required');
            // $this->form_validation->set_rules('image', 'Images', 'required');

            // Validate submitted form data
            if ($this->form_validation->run() == true) {
                $ori_filename = $_FILES['image']['name'];
                $update_image = time() . "" . str_replace(' ', '-', $ori_filename);
                $config = [
                    'upload_path' => './images',
                    'allowed_types' => 'gif|jpg|png',
                    'file_name' => $update_image,
                ];

                $this->load->library('upload', $config);

                if (!$this->upload->do_upload('image')) {
                    $error = array('error' => $this->upload->display_errors());
                    $this->load->view(base_url('admin/packages'), $error);
                } else {

                    $image = $this->upload->data('file_name');
                    $packageData = array(
                        'title' => $this->input->post('title'),
                        'tour_location' => $this->input->post(htmlentities('tour_location')),
                        'description' => $this->input->post(htmlentities('description')),
                        'cost' => $this->input->post('cost'),
                        'status' => $this->input->post('status'),
                        'upload_path' => $image
                    );
                    $img = new Admin_model;
                    // Insert member data
                    $img->insert($packageData);
                    $this->session->set_flashdata('status', 'Package InsertedSuccesfully');
                    redirect(base_url('admin/packages'));
                }
            }
        }

        $data['title'] = 'Add Package';

        $this->load->view('../admin/template/admin_header');
        $this->load->view('../admin/template/admin_topnav');
        $this->load->view('../admin/template/admin_sidebar');
        $this->load->view('../admin/packages/manage_package', $data);
        $this->load->view('../admin/template/admin_footer');
    }

    public function edit_package($id)
    {
        $data['title'] = 'Update Package';

        $this->load->view('../admin/template/admin_header');
        $package = new Admin_model;
        $data['packages'] = $package->edit($id);
        $this->load->view('../admin/template/admin_topnav');
        $this->load->view('../admin/template/admin_sidebar');
        $this->load->view('../admin/packages/manage_package', $data);
        $this->load->view('../admin/template/admin_footer');
    }

    public function update_package($id)
    {
        $this->form_validation->set_rules('title', 'Package Name', 'required');
        $this->form_validation->set_rules('tour_location', 'Inclusions', 'trim');
        $this->form_validation->set_rules('description', 'Description', 'trim|required');
        $this->form_validation->set_rules('cost', 'Price', 'required');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() == true) {
            $current_image = $this->input->post('current_image');
            $new_image = $_FILES['image']['name'];

            if ($new_image == TRUE) {

                $update_image = time() . "-" . str_replace(' ', '-', $_FILES['image']['name']);
                $config = [
                    'upload_path' => './images',
                    'allowed_types' => 'gif|jpg|png',
                    'file_name' => $update_image,
                ];

                $this->load->library('upload', $config);

                if (!$this->upload->do_upload('image')) {
                    if (file_exists('./images' . $current_image)) {
                        unlink('./images' . $current_image);
                    }
                }
            } else {
                $update_image = $current_image;
            }

            $packageData = array(
                'title' => $this->input->post('title'),
                'tour_location' => $this->input->post(htmlentities('tour_location')),
                'description' => $this->input->post(htmlentities('description')),
                'cost' => $this->input->post('cost'),
                'status' => $this->input->post('status'),
                'upload_path' => $update_image
            );
            
            $this->Admin_model->update($packageData, $id);
            $this->session->set_flashdata('status', 'Package InsertedSuccesfully');
            redirect(base_url('admin/packages/'));
        } else {
            return $this->edit_package($id);
        }
    }

我在这里找到了一个问题以及一个答案和建议,但我仍然无法解决我的问题。

重复使用表单进行插入和更新的最简单方法是将表单操作留空。如果表单操作留空,表单将 post 返回到用于显示它的相同 URL。如果您使用相同的方法(一种用于插入,一种用于更新)来处理和呈现来自。

由于您的更新表单处理在 admin/update_package/$id,但您的更新表单呈现在 admin/edit_package/$id,您需要指定的表单操作取决于您使用的 URL显示更新表单。

如果您使用 link 到 admin/update_package/$id 来显示更新表单,您可以将表单操作留空(或完全删除):<form method="POST" enctype="multipart/form-data">

update_package 然后运行表单验证,然后使用 edit_package 显示表单,但 URL 仍然是 admin/update_package/$id,这是您想要 post 返回,因此不需要表单操作。

在这种情况下,我建议您也将控制器中的 edit_package 方法设为私有,这样您就不会意外地通过 edit_package URL 显示表单:private function edit_package($id)


但是,如果您使用 link to/the URL admin/edit_package/$id 来显示更新表单,posting 回到那个 URL 不会触发表单处理,因此在这种情况下您需要指定表单操作。

您可以使用 $packages 变量来判断表单是用于插入还是更新,并将操作设置为 update_package URL if $packages存在:action="<?= isset($packages) ? base_url('admin/update_package/'.$packages->id) : ''; ?>"

Insert 然后得到一个空操作,该操作 post 返回到用于呈现插入表单的相同 URL。


编辑:同时删除表单周围的 <?php if (isset($packages)),否则它也不会在插入时显示。