Action that will update cart

@param type $data
@param type $form
2272
public function doUpdate($data, $form)
    {
        try {
            foreach ($this->Items() as $item) {
                foreach ($data as $key => $value) {
                    $sliced_key = explode("_", $key);
                    if ($sliced_key[0] == "Quantity") {
                        if (isset($item) && ($item->Key == $sliced_key[1])) {
                            if ($value > 0) {
                                ShoppingCartFactory::create()->updateItem(
                                    $item,
                                    $value
                                );
                            } else {
                                $item->delete();
                            }

                            $form->sessionMessage(
                                _t("ShoppingCart.UpdatedShoppingCart", "Shopping cart updated"),
                                ValidationResult::TYPE_GOOD
                            );
                        }
                    }
                }
            }
            ShoppingCartFactory::create()->save();
        } catch (ValidationException $e) {
            $form->sessionMessage(
                $e->getMessage()
            );
        } catch (Exception $e) {
            $form->sessionMessage(
                $e->getMessage()
            );
        }
        
        return $this->redirectBack();
    }
1202214
public function replacePage($data, Form $form) {
        //Start a transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionStart();
        }
        
        $destinationClass=$this->getDestinationClass();
        $destination=SiteTree::get()->byID(intval($data['ReplacePageID']));
        
        
        //Verify we have a destination class
        if(!empty($destination) && $destination!==false && $destination->exists() && is_subclass_of($destinationClass, 'SiteTree')) {
            //Ensure the classes are the same if they're not change and re-load
            if($destination->ClassName!=$destinationClass) {
                $destination->setClassName($destinationClass);
                $destination->write();
                $destination->flushCache();
                
                //Refetch the destination
                $destination=SiteTree::get()->byID(intval($data['ReplacePageID']));
            }
            
            $source=clone $this->record; //Create a clone of the record to be safe
            
            $recordTitle=$this->record->Title;
            $updateURLSegment=false;
            if(!empty($recordTitle) && $recordTitle!=$destination->Title && array_key_exists('UpdateURLSegment', $data) && $data['UpdateURLSegment']==true) {
                $updateURLSegment=true;
            }
            
            
            //Cache the url segment
            $oldURLSegment=$destination->URLSegment;
            
            //Merge the kapost object into the target page
            $this->merge($destination, $source, 'right', true, true);
            
            //Restore the url segment
            $destination->URLSegment=$oldURLSegment;
            
            
            //If the url segment is to be changed then update the url segment
            if($updateURLSegment) {
                $destination->URLSegment=$destination->generateURLSegment($destination->Title);
            }
            
            
            //Write the destination one more time to be sure
            $destination->write();
            
            
            //Allow extensions to update the object
            $this->extend('updateReplacePageConversion', $destination, $this->record, $data, $form);
            
            
            //If the kapost object is to be published publish it
            if($this->record->ToPublish==true) {
                $destination->publish('Stage', 'Live');
            }
            
            
            //Create the conversion history record
            $this->record->createConversionHistory($destination->ID);
            
            
            //Delete the current record
            $this->record->delete();
            
            
            //End the transaction if supported
            if(DB::getConn()->supportsTransactions()) {
                DB::getConn()->transactionEnd();
            }
            
            return 'admin/pages/edit/show/'.$destination->ID;
        }
        
        
        //Rollback the transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionRollback();
        }
        
        return false;
    }
887083
public function doSaveLink($data, Form $form)
    {
        $link = $this->getLinkObject() ? $this->getLinkObject() : Link::create();
        $form->saveInto($link);

        try {
            $link->write();
        } catch (ValidationException $e) {
            $form->sessionMessage($e->getMessage(), 'bad');

            return $form->forTemplate();
        }

        $this->setValue($link->ID);
        $this->setForm($form);

        return $this->FieldHolder();
    }
565823
public function doSave($data, $form)
    {
        $recordType = $this->getRecordType();
        $record = $recordType::create();
        $form->saveInto($record);
        $record->write();
        $this->redirect($this->Link());
    }
77008
public function updateEditAccountForm($form)
    {
        // Add company name field
        $company_field = TextField::create(
            "Company",
            _t('CheckoutUsers.Company', "Company")
        );
        $company_field->setRightTitle(_t("Checkout.Optional", "Optional"));
        $form->Fields()->insertBefore($company_field, "FirstName");

        // Add contact phone number field
        $phone_field = TextField::create(
            "PhoneNumber",
            _t("CheckoutUsers.PhoneNumber", "Phone Number")
        );
        $phone_field->setRightTitle(_t("Checkout.Optional", "Optional"));
        $form->Fields()->add($phone_field);
    }
