I am new in Codeigniter and I need to show success and error message after insert data's in database.
How can I show the message in the view page?
This is my coding:
Model
function addnewproducts($data)
{
if($data['product_name']!="" && $data['product_qty']!="" && $data['product_price']!="" && $data['date']!="")
{
$res=$this->db->insert('product_list',$data);
return $this->db->insert_id();
}
else
{
return false;
}
}
Controller
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
$res = $this->products->addnewproducts($data);
if($res==true)
{
$data['success'] = 'Successful';
$this->load->view('addproduct',$data);
}
}
View
<p><?php echo $success; ?></p>
There are many ways but below is which i recommend:
Set temp session in controller on success or error:
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('success', "SUCCESS_MESSAGE_HERE");
}else{
$this->session->set_flashdata('error', "ERROR_MESSAGE_HERE");
}
In View you can display flashdata as below:
echo $this->session->flashdata('success');
or
echo $this->session->flashdata('error');
Source : Codeigniter official website https://codeigniter.com/userguide3/libraries/sessions.html
I appreciate that you got your answer but I think flash data is bit old now, as we can use bootstrap to alert if any error and that looks good to on web page.
In controller
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('true', 'write_the_message_you_want');
}
else
{
$this->session->set_flashdata('err', "write_the_message_you_want");
}
In View
<?php
if($this->session->flashdata('true')){
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('true'); ?>
<?php
} else if($this->session->flashdata('err')){
?>
<div class = "alert alert-success">
<?php echo $this->session->flashdata('err'); ?>
</div>
<?php } ?>
Controller:
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
if($this->products->addnewproducts($data));
{
$this->session->set_flashdata('Successfully','Product is Successfully Inserted');
}
else
{
$this->session->set_flashdata('Successfully','Failed To
inserted Product');
}
// redirect page were u want to show this massage.
redirect('Controller/Fucntion_name','refresh');
}// close function
view :
On Redirect Page write This code top of Form
<?php if($responce = $this->session->flashdata('Successfully')): ?>
<div class="box-header">
<div class="col-lg-6">
<div class="alert alert-success"><?php echo $responce;?></div>
</div>
</div>
<?php endif;?>
Related
I am getting error of " Trying to get property of non-object" my controller code is
public function productDetails($pro_name,$product_id) {
$data['prodRating'] = $this->ProductsModel -> get_one($product_id);
$this->load->view('home',$data);
}
Model Code
function get_one($pro_id){
$query= $this->db->select('ratingid, pro_item_id, pro_total_points, pro_total_rates, proid ')
->from('tblproducts')
->where('proid',$pro_id)
->join('tblprorating','tblprorating.pro_item_id = tblproducts.proid','left')
->get();
return $query->result();
}
view code
<span dir="ltr" class="inline">
<input id="input-<?=$prodRating->proid ?>" name="rating"
<?php if ($prodRating->$pro_total_rates > 0 or $prodRating->pro_total_points > 0) { ?>
value="<?php echo $prodRating->pro_total_points / $prodRating->pro_total_rates ?>"
<?php } else { ?>
value="0"
<?php } ?>
<?php if ($this->session->userdata('userid') == false) { ?>
data-disabled="false"
<?php } else { ?>
data-disabled="<?= $rated ?>"
<?php } ?>
class="rating "
min="0" max="5" step="0.5" data-size="xs"
accept="" data-symbol="" data-glyphicon="false"
data-rating-class="rating-fa">
</span>
What is problem in my code if i use foreach loop then i can solve my problem. But in this code i not want to use the foreach loop. I want to access the fields of database. but i am getting error.
Return return $query->row() for single item. result() is for many. Further you should check num_rows() before attempting to access the result object/array and handle 0 rows properly as it is good practice.
In this case:
if ($query->num_rows() > 0) {
return $query->row();
}
return false;
in my custom module, I have a form which has radio buttons.
When I click the submit button it does not validate the radio button.
<?php
$question = Mage::getModel('emme_question/question')->getCollection()->getLastItem();
$answers = $question->getSelectedAnswersCollection();
?>
<h4><?php echo $this->escapeHtml($question->getValue()); ?></h4>
<ul>
<?php foreach ($answers as $answer): ?>
<li>
<label><?php echo $this->escapeHtml($answer->getValue()) ?></label>
<input class="required required-field" type="radio" name="my_custom_answer" value="<?php echo $answer->getId() ?>" required>
</li>
<?php endforeach ?>
and
<?php
// app/code/local/Envato/Custompaymentmethod/Model/Paymentmethod.php
class Envato_Custompaymentmethod_Model_Paymentmethod extends Mage_Payment_Model_Method_Abstract {
protected $_code = 'custompaymentmethod';
public function validateRadioIsSelected()
{
$var options = $$('input.Classname');
for( i in options ) {
if( options[i].checked == true ) {
return true;
}
}
return false;
}
public function getOrderPlaceRedirectUrl()
{
return Mage::getUrl('custompaymentmethod/payment/redirect', array('_secure' => false));
}
}
Parse error: syntax error, unexpected 'options' (T_STRING) in /home/mmstore9/public_html/demo/app/code/local/Envato/Custompaymentmethod/Model/Paymentmethod.php on line 27
use this magetno default validation class to validate the radio button
validate-one-required-by-name
OR
validate-one-required
I solved
public function validate()
{
foreach (Mage::getModel('emme_question/question')->load(1)->getSelectedAnswersCollection() as $answer)
{
if ($answer->getIsCorrect())
{
if ($answer->getId() == $_POST['my_custom_answer'])
{
Mage::getSingleton('core/session')->addSuccess('Risposta esatta');
} else
{
Mage::throwException('Risposta sbagliata!');
}
}
}
}
I am using laravel5. I need to add the product into cart. when i add a new product it is add into cart item as 1. but when refresh the page or move to next page my cart item count destroyed. Here i attach my coding. Please help me what is my mistake. i am new to laravel
Controller:
public function cart($request)
{
$quick=Mainpage::get_quick(5);
$logo = Mainpage::get_image();
$result_cart = Mainpage::get_add_to_cart_details();
$session_result = '';
// if(Session::get('cus_id'))
// {
// $navbar = View::make('layout.header');
// }
// else
// {
// $navbar = View::make('layout.header');
// }
return view('cart', ['logo' => $logo, 'quick' =>$quick,'session_result'=>$session_result,'result_cart'=>$result_cart]);
}
Model:
public static function get_add_to_cart_details()
{
$get_pro_dea = "";
if(isset($_SESSION['cart'])){
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
$pid=$_SESSION['cart'][$i]['product_id'];
//$pname="Have to get";
$get_pro_dea[$pid] = DB::table('le_product')->where('product_id',$pid)->get();
}
}
else
{
$get_pro_dea[0] = array();
}
return $get_pro_dea;
}
View:(header.blade.php):
<div class="col-sm-4" style="margin-top:17px">
<div class="cart box_1 pull-right">
<a href="<?php echo url('cart'); ?>">
<?php if(isset($_SESSION['cart']))
{
$item_count_header1 = count($_SESSION['cart']);
}
else {
$item_count_header1 = 0;
}
$item_count_header = $item_count_header1;
if($item_count_header != 0)
{
?>
<img src='<?php echo url(); ?>/assets/images/shopping-cart.png' alt=''><span style='color:black;
'> ( <?php echo $item_count_header; ?> Items) </span>
<?php
}
else
{ ?>
<img src="<?php echo url(); ?>/assets/images/shopping-cart.png" alt=""><span style="color:black;"> (card empty)</span>
<?php }
?>
</strong>
</a>
</div>
</div>
</div>
<?php } ?>
</div>
It is simple to pass a message to flash via:
$this->Flash->error(__('The user could not be saved. Please, try again.'));
But when there are more errors from:
$package->errors();
I use just a simple foreach loop:
foreach ($package->errors() as $error=>$value)
{
foreach ($value as $single_error)
{
$error_array[] = ($single_error);
}
}
Then I pass it to a flash element:
$this->Flash->custom($error_array, [
'key' => 'custom']);
And in the flash message:
if ($message > 0) {
foreach ($message as $m) {
echo h($m).'<br />';
}
} else {
echo h($message);
}
I wonder it here is a better way of handling an array of validation errors.
I am using the following method if there are errors:
Controller:
$errors = $action->errors();
$errorMessages = [];
array_walk_recursive($errors, function($a) use (&$errorMessages) { $errorMessages[] = $a; });
$this->Flash->error(__('Your action cannot be saved!'), ['params' => ['errors' => $errorMessages]]);
Template/Element/Flash/error.tcp:
<?php if (isset($params) AND isset($params['errors'])) : ?>
<ul class="collection with-header">
<li class="collection-header"><h5><?= __('The following errors occurred:') ?></h5></li>
<?php foreach ($params['errors'] as $error) : ?>
<li class="collection-item"><i class="material-icons">error</i><?= h($error) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Result:
Just for anyone interested, I am using MaterializeCSS.
I have a page written in codeigniter framework.
Now I want to add a button to page (eg 'show more') that will get data with 'ajax.php' from the database and display them on the site, but I do not want it separately connect to the database and then get the results, just want to be able to collect data (in ajax.php) as well as in codeigniter controllers (using models)...
Hope you understand me :)
Here you go just add view more button and call this js and ajax function..This is code i have used please see it and use it as per your requirment
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$("ol#updates").addClass('tiny-loader');
this_tag.html('Loading.....');
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").removeClass('tiny-loader');
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old view-more button
});
}
else
{
this_tag.fadeOut('slow');// no results
}
return false;
});
code in ajax file
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_more extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('general_model');
$this->limit =REVIEW_DETAIL;
}
public function index($offset = 0)
{
$lastmsg=$this->input->post('lastmsg');
$rest_id=$this->input->post('restid');
$value=('reviews.*,usermaster.Name as User');
$joins = array
(
array
(
'table' => 'tk_usermaster',
'condition' => 'usermaster.Id = reviews.UserId',
'jointype' => 'leftouter'
),
);
$this->results = $this->general_model->get_joinlist('reviews',$value,$joins,array('reviews.Status'=>'Enable','reviews.RestaurantId'=>$rest_id,'reviews.Id <'=>$lastmsg),'reviews.Id','desc',$this->limit,$offset);
$data['list_review']= $this->results['results'];
?>
<?php foreach ($data['list_review'] as $row): ?>
<div class="user_reviews_data" >
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10 "><div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div></span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id = $row->Id;
endforeach; ?>
</div>
<div id="more<?php echo #$msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
<?php
}
}