-
Ahmed Haroon
Member
-
Posts: 97
Threads: 30
Joined: Nov 2018
Reputation:
0
08-04-2022, 01:03 AM
(This post was last modified: 08-04-2022, 03:04 AM by Ahmed Haroon.)
i am trying to add a checkbox item in my module, i am stuck to have checkbox checked for Editing a row, please help. i will further add other elements radio buttons, select2 to add dropdown list with search and multi select features etc. please advise to learn CI4 and features to explore for How To's and off course the Links to learn & explore the features.
Controller code:
PHP Code: <?php namespace App\Controllers; use CodeIgniter\Controller; use CodeIgniter\API\ResponseTrait;
use App\Models\ProductsModel; use App\Models\CategorysModel; use App\Models\SubCatModel;
class Products extends Controller { public function index() {
$productsModel = new ProductsModel(); $categorysModel = new CategorysModel(); $subcatModel = new SubCatModel(); $data['product'] = $productsModel->getProduct()->getResult(); $data['category'] = $categorysModel->findAll(); $data['subcategory'] = $subcatModel->findAll(); return view('products_view', $data); } // this function used to Insert and Update both actions public function save() { $model = new ProductsModel(); $id = $this->request->getPost('product_id'); if (!$id){ $data = array( 'product_name' => $this->request->getPost('product_name'), 'product_price' => $this->request->getPost('product_price'), 'product_category_id' => $this->request->getPost('product_category'), 'subcategory_id' => $this->request->getPost('subcategory'), 'product_available' => $this->request->getPost('product_available'), 'gender' => $this->request->getPost('gender'), ); $model->saveProduct($data); } else { $data = array( 'product_name' => $this->request->getPost('product_name'), 'product_price' => $this->request->getPost('product_price'), 'product_category_id' => $this->request->getPost('product_category'), 'subcategory_id' => $this->request->getPost('subcategory'), 'product_available' => $this->request->getPost('product_available'), 'gender' => $this->request->getPost('gender'), ); $model->updateProduct($data, $id); } return redirect()->to('/products'); }
public function delete() { $model = new Product_model(); $id = $this->request->getPost('product_id'); $model->deleteProduct($id); return redirect()->to('/products'); }
function action() { if($this->request->getVar('action')) { $action = $this->request->getVar('action');
if($action == 'get_subcategory') { $subcatModel = new SubCatModel(); $subcatdata = $subcatModel->where('category_id', $this->request->getVar('category_id'))->findAll();
echo json_encode($subcatdata); }
if($action == 'get_city') { $cityModel = new CityModel(); $citydata = $cityModel->where('state_id', $this->request->getVar('state_id'))->findAll();
echo json_encode($citydata); } } } }
Model code:
PHP Code: <?php namespace App\Models; use CodeIgniter\Model;
class ProductsModel extends Model { protected $table = 'products_list'; protected $primaryKey = 'product_id'; protected $allowedFields = ['product_name', 'product_price', 'product_category_id', 'subcategory_id', 'product_available', 'gender'];
protected $validationRules = [ 'product_name' =>[ 'rules' =>'required|is_unique[product.product_name,product_id,{product_id}]', 'errors' =>[ 'required'=>'Product Name is required' ] ], 'product_category_id' =>[ 'rules' =>'required', 'errors' =>[ 'required'=>'Product Category is required, select a zone' ] ], 'subcategory_id' =>[ 'rules' =>'required', 'errors' =>[ 'required'=>'Product Sub-Category is required, select a zone' ] ], ];
public function getProduct() { $builder = $this->db->table('products_list'); $builder->select('*'); return $builder->get(); }
public function saveProduct($data){ $query = $this->db->table('product')->insert($data); return $query; }
public function updateProduct($data, $id) { $query = $this->db->table('product')->update($data, array('product_id' => $id)); return $query; }
public function deleteProduct($id) { $query = $this->db->table('product')->delete(array('product_id' => $id)); return $query; }
}
View code ( it contains single Modal for Add & Edit both actions )
PHP Code: <?= $this->extend('layouts/admin') ?>
<?= $this->section('content') ?> <div class="container"> <h3>Product Lists</h3> <!-- <button type="button" class="btn btn-success mb-2" data-toggle="modal" data-target="#addModal">Add New</button> --> <button type="button" class="btn btn-success mb-2 buttonmodel" data-toggle="modal" data-id="" data-name="" data-product_available="" data-price="" data-category_id="" data-subcategory_id="" data-target="#dmlModal">Add New</button> <table id="productstable" class="display table dataTable table-striped table-bordered"> <thead> <tr> <th>Product Name</th> <th>Price</th> <th>Category</th> <th>Sub-Category</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach($product as $row):?> <tr> <td><?= $row->product_name;?></td> <td><?= $row->product_price;?></td> <td><?= $row->category_name;?></td> <td><?= $row->subcategory_name;?></td> <td> <a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?= $row->product_id;?>" data-product_available="<?= $row->product_available;?>" data-name="<?= $row->product_name;?>" data-price="<?= $row->product_price;?>" data-category_id="<?= $row->product_category_id;?>" data-subcategory_id="<?= $row->subcategory_id;?>">Edit</a> <a href="#" class="btn btn-danger btn-sm btn-delete" data-id="<?= $row->product_id;?>">Delete</a> </td> </tr> <?php endforeach;?> </tbody> </table> </div>
<!-- Modal Add/Edit Product--> <link rel="stylesheet" href="<?php echo base_url('dist/vendors/select2/css/select2.min.css'); ?>"/> <link rel="stylesheet" href="<?php echo base_url('dist/vendors/select2/css/select2-bootstrap.min.css'); ?>"/> <form action="<?php echo base_url("/products/save"); ?>" method="post"> <div class="modal fade" id="dmlModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add/Edit Product</h5> <button type="button" id="buttonModal" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label>Product Name</label> <input type="text" class="form-control product_name" name="product_name" placeholder="Product Name"> </div> <div class="form-group"> <label>Price</label> <input type="text" class="form-control product_price" name="product_price" placeholder="Product Price"> </div>
<div class="form-group"> <label>Category</label> <select name="product_category" id="product_category" class="form-control product_category input-lg"> <option value="">Select Category</option> <?php foreach($category as $row) { echo '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>'; } ?> </select> </div> <div class="form-group"> <label>SubCategory</label> <select name="subcategory" id="subcategory" class="form-control subcategory input-lg"> <option value="">Select SubCategory</option> </select> </div> <div class="form-group"> <label>Available</label> <input type="checkbox" class="checkboxitem" name="product_available" id="product_available" /> </div> </div> <div class="modal-footer"> <input type="hidden" name="product_id" class="product_id"> <button type="button" id="buttonModal" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </div> </div> </div> </form> <!-- End Modal Add/Edit Product--> <?= $this->endSection() ?>
<?= $this->section('pagestyles') ?> <!-- START: Page CSS--> <link rel="stylesheet" href="<?php echo base_url('dist/vendors/datatable/css/dataTables.bootstrap4.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('dist/vendors/datatable/buttons/css/buttons.bootstrap4.min.css'); ?>"> <!-- END: Page CSS--> <?= $this->endSection() ?>
<?= $this->section('pagescript') ?> <!-- START: Page JS--> <script src="<?php echo base_url('dist/vendors/datatable/js/jquery.dataTables.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/js/dataTables.bootstrap4.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/jszip/jszip.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/pdfmake/pdfmake.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/pdfmake/vfs_fonts.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/dataTables.buttons.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/buttons.bootstrap4.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/buttons.colVis.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/buttons.flash.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/buttons.html5.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/datatable/buttons/js/buttons.print.min.js'); ?>"></script> <script src="<?php echo base_url('dist/vendors/select2/js/select2.full.min.js'); ?>"></script> <script src="<?php echo base_url('dist/js/datatable.script.js'); ?>"></script> <!-- END: Page JS--> <script>
$('.buttonmodel').on('click',function(){ $('.subcategory').empty(); var html = '<option value="">Select SubCategory</option>'; $('#subcategory').html(html); });
// to fill data in Edit mode var subcategorygobal = ''; $(document).ready(function(){
// get Edit Product $('.btn-edit').on('click',function(){ // get data for Editing a selected row const id = $(this).data('id'); const name = $(this).data('name'); const price = $(this).data('price'); const category = $(this).data('category_id'); const subcategory = $(this).data('subcategory_id'); const product_available = $(this).data('product_available'); // Set data to Form Edit $('.product_id').val(id); $('.product_name').val(name); $('.product_price').val(price); $('.product_category').val(category).trigger('change'); $('.checkboxitem').val(product_available);
if($('#product_available').val() == 'Y') { $('#product_available').attr('checked', true); }else{ $('#product_available').attr('checked', false); }
subcategorygobal = subcategory; // Call Modal Edit $('#dmlModal').modal('show'); });
// get Delete Product $('.btn-delete').on('click',function(){ // get data from button edit const id = $(this).data('id'); // Set data to Form Edit $('.productID').val(id); // Call Modal Edit $('#deleteModal').modal('show'); }); }); </script>
<!-- to clear form input items --> <script> $('#dmlModal').on('hidden.bs.modal', function (e) { $(this) .find("input,textarea,select") .val('') .end() .find("input[type=checkbox], input[type=radio]") .prop("checked", "") .end(); }); </script>
<script> $(document).ready(function () { $('#productstable').DataTable(); }); </script>
<script> $(document).ready(function(){
// on change of Product Category, below function will populate related data in Sub-Category $('#product_category').change(function(){
var category_id = $('#product_category').val(); // console.log(category_id); var action = 'get_subcategory';
if(category_id != '') { $.ajax({ url:"<?php echo base_url('product/action'); ?>", method:"POST", data:{category_id:category_id, action:action}, dataType:"JSON", success:function(data) { var html = '<option value="">Select SubCategory</option>';
for(var count = 0; count < data.length; count++) {
html += '<option value="'+data[count].subcategory_id+'">'+data[count].subcategory_name+'</option>';
}
$('#subcategory').html(html); if(subcategorygobal != '') { $('.subcategory').val(subcategorygobal).trigger('change'); } } }); } else { $('#product_category').val(''); } $('#subcategory').val(''); });
}); </script>
<!-- for checkbox input - mark checked / un-checked and set value --> <script> $('.checkboxitem').change(function(){ if ($('.product_id').val(id) != '') { if($('.checkboxitem').val() == 'Y') { $('#product_available').attr('checked', true); }else{ $('#product_available').attr('checked', false); } } else{ var $checkboxes = $('.checkboxitem'); var checkboxesLength = $checkboxes.length; var checkedCheckboxesLength = $checkboxes.filter(':checked').length; if(checkboxesLength == checkedCheckboxesLength) { $('#product_available').attr('checked', true); $('#product_available').val('Y'); }else{ $('#product_available').attr('checked', false); $('#product_available').val('N'); } } }); </script>
<?= $this->endSection() ?>
regards
Newbie here in CodeIgniter World !! Please appologize if any nonsense from me.
environment: Windows 10, XAMPP 3.3.0, VS Code, SQLyog Community Ed.
-
Ahmed Haroon
Member
-
Posts: 97
Threads: 30
Joined: Nov 2018
Reputation:
0
08-04-2022, 05:57 AM
(This post was last modified: 08-04-2022, 05:59 AM by Ahmed Haroon.)
added these lines in below code but it is showing "checked" first time going to Edit, then on every attempt it is showing it unchecked no matter it is "Y"
please help.
if($('#product_available').val() == 'Y') {
$('#product_available').attr('checked', true);
}else{
$('#product_available').attr('checked', false);
}
PHP Code: // to fill data in Edit mode var subcategorygobal = ''; $(document).ready(function(){
// get Edit Product $('.btn-edit').on('click',function(){ // get data for Editing a selected row const id = $(this).data('id'); const name = $(this).data('name'); const price = $(this).data('price'); const category = $(this).data('category_id'); const subcategory = $(this).data('subcategory_id'); const product_available = $(this).data('product_available'); // Set data to Form Edit $('.product_id').val(id); $('.product_name').val(name); $('.product_price').val(price); $('.product_category').val(category).trigger('change'); $('.checkboxitem').val(product_available); // start: code added here... if($('#product_available').val() == 'Y') { $('#product_available').attr('checked', true); }else{ $('#product_available').attr('checked', false); } // end: code added here... subcategorygobal = subcategory; // Call Modal Edit $('#dmlModal').modal('show'); });
regards
Newbie here in CodeIgniter World !! Please appologize if any nonsense from me.
environment: Windows 10, XAMPP 3.3.0, VS Code, SQLyog Community Ed.
-
SubrataJ
Member
-
Posts: 126
Threads: 27
Joined: Mar 2022
Reputation:
8
08-04-2022, 09:19 AM
(This post was last modified: 08-04-2022, 09:33 AM by SubrataJ.)
Code: <td>
<a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?= $row->product_id;?>" data-product_available="<?= $row->product_available;?>" data-name="<?= $row->product_name;?>" data-price="<?= $row->product_price;?>" data-category_id="<?= $row->product_category_id;?>" data-subcategory_id="<?= $row->subcategory_id;?>">Edit</a>
<a href="#" class="btn btn-danger btn-sm btn-delete" data-id="<?= $row->product_id;?>">Delete</a>
</td>
although it's a bad idea to load everything like this for edit while u can fetch data from the server if you have a git repo I would love to give it a try since it's hard to cope with all the above-given codes here.
else try this out instead of attr, use prop
PHP Code: $('#myCheckbox').prop('checked', true); // Checks it $('#myCheckbox').prop('checked', false); // Unchecks it
since you haven't specified any value for the checkbox
there is no need for this code
Code: $('.checkboxitem').val(product_available);
// start: code added here...
if($('#product_available').val() == 'Y') {
$('#product_available').attr('checked', true);
}else{
$('#product_available').attr('checked', false);
}
use this instead
Code: //$('.checkboxitem').val(product_available); there's no need to set value
// start: code added here...
if(product_available == 'Y') {
$('#product_available').prop('checked', true);
}else{
$('#product_available').prop('checked', false);
}
Learning Codeigniter
-
Ahmed Haroon
Member
-
Posts: 97
Threads: 30
Joined: Nov 2018
Reputation:
0
08-04-2022, 09:34 PM
(This post was last modified: 08-05-2022, 03:28 AM by Ahmed Haroon.)
thanks @ SubrataJ for helping me learning CI4. will check your solution for sure.
as your mentioned below, i am in learning phase and there are various things i have to learn/explore & experience, with help of this community i can write my own code, all the code is from after googling to create Form with some input types to explore How To's and future reference and also will post here for new comers who are willing to learn CI4, so they can have & learn mostly things at one place. please advise how to and if possible, with example, to load data for editing as you prefer to. this Modal Form is for both actions Add & Edit which i preferred.
Quote:although it's a bad idea to load everything like this for edit while u can fetch data from the server if you have a git repo I would love to give it a try since it's hard to cope with all the above-given codes here.
after this, i will add radio buttons, dropdown with search and multiple select like Tags, a file upload -multiple files if possible- (image, doc, pdf etc.) and upload data using user selected .csv file, if you can help with some links to guide i will be much grateful.
regards
Newbie here in CodeIgniter World !! Please appologize if any nonsense from me.
environment: Windows 10, XAMPP 3.3.0, VS Code, SQLyog Community Ed.
-
Ahmed Haroon
Member
-
Posts: 97
Threads: 30
Joined: Nov 2018
Reputation:
0
@ SubrataJ
your code below is working fine, thanks again.
Code: // start: code added here...
if(product_available == 'Y') {
$('#product_available').prop('checked', true);
}else{
$('#product_available').prop('checked', false);
}
@ InsiteFX thanks for your response. will check it.
regards
Newbie here in CodeIgniter World !! Please appologize if any nonsense from me.
environment: Windows 10, XAMPP 3.3.0, VS Code, SQLyog Community Ed.
-
SubrataJ
Member
-
Posts: 126
Threads: 27
Joined: Mar 2022
Reputation:
8
08-05-2022, 08:59 AM
For select or tags, you can use this lib Select 2, it can populate data directly from the server using an ajax request.
For multiple file handling, you can follow this tutorial - multiple file handling
To import data from CSV to the database follow this tutorial - CSV to DB
Learning Codeigniter
-
Ahmed Haroon
Member
-
Posts: 97
Threads: 30
Joined: Nov 2018
Reputation:
0
(08-05-2022, 08:59 AM)SubrataJ Wrote: For select or tags, you can use this lib Select 2, it can populate data directly from the server using an ajax request.
For multiple file handling, you can follow this tutorial - multiple file handling
To import data from CSV to the database follow this tutorial - CSV to DB thank you @ SubrataJ for your concerns to help us. appreciate your inputs and links.
kind regards
Newbie here in CodeIgniter World !! Please appologize if any nonsense from me.
environment: Windows 10, XAMPP 3.3.0, VS Code, SQLyog Community Ed.
|