Show data from multiple checkbox in codeigniter - codeigniter

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;

Related

How to make sortable select multiply in laravel backpack?

I need to make sortable select2_multiple with Laravel Backpack - or a custom one with similar functionality.
In the docs there is a way to simply implement select2_multiple just like this:
$this->crud->addField([
'label' => "Ingredients",
'type' => 'select2_multiple',
'name' => 'ingredients', // the method that defines the relationship in your Model
'entity' => 'ingredients', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => Ingredient::class, // foreign key model
'pivot' => true,
'select_all' => true
]);
But! I dont see any way to store sort data of the entries we selected!
I have created field SORT in my DB ingredients_to_products
table, this should do the trick, but how to implement this to Backpack?
DB structure is really simple: products, ingredients, ingredients_to_products tables. Ingredients_to_products table have only 3 fields: product_id, ingredient_id, sort.
Laravel 5.6, Backpack CRUD 3.3
Any help is appreciated. Thanks!
I found how to do this.
I made a custom view and put some changes to CrudController, manually resolving sort value.
In view section I created some JS and new fields that represents sort values of relevant entries.
By the way, there is a $entry->pivot function that also can help.
So, what i've done: created new view called "ingredients"
<table class="table table-bordered" id="table">
<p>Connected ingredients:</p>
<select hidden multiple name="ingredients[]" id="ingredients">
<?php foreach ($field['value'] as $item){ ?>
<option selected data-id="<?= $item->id ?>" value="<?= $item->id ?>"><?= $item->name ?></option>
<?php } ?>
</select>
<select hidden multiple name="ingredients_sort[]" id="ingredients_sort">
<?php foreach ($field['value'] as $item){ ?>
<option data-id="<?= $item->id ?>" selected value="<?= $item->pivot->sort ?>"><?= $item->pivot->sort ?></option>
<?php } ?>
</select>
<?php foreach ($field['value'] as $item){ ?>
<tr class="item">
<td>
<p><?= $item->name ?></p>
</td>
<td>
<input class="sorter form-control" data-id="<?= $item->id ?>" value="<?= $item->pivot->sort ?>">
</td>
<td>
<span data-id="<?= $item->id ?>" class="btn btn-primary remover">Remove</span>
</td>
</tr>
<?php } ?>
So as you see we now have the ingredients and ingredients_sort arrays that syncronized by positions by JavaScript.
We get list of all avaliable ingredients by AJAX.
Sorting value - is a connected input field to every ingredient entry.
let selected_ingredients = <?= isset($field['value']) ? json_encode($field['value']) : '' ?>;
let ingredients = [];
document.addEventListener("DOMContentLoaded", load);
function load(){
getIngredients();
}
function getIngredients() {
$.get('/ingredients/get').done( (response) => {
ingredients = JSON.parse(response);
printList(ingredients);
} );
}
function printList(ingredients){
// #todo : print search
for (let i = 0; i < ingredients.length; i++){
let item = ingredients[i];
let _item = document.createElement('div');
_item.className = 'item btn btn-default';
_item.setAttribute('data-id', item.id);
_item.innerHTML = `${item.name}`;
_item.onclick = function () {
// #todo: add ingredient to product
let needAdd = true;
for (let i = 0; i < selected_ingredients.length; i++){
if (selected_ingredients[i].id == item.id){
needAdd = false;
}
}
if (needAdd){
$('#ingredients').append(`<option selected data-id="${item.id}" value="${item.id}">${item.name}</option>`);
$('#ingredients_sort').append(`<option data-id=${item.id} selected value="0">0</option>`);
$('#table').append(
`<tr><td>
<p>${item.name}</p>
</td>
<td>
<input class="sorter form-control" data-id="${item.id}" value="0">
</td>
<td>
<span data-id="${item.id}" class="remover btn btn-primary">remove</span>
</td>
</tr>`);
$('.remover').unbind().click(function () {
$(this).parent().parent().remove();
});
$('.sorter').unbind().change(function(){
let id = $(this).attr('data-id');
$(`#ingredients_sort [data-id=${id}]`).val( $(this).val() ).html( $(this).val() );
});
}
};
$('#list').append(_item);
}
$('.remover').unbind().click(function () {
let id = $(this).attr('data-id');
$(`#ingredients [data-id=${id}], #ingredients_sort [data-id=${id}]`).remove();
$(this).parent().parent().remove();
});
$('.sorter').unbind().change(function() {
let id = $(this).attr('data-id');
$(`#ingredients_sort [data-id=${id}]`).val( $(this).val() ).html( $(this).val() );
});
}
function remove(){
console.log(this);
}
And the last step - putting the Update method in ItemCrudController (which in my app is "product" controller)
public function update(UpdateRequest $request)
{
// your additional operations before save here
$redirect_location = parent::updateCrud($request);
$obj = \App\Models\Item::find( $request->get('id') );
$obj->ingredients()->detach();
$i = 0;
foreach ( $request->get('ingredients') as $item){
$obj->ingredients()->save( \App\Models\Ingredient::find($item), ['sort' => $request->get('ingredients_sort')[$i]]);
$i++;
}
return $redirect_location;
}
So - it works.
The result photo below. Hope this will help someone.

