I'm new to joomla development. After having managed to directly list database multiple rows directly into the conttroller, i'm trying to display it using views, but i have an error message :
Controller :
function display($cachable = false, $urlparams = false)
{
// Affichage de la liste des tournois
$db=JFactory::getDBO();
$sql="select * from #__tournois_tournois";
//echo $sql;
$db->setQuery($sql);
$db->query();
$items=$db->loadobjectList();
// set default view if not set
$input = JFactory::getApplication()->input;
$input->set('view', $input->getCmd('view', 'Tournois'));
// call parent behavior
parent::display($cachable);
in my view :
function display($tpl = null)
{
// Get data from the model
$items = $this->get('Items');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Assign data to the view
$this->items = $items;
// Set the toolbar
$this->addToolBar();
// Display the template
parent::display($tpl);
}
In the default tpl :
<form action="<?php echo JRoute::_('index.php?option=com_tournoi&ask=edit'); ?>" method="post" name="adminTournoisForm" id="adminTournoisForm">
<table class='adminlist'>
<thead>
<tr>
<th width='1%'> </th>
<th class='title'>ID</th>
<th class='title'>Tournoi</th>
<?
foreach ($this->items as $i => $item)
{
//$row=$rows[$i]?>
<tr>
<th><? echo $item->tournois_id?></th>
<th><? echo $item->tournois_title?></th>
</tr>
<?}?>
</table>
</form>
Related
sorry for being a newbie, if someone may point me to the right direction to solve my issue I would be super grateful.
I have created a cart system using codeigniter 3's deprecated library and with AJAX am able to do the usual add item to cart, remove item from cart, show item quantity in cart, ONLY IN the table of the renderred datatable.
My issue is at my header I have a cart counter that shows a number to display the number of items in the cart. As I call it currently it is not using AJAX and is showing the number of items in the cart after a refresh or redirect. I want it to be AJAX like it's counterpart at the datatable instead of showing the correct number only after a refresh.
Attached is the portion of the code I believe to be relevant
Controller
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('products_model');
$this->load->model('products_category_model');
$this->load->model('products_subcategory_model');
$this->load->model('products_price_model');
$this->load->library('pagination');
$this->load->database();
$this->load->helper('url');
}
public function lists($slug="") {
// $locale = $this->session->userdata('site_lang');
$config = array();
$config['base_url'] = base_url() . 'products';
$config['total_rows'] = $this->products_model->get_count();
$config['per_page'] = 3;
$config['uri_segment'] = 2;
$config['num_links'] = 2;
$config['first_link'] = '<span style="letter-spacing:1px; margin-right: 20px;"> First </span>';
$config['last_link'] = '<span style="letter-spacing:1px;"> Last </span>';
$config['use_page_numbers'] = FALSE;
$config['next_link'] = '<i class="fas fa-long-arrow-alt-right"></i>';
$config['prev_link'] = '<i class="fas fa-long-arrow-alt-left"></i>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(2))? $this->uri->segment(2) : 0;
$data['products_count'] = count($this->products_model->getList());
$data['links'] = $this->pagination->create_links();
$data['records'] = $this->products_model->getActiveProductPriceList($config['per_page'], $page);
$data['category'] = $this->products_category_model->getActiveList();
$data['subcategory'] = $this->products_subcategory_model->getActiveList();
$this->load->view('include/head',$data);
$this->load->view('products', $data);
// custom JS needed for cart functionality
// $this->load->view('include/footer');
}
function add_to_cart() {
if($this->session->userdata('site_lang') == 'en'){
$name = $this->input->post('title_en');
} else {
$name = $this->input->post('title_zh');
}
$data = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $this->input->post('discount_price'),
'name' => $name,
'thumbnail' => $this->input->post('thumbnail'),
);
$this->cart->insert($data);
echo $this->show_cart();
}
function show_cart(){
$output = '';
$no = 0;
foreach ($this->cart->contents() as $items) {
$no++;
$output .='
<tr>
<td>'.$items['name'].'</td>
<td><img src="'.$items['thumbnail'].'"></td>
<td>'.number_format($items['price']).'</td>
<td>'.$items['qty'].'</td>
<td>'.number_format($items['subtotal']).'</td>
<td><button type="button" id="'.$items['rowid'].'" class="remove_cart btn btn-danger btn-sm">Cancel</button></td>
</tr>
';
}
$output .= '
<tr>
<th colspan="3">Total</th>
<th colspan="1">'.number_format($this->cart->total_items()).'</th>
<th colspan="2">'.'RM '.number_format($this->cart->total()).'</th>
</tr>
';
return $output;
}
function load_cart(){
echo $this->show_cart();
}
}
View
<div class="col-md-4">
<h4>Shopping Cart</h4>
<table class="table table-striped">
<thead>
<tr>
<th>Items</th>
<th>Thumbnail</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="product_detail_cart"></tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.add_product_to_cart').click(function(){
var id = $(this).data("id");
var thumbnail = $(this).data("thumbnail")
var title_en = $(this).data("title_en");
var title_zh = $(this).data("title_zh");
var discount_price = $(this).data("discount_price");
var quantity = 1;
$.ajax({
url : "<?php echo base_url('products/add_to_cart');?>",
method : "POST",
data : {id: id, thumbnail: thumbnail, title_en: title_en, title_zh: title_zh,discount_price: discount_price, quantity: quantity},
success: function(data){
$('#product_detail_cart').html(data);
}
});
});
$('#product_detail_cart').load("<?php echo base_url('products/load_cart');?>");
$(document).on('click','.remove_cart',function(){
var row_id=$(this).attr("id");
$.ajax({
url : "<?php echo base_url('products/delete_cart');?>",
method : "POST",
data : {row_id : row_id},
success :function(data){
$('#product_detail_cart').html(data);
}
});
});
});
</script>
How I'm calling it at header
<i class="fas fa-shopping-cart"></i>
<span class="count" id="product_detail_cart_count">
<?php
if (!empty($this->cart->contents())) {
echo number_format($this->cart->total_items());
} else {
print 0;
}
?>
</span>
Thank you again
I figured out what was missing, what I needed to do is to assign an id/div to the specific part of the view page I need to refresh and just refresh it using jquery
$(document).on('click','.remove_cart',function(){
var row_id=$(this).attr("id");
$.ajax({
url : "<?php echo base_url('products/delete_cart');?>",
method : "POST",
data : {row_id : row_id},
success :function(data){
$('#product_detail_cart').html(data);
$('#cart-counter').load(location.href + " #cart-counter");
}
});
});
The #cart-counter is the id i refreshed using the load(location.href + " #cart-counter");
I can print the data out but data is not displayed in the table.
I'm trying to use Datatable to display the data.
Here are error messages:
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
model
function allposts_count()
{
$query = $this
->db
->get('books');
return $query->num_rows();
}
function allposts($limit,$start,$col,$dir)
{
$query = $this
->db
->limit($limit,$start)
->order_by($col,$dir)
->get('books');
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
controller
function Book()
{
$columns = array(
0 =>'id',
1 =>'title',
);
$limit = $this->input->post('length');
$start = $this->input->post('start');
$columns=$this->input->post('order')[0]['column'];
$order = $columns;
$dir = $this->input->post('order')[0]['dir'];
$totalData = $this->user_model->allposts_count();
$totalFiltered = $totalData;
if(empty($this->input->post('search')['value']))
{
$posts = $this->user_model->allposts($limit,$start,$order,$dir);
}
else {
$search = $this->input->post('search')['value'];
$posts = $this->user_model->posts_search($limit,$start,$search,$order,$dir);
$totalFiltered = $this->user_model->posts_search_count($search);
}
$data = array();
if(!empty($posts))
{
foreach ($posts as $post)
{
$nestedData['id'] = $post->book_id;
$nestedData['title'] = $post->book_title;
$data[] = $nestedData;
}
}
$json_data = array(
"draw" => intval($this->input->post('draw')),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
}
view
<div class="container">
<h1>Server Side Process Datatable</h1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</tfoot>
</table>
<!--create modal dialog for display detail info for edit on button cell click-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div id="content-data"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var dataTable=$('#example').DataTable({
"processing": true,
"serverSide":true,
"ajax":{
"url": "<?php echo base_url('users/Book') ?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
"columns": [
{ "data": "book_id" },
{ "data": "book_title" },
]
});
});
</script>
datatables expects a pure json response. if you followed the debugging steps in the link you posted you would have seen that your response also contains a view.
here you have json then a view:
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
remove the views and/or move the json stuff to another url. then update "url": "<?php echo base_url('users/Book') ?>", to the new url.
you should echo $data to show data in table #example.
<table id="example" cellpadding="0" cellspacing="0">
<thead><tr>
<th>ID</th>
<th>Name</th>
</tr></thead>
<tbody>
<!-- rows will go here -->
</tbody>
</table>
And in javascript
$("#example tbody").html(someHtmlString);
You dont have tbody to put return query in your code.
And debug to check if the data is valid or not.
Controller : here productlist2() just call the view page .
function productlist2()
{
$this->load->view("admin/bill/datatable.php", array());
}
public function productlist_page()
{
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$books = $this->Category_model->get_all_product_datatable();
$data = array();
foreach($books->result() as $r) {
$data[] = array(
$r->categoryID,
$r->productName,
$r->costPrice,
$r->salesPrice,
$r->unit,
$r->origin,
$r->files
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $books->num_rows(),
"recordsFiltered" => $books->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
After ajax calling the productlist_page() function this productlist_page() gets the value from model.
View:
<table id="book-table" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>ID</td>
<td>Product Name</td>
<td>Cost Price</td>
<td>Sales Price</td>
<td>Unit</td>
<td>Description</td>
<td>Picture</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my js script code.
<script type="text/javascript">
$(document).ready(function() {
$('#book-table').DataTable({
"ajax": {
url : "<?php echo site_url("admin/category/productlist_page") ?>",
type : 'GET'
},
});
});
</script>
Here , in picture column i want to show images , only the string value is there as output in files column . Question is how can i show the image ?
i hope all of you can help me to solve my application problem
my problem is when i would like to show data from my multiple checkbox , data success to show but just showing my first data that i have check.
example is i check data 1 , data 2 , data 3, but the only data 1 are showing on my page.
my controller :
function comparison()
{
if ($this->input->post('submit')) {
foreach ($id_product = $this->input->post('id_product') as $rm) {
$show_compare = $this->Compare->start_compare($rm);
}
$data['comparison'] = $show_compare;
$data['title'] = "Comparison";
$data['meta_keywords'] = ". . .";
$data['meta_descriptions'] = ". . .";
$this->load->view('theme/comparison',$data);
}
}
My Model :
function start_compare($id_product)
{
$this->db->select('product.id_subcategory,product.type,product.product_name,specificcategory.specificcategory_name,specification_biostar.*');
$this->db->join('specification_biostar', 'specification_biostar.id_product = product.id_product', 'left');
$this->db->join('specificcategory', 'specificcategory.id_specificcategory = product.id_subcategory', 'left');
$this->db->where('product.id_product', $id_product);
$sql = $this->db->get('product')->result_array();
return $sql;
}
my view (option multiple-checkbox) :
<div class="box-body">
<input type="checkbox" name="id_product[]" id="txt" onClick="EnableSubmit3(this)" value="<?php echo $row['id_product']; ?>"><label>Choose</label>
</div>
my view (result data) :
<table class="table">
<?php foreach ($comparison as $row){ ?>
<tr>
<td colspan="2"><?php echo $row['id_product'] ?></td>
</tr>
<?php } ?>
</table>
in your code take $show_compare = array(); before foreach loop and use array_push in foreach.
$show_compare = array();
foreach ($id_product = $this->input->post('id_product') as $rm) {
array_push($show_compare,$this->Compare->start_compare($rm));
}
$data['comparison'] = $show_compare;
How can i get Hierarchical Data from db in Codeigniter. I read this :
http://www.sitepoint.com/hierarchical-data-database/
And i do good that but i cant optimize this tutorial with my model, controler and views
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
I try but dont show sub category:
My model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
Controller :
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
Views:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And output is :
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
When i do this in model all work fine but when i try that to call in controler and loop in view i have result like above example:
This work onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
And like output i have :
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
Any one have solution or example thanks.
Try storing the level value for each category.
In your model:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
In your controller:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
In your view
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>