/** * Adds a given product to the cart. If a hidden field is passed * (ValidateVariant) then simply a validation of the user including that * product is done and the users cart isn't actually changed. * * @return mixed */ public function addtocart($data, $form) { if ($variation = $this->getBuyable($data)) { $quantity = isset($data['Quantity']) && is_numeric($data['Quantity']) ? (int) $data['Quantity'] : 1; $cart = ShoppingCart::singleton(); // if we are in just doing a validation step then check if ($this->request->requestVar('ValidateVariant')) { $message = ''; $success = false; try { $success = $variation->canPurchase(null, $data['Quantity']); } catch (ShopBuyableException $e) { $message = get_class($e); // added hook to update message $this->extend('updateVariationAddToCartMessage', $e, $message, $variation); } $ret = array('Message' => $message, 'Success' => $success, 'Price' => $variation->dbObject('Price')->TrimCents()); $this->extend('updateVariationAddToCartAjax', $ret, $variation, $form); return json_encode($ret); } if ($cart->add($variation, $quantity)) { $form->sessionMessage("Successfully added to cart.", "good"); } else { $form->sessionMessage($cart->getMessage(), $cart->getMessageType()); } } else { $variation = null; $form->sessionMessage("That variation is not available, sorry.", "bad"); //validation fail } $this->extend('updateVariationAddToCart', $form, $variation); $request = $this->getRequest(); $this->extend('updateVariationFormResponse', $request, $response, $variation, $quantity, $form); return $response ? $response : ShoppingCart_Controller::direct(); }
/** * Handles form submission * @param array $data * @return bool|\SS_HTTPResponse */ public function addtocart(array $data) { $groupedProduct = $this->getController()->data(); if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) { $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad'); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } $cart = ShoppingCart::singleton(); foreach ($data['Product'] as $id => $prodReq) { if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) { $prod = Product::get()->byID($id); if ($prod && $prod->exists()) { $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $prodReq; $buyable = $prod; if (isset($prodReq['Attributes'])) { $buyable = $prod->getVariationByAttributes($prodReq['Attributes']); if (!$buyable || !$buyable->exists()) { $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad"); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } if (!$cart->add($buyable, (int) $prodReq['Quantity'], $saveabledata)) { $this->sessionMessage($cart->getMessage(), $cart->getMessageType()); $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : $this->controller->redirectBack(); } } } } $this->extend('updateGroupCartResponse', $this->request, $response, $groupedProduct, $data, $this); return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType()); }
function __construct($controller, $name) { $member = Member::currentUser(); $requiredFields = null; if ($member && $member->exists()) { $fields = $member->getEcommerceFields(true); $fields->push(new HeaderField('LoginDetails', _t('Account.LOGINDETAILS', 'Login Details'), 3)); $logoutLink = ShoppingCart_Controller::clear_cart_and_logout_link(); $fields->push(new LiteralField('LogoutNote', "<p class=\"message warning\">" . _t("Account.LOGGEDIN", "You are currently logged in as ") . $member->FirstName . ' ' . $member->Surname . '. <a href="' . $logoutLink . '">' . _t('Account.LOGOUT', 'Log out now?') . "</a></p>")); // PASSWORD KEPT CHANGING - SO I REMOVED IT FOR NOW - Nicolaas $passwordField = new ConfirmedPasswordField('Password', _t('Account.PASSWORD', 'Password'), "", null, true); $fields->push($passwordField); $requiredFields = new ShopAccountForm_Validator($member->getEcommerceRequiredFields()); $actions = new FieldSet(new FormAction('submit', _t('Account.SAVE', 'Save Changes'))); if ($order = ShoppingCart::current_order()) { if ($order->Items()) { $actions->push(new FormAction('proceed', _t('Account.SAVEANDPROCEED', 'Save changes and proceed to checkout'))); } } } else { $member = new Member(); $fields = new FieldSet(); $fields->push(new HeaderField('SignUp', _t('ShopAccountForm.CREATEACCOUNT', 'Create Account'))); $fields->push(new LiteralField('MemberInfo', '<p class="message good">' . _t('OrderForm.MEMBERINFO', 'If you are already have an account then please') . " <a href=\"Security/login?BackURL=" . $controller->Link() . "\">" . _t('OrderForm.LOGIN', 'log in') . '</a>.</p>')); $memberFields = $member->getEcommerceFields(true); if ($memberFields) { foreach ($memberFields as $memberField) { $fields->push($memberField); } } // PASSWORD KEPT CHANGING - SO I REMOVED IT FOR NOW - Nicolaas $passwordField = new PasswordField('Password', _t('Account.PASSWORD', 'Password')); $fields->push($passwordField); $requiredFields = new ShopAccountForm_Validator($member->getEcommerceRequiredFields()); $actions = new FieldSet(new FormAction('creatememberandaddtoorder', _t('Account.SAVE', 'Create Account'))); } parent::__construct($controller, $name, $fields, $actions, $requiredFields); //extensions need to be set after __construct if ($this->extend('updateFields', $fields) !== null) { $this->setFields($fields); } if ($this->extend('updateActions', $actions) !== null) { $this->setActions($actions); } if ($this->extend('updateValidator', $requiredFields) !== null) { $this->setValidator($requiredFields); } if ($member && $member->Password) { $this->loadDataFrom($member); if (!isset($_REQUEST["Password"])) { $this->fields()->fieldByName("Password")->SetValue(""); } $this->fields()->fieldByName("Password")->setCanBeEmpty(true); } $this->extend('updateShopAccountForm', $this); }
public function addtocart($data, $form) { if ($buyable = $this->getBuyable($data)) { $cart = ShoppingCart::singleton(); $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $data; $quantity = isset($data['Quantity']) ? (int) $data['Quantity'] : 1; $cart->add($buyable, $quantity, $saveabledata); if (!ShoppingCart_Controller::config()->direct_to_cart_page) { $form->SessionMessage($cart->getMessage(), $cart->getMessageType()); } ShoppingCart_Controller::direct($cart->getMessageType()); } }
public function addtocart($data, $form) { if ($buyable = $this->getBuyable($data)) { $cart = ShoppingCart::singleton(); $request = $this->getRequest(); $order = $cart->current(); if ($request && $request->isAjax() && $order) { ShopTools::install_locale($order->Locale); } $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $data; $quantity = isset($data['Quantity']) ? (int) $data['Quantity'] : 1; $cart->add($buyable, $quantity, $saveabledata); if (!ShoppingCart_Controller::config()->direct_to_cart_page) { $form->SessionMessage($cart->getMessage(), $cart->getMessageType()); } $this->extend('updateAddToCart', $form, $buyable); $this->extend('updateAddProductFormResponse', $request, $response, $buyable, $quantity, $form); return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType()); } }
public function setquantityLink() { return ShoppingCart_Controller::set_quantity_item_link($this->Buyable(), $this->uniquedata()); }
/** * returns the link that can be used to remove (make Obsolete) an address. * @return String */ function RemoveLink() { return ShoppingCart_Controller::remove_address_link($this->ID, $this->ClassName); }
/** * @return string */ public function setquantityLink() { $buyable = $this->Buyable(); return $buyable ? ShoppingCart_Controller::set_quantity_item_link($buyable, $this->uniquedata()) : ''; }
/** * Link that can be used to remove the modifier * @return String **/ public function RemoveLink() { return ShoppingCart_Controller::remove_modifier_link($this->ID, $this->ClassName); }
function removeLink() { return ShoppingCart_Controller::remove_modifier_link($this->_id); }
function setquantityLink() { return ShoppingCart_Controller::set_quantity_item_link($this->_productID); }
/** * Link that can be used to remove the modifier * @return String **/ public function RemoveLink() { $param = array(); $updatedLinkParameters = $this->extend("ModifierRemoveLinkUpdate", $param); if ($updatedLinkParameters !== null && is_array($updatedLinkParameters) && count($updatedLinkParameters)) { foreach ($updatedLinkParameters as $updatedLinkParametersUpdate) { $param += $updatedLinkParametersUpdate; } } return ShoppingCart_Controller::remove_modifier_link($this->ID, $param, $this->ClassName); }
/** * * @return String */ protected function getQuantityLink() { return ShoppingCart_Controller::set_quantity_item_link($this->orderItem->BuyableID, $this->orderItem->BuyableClassName, $this->parameters); }
/** * This returns a link that displays just the cart, for use in ajax calls. * @see ShoppingCart::showcart * It uses AjaxSimpleCart.ss to render the cart. * @return string **/ function SimpleCartLinkAjax() { return ShoppingCart_Controller::get_url_segment() . "/showcart/?ajax=1"; }
public function testVariations() { $this->loadFixture('shop/tests/fixtures/variations.yml'); $ballRoot = $this->objFromFixture('Product', 'ball'); $ballRoot->publish('Stage', 'Live'); $ball1 = $this->objFromFixture('ProductVariation', 'redlarge'); $ball2 = $this->objFromFixture('ProductVariation', 'redsmall'); // Add the two variation items $r = $this->get(ShoppingCart_Controller::add_item_link($ball1), null, $this->ajaxHeaders); $this->assertTrue($r instanceof AjaxHTTPResponse); $r = $this->get(ShoppingCart_Controller::add_item_link($ball2)); $this->assertFalse($r instanceof AjaxHTTPResponse); $items = ShoppingCart::curr()->Items(); $this->assertNotNull($items); $this->assertEquals($items->Count(), 2, 'There are 2 items in the cart'); // Remove one and see what happens $r = $this->get(ShoppingCart_Controller::remove_all_item_link($ball1), null, $this->ajaxHeaders); $this->assertTrue($r instanceof AjaxHTTPResponse); $this->assertEquals($items->Count(), 1, 'There is 1 item in the cart'); $this->assertFalse($this->cart->get($ball1), "first item not in cart"); $this->assertNotNull($this->cart->get($ball1), "second item is in cart"); }
/** * * @return String */ function AddToCartAndGoToCheckoutLink() { $array = $this->linkParameters(); $array["BackURL"] = urlencode(CheckoutPage::find_link()); return ShoppingCart_Controller::add_item_link($this->ID, $this->ClassName, $array); }
function getCopyOrderLink() { if ($this->canView() && $this->IsSubmitted()) { return ShoppingCart_Controller::copy_order_link($this->ID); } else { return ""; } }
/** * Returns the link that can be used in the shopping cart to * set the preferred currency to this one. * For example: /shoppingcart/setcurrency/nzd/ * @return String */ public function Link() { return ShoppingCart_Controller::set_currency_link($this->Code); }
public function testSecurityToken() { $enabled = SecurityToken::is_enabled(); // enable security tokens SecurityToken::enable(); $productId = $this->mp3player->ID; // link should contain the security-token $link = ShoppingCart_Controller::add_item_link($this->mp3player); $this->assertRegExp('{^shoppingcart/add/Product/' . $productId . '\\?SecurityID=[a-f0-9]+$}', $link); // should redirect back to the shop $response = $this->get($link); $this->assertEquals($response->getStatusCode(), 302); // disable security token for cart-links Config::inst()->update('ShoppingCart_Controller', 'disable_security_token', true); $link = ShoppingCart_Controller::add_item_link($this->mp3player); $this->assertEquals('shoppingcart/add/Product/' . $productId, $link); // should redirect back to the shop $response = $this->get($link); $this->assertEquals($response->getStatusCode(), 302); SecurityToken::disable(); Config::inst()->update('ShoppingCart_Controller', 'disable_security_token', false); $link = ShoppingCart_Controller::add_item_link($this->mp3player); $this->assertEquals('shoppingcart/add/Product/' . $productId, $link); // should redirect back to the shop $response = $this->get($link); $this->assertEquals($response->getStatusCode(), 302); SecurityToken::enable(); // should now return a 400 status $response = $this->get($link); $this->assertEquals($response->getStatusCode(), 400); // restore previous setting if (!$enabled) { SecurityToken::disable(); } }
/** * * @return String (URLSegment) **/ function SetSpecificQuantityItemLink($quantity) { return ShoppingCart_Controller::set_quantity_item_link($this->BuyableID, $this->BuyableClassName, array_merge($this->linkParameters(), array("quantity" => $quantity))); }
/** * Link to remove all of this product from cart. * @return string link */ public function removeallLink() { return ShoppingCart_Controller::remove_all_item_link($this); }
/** * * @param Controller $controller * @param String $name, Name of the form */ function __construct($controller, $name) { $member = Member::currentUser(); $requiredFields = null; if ($member && $member->exists()) { $fields = $member->getEcommerceFields(true); $clearCartAndLogoutLink = ShoppingCart_Controller::clear_cart_and_logout_link(); $loginMessage = "<span class=\"customerName\">" . Convert::raw2xml($member->FirstName) . ' ' . Convert::raw2xml($member->Surname) . '</span>, ' . '<a href="' . $clearCartAndLogoutLink . '">' . _t('Account.LOGOUT', 'Log out now?') . '</a>'; if ($loginMessage) { $loginField = new ReadonlyField('LoggedInAsNote', _t("Account.LOGGEDIN", "You are currently logged in as "), $loginMessage); $loginField->dontEscape = true; $fields->push($loginField); } $actions = new FieldList(new FormAction('submit', _t('Account.SAVE', 'Save Changes'))); if ($order = ShoppingCart::current_order()) { if ($order->getTotalItems()) { $actions->push(new FormAction('proceed', _t('Account.SAVE_AND_PROCEED', 'Save changes and proceed to checkout'))); } } } else { if (!$member) { $member = new Member(); } $fields = new FieldList(); $urlParams = $controller->getURLParams(); $backURLLink = Director::baseURL(); if ($urlParams) { foreach ($urlParams as $urlParam) { if ($urlParam) { $backURLLink = Controller::join_links($backURLLink, $urlParam); } } } $backURLLink = urlencode($backURLLink); $fields->push(new LiteralField('MemberInfo', '<p class="message good">' . _t('OrderForm.MEMBERINFO', 'If you already have an account then please') . " <a href=\"Security/login?BackURL=" . $backURLLink . "\">" . _t('OrderForm.LOGIN', 'log in') . '</a>.</p>')); $memberFields = $member->getEcommerceFields(); if ($memberFields) { foreach ($memberFields as $memberField) { $fields->push($memberField); } } $passwordField = new PasswordField('PasswordCheck1', _t('Account.PASSWORD', 'Password')); $passwordFieldCheck = new PasswordField('PasswordCheck2', _t('Account.PASSWORDCHECK', 'Password (repeat)')); $fields->push($passwordField); $fields->push($passwordFieldCheck); $actions = new FieldList(new FormAction('creatememberandaddtoorder', _t('Account.SAVE', 'Create Account'))); } $requiredFields = ShopAccountForm_Validator::create($member->getEcommerceRequiredFields()); parent::__construct($controller, $name, $fields, $actions, $requiredFields); $this->setAttribute("autocomplete", "off"); //extensions need to be set after __construct //extension point $this->extend('updateFields', $fields); $this->setFields($fields); $this->extend('updateActions', $actions); $this->setActions($actions); $this->extend('updateValidator', $requiredFields); $this->setValidator($requiredFields); if ($member) { $this->loadDataFrom($member); } $oldData = Session::get("FormInfo.{$this->FormName()}.data"); if ($oldData && (is_array($oldData) || is_object($oldData))) { $this->loadDataFrom($oldData); } $this->extend('updateShopAccountForm', $this); }
function __construct($controller, $name) { Requirements::themedCSS('OrderForm'); // 1) Member and shipping fields $member = Member::currentUser() ? Member::currentUser() : singleton('Member'); $memberFields = new CompositeField($member->getEcommerceFields()); $requiredFields = $member->getEcommerceRequiredFields(); if (ShoppingCart::uses_different_shipping_address()) { $countryField = new DropdownField('ShippingCountry', 'Country', Geoip::getCountryDropDown(), EcommerceRole::findCountry()); $shippingFields = new CompositeField(new HeaderField('Send goods to different address', 3), new LiteralField('ShippingNote', '<p class="warningMessage"><em>Your goods will be sent to the address below.</em></p>'), new LiteralField('Help', '<p>You can use this for gift giving. No billing information will be disclosed to this address.</p>'), new TextField('ShippingName', 'Name'), new TextField('ShippingAddress', 'Address'), new TextField('ShippingAddress2', ''), new TextField('ShippingCity', 'City'), $countryField, new HiddenField('UseShippingAddress', '', true), new FormAction_WithoutLabel('useMemberShippingAddress', 'Use Billing Address for Shipping')); $requiredFields[] = 'ShippingName'; $requiredFields[] = 'ShippingAddress'; $requiredFields[] = 'ShippingCity'; $requiredFields[] = 'ShippingCountry'; } else { $countryField = $memberFields->fieldByName('Country'); $shippingFields = new FormAction_WithoutLabel('useDifferentShippingAddress', 'Use Different Shipping Address'); } $countryField->addExtraClass('ajaxCountryField'); $setCountryLinkID = $countryField->id() . '_SetCountryLink'; $setContryLink = ShoppingCart_Controller::set_country_link(); $memberFields->push(new HiddenField($setCountryLinkID, '', $setContryLink)); $leftFields = new CompositeField($memberFields, $shippingFields); $leftFields->setID('LeftOrder'); $rightFields = new CompositeField(); $rightFields->setID('RightOrder'); if (!$member->ID || $member->Password == '') { $rightFields->push(new HeaderField('Membership Details', 3)); $rightFields->push(new LiteralField('MemberInfo', "<p class=\"message good\">If you are already a member, please <a href=\"Security/login?BackURL=" . CheckoutPage::find_link(true) . "/\">log in</a>.</p>")); $rightFields->push(new LiteralField('AccountInfo', "<p>Please choose a password, so you can login and check your order history in the future.</p><br/>")); $rightFields->push(new FieldGroup(new ConfirmedPasswordField('Password', 'Password'))); $requiredFields[] = 'Password[_Password]'; $requiredFields[] = 'Password[_ConfirmPassword]'; } // 2) Payment fields $currentOrder = ShoppingCart::current_order(); $total = '$' . number_format($currentOrder->Total(), 2); $paymentFields = Payment::combined_form_fields("{$total} " . $currentOrder->Currency(), $currentOrder->Total()); foreach ($paymentFields as $field) { $rightFields->push($field); } if ($paymentRequiredFields = Payment::combined_form_requirements()) { $requiredFields = array_merge($requiredFields, $paymentRequiredFields); } // 3) Put all the fields in one FieldSet $fields = new FieldSet($leftFields, $rightFields); // 4) Terms and conditions field // If a terms and conditions page exists, we need to create a field to confirm the user has read it if ($controller->TermsPageID && ($termsPage = DataObject::get_by_id('Page', $controller->TermsPageID))) { $bottomFields = new CompositeField(new CheckboxField('ReadTermsAndConditions', "I agree to the terms and conditions stated on the <a href=\"{$termsPage->URLSegment}\" title=\"Read the shop terms and conditions for this site\">terms and conditions</a> page")); $bottomFields->setID('BottomOrder'); $fields->push($bottomFields); $requiredFields[] = 'ReadTermsAndConditions'; } // 5) Actions and required fields creation $actions = new FieldSet(new FormAction('processOrder', 'Place order and make payment')); $requiredFields = new CustomRequiredFields($requiredFields); // 6) Form construction parent::__construct($controller, $name, $fields, $actions, $requiredFields); // 7) Member details loading if ($member->ID) { $this->loadDataFrom($member); } // 8) Country field value update $currentOrder = ShoppingCart::current_order(); $currentOrderCountry = $currentOrder->findShippingCountry(true); $countryField->setValue($currentOrderCountry); }
/** * Return an instance of {@link ShoppingCart_Controller} * so that we can show a cart template across the site. * * @return object ShoppingCart object */ public function Cart() { $cart = new ShoppingCart_Controller(); $cart->init(); return $cart; }