101056
public function updateTransaction()
    {        
        $cart = $this->cartProvider->getCart();

        if (0 === $cart->countItems() || $this->isTransactionUpdated($cart)) {
            return;
        }

        /** @var TransactionRepository $transactionRepository */
        $transactionRepository = $this->manager->getRepository('EcommerceBundle:Transaction');

        if ($this->session->has('transaction-id')) {
            /** @var Transaction $transaction */
            $transaction = $transactionRepository->find($this->session->get('transaction-id'));

            $transactionRepository->removeItems($transaction);
        } else {
            $transactionKey = $transactionRepository->getNextNumber();

            // create a new transaction
            $transaction = new Transaction();
            $transaction->setTransactionKey($transactionKey);
            $transaction->setStatus(Transaction::STATUS_CREATED);
            $transaction->setActor($this->securityContext->getToken()->getUser());
            $cartItem = $cart->getItems()->first();
            $product = $cartItem->getProduct();
        }

        $orderTotalPrice = 0;

        foreach ($cart->getItems() as $cartItem) {
            /** @var Product $product */
            $product = $cartItem->getProduct();

            $productPurchase = new ProductPurchase();
            $productPurchase->setProduct($product);
            $productPurchase->setBasePrice($cartItem->getUnitPrice());
            $productPurchase->setQuantity($cartItem->getQuantity());
            $productPurchase->setDiscount($product->getDiscount());
            $productPurchase->setTotalPrice($cartItem->getTotal());
            $productPurchase->setTransaction($transaction);
            $productPurchase->setReturned(false);
            //free transport
            if($cartItem->isFreeTransport()){
                $productPurchase->setDeliveryExpenses(0);
            }else{ 
                $productPurchase->setDeliveryExpenses($cartItem->getShippingCost());
            }
            $orderTotalPrice += $cartItem->getProduct()->getPrice() * $cartItem->getQuantity();

            $this->manager->persist($productPurchase);
        }

        $transaction->setTotalPrice($orderTotalPrice);

        $this->manager->persist($transaction);
        $this->manager->flush();

        $this->session->set('transaction-id', $transaction->getId());
        $this->session->save();
        
    }
194877
public function save(array $data, Form $form)
    {
        $member = Member::currentUser();

        $groupIds = $this->getSettableGroupIdsFrom($form, $member);
        $member->Groups()->setByIDList($groupIds);

        $form->saveInto($member);

        try {
            $member->write();
        } catch (ValidationException $e) {
            $validationMessages = implode("; ", $e->getResult()->getMessages());
            $form->sessionMessage($validationMessages, 'bad');
            return $this->redirectBack();
        }

        $form->sessionMessage(
            _t('MemberProfiles.PROFILEUPDATED', 'Your profile has been updated.'),
            'good'
        );
        return $this->redirectBack();
    }
270944
public function updateworkflow($data, Form $form, $request)
    {
        /** @var WorkflowService $service */
        $service = singleton(WorkflowService::class);
        /** @var DataObject $record */
        $record = $form->getRecord();
        $workflow = $service->getWorkflowFor($record);
        if (!$workflow) {
            return null;
        }

        $action = $workflow->CurrentAction();

        if (!$record || !$record->canEditWorkflow()) {
            return null;
        }

        $allowedFields = $workflow->getWorkflowFields()->saveableFields();
        unset($allowedFields['TransitionID']);

        $allowed = array_keys($allowedFields);
        if (count($allowed)) {
            $form->saveInto($action, $allowed);
            $action->write();
        }

        if (isset($data['TransitionID']) && $data['TransitionID']) {
            $service->executeTransition($record, $data['TransitionID']);
        } else {
            // otherwise, just try to execute the current workflow to see if it
            // can now proceed based on user input
            $workflow->execute();
        }

        return $this->returnResponse($form);
    }
1209512
public function doNew($data, $form)
    {
        return $this->redirect(Controller::join_links($this->gridField->Link('item'), 'new'));
    }
