session destrioyed on add to cart in laravel - laravel-5

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>

Related

Codeigniter after insert success message show in view

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;?>

Magento - How to validate my radio button?

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!');
}
}
}
}

Display message is Not working for out of stock products

please visit link1 , you can see there is option to find shipping is available or not for particular zip code : image1
here shipping charges are working for instock products but not for out-of -stock products.
Form.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/form.phtml
<?php if ($this->isFieldVisible('postcode')): ?>
<li class="item">
<label for="search"<?php if ($this->isFieldRequired('postcode')):?> class="required" <?php endif;?>>
<?php if ($this->isFieldRequired('postcode')):?>
<em>*</em>
<?php endif;?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->__('') ?>
</label>
<div class="search">
<input placeholder="Enter your PIN Code"
class="input-text validate-postcode<?php if ($this->isFieldRequired('postcode')):?> required-entry<?php endif;?>"
type="text" id="estimate_postcode"
name="estimate[postcode]"
value="<?php echo $this->htmlEscape($this->getFieldValue('postcode')) ?>"
onkeydown="if (event.keyCode == 13) { return false;}" />
</div>
</li>
<?php endif; ?>
Script
<script type="text/javascript">
var $ = jQuery.noConflict();
(function($) {
$(document).ready(function(){
$('#estimate_postcode').keydown(function(e){
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var parameters = Form.serializeElements(items, true);
console.log("zipcode onkeypress worked");
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
//disable default enter action
e.preventDefault();
console.log("Enter button was pressed");
$('#shipping-estimate-loading-message').show();
$('#shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('#shipping-estimate-loading-message').hide();
$('#shipping-estimate-results').show();
$('#unique_id').hide();
//$('unique_id').hide();
$('estimate_postcode').val()
}
});
};
});
});
}) ( jQuery );
function estimateProductShipping()
{
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var validationResult = true;
// Check the valid input
if (!items.map(Validation.validate).all()) {
return;
}
var parameters = Form.serializeElements(items, true);
$('shipping-estimate-loading-message').show();
$('shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('shipping-estimate-loading-message').hide();
$('shipping-estimate-results').show();
// $('#unique_id').hide();
$('unique_id').hide();
$('estimate_postcode').val()
}
});
}
//]]>
</script>
complete code of the file : https://gist.github.com/anonymous/ebe868508b2c21e9c032
result.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/result.phtml
<div class="block block-shipping-estimate block-shipping-results">
<div class="block-title">
<strong><span>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getShiptitle(); ?>
</span></strong>
</div>
<div class="block-content">
<?php if ($this->getResult()):?>
<dl>
<?php foreach ($this->getResult() as $code => $_rates): ?>
<dt><?php echo $this->getCarrierName($code) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $_rate->getErrorMessage() ?>
<?php else: ?>
<?php
// echo $_rate->getMethodTitle()
?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<!-- sat -->
<p>
<?php echo "Shipping is available";?>
</p>
<p class="vship1">
<?php echo "Selling Price + " . str_replace('.00','',$_excl) . " Delivery ";?>
</p>
<!-- sat -->
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo Mage::helper('webdevlopers_productpageshipping')->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
<?php else: ?>
<?php //echo $this->getMessagesBlock()->toHtml(); ?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getResult(); ?>
<?php endif;?>
</div>
</div>
app/code/community/webdevolopers/productpageshiping/Block/estimate/ Result.php
<?php
class WebDevlopers_ProductPageShipping_Block_Estimate_Result extends WebDevlopers_ProductPageShipping_Block_Estimate_Abstract
{
public function getResult()
{
return $this->getEstimate()->getResult();
}
public function hasResult()
{
return $this->getResult() !== null;
}
public function getCarrierName($code)
{
$carrier = Mage::getSingleton('shipping/config')->getCarrierInstance($code);
if ($carrier) {
return $carrier->getConfigData('title');
}
return null;
}
public function getShippingPrice($price, $flag)
{
return $this->formatPrice(
$this->helper('tax')->getShippingPrice(
$price,
$flag,
$this->getEstimate()
->getQuote()
->getShippingAddress()
)
);
}
public function formatPrice($price)
{
return $this->getEstimate()
->getQuote()
->getStore()
->convertPrice($price, true);
}
}
changing the settings in System > Config > Inventory
Easiest way to do this is select all products you want to allow to be backordered, then select Update attributes from the actions drop down and click submit. then shipping problem will not be problem.

Rendering part of form in main view

