Sorry for my English, but I hope You will understand me.
Field availability does not exist in the database. It was subsequently created in formatResults. The results are displayed correctly, but it is not possible to sort by the availability field.
I tried this way but it does not work:
$query = $this
->WebshopProducts
->find('all')
->
->formatResults(function($results) {
return $results->map(function($row) {
if($row->stock_total - $row->stock_min > 0){
$row->availability='Yes';
}else{
$row->availability='No';
}
return $row;
});
});
$query = $this
->WebshopProducts
->find('all')
->select('Availibility'=>'(WebshopProducts.stock_total - WebshopProducts.stock_min)', **(Other required fields)**)
->order('Availibility'=>"DESC")
->formatResults(function($results) {
return $results->map(function($row) {
if($row->stock_total - $row->stock_min > 0){
$row->availability='Yes';
}else{
$row->availability='No';
}
return $row;
});
});
In your view file it should be
<th><?php echo $this->Paginator->sort('Availibility'); ?></th>
I am not sure but you can try this.
I've found a solution. This may helps someone:
$query = $this->WebshopProducts->find('all');
$availabilityCase = $query->newExpr()->addCase(
[$query->newExpr()->add(['(stock_total - stock_min) >' => 0]),$query->newExpr()->add(['(stock_total - stock_min) <=' => 0])],['YES','NO'],['string','string']);
$query->select(['id','active','title','price','stock_total','position','availability' => $availabilityCase]);
$this->set('webshopProducts', $this->paginate($query));
Related
I have a table 'companies' with 'approval' as a column with enum type data ('Need Approval', 'Approved).
I want to change the color of the text if the approval is Approved with green color, and else with red.
$data = DB::table('companies')
->select('approval')
->get();
if($data == 'Approved')
{
return "<span class='badge' style='background-color:green'>".$this->approval."</span>";
}
else
{
return "<span class='badge' style='background-color:orange'>".$this->approval."</span>";
}
//return '<span style="color:red">'.$this->approval.'<span>'>'.';
}
but The Result always shows the Else clause. Can someone help ?
The if statement will always return false because $data is an object and you are comparing object (that contains all your companies approval column) to string.
Okay so i've finished my problem before with a little repair
$data = DB::table('companies')
->select('approval')
->first();
foreach ($data as $datas)
// {
if($data->approval == 'Approved')
{
return "<span class='badge' style='background-color:green'>".$this->approval."</span>";
}
else
{
return "<span class='badge' style='background-color:orange'>".$this->approval."</span>";
}
Now i have a new problem, if i create more than 1 data. The colour cannot separated based on the status
the approved should be green, if its not approved it should be orange
Problem solved thanks a lot guys i just made a little change
public function changeColor()
{
$data = DB::table('companies')
->select('approval')
->first();
if($this->approval == 'Approved')
{
return "<span class='badge' style='background-color:green'>".$this->approval."</span>";
}
else
{
return "<span class='badge' style='background-color:orange'>".$this->approval."</span>";
}
}
Hi i am having problem on my live server when i am checking the add to cart builtin function of CI. But its working fine on my localhost.
Here is my Model code where i am saving the cart
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = 1;// Assign posted quantity to $cty
$this->db->from($this->table_name);
$this->db->join($this->desc_table_name, "$this->desc_table_name.products_id = $this->table_name.id");
$this -> db -> where('id', $id); // Select where id matches the posted id$this->db->from($this->table_name);
$this -> db -> limit(1);
$query = $this->db->get(); // Select the products where a match is found and limit the query by 1
// Check if a row has been found
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => "$row->title",
'options' => array('description' => $row->description,'short_desc'=> $row->short_desc,'image'=>$row->image,),
);
//print_r($data);
$res = $this -> cart -> insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
return FALSE;
}`
and my ajax function is like this
var link = window.location.protocol + "//" + window.location.host + "/youth_fashion/";
$(".add_item").click(function() {
// Get the product ID and the quantity
var id = $(this).attr('id');
$.post(link + "front/cart_controller/add_cart_item1", { product_id: id, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "front/cart_controller/show_cart", function(cart){
$("#cart_content").html(cart);
var x = location.href;
window.location.href= x;
});
}else{
alert("Product does not exist");
}
});
return false;
});`
I am using CI 2.0. Thank you in advance
The issue is resolved.
The issue is in session file (config.php). I am using the library of cart but it is not storing the data into table.
$config['sess_use_database'] = TRUE; i turned true and its storing and working for me
I need help to help me correct my php function in codeigniter.
I have a database; I want addirionner all values of " from_user_id ".
Check data
I use this sql to get the desired result.
SELECT SUM(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) AS total_stats FROM score WHERE from_user_id = ?
In codeingniter I use this function.
It allows me to check if " from_user_id " exists, if it exists, we calculate the total different tables and we update the result in " total_stats ". If " from_user_id " does not exist, create it.
But my function does not return me the right result.
I had to make a big mistake but I do not know where!
Does someone could help me please.
public function count_tout_stats($user_id) //total des stats
{
$this->db->select_sum(conv_recu, conv_envoi, repon_topic, etc...);
$query = $this->db->from('score');
$this->db->where('from_user_id', $user_id);
$total_stats = $this->db->count_all_results();
if ($this->ttl_stats_score($user_id) > 0) // Check if exists
{
$data = array(
'total_stats' => $total_stats
);
$this->db->where('from_user_id', $user_id);
$this->db->update('score', $data);
}
else
{
$data = array(
'from_user_id' => $user_id,
'total_stats' => $total_stats
);
$this->db->insert('score', $data);
}
return $total_stats;
}
public function ttl_stats_score($user_id)
{
$this->db->where('from_user_id', $user_id);
$this->db->from('score');
return $this->db->count_all_results();
}
Thank you in advance for your assistance
Violette
You can try this:
$this->db->select('(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) as total_stats');
$this->db->from('score');
$this->db->where('from_user_id', $user_id);
$result = $this->db->get()->row_array();
print_r($result);
You will get your result
i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.
I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.