243124
private function updateCart(FormStateInterface $form_state) {
    try {
      $cart = $this->cartStorage->updateCart();
      $response_message = $cart->get('response_message');
      // We will have type of message like error or success. key '0' contains
      // the response message string while key '1' contains the response
      // message context/type like success or coupon.
      if (!empty($response_message[1])) {
        // If its success.
        if ($response_message[1] == 'success') {
          $this->successMessage = $response_message[0];
        }
        elseif ($response_message[1] == 'error_coupon') {
          // Set the error and require rebuild.
          $form_state->setErrorByName('coupon', $response_message[0]);
          $form_state->setRebuild(TRUE);

          // Remove the coupon and update the cart.
          $this->cartStorage->setCoupon('');
          $this->updateCart($form_state);
        }
      }
    }
    catch (\Exception $e) {
      if (acm_is_exception_api_down_exception($e)) {
        $this->messenger()->addError($e->getMessage());
        $form_state->setErrorByName('custom', $e->getMessage());
        $form_state->setRebuild(TRUE);
      }

      // Dispatch event so action can be taken.
      $dispatcher = \Drupal::service('event_dispatcher');
      $event = new UpdateCartErrorEvent($e);
      $dispatcher->dispatch(UpdateCartErrorEvent::SUBMIT, $event);
      $this->messenger()->addError($e->getMessage());
    }
  }
470870
protected function updateErrorBox(Form $form, $errors)
    {
        foreach ($form->getChildrenByType('\\Zepi\\Web\\UserInterface\\Form\\ErrorBox', true) as $errorBox) {
            $errorBox->updateErrorBox($form, false, $errors);
        }
    }
1006090
public function doAddNew($data, $form)
    {
        $obj = Object::create($this->addNewClass);
        if (!$obj->canCreate()) {
            return Security::permissionFailure(Controller::curr(), "You don't have permission to create this object");
        }
        $form->saveInto($obj);

        try {
            $obj->write();
        } catch (Exception $e) {
            $form->setMessage($e->getMessage(), 'error');
            return $form->forTemplate();
        }

        $callback = $this->sourceCallback;
        $items = $callback($obj);
        $this->owner->setSource($items);

        // if this field is a multiselect field, we add the new Object ID to the existing
        // options that are selected on the field then set that as the value
        // otherwise we just set the new Object ID as the value
        if (isset($data['existing'])) {
            $existing = $data['existing'];
            $value = explode(',', $existing);
            $value[] = $obj->ID;
        } else {
            $value = $obj->ID;
        }

        $this->owner->setValue($value);
        // NOTE(Jake): Below line causes cyclic issues, I assume it's not necessary.
        //$this->owner->setForm($form);
        return $this->owner->FieldHolder();
    }