Is there any way to render partial view using AJAX that is a part of form which other part starts ActiveForm->begin() in main view?
Controller:
public function actionCreate()
{
$model = new order();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
try {
if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'New record has been saved.');
return $this->redirect(['index']);
}
}
catch(yii\db\IntegrityException $e) {
Yii::$app->getSession()->setFlash('error', 'Cannot save new record. Please try again.');
return $this->redirect(['index']);
}
}
else {
return $this->render('create', ['model' => $model, ]);
}
}
public function actionSpecialdetform()
{
$model = new order();
return $this->renderAjax('_specialform');
}
public function actionDetform()
{
$model = new order();
return $this->renderAjax('_form');
}
View (main - create.php):
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\order */
$this->title = 'Create';
$this->params['breadcrumbs'][] = ['label' => 'Orders', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="order-create">
<h1><?= Html::encode($this->title) ?></h1>
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true,]); ?>
<div class="panel panel-default wizard" id="order-wizard">
<div class="wizard-steps clearfix" id="form-wizard">
<ul class="steps">
<li data-target="#step1" class="active"><span class="badge badge-info">1</span>Order</li>
<li data-target="#step2"><span class="badge">2</span>Details</li>
</ul>
</div>
<div class="step-content clearfix">
<div class="step-pane active" id="step1">
<?php echo $form->field($model, 'order_date')->input(); ?>
</div>
<div class="step-pane" id="step2">
<div id="order-details">
</div>
</div>
<div class="actions pull-left">
<button type="button" class="btn btn-default btn-sm btn-prev wizard-btn" disabled="disabled"><i class="fa fa-angle-double-left" style="margin-right:5px"></i> Previous step</button>
<button type="button" class="btn btn-default btn-sm btn-next wizard-btn" data-last="Save">Next step <i class="fa fa-angle-double-right" style="margin-left:5px"></i></button>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$js = '
$(document).ready(function() {
$("#order-wizard").on("change", function(e, data) {
if(data.step===1 && data.direction==="next")
{
var date = $("#order-order_date").val();
if(date==="")
{
e.preventDefault();
}
var form = null;
if(date === "2015-01-01")
{
form = "/order/specialdetform"
}
else
{
form = "order/detform"
}
$.ajax({
url: form,
dataType: "html",
success: function(data) {
$("#order-details").html(data);
}
});
}
});
});
';
$this->registerJs($js, \yii\web\View::POS_END);
?>
Partial View - (_specialform.php):
<?= $form->field($model, 'promo_code')->input(); ?>
<?= $form->field($model, 'Surname')->input(); ?>
Partial View - (_form.php):
<?= $form->field($model, 'Surname')->input(); ?>
I don't want to just create one partial view, because this is only one different field, but it's an example.

Magento sidebar parent curent category and subcategory permanent

I want to add to sidebar the CURENT category and subcategory of the products, but to be the same even if i am entering a subcategory. Right now i have this script for left menu ( sidebar )
<?php $_menu = $this->renderCategoriesMenuHtml(0,'level-top') ?>
<?php if($_menu): ?>
<div class="block block-menu-navleft">
<div class="block-title">
<strong><span><?php echo $this->__('Category') ?></span></strong>
</div>
<div class="block-content">
<ul id="nav1" class="menu-left">
<?php echo $_menu ?>
</ul>
</div>
</div>
<?php endif ?>
<script type="text/javascript">
var lis=$$('#nav1 li.parent');
lis.each(function(li) {
var dt = new Element('dt');
var dd = new Element('dd');
var a = li.down(0);
var ul = li.down(2);
dt.insert(a);
dd.insert(ul);
li.insert(dt,{position:top});
li.insert(dd);
});
jQuery('#nav1 li.parent dd ul ').hide();
jQuery('#nav1 dt a').click(function() {
jQuery('.td_active').removeClass('td_active');
var string = jQuery(this).parent().parent().parent().parent().parent().attr('class');
if(string.indexOf('parent')!=-1)
{
jQuery(this).parent().parent().parent().parent().parent().addClass('td_active');
jQuery(this).parent().parent().parent().css("display","block");
jQuery(this).parent().parent().find('ul').slideUp('slow');
}
else
{
jQuery('#nav1 li.parent dd ul:visible').slideUp('slow');
}
jQuery(this).parent().parent().addClass('td_active').next().slideDown('fast');
if(jQuery(this).parent().parent().find('ul').css('display')=='block')
{
jQuery(this).parent().parent().removeClass('td_active');
}
jQuery(this).parent().parent().children().children(':first-child').css("display","block");
return false;
});
</script>
This script works fine but it shows me ALL FATHER CATEGORIES and SUBCATEGORIES. I want to show me just the CURENT CATEGORY AND SUBCATEGORY.
!example image1
Use this :
$menu = $this->drawItem(Mage::registry('current_category'),Mage::registry('current_category')->getLevel());
instead of
$_menu = $this->renderCategoriesMenuHtml(0,'level-top')
To handle all case you should consider do something like :
$menu = (isset(Mage::registry('current_category'))?$this->drawItem(Mage::registry('current_category'),Mage::registry('current_category')->getLevel()):$this->renderCategoriesMenuHtml(0,'level-top');

Resources