Codeigniter get parameters from url?

I have one view
<div class="panel-body">
<div class="table-responsive">
<table id="mytable" class="table table-responsive table-striped table-bordered" cellspacing="0"
width-="100%">
<tbody>
<?php
foreach ($result as $row) {
if ($row->active == 1) {
foreach ($countries as $country) {
if ($country->id == $row->country) {
if ($this->session->userdata('language') == 3) {
$ccountry = $country->ro_name;
} else if ($this->session->userdata('language') == 2) {
$ccountry = $country->ru_name;
} else {
$ccountry = $country->name;
}
}
}
$time_sbs = substr($row->time, 0, 5);
echo '<tr ">
<td width="20%">' . $row->name . '</td>
<td width="10%">' . $row->date . ' ' . $time_sbs . '</td>
<td width="10%">' . $row->registration_date . '</td>
<td width="10%">' . $ccountry . '</td>
<td width="10%">' . $row->city . '</td>
<td width="10%">' . $row->address . ' </td>
<td width="20%">' . $row->description . '</td>
I sampled from the database for the date
function get_tournaments()
{
//data is retrive from this query
$query = $this->ci->db->query("SELECT * FROM tournaments WHERE date > CURDATE() ORDER BY date");
/*$query = $this->ci->db->query("SELECT * FROM tournaments");*/
return $query;
}
function get_tournaments_finished()
{
//data is retrive from this query
$query = $this->ci->db->query("SELECT * FROM tournaments WHERE date < CURDATE() ORDER BY date");
/*$query = $this->ci->db->query("SELECT * FROM tournaments");*/
return $query;
}
I need to have one table in the view, but with the help of the get parameter, I showed the tournament maps:
<?php echo base_url(); ?>tournaments?type=upcoming",
<?php echo base_url(); ?>tournaments?type=finished"
How to check for a get parameter type
In Codeigniter You can check input parameter by using
$input_params=$this->input->get();// this will give you all parameters
or
$single_param=$this->input->get('name_of_the_parameter');// this will give you individual parameter
use
$_GET['type'];
Or if you prefer, instead of using get, you could use the method parameter to know the type
//something like this
//your url will be like this
base_url('tournament/upcoming'); or
base_url('tournament/finished');
//then your controller method will look like this
public function tournament(){
$type = $this->uri->segment(3);
//then fetch the data based on the type
}
I hope this helps you, if you have any issue, let me know so we can sort it out.

Joomla 2.5 displaying data /multiple rows in view

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>

Codeigniter Get Nested Hierarchical Data from Database

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>

pass two query result to view in codeigniter

i have two query $q1 and $q2.
from the query1 i get multiple records and each record having id and i want use this id for second query in where condition.
i am doing this in controller.
i have tried following code.
In the foreach i am trying to store id and pass to $q2 where condition.
//Query 1
$q1 = $this->db->select(array(
'spf.id as id' ,
'spf.name',
'spf.added_on'
))->from('sp_form spf')->where($where)->order_by('spf.id desc')->limit(10, $page * 10)->get();
$data['data'] = $q1->result_array();
foreach($data as $rec)
{
$id = $rec['id']; // here how i catch id for each row
//Query 2
$q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')->where('spft.formid',$id)->get();
$data['count'] = $q1->row_object();
}
// pass combine result to view
$this->load->view('myview', $data,true);
Edit:
This is my view.
I have try Nishant answer and i get resultq1 using foreach but how can i get result of resultq2.
<table width="100%">
<tr>
<td class="th"> Details</td>
<td width="5%" class="th"> Answer</td>
<td width="15%" class="th">Started by</td>
<td width="15%" class="th">Created on</td>
</tr>
<?php foreach($resultq1 as $row):?>
<tr>
<td><?php echo $row['name'] ;?></td>
<td >---- </td> // here i want to use resultq2
<td><?php echo $row['added_by'] ;?></td>
<td ><?php echo $row['added_on'];?></td>
</tr>
<?php endforeach;?>
</table>
you can do it like This.
$resultq1= $q1->result_array();
$data['resultq1'] = $resultq1;
$resultq2 = array();$i=0;
foreach($resultq1 as $row){
$id = $row['id'];
$q2 = $this->db->select("count('id') as count ")->from('sp_topic spft')>where('spft.formid',$id)->get();
$resultq2[$i]['count'] = $q1->row_object();
$i++;
}
$data['resultq2'] = $resultq2;
$this->load->view('myview', $data,true);
OR
You can use array_merge
like
$data = array_merge($resultq1, $resultq2);
Then in the myview you will get both the results in variables $resultq1, and $resultq2.
You can pass any numbers of the variables from the controller to the view file by $data['variable_name'] and it can be retrieved in the view file like simple variable $variable_name.
Some Sample links which might help :-
Passing 2 types of array variables in codeigniter view files
$data['count'] = $q1->row_object();
change this like below:
foreach($data as $rec)
{
$id = $rec['id']; // here how i catch id for each row
$q2 = $this->db->select("count('id') as count ")->
from('sp_topic spft')->where('spft.formid',$id)->get();
$data[$id]['count'] = $q2->result_array();
}
$this->load->view('myview', $data,true);

Resources