/** * Automatically create a CheckoutPage if one is not found * on the site at the time the database is built (dev/build). */ function requireDefaultRecords() { parent::requireDefaultRecords(); if (!DataObject::get_one('CheckoutPage')) { $page = new CheckoutPage(); $page->Title = 'Checkout'; $page->Content = ''; $page->URLSegment = 'checkout'; $page->ShowInMenus = 0; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); DB::alteration_message('Checkout page \'Checkout\' created', 'created'); } }
/** * Get first step from stored steps */ public function index() { if (CheckoutPage::config()->first_step) { return $this->owner->{CheckoutPage::config()->first_step}(); } return array(); }
public function testFindLink() { $this->checkoutpage = $this->objFromFixture('CheckoutPage', 'checkout'); $this->checkoutpage->publish('Stage', 'Live'); $link = CheckoutPage::find_link(); $this->assertEquals(Director::baseURL() . 'checkout/', $link, 'find_link() returns the correct link to checkout.'); }
function redirect($status = "success", $message = "") { if (Director::is_ajax()) { return $status; //TODO: allow for custom return types, eg json - similar to ShoppingCart::return_data() } Director::redirect(CheckoutPage::find_link()); }
public function getPasswordFields() { $loginlink = "Security/login?BackURL=" . CheckoutPage::find_link(true); $fields = FieldList::create(HeaderField::create(_t('CheckoutField.MembershipDetails', 'Membership Details'), 3), LiteralField::create('MemberInfo', '<p class="message warning">' . _t('CheckoutField.MemberLoginInfo', 'If you are already a member please <a href="{LoginUrl}">log in</a>', '', array('LoginUrl' => $loginlink)) . '</p>'), LiteralField::create('AccountInfo', '<p>' . _t('CheckoutField.AccountInfo', 'Please choose a password, so you can login and check your order history in the future') . '</p>'), $pwf = $this->getPasswordField()); if (!Checkout::user_membership_required()) { $pwf->setCanBeEmpty(true); } return $fields; }
public function getPasswordFields() { $loginlink = "Security/login?BackURL=" . CheckoutPage::find_link(true); $fields = FieldList::create(HeaderField::create(_t('CheckoutField.MEMBERSHIPDETAILS', 'Membership Details'), 3), LiteralField::create('MemberInfo', '<p class="message warning">' . _t('CheckoutField.MEMBERINFO', 'If you are already a member please') . " <a href=\"{$loginlink}\">" . _t('OrderForm.LogIn', 'log in') . '</a>.' . '</p>'), LiteralField::create('AccountInfo', '<p>' . _t('CheckoutField.ACCOUNTINFO', 'Please choose a password, so you can login and check your order history in the future') . '</p>'), $this->getPasswordField()); if (!Checkout::user_membership_required()) { $pwf->setCanBeEmpty(true); } return $fields; }
public function getCMSFields() { $fields = parent::getCMSFields(); if ($checkouts = CheckoutPage::get()) { $fields->addFieldToTab('Root.Links', DropdownField::create('CheckoutPageID', _t('CartPage.has_one_CheckoutPage', 'Checkout Page'), $checkouts->map("ID", "Title"))); } $fields->addFieldToTab('Root.Links', TreeDropdownField::create('ContinuePageID', _t('CartPage.has_one_ContinuePage', 'Continue Shopping Page'), 'SiteTree')); return $fields; }
public function getCMSFields() { $fields = parent::getCMSFields(); if ($checkouts = CheckoutPage::get()) { $fields->addFieldToTab('Root.Links', DropdownField::create('CheckoutPageID', _t('CartPage.has_one_CheckoutPage', 'Checkout Page'), $checkouts->map("ID", "Title"))); } if ($pgroups = ProductCategory::get()) { $fields->addFieldToTab('Root.Links', DropdownField::create('ContinuePageID', _t('CartPage.has_one_ContinuePage', 'Continue Product Group Page'), $pgroups->map("ID", "Title"))); } return $fields; }
function testFindLink() { $link = CheckoutPage::find_link(); $this->assertEquals(Director::baseURL() . 'checkout/', $link, 'find_link() returns the correct link to checkout.'); /* If there is no checkout page, then an exception is thrown */ $page = DataObject::get_one('CheckoutPage'); $page->delete(); $page->flushCache(); $this->setExpectedException('Exception'); $link = CheckoutPage::find_link(); }
/** * Save the changes to the form, and redirect to the checkout page */ function proceed($data, $form, $request) { $member = Member::currentUser(); if (!$member) { return false; } $form->saveInto($member); $member->write(); $form->sessionMessage(_t("MemberForm.DETAILSSAVED", 'Your details have been saved'), 'good'); Director::redirect(CheckoutPage::find_link()); return true; }
/** * Save the changes to the form, and redirect to the checkout page * * @param array $data * @param Form $form * @param SS_HTTPRequest $request * * @return bool|SS_HTTPResponse */ public function proceed($data, $form, $request) { $member = Member::currentUser(); if (!$member) { return false; } $form->saveInto($member); $member->write(); $form->sessionMessage(_t("MemberForm.DetailsSaved", 'Your details have been saved'), 'good'); $this->extend('updateShopAccountFormResponse', $request, $form, $data, $response); return $response ?: $this->getController()->redirect(CheckoutPage::find_link()); }
/** * @param string $template * @param string $subject * * @return Email */ private function buildEmail($template, $subject) { $from = ShopConfig::config()->email_from ? ShopConfig::config()->email_from : Email::config()->admin_email; $to = $this->order->getLatestEmail(); $checkoutpage = CheckoutPage::get()->first(); $completemessage = $checkoutpage ? $checkoutpage->PurchaseComplete : ''; $email = Email::create(); $email->setTemplate($template); $email->setFrom($from); $email->setTo($to); $email->setSubject($subject); $email->populateTemplate(array('PurchaseCompleteMessage' => $completemessage, 'Order' => $this->order, 'BaseURL' => Director::absoluteBaseURL())); return $email; }
/** * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function claim(SS_HTTPRequest $request) { /** @var Order $order */ $order = Order::get()->byID($request->param('ID')); $hash = $request->param('OtherID'); $realHash = FollowUpEmail::generate_hash($order); if (!$order || !$order->exists() || empty($hash) || $hash !== $realHash) { $this->httpError(404); } // Require a login if the order is attached to an account if ($order->MemberID && $order->MemberID != Member::currentUserID()) { return Security::permissionFailure($this->owner, _t('ShopEmail.NotYourOrder', 'You must log in to access this order.')); } // Otherwise if all is good, proceed to checkout ShoppingCart::singleton()->setCurrent($order); return $this->redirect(CheckoutPage::get()->first()->Link()); }
/** * Send a mail of the order to the client (and another to the admin). * * @param $template - the class name of the email you wish to send * @param $subject - subject of the email * @param $copyToAdmin - true by default, whether it should send a copy to the admin */ public function sendEmail($template, $subject, $copyToAdmin = true) { $from = ShopConfig::config()->email_from ? ShopConfig::config()->email_from : Email::config()->admin_email; $to = $this->order->getLatestEmail(); $checkoutpage = CheckoutPage::get()->first(); $completemessage = $checkoutpage ? $checkoutpage->PurchaseComplete : ""; $email = new Email(); $email->setTemplate($template); $email->setFrom($from); $email->setTo($to); $email->setSubject($subject); if ($copyToAdmin) { $email->setBcc(Email::config()->admin_email); } $email->populateTemplate(array('PurchaseCompleteMessage' => $completemessage, 'Order' => $this->order, 'BaseURL' => Director::absoluteBaseURL())); return $email->send(); }
public function run($request) { $cart = ShoppingCart::singleton(); $count = $request->getVar('count') ? $request->getVar('count') : 5; if ($products = Versioned::get_by_stage("Product", "Live", "", "RAND()", "", $count)) { foreach ($products as $product) { $variations = $product->Variations(); if ($variations->exists()) { $product = $variations->sort("RAND()")->first(); } $quantity = (int) rand(1, 5); if ($product->canPurchase(Member::currentUser(), $quantity)) { $cart->add($product, $quantity); } } } Controller::curr()->redirect(CheckoutPage::find_link()); }
public function getCheckoutLink() { return CheckoutPage::find_link(); }
/** * Ensures member unique id stays unique and other basic stuff... * @param array $data = Form Data * @return Boolean */ function php($data) { $valid = parent::php($data); $checkoutPage = CheckoutPage::get()->First(); if ($checkoutPage && $checkoutPage->TermsAndConditionsMessage) { if (isset($data["ReadTermsAndConditions"])) { if (!$data["ReadTermsAndConditions"]) { $this->validationError("ReadTermsAndConditions", $checkoutPage->TermsAndConditionsMessage, "required"); $valid = false; } } } $order = ShoppingCart::current_order(); if (!$order) { $this->validationError("Order", _t("OrderForm.ORDERNOTFOUND", "There was an error in processing your order, please try again or contact the administrator."), "required"); $valid = false; } $billingAddress = BillingAddress::get()->byID($order->BillingAddressID); if (!$billingAddress) { $this->validationError("BillingAddress", _t("OrderForm.MUSTHAVEBILLINGADDRESS", "All orders must have a billing address, please go back and add your details."), "required"); $valid = false; } return $valid; }
function run($request) { $update = array(); // ACCOUNT PAGE $accountPage = DataObject::get_one('AccountPage'); if (!$accountPage) { $accountPage = new AccountPage(); $accountPage->Title = 'Account'; $accountPage->MenuTitle = 'Account'; $accountPage->MetaTitle = 'Account'; $accountPage->Content = '<p>This is the account page. It is used for shop users to login and change their member details if they have an account.</p>'; $accountPage->URLSegment = 'account'; $accountPage->ShowInMenus = 0; $accountPage->writeToStage('Stage'); $accountPage->publish('Stage', 'Live'); DB::alteration_message('Account page \'Account\' created', 'created'); } else { DB::alteration_message('No need to create an account page, it already exists.'); } //CHECKOUT PAGE //CHECKOUT PAGE $checkoutPage = DataObject::get_one('CheckoutPage'); if (!$checkoutPage) { $checkoutPage = new CheckoutPage(); $checkoutPage->Content = '<p>This is the checkout page. You can edit all the messages in the Content Management System.</p>'; $checkoutPage->Title = 'Checkout'; $checkoutPage->TermsAndConditionsMessage = 'You must agree with the terms and conditions to proceed. '; $checkoutPage->MetaTitle = 'Checkout'; $checkoutPage->MenuTitle = 'Checkout'; $checkoutPage->URLSegment = 'checkout'; $update[] = 'Checkout page \'Checkout\' created'; $checkoutPage->ShowInMenus = 0; DB::alteration_message('new checkout page created.', 'created'); } else { DB::alteration_message('No need to create an checkout page, it already exists.'); } if ($checkoutPage) { if ($checkoutPage->TermsPageID == 0 && ($termsPage = DataObject::get_one('Page', "\"URLSegment\" = 'terms-and-conditions'"))) { $checkoutPage->TermsPageID = $termsPage->ID; DB::alteration_message('terms and conditions page linked.', "created"); } else { DB::alteration_message('No terms and conditions page linked.'); } $checkoutPage->writeToStage('Stage'); $checkoutPage->publish('Stage', 'Live'); DB::alteration_message('Checkout page saved'); if (!DataObject::get_one('OrderConfirmationPage')) { $orderConfirmationPage = new OrderConfirmationPage(); $orderConfirmationPage->ParentID = $checkoutPage->ID; $orderConfirmationPage->Title = 'Order confirmation'; $orderConfirmationPage->MenuTitle = 'Order confirmation'; $orderConfirmationPage->MetaTitle = 'Order confirmation'; $orderConfirmationPage->Content = '<p>This is the order confirmation page. It is used to confirm orders after they have been placed in the checkout page.</p>'; $orderConfirmationPage->URLSegment = 'order-confirmation'; $orderConfirmationPage->ShowInMenus = 0; $orderConfirmationPage->writeToStage('Stage'); $orderConfirmationPage->publish('Stage', 'Live'); DB::alteration_message('Order Confirmation created', 'created'); } else { DB::alteration_message('No need to create an Order Confirmation Page. It already exists.'); } } $update = array(); $ecommerceConfig = EcommerceDBConfig::current_ecommerce_db_config(); if ($ecommerceConfig) { if (!$ecommerceConfig->ReceiptEmail) { $ecommerceConfig->ReceiptEmail = Email::getAdminEmail(); if (!$ecommerceConfig->ReceiptEmail) { user_error("you must set an AdminEmail (Email::setAdminEmail)", E_USER_NOTICE); } $update[] = "created default entry for ReceiptEmail"; } if (!$ecommerceConfig->NumberOfProductsPerPage) { $ecommerceConfig->NumberOfProductsPerPage = 12; $update[] = "created default entry for NumberOfProductsPerPage"; } if (count($update)) { $ecommerceConfig->write(); DB::alteration_message($ecommerceConfig->ClassName . " created/updated: " . implode(" --- ", $update), 'created'); } } }
/** * * @return String (URLSegment) **/ function CheckoutLink() { return CheckoutPage::find_link(); }
static function get_login_invite_alternative_text() { return str_replace("Security/login/", "Security/login/?BackURL=/" . CheckoutPage::find_link(true), self::$login_invite_alternative_text); }
/** * Process the items in the shopping cart from session, * creating a new {@link Order} record, and updating the * customer's details {@link Member} record. * * {@link Payment} instance is created, linked to the order, * and payment is processed {@link Payment::processPayment()} * * @param array $data Form request data submitted from OrderForm * @param Form $form Form object for this action * @param HTTPRequest $request Request object for this action */ function saveAddress(array $data, Form $form, SS_HTTPRequest $request) { Session::set("BillingEcommerceGeocodingFieldValue", empty($data["BillingEcommerceGeocodingField"]) ? null : $data["BillingEcommerceGeocodingField"]); Session::set("ShippingEcommerceGeocodingFieldValue", empty($data["ShippingEcommerceGeocodingField"]) ? null : $data["ShippingEcommerceGeocodingField"]); $data = Convert::raw2sql($data); //check for cart items if (!$this->order) { $form->sessionMessage(_t('OrderForm.ORDERNOTFOUND', 'Your order could not be found.'), 'bad'); $this->controller->redirectBack(); return false; } if ($this->order && $this->order->TotalItems($recalculate = true) < 1) { // WE DO NOT NEED THE THING BELOW BECAUSE IT IS ALREADY IN THE TEMPLATE AND IT CAN LEAD TO SHOWING ORDER WITH ITEMS AND MESSAGE $form->sessionMessage(_t('OrderForm.NOITEMSINCART', 'Please add some items to your cart.'), 'bad'); $this->controller->redirectBack(); return false; } //----------- START BY SAVING INTO ORDER $form->saveInto($this->order); //----------- -------------------------------- //MEMBER $this->orderMember = $this->createOrFindMember($data); if ($this->orderMember && is_object($this->orderMember)) { if ($this->memberShouldBeSaved($data)) { $form->saveInto($this->orderMember); $password = $this->validPasswordHasBeenEntered($data); if ($password) { $this->orderMember->changePassword($password); } $this->orderMember->write(); } if ($this->memberShouldBeLoggedIn($data)) { $this->orderMember->LogIn(); } //this causes ERRORS .... //$this->order->MemberID = $this->orderMember->ID; Session::set("Ecommerce_Member_For_Order", $this->orderMember->ID); } //BILLING ADDRESS if ($billingAddress = $this->order->CreateOrReturnExistingAddress("BillingAddress")) { $form->saveInto($billingAddress); // NOTE: write should return the new ID of the object $this->order->BillingAddressID = $billingAddress->write(); } // SHIPPING ADDRESS if (isset($data['UseShippingAddress'])) { if ($data['UseShippingAddress']) { if ($shippingAddress = $this->order->CreateOrReturnExistingAddress("ShippingAddress")) { $form->saveInto($shippingAddress); // NOTE: write should return the new ID of the object $this->order->ShippingAddressID = $shippingAddress->write(); } } } $this->extend("saveAddressExtension", $data, $form, $order, $this->orderMember); //SAVE ORDER $this->order->write(); //----------------- CLEAR OLD DATA ------------------------------ $this->clearSessionData(); //clears the stored session form data that might have been needed if validation failed //----------------------------------------------- $nextStepLink = CheckoutPage::find_next_step_link("orderformaddress"); $this->controller->redirect($nextStepLink); return true; }
/** * Save the changes to the form, and redirect to the checkout page * @return Boolean + redirection */ function proceed($data, $form, $request) { return $this->processForm($data, $form, $request, CheckoutPage::find_link()); }
/** * work out the options for the user **/ protected function workOutMessagesAndActions() { if (!$this->workedOutMessagesAndActions) { $this->actionLinks = new ArrayList(array()); //what order are we viewing? $viewingRealCurrentOrder = $this->CurrentOrderIsInCart(); $currentUserID = Member::currentUserID(); //Continue Shopping if (isset($this->ContinueShoppingLabel) && $this->ContinueShoppingLabel) { if ($viewingRealCurrentOrder) { if ($this->isCartPage()) { $continueLink = $this->ContinueShoppingLink(); if ($continueLink) { $this->actionLinks->push(new ArrayData(array("Title" => $this->ContinueShoppingLabel, "Link" => $continueLink))); } } } } //Proceed To CheckoutLabel if (isset($this->ProceedToCheckoutLabel) && $this->ProceedToCheckoutLabel) { if ($viewingRealCurrentOrder) { if ($this->isCartPage()) { $checkoutPageLink = CheckoutPage::find_link(); if ($checkoutPageLink && $this->currentOrder && $this->currentOrder->getTotalItems()) { $this->actionLinks->push(new ArrayData(array("Title" => $this->ProceedToCheckoutLabel, "Link" => $checkoutPageLink))); } } } } //view account details if (isset($this->ShowAccountLabel) && $this->ShowAccountLabel) { if ($this->isOrderConfirmationPage() || $this->isCartPage()) { if (AccountPage::find_link()) { if ($currentUserID) { $this->actionLinks->push(new ArrayData(array("Title" => $this->ShowAccountLabel, "Link" => AccountPage::find_link()))); } } } } //go to current order if (isset($this->CurrentOrderLinkLabel) && $this->CurrentOrderLinkLabel) { if ($this->isCartPage()) { if (!$viewingRealCurrentOrder) { $this->actionLinks->push(new ArrayData(array("Title" => $this->CurrentOrderLinkLabel, "Link" => ShoppingCart::current_order()->Link()))); } } } //Save order - we assume only current ones can be saved. if (isset($this->SaveOrderLinkLabel) && $this->SaveOrderLinkLabel) { if ($viewingRealCurrentOrder) { if ($currentUserID && $this->currentOrder->MemberID == $currentUserID) { if ($this->isCartPage()) { if ($this->currentOrder && $this->currentOrder->getTotalItems() && !$this->currentOrder->IsSubmitted()) { $this->actionLinks->push(new ArrayData(array("Title" => $this->SaveOrderLinkLabel, "Link" => $this->Link("saveorder") . "/" . $this->currentOrder->ID . "/"))); } } } } } //load order if (isset($this->LoadOrderLinkLabel) && $this->LoadOrderLinkLabel) { if ($this->isCartPage() && $this->currentOrder) { if (!$viewingRealCurrentOrder) { $this->actionLinks->push(new ArrayData(array("Title" => $this->LoadOrderLinkLabel, "Link" => $this->Link("loadorder") . "/" . $this->currentOrder->ID . "/"))); } } } //delete order if (isset($this->DeleteOrderLinkLabel) && $this->DeleteOrderLinkLabel) { if ($this->isCartPage() && $this->currentOrder) { if (!$viewingRealCurrentOrder) { $this->actionLinks->push(new ArrayData(array("Title" => $this->DeleteOrderLinkLabel, "Link" => $this->Link("deleteorder") . "/" . $this->currentOrder->ID . "/"))); } } } //Start new order //Strictly speaking this is only part of the //OrderConfirmationPage but we put it here for simplicity's sake if (isset($this->StartNewOrderLinkLabel) && $this->StartNewOrderLinkLabel) { if ($this->isOrderConfirmationPage()) { $this->actionLinks->push(new ArrayData(array("Title" => $this->StartNewOrderLinkLabel, "Link" => CartPage::new_order_link($this->currentOrder->ID)))); } } //copy order //Strictly speaking this is only part of the //OrderConfirmationPage but we put it here for simplicity's sake if (isset($this->CopyOrderLinkLabel) && $this->CopyOrderLinkLabel) { if ($this->isOrderConfirmationPage() && $this->currentOrder->ID) { $this->actionLinks->push(new ArrayData(array("Title" => $this->CopyOrderLinkLabel, "Link" => OrderConfirmationPage::copy_order_link($this->currentOrder->ID)))); } } //actions from modifiers if ($this->isOrderConfirmationPage() && $this->currentOrder->ID) { $modifiers = $this->currentOrder->Modifiers(); if ($modifiers->count()) { foreach ($modifiers as $modifier) { $array = $modifier->PostSubmitAction(); if (is_array($array) && count($array)) { $this->actionLinks->push(new ArrayData($array)); } } } } //log out //Strictly speaking this is only part of the //OrderConfirmationPage but we put it here for simplicity's sake if (Member::currentUser()) { if ($this->isOrderConfirmationPage()) { $this->actionLinks->push(new ArrayData(array("Title" => _t("CartPage.LOGOUT", "log out"), "Link" => "/Security/logout/"))); } } //no items if ($this->currentOrder) { if (!$this->currentOrder->getTotalItems()) { $this->message = $this->NoItemsInOrderMessage; } } else { $this->message = $this->NonExistingOrderMessage; } $this->workedOutMessagesAndActions = true; //does nothing at present.... } }
function __construct($controller, $name) { //requirements Requirements::javascript('ecommerce/javascript/EcomOrderForm.js'); //set basics $order = ShoppingCart::current_order(); $order->calculateOrderAttributes($force = true); $requiredFields = array(); // ________________ 3) Payment fields - BOTTOM FIELDS $bottomFields = new CompositeField(); $bottomFields->setID('BottomOrder'); $totalAsCurrencyObject = $order->TotalAsCurrencyObject(); //should instead be $totalobj = $order->dbObject('Total'); $totalOutstandingAsMoneyObject = $order->TotalAsMoneyObject(); $paymentFields = Payment::combined_form_fields($totalOutstandingAsMoneyObject->Nice()); foreach ($paymentFields as $paymentField) { if ($paymentField->class == "HeaderField") { $paymentField->setTitle(_t("OrderForm.MAKEPAYMENT", "Choose Payment")); } $bottomFields->push($paymentField); } if ($paymentRequiredFields = Payment::combined_form_requirements()) { $requiredFields = array_merge($requiredFields, $paymentRequiredFields); } // ________________ 4) FINAL FIELDS $finalFields = new CompositeField(); $finalFields->setID('FinalFields'); $finalFields->push(new HeaderField('CompleteOrder', _t('OrderForm.COMPLETEORDER', 'Complete Order'), 3)); // If a terms and conditions page exists, we need to create a field to confirm the user has read it if ($termsAndConditionsPage = CheckoutPage::find_terms_and_conditions_page()) { $checkoutPage = DataObject::get_one("CheckoutPage"); if ($checkoutPage && $checkoutPage->TermsAndConditionsMessage) { $alreadyTicked = false; $requiredFields[] = 'ReadTermsAndConditions'; } else { $alreadyTicked = true; } $finalFields->push(new CheckboxField('ReadTermsAndConditions', _t('OrderForm.AGREEWITHTERMS1', 'I have read and agree with the ') . ' <a href="' . $termsAndConditionsPage->Link() . '">' . Convert::raw2xml($termsAndConditionsPage->Title) . '</a>' . _t('OrderForm.AGREEWITHTERMS2', '.'), $alreadyTicked)); } $finalFields->push(new TextareaField('CustomerOrderNote', _t('OrderForm.CUSTOMERNOTE', 'Note / Question'), 7, 30)); // ________________ 5) Put all the fields in one FieldSet $fields = new FieldSet($bottomFields, $finalFields); // ________________ 6) Actions and required fields creation + Final Form construction $actions = new FieldSet(new FormAction('processOrder', _t('OrderForm.PROCESSORDER', 'Place order and make payment'))); $validator = new OrderForm_Validator($requiredFields); //we stick with standard validation here, because of the complexity and //hard-coded payment validation that is required $validator->setJavascriptValidationHandler("prototype"); parent::__construct($controller, $name, $fields, $actions, $validator); //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', $validator) !== null) { $this->setValidator($validator); } // ________________ 7) Load saved data if ($order) { $this->loadDataFrom($order); } //allow updating via decoration $this->extend('updateOrderForm', $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); }
/** * returns the link to finalise the Order * @return String(URLSegment) */ function CheckoutLink() { $page = CheckoutPage::get()->First(); if ($page) { return $page->Link(); } else { $page = ErrorPage::get()->Filter(array("ErrorCode" => '404'))->First(); if ($page) { return $page->Link(); } } }
/** * * @return String */ function AddToCartAndGoToCheckoutLink() { $array = $this->linkParameters(); $array["BackURL"] = urlencode(CheckoutPage::find_link()); return ShoppingCart_Controller::add_item_link($this->ID, $this->ClassName, $array); }
/** * Get the link for finishing order processing. */ public function Link() { if (Member::currentUser()) { return Controller::join_links(AccountPage::find_link(), 'order', $this->ID); } return CheckoutPage::find_link(false, "order", $this->ID); }
function checkoutAndModifierDetails() { $checkoutPage = CheckoutPage::get()->First(); if (!$checkoutPage) { $task = new EcommerceTaskDefaultRecords(); $task->run(null); $checkoutPage = CheckoutPage::get()->First(); if (!$checkoutPage) { user_error("There is no checkout page available and it seems impossible to create one."); } } $steps = CheckoutPage_StepDescription::get(); if ($steps->count()) { foreach ($steps as $key => $step) { $stepNumber = $key + 1; $fields = Config::inst()->get($step->ClassName, "db"); $defaultsArray = $step->stat("defaults", true); $configArray = array(); foreach ($fields as $fieldKey => $fieldType) { if ($fields) { $configArray[$fieldKey] = $step->{$fieldKey}; if (!isset($defaultsArray[$fieldKey])) { $defaultsArray[$fieldKey] = "[default not set]"; } } } $this->definitions["CheckoutPage_Controller"]["STEP_{$stepNumber}" . "_" . $step->getCode()] = $step->Description . "<br />see: <a href=\"/admin/pages/edit/show/" . $checkoutPage->ID . "/\">checkout page</a>."; $this->configs["CheckoutPage_Controller"]["STEP_{$stepNumber}" . "_" . $step->getCode()] = $configArray; $this->defaults["CheckoutPage_Controller"]["STEP_{$stepNumber}" . "_" . $step->getCode()] = $defaultsArray; $this->databaseValues["CheckoutPage_Controller"]["STEP_{$stepNumber}" . "_" . $step->getCode()] = true; } } $steps = OrderModifier_Descriptor::get(); if ($steps->count()) { foreach ($steps as $step) { $fields = Config::inst()->get($step->ClassName, "db"); $defaultsArray = $step->stat("defaults", true); $configArray = array(); foreach ($fields as $fieldKey => $fieldType) { if ($fields) { $configArray[$fieldKey] = $step->{$fieldKey}; if (!isset($defaultsArray[$fieldKey])) { $defaultsArray[$fieldKey] = "[default not set]"; } } } $this->definitions["CheckoutPage_Controller"]["OrderModifier_Descriptor_" . $step->ModifierClassName] = $step->Description . "<br />see: <a href=\"/admin/pages/edit/show/" . $checkoutPage->ID . "/\">checkout page</a>."; $this->configs["CheckoutPage_Controller"]["OrderModifier_Descriptor_" . $step->ModifierClassName] = $configArray; $this->defaults["CheckoutPage_Controller"]["OrderModifier_Descriptor_" . $step->ModifierClassName] = $defaultsArray; $this->databaseValues["CheckoutPage_Controller"]["OrderModifier_Descriptor_" . $step->ModifierClassName] = true; } } }
function doAddNewPriceForm($data, $form) { $amount = $this->parseFloat($data["Amount"]); if ($this->MinimumAmount && $amount < $this->MinimumAmount) { $form->sessionMessage(_t("AnyPriceProductPage.ERRORINFORMTOOLOW", "Please enter a higher amount."), "bad"); $this->redirectBack(); return; } elseif ($this->MaximumAmount && $amount > $this->MaximumAmount) { $form->sessionMessage(_t("AnyPriceProductPage.ERRORINFORMTOOHIGH", "Please enter a lower amount."), "bad"); $this->redirectBack(); return; } Session::clear("AnyPriceProductPageAmount"); $obj = AnyPriceProductPage_ProductVariation::get()->filter(array("ProductID" => $this->ID, "Price" => $amount))->First(); //create new one if needed if (!$obj) { Currency::setCurrencySymbol(EcommercePayment::site_currency()); $titleDescriptor = new Currency("titleDescriptor"); $titleDescriptor->setValue($amount); $obj = new AnyPriceProductPage_ProductVariation(); $obj->Title = _t("AnyPriceProductPage.PAYMENTFOR", "Payment for: ") . $titleDescriptor->Nice(); $obj->Price = $amount; $obj->AllowPurchase = true; $obj->ProductID = $this->ID; $obj->write("Stage"); // line below does not work - suspected bug in framework Versioning System //$componentSet->add($obj); } //check if we have one now if (!$obj) { $obj = AnyPriceProductPage_ProductVariation::get()->filter(array("ProductID" => $this->ID, "Price" => $amount))->First(); } if ($obj) { $shoppingCart = ShoppingCart::singleton(); $shoppingCart->addBuyable($obj); } else { $form->sessionMessage(_t("AnyPriceProductPage.ERROROTHER", "Sorry, we could not add our entry."), "bad"); $this->redirectBack(); return; } $checkoutPage = CheckoutPage::get()->First(); if ($checkoutPage) { $this->redirect($checkoutPage->Link()); } return; }