Handles conversion of the current record
@param array $data Submitted Data
@param Form $form Submitting Form
@return mixed Returns an SS_HTTPResponse or an HTML string
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();
    }
181378
public function doSaveAddress($data, $form)
    {
        if (!$data["ID"]) {
            $new = true;
            $address = ContactLocation::create();
        } else {
            $new = false;
            $address = ContactLocation::get()->byID($data["ID"]);
        }

        if ($address) {
            $form->saveInto($address);
            $address->write();
            $form->sessionMessage(
                _t("SilverCommerce\ContactAdmin.AddressSaved", "Address Saved"),
                ValidationResult::TYPE_GOOD
            );
        } else {
            $form->sessionMessage(
                _t("SilverCommerce\ContactAdmin.Error", "There was an error"),
                ValidationResult::TYPE_ERROR
            );
        }

        // If a new record, redirect to base, else redirect back to the edit form
        if ($new && !empty($address)) {
            return $this
                ->getOwner()
                ->redirect(
                    Controller::join_links(
                        $this->getOwner()->Link("editaddress"),
                        $address->ID
                    )
                );
        } else {
            return $this
                ->getOwner()
                ->redirectBack();
        }
    }
65102
public function doRollback($data, $form)
    {
        $this->extend('onBeforeRollback', $data['ID'], $data['Version']);

        $id = (isset($data['ID'])) ? (int) $data['ID'] : null;
        $version = (isset($data['Version'])) ? (int) $data['Version'] : null;

        /** @var DataObject|Versioned $record */
        $record = Versioned::get_latest_version($this->config()->get('tree_class'), $id);
        if ($record && !$record->canEdit()) {
            return Security::permissionFailure($this);
        }

        if ($version) {
            $record->doRollbackTo($version);
            $message = _t(
                __CLASS__ . '.ROLLEDBACKVERSIONv2',
                "Rolled back to version #{version}.",
                array('version' => $data['Version'])
            );
        } else {
            $record->doRevertToLive();
            $record->publishRecursive();
            $message = _t(
                __CLASS__ . '.ROLLEDBACKPUBv2',
                "Rolled back to published version."
            );
        }

        $this->getResponse()->addHeader('X-Status', rawurlencode($message));

        // Can be used in different contexts: In normal page edit view, in which case the redirect won't have any effect.
        // Or in history view, in which case a revert causes the CMS to re-load the edit view.
        // The X-Pjax header forces a "full" content refresh on redirect.
        $url = Controller::join_links(CMSPageEditController::singleton()->Link('show'), $record->ID);
        $this->getResponse()->addHeader('X-ControllerURL', $url);
        $this->getRequest()->addHeader('X-Pjax', 'Content');
        $this->getResponse()->addHeader('X-Pjax', 'Content');

        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
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();
    }
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;
    }
1235875
public function doSetPostage($data, $form)
    {
        $country = $data["Country"];
        $code = $data["ZipCode"];

        $this->setAvailablePostage($country, $code);
        
        $postage = Session::get("Checkout.AvailablePostage");

        // Check that postage is set, if not, see if we can set a default
        if (array_key_exists("PostageID", $data) && $data["PostageID"]) {
            
            // First is the current postage ID in the list of postage
            // areas
            if ($postage && $postage->exists() && $postage->find("ID", $data["PostageID"])) {
                $id = $data["PostageID"];
            } else {
                $id = $postage->first()->ID;
            }
                
            $data["PostageID"] = $id;
            Session::set("Checkout.PostageID", $id);
        } else {
            // Finally set the default postage
            if ($postage && $postage->exists()) {
                $data["PostageID"] = $postage->first()->ID;
                Session::set("Checkout.PostageID", $postage->first()->ID);
            }
        }

        // Set the form pre-populate data before redirecting
        Session::set("Form.{$form->FormName()}.data", $data);
        
        $url = Controller::join_links($this->Link(), "#{$form->FormName()}");

        return $this->redirect($url);
    }
49008
private function serializeForm(Form $form)
    {
        $result = $children = [];
        $errors = iterator_to_array($form->getErrors());

        foreach ($form as $child) {
            if ($child instanceof Form) {
                $children[$child->getName()] = $this->serializeForm($child);
            }
        }

        if (!empty($errors)) {
            $result['errors'] = $errors;
        }

        if (!empty($children)) {
            $result['children'] = $children;
        }

        return $result;
    }
1047367
public function doNext($data, $form)
    {
        $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
        $link = $this->getEditLink($this->getNextRecordID());
        return $this->redirect($link);
    }
