Handler for the form submission.

@param array $data
@param Form $form

@return SS_HTTPResponse
967113
public function doSearchKnowledgeBase($data, $form)
    {
        if (!$this->kbPageId) {
            return $this->controller->redirectBack();
        }

        $page = KnowledgebasePage::get()->byID($this->kbPageId);

        // just in case the page doesn't actually exist anymore
        if (!$page) {
            return $this->controller->redirectBack();
        }

        // should either go to the results page or the landing page depending on if there is a query
        $link = (!empty($data['Query']))
            ? sprintf('%s?q=%s', $page->AbsoluteLink(), strip_tags($data['Query']))
            : $page->AbsoluteLink();

        $this->extend('UpdateLink', $link, $data);

        return $this->controller->redirect($link);
    }
817971
public function doSaveAndQuit($data, $form)
    {
        $this->save($data, $form);
        $controller = $this->getToplevelController();
        $controller->getResponse()->addHeader("X-Pjax", "Content");
        $controller->redirect($this->getBackLink());
    }
1146379
public function newPage($data, Form $form) {
        //Start a transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionStart();
        }
        
        $convertToClass=$this->getDestinationClass();
        
        
        //Verify we have a destination class
        if($convertToClass!==false) {
            $source=clone $this->record; //Create a clone of the record to be safe
            
            
            //Create the new page
            $destination=new $convertToClass();
            $destination->writeWithoutVersion();
            $destination->flushCache();
            
            
            //Merge the kapost object into the new page
            $this->merge($destination, $source, 'right', true, true);
            
            
            //If a target was set and the parent has been found set the parent of the page
            if(intval($data['ParentPageID']) && SiteTree::get()->filter('ID', intval($data['ParentPageID']))->count()>0) {
                $destination->ParentID=intval($data['ParentPageID']);
            }
            
            //Write the destination one more time to be sure
            $destination->write();
            
            
            //Allow extensions to update the object
            $this->extend('updateNewPageConversion', $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;
    }
167311
public function doImportData($data, Form $form) {
        if(!Permission::check('ADMIN')) {
            Security::permissionFailure($this);
            return;
        }
        
        $fileData=$form->Fields()->dataFieldByName('ImportFile')->Value();
        //Check that the file uploaded
        if(!array_key_exists('tmp_name', $fileData) || !file_exists($fileData['tmp_name'])) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Load the file into memory
        $fileData=file_get_contents($fileData['tmp_name']);
        if($fileData===false || empty($fileData)) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Decode the json
        $fileData=json_decode($fileData);
        if($fileData===false || !is_object($fileData)) {
            $form->sessionMessage(_t('CodeBank.IMPORT_READ_ERROR', '_Could not read the file to be imported'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Verify the format is ToServer
        if($fileData->format!='ToServer') {
            $form->sessionMessage(_t('CodeBank.IMPORT_FILE_FORMAT_INCORRECT', '_Import file format is incorrect'), 'bad');
            return $this->redirectBack();
        }
        
        
        //Bump Up the time limit this may take time
        set_time_limit(480);
        
        
        //Start transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionStart();
        }
        
        
        //If not appending empty the tables
        if(!isset($data['AppendData'])) {
            DB::query('DELETE FROM Snippet');
            DB::query('DELETE FROM SnippetVersion');
            DB::query('DELETE FROM SnippetLanguage');
            DB::query('DELETE FROM SnippetPackage');
            DB::query('DELETE FROM SnippetFolder');
        }else {
            $langMap=array();
            $pkgMap=array();
            $folderMap=array();
            $snipMap=array();
        }
        
        
        //Import Languages
        foreach($fileData->data->languages as $lang) {
            if(isset($data['AppendData'])) {
                $dbLang=SnippetLanguage::get()->filter('Name:ExactMatch:nocase', Convert::raw2sql($lang->language))->first();
                if(!empty($dbLang) && $dbLang!==false && $dbLang->ID>0) {
                    $langMap['lang-'.$lang->id]=$dbLang->ID;
                }else {
                    $newLang=new SnippetLanguage();
                    $newLang->Name=$lang->language;
                    $newLang->FileExtension=$lang->file_extension;
                    $newLang->HighlightCode=$lang->shjs_code;
                    $newLang->UserLanguage=$lang->user_language;
                    $newLang->write();
                    
                    $langMap['lang-'.$lang->id]=$newLang->ID;
                    unset($newLang);
                }
            }else {
                DB::query('INSERT INTO "SnippetLanguage" ("ID", "ClassName", "Created", "LastEdited", "Name", "FileExtension", "HighlightCode", "UserLanguage") '.
                        "VALUES(".intval($lang->id).",'SnippetLanguage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($lang->language)."','".Convert::raw2sql($lang->file_extension)."','".Convert::raw2sql($lang->shjs_code)."',".intval($lang->user_language).")");
            }
        }
        
        
        //Import Packages
        foreach($fileData->data->packages as $pkg) {
            if(isset($data['AppendData'])) {
                $newPkg=new SnippetPackage();
                $newPkg->Title=$pkg->title;
                $newPkg->write();
                
                $pkgMap['pkg-'.$pkg->id]=$newPkg->ID;
                unset($newPkg);
            }else {
                DB::query('INSERT INTO "SnippetPackage" ("ID", "ClassName", "Created", "LastEdited", "Title") '.
                        "VALUES(".intval($pkg->id).",'SnippetPackage', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($pkg->title)."')");
            }
        }
        
        
        //Import Folders
        foreach($fileData->data->folders as $folder) {
            if(isset($data['AppendData'])) {
                if(!isset($langMap['lang-'.$folder->fkLanguageId])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                    
                    $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad');
                    return $this->redirectBack();
                }
                
                $newFld=new SnippetFolder();
                $newFld->Name=$folder->name;
                $newFld->ParentID=($folder->fkParentId>0 && isset($folderMap['fld-'.$folder->fkParentId]) ? $folderMap['fld-'.$folder->fkParentId]:0);
                $newFld->LanguageID=$langMap['lang-'.$folder->fkLanguageId];
                $newFld->write();
                
                $folderMap['fld-'.$folder->id]=$newFld->ID;
                unset($newFld);
            }else {
                DB::query('INSERT INTO "SnippetFolder" ("ID", "ClassName", "Created", "LastEdited", "Name", "ParentID", "LanguageID") '.
                        "VALUES(".intval($folder->id).",'SnippetFolder', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($folder->name)."', ".intval($folder->fkParentId).", ".intval($folder->fkLanguageId).")");
            }
        }
        
        
        //Import Snippets
        foreach($fileData->data->snippets as $snip) {
            if(isset($data['AppendData'])) {
                if(!isset($langMap['lang-'.$snip->fkLanguage])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                    
                    $form->sessionMessage(_t('CodeBank.IMPORT_LANG_NOT_FOUND', '_Import failed language not found'), 'bad');
                    return $this->redirectBack();
                }
                
                $newSnip=new Snippet();
                $newSnip->Title=$snip->title;
                $newSnip->Description=$snip->description;
                $newSnip->Tags=$snip->tags;
                $newSnip->LanguageID=$langMap['lang-'.$snip->fkLanguage];
                $newSnip->CreatorID=Member::currentUserID();
                $newSnip->LastEditorID=Member::currentUserID();
                $newSnip->PackageID=($snip->fkPackageID>0 && isset($pkgMap['pkg-'.$snip->fkPackageID]) ? $pkgMap['pkg-'.$snip->fkPackageID]:0);
                $newSnip->FolderID=($snip->fkFolderID>0 && isset($folderMap['fld-'.$snip->fkFolderID]) ? $folderMap['fld-'.$snip->fkFolderID]:0);
                $newSnip->write();
                
                $snipMap['snip-'.$snip->id]=$newSnip->ID;
                unset($newSnip);
            }else {
                DB::query('INSERT INTO "Snippet" ("ID", "ClassName", "Created", "LastEdited", "Title", "Description", "Tags", "LanguageID", "CreatorID", "LastEditorID", "PackageID", "FolderID") '.
                        "VALUES(".intval($snip->id).",'Snippet', '".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($snip->title)."', '".Convert::raw2sql($snip->description)."', '".Convert::raw2sql($snip->tags)."', ".intval($snip->fkLanguage).", ".Member::currentUserID().", ".Member::currentUserID().", ".intval($snip->fkPackageID).", ".intval($snip->fkFolderID).")");
            }
        }
        
        
        //Import Snippet Versions
        foreach($fileData->data->versions as $ver) {
            if(isset($data['AppendData'])) {
                if(!isset($snipMap['snip-'.$ver->fkSnippit])) {
                    if(DB::getConn()->supportsTransactions()) {
                        DB::getConn()->transactionRollback();
                    }
                
                    $form->sessionMessage(_t('CodeBank.IMPORT_SNIP_NOT_FOUND', '_Import failed snippet not found'), 'bad');
                    return $this->redirectBack();
                }
                
                DB::query('INSERT INTO "SnippetVersion" ("ClassName", "Created", "LastEdited", "Text", "ParentID") '.
                        "VALUES('SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($snipMap['snip-'.$ver->fkSnippit]).")");
            }else {
                DB::query('INSERT INTO "SnippetVersion" ("ID", "ClassName", "Created", "LastEdited", "Text", "ParentID") '.
                        "VALUES(".intval($ver->id).",'SnippetVersion', '".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->date)."','".Convert::raw2sql($ver->text)."', ".intval($ver->fkSnippit).")");
            }
        }
        
        
        //End transaction if supported
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionEnd();
        }
        
        
        //Display success after redirecting back
        Session::set('reloadOnImportDialogClose', true);
        $form->sessionMessage(_t('CodeBank.IMPORT_COMPLETE', '_Import Completed'), 'good');
        return $this->redirectBack();
    }
1359903
public function save($data, $form) {
		if (!$this->data()->canEdit()) {
			return Security::permissionFailure($this);
		}

		$existing = $this->getEditingLocks($this->data(), true);
		// oops, we've somehow got here even though we shouldn't have
		if ($existing && $existing['user'] != Member::currentUser()->Email) {
			return "Someone somehow locked it while you were gone, this shouldn't happen like this :(";
		}

		$this->savePage($this->data(), $form);
		if (WikiPage::$auto_publish) {
			// do publish
			$this->data()->doPublish();
		}

		return $this->redirect($this->data()->Link('edit') . '?stage=Stage');
	}
962534
public function submit(FormEvent $event)
    {
        $user = $event->getData();
        if (null === $user) {
            return;
        }
        if ($this->currentUser !== null && $this->currentUser !== $user && $event->getForm()->has('activated')) {
            $activated = $event->getForm()->get('activated')->getData();
            if ($activated && $user->getRegistrationToken()) {
                $user->setRegistrationToken(null);
            } elseif (!$activated && !$user->getRegistrationToken()) {
                $user->setRegistrationToken(hash("sha1",rand()));
            }
        }
    }
713945
public function save_siteconfig($data, $form)
    {
        $data = $form->getData();
        $siteConfig = DataObject::get_by_id(SiteConfig::class, $data['ID']);
        $form->saveInto($siteConfig);
        $siteConfig->write();
        if ($siteConfig->hasExtension(RecursivePublishable::class)) {
            $siteConfig->publishRecursive();
        }
        $this->response->addHeader(
            'X-Status',
            rawurlencode(_t('SilverStripe\\Admin\\LeftAndMain.SAVEDUP', 'Saved.'))
        );
        return $form->forTemplate();
    }
704365
public function doUnpublish($data, $form)
    {
        /** @var Versioned|DataObject $record */
        $record = $this->getRecord();
        if (!$record->canUnpublish()) {
            return $this->httpError(403);
        }

        // Record name before it's deleted
        $title = $record->Title;
        $record->doUnpublish();

        $message = _t(
            __CLASS__ . '.Unpublished',
            'Unpublished {name} {title}',
            [
                'name' => $record->i18n_singular_name(),
                'title' => Convert::raw2xml($title)
            ]
        );
        $this->setFormMessage($form, $message);

        // Redirect back to edit
        return $this->redirectAfterSave(false);
    }
1165607
public function doAddPackage($data, Form $form) {
        $record=new SnippetPackage();
        if($record->canEdit()) {
            $form->saveInto($record);
            $record->write();
            
            
            Requirements::customScript("window.parent.jQuery('#".$this->getName()."').entwine('ss').handleSuccessResult(".$record->ID.");");
            return $this->renderWith('CMSDialog', array('Form'=>''));
        }
        
        return Controller::curr()->redirectBack();
    }
1078295
public function validateField($data, $form)
    {
        $formField = $this->getFormField();
        $formField->setForm($form);

        if (isset($data[$this->Name])) {
            $formField->setValue($data[$this->Name]);
        }

        $validator = $form->getValidator();
        if (!$formField->validate($validator)) {
            $errors = $validator->getErrors();
            $foundError = false;

            // field validate implementation may not add error to validator
            if (count($errors) > 0) {
                // check if error already added from fields' validate method
                foreach ($errors as $error) {
                    if ($error['fieldName'] == $this->Name) {
                        $foundError = $error;
                        break;
                    }
                }
            }

            if ($foundError !== false) {
                // use error messaging already set from validate method
                $form->sessionMessage($foundError['message'], $foundError['messageType']);
            } else {
                // fallback to custom message set in CMS or default message if none set
                $form->sessionError($this->getErrorMessage()->HTML());
            }
        }
    }
678752
public static function execute(ContainerInterface $form, array $data)
    {
        self::$form = $form;
        $hasElements = isset($data['elements']) && is_array($data['elements']);
        if (!$hasElements) {
            return;
        }

        foreach ($data['elements'] as $name => $element) {
            $input = self::create($element);
            self::setSettings($input, $element);
            $input->setName($name);
            self::populateInputs($input, $element);
            $form->add($input);
        }
    }
1123819
public function submitted(Form $form)
	{
		if (!isset($form['group_action']['submit']) || !$form['group_action']['submit']->isSubmittedBy()) {
			return;
		}

		$values = $form->getValues();
		$values = $values['group_action'];

		if ($values->group_action === 0 || $values->group_action === null) {
			return;
		}

		/**
		 * @todo Define items IDs
		 */
		$http_ids = $form->getHttpData(Form::DATA_LINE | Form::DATA_KEYS, strtolower($this->datagrid->getName()) . '_group_action_item[]');
		$ids = array_keys($http_ids);

		$id = $values->group_action;
		$this->group_actions[$id]->onSelect($ids, isset($values->{$id}) ? $values->{$id} : null);

		$form['group_action']['group_action']->setValue(null);
	}
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();
    }
1067053
public function doAddToList($data, /** @scrutinizer ignore-unused */ $form)
    {
        $className  = $this->gridField->list->dataClass;
        $controller = $this->getToplevelController();
        $form = $controller->EditForm();
        $return = array();

        if (isset($data['RecordIDs'])) {
            $ids = explode(",", $data['RecordIDs']);
        } else {
            $ids = array();
        }

        $list_id = (isset($data['ContactListID'])) ? $data['ContactListID'] : 0;
        $list = ContactList::get()->byID($list_id);
        
        try {
            foreach ($ids as $record_id) {
                if ($list_id) {
                    $record = DataObject::get_by_id($className, $record_id);
                    
                    if ($record->hasMethod("Lists")) {
                        $list->Contacts()->add($record);
                        $list->write();
                    }
                    
                    $return[] = $record->ID;
                }
            }
        } catch (\Exception $e) {
            $form->sessionMessage(
                $e->getMessage(),
                ValidationResult::TYPE_ERROR
            );
                
            $responseNegotiator = new PjaxResponseNegotiator(array(
                'CurrentForm' => function () use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function () use (&$controller) {
                    return $controller->redirectBack();
                }
            ));
            
            if ($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            
            return $responseNegotiator->respond($controller->getRequest());
        }
        
        if (!empty($list)) {
            $message = "Added " . count($return) . " contacts to mailing list '{$list->Title}'";
        } else {
            $message = _t("Contacts.NoListSelected", "No list selected");
        }

        $form->sessionMessage(
            $message,
            ValidationResult::TYPE_GOOD
        );
        
        // Changes to the record properties might've excluded the record from
        // a filtered list, so return back to the main view if it can't be found
        $link = $controller->Link();
        $controller->getRequest()->addHeader('X-Pjax', 'Content');
        return $controller->redirect($link);
    }
459014
public function save($data, $form)
    {
        $className = $this->config()->get('tree_class');

        // Existing or new record?
        $id = $data['ID'];
        if (substr($id, 0, 3) != 'new') {
            /** @var SiteTree $record */
            $record = DataObject::get_by_id($className, $id);
            // Check edit permissions
            if ($record && !$record->canEdit()) {
                return Security::permissionFailure($this);
            }
            if (!$record || !$record->ID) {
                throw new HTTPResponse_Exception("Bad record ID #$id", 404);
            }
        } else {
            if (!$className::singleton()->canCreate()) {
                return Security::permissionFailure($this);
            }
            $record = $this->getNewItem($id, false);
        }

        // Check publishing permissions
        $doPublish = !empty($data['publish']);
        if ($record && $doPublish && !$record->canPublish()) {
            return Security::permissionFailure($this);
        }

        // TODO Coupling to SiteTree
        $record->HasBrokenLink = 0;
        $record->HasBrokenFile = 0;

        if (!$record->ObsoleteClassName) {
            $record->writeWithoutVersion();
        }

        // Update the class instance if necessary
        if (isset($data['ClassName']) && $data['ClassName'] != $record->ClassName) {
            // Replace $record with a new instance of the new class
            $newClassName = $data['ClassName'];
            $record = $record->newClassInstance($newClassName);
        }

        // save form data into record
        $form->saveInto($record);
        $record->write();

        // If the 'Publish' button was clicked, also publish the page
        if ($doPublish) {
            $record->publishRecursive();
            $message = _t(
                __CLASS__ . '.PUBLISHED',
                "Published '{title}' successfully.",
                ['title' => $record->Title]
            );
        } else {
            $message = _t(
                __CLASS__ . '.SAVED',
                "Saved '{title}' successfully.",
                ['title' => $record->Title]
            );
        }

        $this->getResponse()->addHeader('X-Status', rawurlencode($message));
        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
637657
public function doAdd($data, Form $form) {
        $record=$this->getRecord(null);
        $form->saveInto($record);
        $record->write();
        
        $editController=singleton('CodeBank');
        $editController->setCurrentPageID($record->ID);
        
        return $this->redirect(Controller::join_links(singleton('CodeBank')->Link('show'), $record->ID));
    }
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();
    }