335116
public function doConvertObject($data, Form $form) {
        //Make sure the record still exists
        if(empty($this->record) || $this->record===false || !$this->record->exists()) {
            return $this->httpError(404);
        }
        
        if($data['ConvertMode']=='ReplacePage') {
            if(empty($data['ReplacePageID']) || $data['ReplacePageID']==0) {
                $form->sessionMessage(_t('KapostAdmin.NO_REPLACE_PAGE_TARGET', '_You must select a page to replace'), 'error');
                return $this->popupController->redirectBack();
            }
            
            
            try {
                $redirectURL=$this->replacePage($data, $form);
            }catch(ValidationException $e) {
                //Catch any validation exception and return it as an error message on the form
                $form->sessionMessage($e->getMessage(), 'error');
                return $this->popupController->redirectBack();
            }
            
            if($redirectURL===false) {
                $form->sessionMessage(_t('KapostAdmin.ERROR_COULD_NOT_REPLACE', '_Sorry an error occured and the target page could not be replaced.'), 'error');
                return $this->popupController->redirectBack();
            }else {
                Requirements::clear();
                Requirements::customScript('window.parent.jQuery(\'.cms-edit-form.KapostAdmin\').entwine(\'ss\').panelRedirect('.json_encode($redirectURL).')');
                
                //Clean up the expired previews
                $this->cleanUpExpiredPreviews();
                
                return $this->customise(array(
                                            'Title'=>null,
                                            'Content'=>null,
                                            'Form'=>null
                                        ))->renderWith('CMSDialog');
            }
        }else if($data['ConvertMode']=='NewPage') {
            try {
                $redirectURL=$this->newPage($data, $form);
            }catch(ValidationException $e) {
                //Catch any validation exception and return it as an error message on the form
                $form->sessionMessage($e->getMessage(), 'error');
                return $this->popupController->redirectBack();
            }
            
            if($redirectURL===false) {
                $form->sessionMessage(_t('KapostAdmin.ERROR_COULD_NOT_CREATE', '_Sorry an error occured and the page could not be created.'), 'error');
                return $this->popupController->redirectBack();
            }else {
                Requirements::clear();
                Requirements::customScript('window.parent.jQuery(\'.cms-edit-form.KapostAdmin\').entwine(\'ss\').panelRedirect('.json_encode($redirectURL).')');
                
                //Clean up the expired previews
                $this->cleanUpExpiredPreviews();
                
                return $this->customise(array(
                                            'Title'=>null,
                                            'Content'=>null,
                                            'Form'=>null
                                        ))->renderWith('CMSDialog');
            }
        }
        
        
        //Allow extensions to convert the object
        if(in_array($data['ConvertMode'], KapostAdmin::config()->extra_conversion_modes)) {
            try {
                $results=$this->extend('doConvert'.$data['ConvertMode'], $this->record, $data, $form);
            }catch(ValidationException $e) {
                //Catch any validation exception and return it as an error message on the form
                $form->sessionMessage($e->getMessage(), 'error');
                return $this->popupController->redirectBack();
            }
            
            if(count($results)>0) {
                foreach($results as $result) {
                    if($result!==false) {
                        Requirements::clear();
                        Requirements::customScript('window.parent.jQuery(\'.cms-edit-form.KapostAdmin\').entwine(\'ss\').panelRedirect('.json_encode($result).')');
                        
                        //Clean up the expired previews
                        $this->cleanUpExpiredPreviews();
                        
                        return $this->customise(array(
                                                    'Title'=>null,
                                                    'Content'=>null,
                                                    'Form'=>null
                                                ))->renderWith('CMSDialog');
                    }
                }
                
                
                $message=$form->Message();
                if(empty($message)) {
                    $form->sessionMessage(_t('KapostAdmin.GENERIC_CONVERSION_ERROR', '_Conversion method returns an error and no specific message'), 'error');
                }
                
                //All failed redirect back
                return $this->popupController->redirectBack();
            }
        }
        
        
        $form->sessionMessage(_t('KapostAdmin.UNKNOWN_CONVERSION_MODE', '_Unknown conversion mode: {mode}', array('mode'=>$data['ConvertMode'])), 'error');
        return $this->popupController->redirectBack();
    }
754305
protected function setFormDataRequestServicesCheckout($type)
    {
        $this->data_form["request_{$type}_methods"] = false;

        if (!empty($this->data_form["get_{$type}_methods"])
            || (!empty($this->data_form['order'][$type]) && !empty($this->data_form["has_dynamic_{$type}_methods"]))) {
            $this->data_form["show_{$type}_methods"] = true;
            $this->data_form["request_{$type}_methods"] = true;
        }
    }
1221180
public function setActionUrl(Form $form)
    {

        $current = explode('/', rtrim($this->urlProvider->currentUrl(), '/'));

        $lastSegment = array_pop($current);

        if (in_array($lastSegment, ['create','edit'])) {

            $parentUrl = implode('/', $current);

            $form->setAction($parentUrl);

        } else {
            $form->setAction($this->urlProvider->currentUrl());
        }

        if ($lastSegment == 'create') {
            $form->setVerb('post');
            return;
        }

        if($lastSegment == 'edit') {
            $form->setVerb('put');
            return;
        }

    }
817971
public function doSaveAndQuit($data, $form)
    {
        $this->save($data, $form);
        $controller = $this->getToplevelController();
        $controller->getResponse()->addHeader("X-Pjax", "Content");
        $controller->redirect($this->getBackLink());
    }
621443
public function updateSearchForm($form){
		if($this->modelIsMultiSitesAware()) {
			$managedSites = Multisites::inst()->sitesManagedByMember();

			$source = Site::get()->filter('ID', Multisites::inst()->sitesManagedByMember())->map('ID', 'Title')->toArray();
			$plural = singleton($this->owner->modelClass)->plural_name();
			if(count($source)){
				$activeSite = $this->getActiveSite();
				$form->Fields()->push(DropdownField::create(
					'SiteID', 
					"Site: ", 
					$source,
					$activeSite ? $activeSite->ID : null
				));
			}
		}
	}