I have have a website where there are multiple products, the user can add one to their cart and get on screen feedback via ajax that the basket updated.
However on certain products this does not work below is the code that gets used.
THE PHP
function updateBasket()
{
$this->load->model('Checkout_model');
$this->load->model('Product_model');
$derivativeId = $this->input->post('selDerivative-1');
$quantity = $this->input->post('selQuantity');
$derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');
// Add item to shopping bag.
$attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
$this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
$this->data['message'] = 'Item added to Shopping Bag.';
// Update Delivery Price
$this->Checkout_model->updateDelivery(49);
$this->data['items'] = $this->Checkout_model->GetProducts();
$this->template
->build('checkout/quickbasket', $this->data);
}
THE HTML FEEDBACK
<?php
//var_dump($items);
//print_r($this->session->userdata);
?>
<div id="basketoverview">
<div id="quickbasket">
<h1><?php echo $this->cart->total_items(); ?> item in bag</h1>
<?php foreach ($items as $item) : ?>
<div class="item">
<img src="<?php echo base_url().$item['imageUrl'];?>" alt="<?php echo $item['imageAlt'];?>" width="70"/>
<h4><?php echo $item['imageAlt'];?></h4>
<span class="price">£<?php echo $item["price"]; ?></span>
<span class="qauntity">Quantity: <?php echo $item['qty']; ?></span>
</div>
<?php endforeach; ?>
</div>
<div id="basket_options">
VIEW BAG / CHECKOUT
</div>
</div>
** THE AJAX SCRIPT**
$("#frmProducts").submit(function(){
var dataSet = $("#frmProducts").serialize();
$.ajax({
url: "<?php echo base_url();?>products/updateBasket",
data: dataSet,
type: "POST",
success: function(data){
$('html, body').animate({scrollTop:0}, 'slow');
$("#miniCart").load("<?php echo base_url();?>checkout/loadCartView");
$('body').append(data);
$('#basketoverview').fadeIn(2000);
setTimeout(function () { $('#basketoverview').fadeOut(2000).hide(); }, 8000);
}
});
return false;
});
A SUCCESSFUL POST
selDerivative-1 171
selQuantity 1
submitted 1
** AN UNSUCCESSFUL POST **
selDerivative-1 223
selQuantity 1
selURL-1 colonial/dining/prestige-dining-for-six
submitted 1
The frmProducts form
<?php echo form_open(current_url(), array('id' => 'frmProducts'), array('submitted' => '1')); ?>
<div class="formRow">
<label for="rattanType"><?php echo $product_attribute_names; ?> </label><br />
<?php
$options = array();
foreach ($product_derivatives as $derivative) :
$options[$derivative['derivativeId']] = $derivative['attributeValues'];
endforeach;
?>
<?php echo form_dropdown('selDerivative-1', $options, $product_details->pdId, 'class="select clear" id="selDerivative-1"'); ?>
</div>
<?php if (count($individual_products) > 0) : ?>
<div class="formRow">
<label for="itemType">Item</label><br />
<select class="select clear" id="selURL-1" name="selURL-1">
<option value="<?php echo current_url(); ?>">Full Set</option>
<?php foreach ($individual_products as $product) : ?>
<option value="<?php echo site_url($product->fullProductPath); ?>"><?php echo $product->productTitle; ?> - £<?php echo ($product->productSavingType != 'none' ? $product->productSavingPrice : $product->productPrice); ?></option>
<?php endforeach; ?>
</select>
<input id="btnGo-1" name="btnGo-1" type="submit" value="GO" />
</div>
<?php endif; ?>
<div class="formRow">
<label for="addQty">Quantity</label><br />
<?php
$options = array();
for ($i = 1; $i < 10; $i++) :
$options[$i] = $i;
endfor;
?>
<?php echo form_dropdown('selQuantity', $options, '1', 'class="small select clear"'); ?>
</div>
<input type="submit" value="add to bag" name="btnAddToBag" id="btnAddToBag" />
<?php echo form_close(); ?>
I have absolutly why the first post would get added to the basket and the second would not, does any one have any idea from looking at my code?
This is kind of a longshot, but I have the suspicion that you have a session problem. The CI Session manager has a few issues randomly creating new sessions from Ajax calls. The issue and some solutions are discussed here:
http://codeigniter.com/forums/viewthread/186070/
Related
I have this list of poll questions (with distinct id) along with options. When I submit a poll option I get an AJAX response back.
I want to use this response to publish as result instantly without page refresh but exactly replacing the html of the same poll question with the success ajax data received.
Specifically, my question is on submitting a poll answer how to change/remove the question (html) to that of new html containing answer(different html). Only the html of the related poll should change not all the poll's html. I'm successfully getting the ajax success callback.
This is the code:
php:
<?php if(isset($GLOBALS['questions']) && is_array($questions)): ?>
<?php foreach($questions as $key => $question): ?>
<?php require 'poll.php'; ?>
<?php $user = Subscribers::getSubscriber($question->userID); ?>
<li class="comment-holder" id="_<?php echo $question->id; ?>">
<div class="user-img">
<img src="<?php echo $user->profile_img; ?>" class="user-img-pic" />
</div>
<div class="comment-body">
<h3 class="username-field"><?php echo $user->username; ?></h3>
<div class="comment-text">
<?php echo $question->question; ?>
<hr />
</div>
</div>
<!--Relevant part: display choices -->
<div class="poll-option">
<?php if($completed):?>
<div id="completed">
<p>You have completed this poll, thanks.</p>
<!--**This is where ajax response should appear**-->
</div>
<?php else: ?>
<?php if(!empty($opts)): ?>
<div class="poll-options">
<?php
$TypeOfPoll = $question->pollType;
switch($TypeOfPoll) {
case "option1":
foreach($opts as $index => $opt) {
if ($opt->id == $question->id) {
echo "<input type='radio' name='choice' value='$opt->choice_id' />";
echo $opt->name,'<br />';
}}
echo "<input type='submit' value='Submit' id='$question->id' class='submitPoll' />";
break;
case "option2":
echo 'Option 2';
break;
case "option3":
echo 'Option 3';
break;
case "option4":
echo 'Option 4';
break;
default:
foreach($opts as $index => $opt) {
if ($opt->id == $question->id) {
echo '<input type="radio" name="choice" value="<?php echo $opt->choice_id; ?>" />';
echo $opt->name,'<br /><br />';
}}
echo "<input type='submit' value='Submit' id='$question->id' class='submitPoll' />";
break;
}
?>
</div>
<?php else: ?>
<p>No choices available!</p>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="comment-buttons-holder">
<ul>
<li id="<?php echo $question->id; ?>" class="delete-btn">X</li>
</ul>
</div>
</li>
<?php endforeach; ?>
<?php endif; ?>
Ajax:
$(document).ready(function() {
add_submitPoll_handlers();
});
function add_submitPoll_handlers() {
$('.submitPoll').each(function() {
// 'submitPoll' is class for submit button
var btn = this;
$(btn).click(function() {
var ChoiceAnsVal = $('input:radio[name=choice]:checked').val();
var userId = $('#userId').val();
var id = btn.id;
console.log('user:'+userId+'poll:'+btn.id+'choice:'+ChoiceAnsVal);
submit_poll(userId, id, ChoiceAnsVal);
});
});
}
function submit_poll(userId, id, ChoiceAnsVal) {
$('.submitPoll').click(function() {
$.post("ajax/submit_poll.php",
{
task:"submit_poll",
userId: userId,
poll_id: id,
choice_id:ChoiceAnsVal
}
).error(
function() {
console.log("Error in script.js")
}
).success(
function(data) {
$('#completed').html('You have completed the poll!');//not working
//console.log("ResponseText:" + data); //I'm getting the //response
}
);
});
Ajax is exactly designed for the above purpose. But for this i would suggest using jQuery+AJAX. This will be an easy method.Since you haven't provide you code I cannot provide you the exact code needed. The code will be like this
HTML
<div id="question_id">html</div>
Jquery
$(selector).something(function(){
var id=$(this).id; //assuming this will be the id of question that is selected
$.ajax({
url:url. //url to which data to be submitted
type:post,
data: //data to be submitted
success:function(data){
//data will be page/data that returned by the server page
$(selector).html(html_daya);// you can create html string that to replaced and pass it as argument to html function
}
});
});
Please refer http://api.jquery.com/jquery.ajax/ for complete documentation.
I am trying to send 2 values from different parts of a page to the same ajax function. Basically, it's a search filter wherein selecting categories is one module and selecting brands is another both of which are attributes of a product and independent of each other.
I need 3 conditions where search is performed either
only if brand is selected or
only if cat is selected or
if both are selected.
My issue is 1 and 3 are working. but 2nd condition isn't as it takes the cat value as the brand. Please help me correct my function.
My AJAX function:
function filter(subid) {
alert(subid);
var brand_filter = new Array();
$("input:checked").each(function() {
brand_filter.push($(this).val());
});
$.ajax({
type: 'POST',
url: 'getSubcategoryProducts.php',
data: {
brand_filter:brand_filter,
subId: subid
},
success: function(data) {
//alert(data);
$('#productDetail').html(data).fadeIn('slow');
$('#sub_cat_menuItem a').addClass('.collection-category-brands li.active, .collection-category-brands li:hover');
}
});
}
Module of selecting brand:
<div class="collection-brands-filter">
<h4>Filter by Brands</h4>
<div class="brand-filter-form">
<form>
<?php $brandlist = $objBrands-> getAll("status=1");
foreach($brandlist as $branditem){
?>
<span><input type="checkbox" name="brand_filter[]" <?php if ('checked="checked"'){ ?> onClick="filter(<?php echo $branditem['id'];?>);" <?php } ?> value="<?php echo $branditem['id'];?>"/><?php echo $branditem['name'];?></span>
<?php } ?>
</form>
</div>
</div>
Module of selecting category:
<div class="collection-category-brands">
<ul>
<?php
//Fetching sub categories of the main_category
while($query2res = mysql_fetch_array($query2)){ ?>
<li id="sub_cat_menuItem"><?php echo $query2res['1'];?></li>
<?php $subId = $query2res['id'];}?>
</ul>
</div>
getSubcategoryProducts.php code:
<?php
include_once("class/site_root.php");
include('includes/connect.php');
include_once(DIR_ROOT."class/functions.php");
include_once(DIR_ROOT."class/products.php");
$objProducts = new products();
$subId = $_POST['subId'];
//IF ONLY BRAND IS SELECTED AND NOT SUB CATEGORY
if(isset($_POST['brand_filter'])&&!isset($_POST['subId']))
{
echo "only brand is selected";
foreach($_POST['brand_filter'] as $item)
{
$res = $objProducts->getAll('status=1 and brand_id='.$item);?>
<ul>
<?php foreach($res as $val){?>
<li>
<img src="<?php echo $val['img_small']; ?>" alt="icon"/>
<div class="collection-item-hover">
<div class="collection-category-detail">
Know More
<div class="collection-item-detail">
<h4><?php echo $val['product_name']; ?></h4>
<p><?php echo $val['descr_small']; ?></p>
</div>
</div>
</div>
</li>
<?php }?>
</ul>
<?php }
}
//IF ONLY SUB CATEGORY IS CHOSEN!
else if(isset($subId)&&!isset($_POST['brand_filter'])){
echo "only sub cat selected!";
$productsquery=mysql_query("SELECT products.product_name,products.id,products.main_id,
products.img_small,products.descr_small,sub_category.name
FROM products
LEFT JOIN sub_category on
products.sub_id=sub_category.id
WHERE sub_category.id=".$subId);
$count = mysql_num_rows($productsquery);
$subNameVal=mysql_fetch_array(mysql_query("select name from sub_category where id=".$subId));
?>
<h3><?php echo $subNameVal['name'];?></h3>
<?php
if($count>0)
{
?>
<ul>
<?php
while($productsRes=mysql_fetch_array($productsquery))
{
?>
<li>
<img src="<?php echo $productsRes['img_small']; ?>" alt="icon"/>
<div class="collection-item-hover">
<div class="collection-category-detail">
Know More
<div class="collection-item-detail">
<h4><?php echo $productsRes['product_name']; ?></h4>
<p><?php echo $productsRes['descr_small']; ?></p>
</div>
</div>
</div>
</li>
<?php }
?>
</ul>
<?php }
}
//IF BOTH ARE SELECTED
else //if(isset($_POST['brand_filter'])&&isset($subId))
{
echo "both selected!";
echo
"SUB-".$subId."<br/>";
foreach ($_POST['brand_filter'] as $item)
{
echo "brand-".$item."<br/>";
}
}
?>
I have several quantity boxes next to products so a user can input what quantity they want of a certain product.
The setup uses a step by step process using Jquery with the first step made up of checkboxes, the second made up of quantity inputs (where I need the help!) and the final step shows what has been selected... on submit it all gets emailed to me.
Step 1 with checkboxes is complete (with a lot of help from #Beetroot-Beetroot -Step by step checkbox process with summary of selections). Step 2 is where I need the help, how can I show the user quantity inputs on the summary page?
Here's the HTML:
<form id="customisesystem" method="post" action="">
<div id="first-step">
<div class="steps">
<p><b>Step 1 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area">
<div id="customise-title">
<p><b>1. Hardware & software options</b> <span>Please choose one or more of the following</span></p>
</div>
<div id="customise-area">
<?php $posts = get_field('options');
if( $posts ):
$items = 0;
foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post); ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p>
<input type="checkbox" name="hardware[]" value="<?php the_title(); ?>">
Select</p>
<div class="clear"></div>
</div>
<?php $items++; endforeach;
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
endif; ?>
</div>
</div>
</div>
<!-- end first-step -->
<div id="second-step">
<div class="steps">
<p><b>Step 2 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area">
<div id="customise-title">
<p><b>2. Accessories</b> <span>Please choose one or more of the following</span></p>
</div>
<div id="customise-area">
<?php $posts = get_field('accessories');
if( $posts ):
$items = 0;
foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post); ?>
<?php if ($items&1) { ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p style="clear:right;float:right;width:180px;">
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" style="width:15px;" value="0">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>">
<?php } ?>
<?php } else { ?>
<input type="text" name="quantity[]" style="width:15px;" value="">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?>">
<?php } ?>
</p>
<div class="clear"></div>
</div>
<?php } else { ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p style="clear:right;float:right;width:180px;">
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" style="width:15px;" value="0">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>">
<?php } ?>
<?php } else { ?>
<input type="text" name="quantity[]" style="width:15px;" value="">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?>">
<?php } ?>
</p>
<div class="clear"></div>
</div>
<?php } ?>
<?php $items++; endforeach;
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
endif; ?>
</div>
</div>
</div>
<!-- end second-step -->
<div id="third-step">
<div class="steps">
<p><b>Step 3 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area-3">
<p>Summary</p>
<div id="customise-area-3-child">
<input type="submit" name="submit" id="submit" value="submit" />
</div>
</div>
</div>
<!-- end third-step -->
</form>
Here's the Jquery:
jQuery(document).ready(function( $ ) {
//Create nav wrapper
var $nav = $('<div/>').addClass('prev-next');
//Create Prev button, attach click handler and append to nav wrapper
$('<a class="prev" href="#">Back</a>').on('click', function () {
$(this).closest(".step").hide().prev(".step").show();
}).prependTo($nav);
//Create Next button, attach click handler and append to nav wrapper
$('<a class="next" href="#">Next</a>').on('click', function () {
$('.summary_text').html(makeSummary());
var $step = $(this).closest(".step");
if (validate($step)) {
$step.hide().next(".step").show();
}
}).appendTo($nav);
//In one long jQuery chain ...
//* prepend nav to each step div
//* hide all steps except the first
//* convert first 'Back' link and last 'Next' link to spans.
var $steps = $(".step").prepend($nav).hide()
.filter(":first").show().find("a.prev").after('Back').remove().end().end()
.filter(":last").find("a.next").after('').remove().end().end();
//Set step titles
$steps.each(function (i, step) {
$(step).find(".step-title").text('Step ' + (i + 1) + ' of ' + $steps.length);
});
$('a.back-to-product').click(function(){
$(".customise").hide();
$(".entire_product").show();
});
//Unfortunately, hidden form elements are not inlcuded in the submission,
//so all steps must be shown before the form is submitted.
var $submitButton = $("input[name='submit']").on('submit', function () {
$steps.show();
return true;
});
function validate($step) {
//var valid = false;
var valid = true; //for debugging
//Perform validation
switch ($step.index(".step")) { //index-origin is zero
case 0:
//Validate step 1 here
//if valid, set `valid` to true
break;
case 1:
//Validate step 2 here
//if valid, set `valid` to true
break;
case 2:
//No validatation required
break;
}
return valid; //Important - determines behaviour after validate() returns.
}
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $step.find('input[type="checkbox"]:checked');
if (!$ch.length) {
summary.push('<p>No items selected</p><br />');
} else {
$ch.each(function (i, ch) {
summary.push('<p>' + $(ch).val() + '</p><br />');
});
}
});
return summary.join('');
}
});
First, make the quantity[] and product[] fields more readily selectable by hard-coding class="quantity" and class="product" in the HTML.
<input type="text" name="quantity[]" class="quantity" style="width:15px;" value="0">25 cm²<br />
<input type="hidden" name="product[]" class="product" value="Equipment Electrode Set - 25 cm²">
Here's the javascript :
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $('input[type="checkbox"]:checked', $step);
var $qty = $('input.quantity', $step).filter(function() {
return this.value !== '0';
});
var $selected = $ch.add($qty);//jQuery collection of checkeboxes, or quantity fields, or a mixture of both.
if (!$selected.length) {
summary.push('<p>No items selected</p><br />');
} else {
$selected.each(function (i, s) {
var $s = $(s);
var prefix = ($s.hasClass('quantity')) ? ($s.nextAll("input.product").val() + ' : ') : '';
summary.push('<p>' + prefix + $s.val() + '</p><br />');
});
}
});
return summary.join('');
}
By doing it this way, the function remains general with regard to the number of steps, but also with regard to the composition of each step; it will handle completely specialized "checkbox step(s)" and "quantity step(s)", and (should you ever have the need) mixed "checkbox/quantity step(s)". In every case, the selected items will be summarized in their original DOM order.
DEMO
I am trying to get the related products block to show up on my product detail page.
I have the folling code in the respective .phtml file
<?php
<?php echo "Related product block"?>
<?php if($this->getItems()->getSize()): ?>
<div class="block block-related">
<div class="block-title">
<strong><span><?php echo $this->__('Related Products') ?></span></strong>
</div>
<div class="block-content">
<p class="block-subtitle"><?php echo $this->__('Check items to add to the cart or') ?> <?php echo $this->__('select all') ?></p>
<ol class="mini-products-list" id="block-related">
<?php foreach($this->getItems() as $_item): ?>
<li class="item">
<?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
<?php endif; ?>
<?php endif; ?>
<div class="product">
<img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />
<div class="product-details">
<p class="product-name"><?php echo $this->htmlEscape($_item->getName()) ?></p>
<?php echo $this->getPriceHtml($_item, true, '-related') ?>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<?php echo $this->__('Add to Wishlist') ?>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">decorateList('block-related', 'none-recursive')</script>
</div>
<script type="text/javascript">
//<![CDATA[
$$('.related-checkbox').each(function(elem){
Event.observe(elem, 'click', addRelatedToProduct)
});
var relatedProductsCheckFlag = false;
function selectAllRelated(txt){
if (relatedProductsCheckFlag == false) {
$$('.related-checkbox').each(function(elem){
elem.checked = true;
});
relatedProductsCheckFlag = true;
txt.innerHTML="<?php echo $this->__('unselect all') ?>";
} else {
$$('.related-checkbox').each(function(elem){
elem.checked = false;
});
relatedProductsCheckFlag = false;
txt.innerHTML="<?php echo $this->__('select all') ?>";
}
addRelatedToProduct();
}
function addRelatedToProduct(){
var checkboxes = $$('.related-checkbox');
var values = [];
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked) values.push(checkboxes[i].value);
}
if($('related-products-field')){
$('related-products-field').value = values.join(',');
}
}
//]]>
</script>
The echo above the code shows up on my page. Which of course proves that i implemented the block correctly.
Just everything in the if-statement doesn't show.
I spend some time looking for solutions and i tried rebuilding the indexes and my related product is visible on the frontend.
Anyone know how i can fix this?
Magento will always return a low number or 0 for the condition:
$this->getItems()->getSize()
if some/all of the related products are in the user's cart, and consequently items will appear as though they are missing.
To prevent this behaviour, duplicate the core Magento 'Related' class:
/app/code/core/Mage/Catalog/Block/Product/List/Related.php
to local:
/app/code/local/Mage/Catalog/Block/Product/List/Related.php
Then comment out the following lines in the if statement:
if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
//mod - show all related products, even if they have been added to the cart
//Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
// Mage::getSingleton('checkout/session')->getQuoteId()
//);
$this->_addProductAttributesAndPrices($this->_itemCollection);
}
On your 4 line:
<?php if($this->getItems()->getSize() > 0 ? true : false) ?>
Try it.
At the top of your code type
var_dump($this->getItems()->getSize()) // does this print NUll, False or > 0
If the code above print NULL or false or less than 1, then do
print_r($this->getItems());
If none of the above print the information you expected then check your block getItems() method
Also where is the closing IF for if($this->getItems()->getSize()):
public function actionEquipmentLoanRequestCreate()
{
if(isset($_POST['EquipmentRequest']))
{
$ids = $_POST['EquipmentRequest']['equipID'];
$equipment = Equipment::model()->findAllByPk($ids);
$requests = self::instantiateEquipmentRequests($equipment);
//echo "<pre>";
//die(count($requests)." ".CActiveForm::validate($requests));
$booking = new EquipmentBooking;
if(isset($_POST['EquipmentRequest']) && $_POST['EquipmentBooking'])
{
$booking->attributes = $_POST['EquipmentBooking'];
$requestPostedVars = $_POST['EquipmentRequest'];
//have posted collection of equipment
//need to take count
//request below not really useful???
$equipmentRequests = array();
foreach($requestPostedVars as $request)
{
if(isset($request))
{
$equipmentRequest = new EquipmentRequest('loanRequest');
$equipmentRequest->attributes = $request;
array_push($equipmentRequests,$equipmentRequest);
}
}
$models = $equipmentRequests;
$models[]=$booking;
$this->performAjaxValidation($models);
$booking->equipment = $equipmentRequests;
if ($booking->save()){
self::assignBookingIds($equipmentRequests,$booking);
$this->redirect('index');
}
}
//displays view to create loan request
$this->render('equipment-loan-request',array('requests' => $requests,'booking' => $booking));
} else {
Yii::app()->user->setFlash('error', "You need to select equipment first!");
$this->redirect(array('simulation/equipment'), true);
}
}
public function instantiateEquipmentRequests($equipment)
{
$equipmentRequests = array();
foreach($equipment as $item)
{
$request = new EquipmentRequest('loanRequest');
$request->equipment = $item;
$request->qty = 1;
array_push($equipmentRequests,$request);
}
return $equipmentRequests;
}
form view ignore excess button replacing later -- ive directly tried calling the requests as opposed to just the bookings or both below as well to no avail.
<?php $form=$this->beginWidget('CActiveFormExtended', array(
'id' => 'equipment-booking-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>true,
),
)); ?>
<div class="content-bg">
<?php
echo $form->errorSummary($requests);
if(isset($requests) && count($requests) > 0) {
foreach($requests as $i => $request) {
$this->renderPartial('_requestedEquipment', array("index" => $i, "request" => $request, "form"=> $form));
}
}?>
</div>
<br />
<hr class="brown"/>
<h2>Request Details</h2>
<div class="content-bg">
<h3>Step 1</h3>
<?php echo $form->label($booking,'organisation'); ?>
<?php echo $form->dropDownList($booking, 'organisation', $booking::$organisations,array('id' => 'organisation', 'class' => "selectfield",'empty' => 'Select')); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 2</h3>
<?php echo $form->label($booking,'name'); ?>
<?php echo $form->textField($booking,'name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'name'); ?>
<?php echo $form->label($booking,'email'); ?>
<?php echo $form->textField($booking,'email',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'email'); ?>
<?php echo $form->label($booking,'phone'); ?>
<?php echo $form->textField($booking,'phone',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'phone'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 3</h3>
<?php echo $form->label($booking,'address'); ?>
<?php echo $form->textField($booking,'address',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'address'); ?>
<?php echo $form->label($booking,'suburb'); ?>
<?php echo $form->textField($booking,'suburb',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'suburb'); ?>
<?php echo $form->label($booking,'postcode'); ?>
<?php echo $form->textField($booking,'postcode',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($booking,'postcode'); ?>
</div>
<br />
<div class="content-bg">
<h3>Step 4</h3>
<div class="five columns alpha">
<?php echo $form->label($booking,'pickupDate'); ?>
<?php echo $form->dropDownDayList($booking, 'pickupDate',array('class' => 'date-day pickup_select','id' => 'pickup')); ?>
<?php echo $form->dropDownYearList($booking,1, 'pickupDate',array('class' => 'date-monthyear pickup_select','id' => 'pickup-month')); ?>
<?php echo $form->hiddenField($booking, 'pickupDate',array('id' => 'pickupData')); ?>
<?php echo $form->error($booking,'pickupDate'); ?>
</div>
<div class="five columns alpha">
<?php echo $form->label($booking,'returnDate'); ?>
<?php echo $form->dropDownDayList($booking, 'returnDate',array('class' => 'date-day return_select','id' => 'return')); ?>
<?php echo $form->dropDownYearList($booking,1, 'returnDate',array('class' => 'date-monthyear return_select','id' => 'return-month')); ?>
<?php echo $form->hiddenField($booking, 'returnDate',array('id' => 'returnData')); ?>
<?php echo $form->error($booking,'returnDate'); ?>
</div>
<br class="clear"/>
</div>
<br />
<div class="content-bg">
<h2>Terms & Conditions</h2>
<p>By submitting this loan enquiry you agree to and acknowledge our Equipment Loan Terms and Conditions.</p>
</div>
<?php echo CHtml::submitButton('Submit'); ?>
<br />
<input class="orange-btn right" type="submit" value="Submit Loan Request">
<?php $this->endWidget(); ?>
</div>
EquipmentRequest partial
<div class="selected-equipment" id="request_<?php echo $request->equipment->equipName; ?>">
<div class="equipment-selected"><?php echo $request->equipment->equipName; ?></div>
<div class="equipment-qty"><?php echo $form->textField($request, "[$index]qty", array('value' => 1,'class' => 'requestQuantity')); ?></div>
<?php echo $form->error($request,"[$index]qty"); ?>
<div class="equipment-update"><span>Remove</span></div>
<?php echo $form->hiddenField($request, "[$index]equipID",array('value' => $request->equipment->equipID)); ?>
<?php echo $form->error($request,"[$index]equipID"); ?>
<br class="clear">
</div>
EDIT
Please note I have rectified the above issue. Was mainly caused by an incorrect usage of performAjaxValidate, which I have now set to call both the booking and the collection of equipmentRequests.
This is now letting me get 2 validation error message objects back, 1 for both models. however only the booking model is being passed to the error summary div.
#bool.dev appreciate your assistance so far, any ideas with the above, have tried merging the collection of equipment request objects and booking object to the one argument call in errorSummary
I've edited the above to show updated controller actions and views
When you want errorSummary() for more than one model, use:
$form->errorSummary(array($model1,$model2,$model3));