294109
public function form(Form $form)
    {
        $tag = new Tag('form');
        $tag->setAttribute('action', $form->getAction());
        $tag->setAttribute('accept', $form->getAccept());
        $tag->setAttribute('accept-charset', $form->getAcceptCharset());
        $tag->setAttribute('enctype', $form->getEnctype());
        $tag->setAttribute('method', $form->getMethod());
        $tag->setAttribute('target', $form->getTarget());

        $html = $this->parseTag($tag, $form);

        $fields = $form->getFieldsByClass('HiddenField');

        if (sizeof($fields) > 0) {
            $html .= '<ins>' . PHP_EOL;

            foreach ($fields as $field) {
                // hidden fields
                $tag = new Tag('input');
                $tag->setAttribute('type', 'hidden');

                $html .= $this->parseTag($tag, $field) . PHP_EOL;
            }
            $html .= '</ins>' . PHP_EOL;
        }

        return $html;
    }
450911
public function onFakeSubmit(&$form, &$data) {
        if ($this->useMultiRowForm) {
            //Check if the insert button was pressed and act upon that
            if ($this->hasNew() && isset($data['insert_button']) && $data['insert_button']) {
                    // Add a row
                    $model          = $this->getModel();
                    $mname          = $model->getName();
                    $data[$mname][] = $model->loadNew();
            }
        }
    }
922296
protected function getRecordUpdatedResponse($record, $form)
    {
        // Return the record data in the same response as the schema to save a postback
        $schemaData = ['record' => $this->getObjectFromData($record)];
        $schemaId = Controller::join_links($this->Link('schema/fileEditForm'), $record->ID);
        return $this->getSchemaResponse($schemaId, $form, null, $schemaData);
    }
1147989
public static function form ($in = '', $data = []) {
		if (isset($in['insert']) || isset($data['insert'])) {
			return static::__callStatic_internal(__FUNCTION__, func_get_args());
		}
		if ($in === false) {
			return '';
		}
		if (is_array($in)) {
			return static::__callStatic_internal(__FUNCTION__, [$in, $data]);
		}
		if (isset($in['method'])) {
			$data['method'] = $in['method'];
		}
		if (!isset($data['method'])) {
			$data['method'] = 'post';
		}
		if (strtolower($data['method']) == 'post') {
			if (!is_array($in)) {
				$in .= static::form_csrf();
			} else {
				$in['in'] .= static::form_csrf();
			}
		}
		return static::wrap($in, $data, __FUNCTION__);
	}
879731
protected function pushSecondaryKeys($data, $form)
    {
        if (isset($data[$form]) && is_array($data[$form])) {
            foreach ($data[$form] as $secondaryKey => $values) {
                $data[$form][$secondaryKey][$this->relSecondaryKey] = $secondaryKey;
            }
        }

        return $data;
    }
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);
    }
505671
public function getFormElements(&$form, &$data)
    {
        $element = $form->createElement('multiCheckbox', 'format');
        $element->setLabel($this->_('CSV options'))
                ->setMultiOptions(array(
                    'addHeader' => $this->_('Add headers with column names'),
                    'formatVariable' => $this->_('Export labels instead of field names'),
                    'formatAnswer' => $this->_('Format answers')
                ))
                ->setBelongsTo($this->getName())
                ->setSeparator(' ');
        $elements['format'] = $element;

        $element = $form->createElement('select', 'delimiter');
        $element->setLabel($this->_('Delimiter'))
                ->setMultiOptions(array(',' => ',', ';' => ';'))
                ->setBelongsTo($this->getName());
        $elements['delimiter'] = $element;

        return $elements;
    }
174900
public function doRegister($data, $form)
    {
        $r = new EventRegistration();
        $form->saveInto($r);
        $r->write();

        return "Thanks. We've received your registration.";
    }
653448
public function doUpdate($data, $form)
    {
        foreach ($this->items as $cart_item) {
            foreach ($data as $key => $value) {
                $sliced_key = explode("_", $key);
                if ($sliced_key[0] == "Quantity") {
                    if (isset($cart_item) && ($cart_item->Key == $sliced_key[1])) {
                        try {
                            if ($value > 0) {
                                $this->update($cart_item->Key, $value);
                                
                                $this->setSessionMessage(
                                    "success",
                                    _t("Checkout.UpdatedShoppingCart", "Shopping cart updated")
                                );
                            } else {
                                $this->remove($cart_item->Key);
                                
                                $this->setSessionMessage(
                                    "success",
                                    _t("Checkout.EmptiedShoppingCart", "Shopping cart emptied")
                                );
                            }
                        } catch (ValidationException $e) {
                            $this->setSessionMessage(
                                "bad",
                                $e->getMessage()
                            );
                        } catch (Exception $e) {
                            $this->setSessionMessage(
                                "bad",
                                $e->getMessage()
                            );
                        }
                    }
                }
            }
        }

        $this->save();

        return $this->redirectBack();
    }