Save  handler

@param array $data
@param Form $form
@return HTTPResponse
773920
public function save($data, $form)
    {
        $errors = null;

        // Existing or new record?
        $id = empty($data['ID']) ? 0 : $data['ID'];
        if ($id) {
            $record = ChangeSet::get()->byID($id);
            if ($record && !$record->canEdit()) {
                return Security::permissionFailure($this);
            }
            if (!$record || !$record->ID) {
                $this->httpError(404, "Bad record ID #" . (int)$id);
            }
        } else {
            if (!ChangeSet::singleton()->canCreate()) {
                return Security::permissionFailure($this);
            }
            $record = ChangeSet::create();
        }

        $hasExistingName = Changeset::get()
            ->filter('Name:nocase', $data['Name'])
            ->exclude('ID', $id)
            ->count() > 0;

        if (!$hasExistingName) {
            // save form data into record
            $form->saveInto($record, true);
            $record->write();
            $this->extend('onAfterSave', $record);
            $message = _t(__CLASS__.'.SAVEDUP', 'Saved.');
            $form->setMessage($message, ValidationResult::TYPE_GOOD);
        } else {
            $nameDuplicateMsg = _t(__CLASS__ . '.ERROR_DUPLICATE_NAME', 'Name "{Name}" already exists', '', [ 'Name' => $data['Name']]);
            $errors = new ValidationResult();
            $errors->addFieldMessage('Name', $nameDuplicateMsg);
            $message = _t(__CLASS__.'.SAVEDERROR', 'Error.');
            // Need to set the form message or the field message won't show up at all
            $form->setMessage($message, ValidationResult::TYPE_ERROR);
        }

        if ($id) {
            $schemaId = Controller::join_links($this->Link('schema'), 'campaignEditForm', $id);
        } else {
            $schemaId = Controller::join_links($this->Link('schema'), 'campaignCreateForm');
        }

        // Ensure that newly created records have all their data loaded back into the form.
        $form->loadDataFrom($record);
        $extra = ['record' => ['id' => $record->ID]];
        $response = $this->getSchemaResponse($schemaId, $form, $errors, $extra);
        $response->addHeader('X-Status', rawurlencode($message));
        return $response;
    }
610677
function saveToSession($data, $name = '') {
		if(!$name) $name = $this->owner->FormName();

		\Session::set("FormInfo.{$name}.data", $data);
	}
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();
    }
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;
    }
1020797
public function notify(Form $form = null, array $values = null)
    {
        //if define form in parameters
        if ($form) {
            $this->form = $form;
        }

        //if define values in parameters
        if ($values) {
            $this->setValues($values);
        }

        // iterate events
        foreach ($this->events as $eventIndex => $event) {
            // save index event
            $this->eventIndex = $eventIndex;

            // check instance of event
            if ($event instanceof IEvent) {
                $event->update($this, $this->values);
            } else {
                throw new EventException(get_class($event) . ' is not implements of ' . IEvent::class);
            }
        }
    }
1019977
public function setForm(Form $form)
	{
		$this->form = $form;
		$this->formControl = $form->getFormControl();

		return $this;
	}
1177492
public function handleTicketForm(array $data, TicketForm $form)
    {
        $reservation = ReservationSession::start($this->getEvent());

        foreach ($data['Tickets'] as $ticketID => $ticketData) {
            for ($i = 0; $i < $ticketData['Amount']; $i++) {
                $attendee = Attendee::create();
                $attendee->TicketID = $ticketID;
                $attendee->ReservationID = $reservation->ID;
                $attendee->EventID = $reservation->EventID;
                $attendee->write();
                $reservation->Attendees()->add($attendee);
            }
        }

        $reservation->calculateTotal();
        $reservation->write();

        $this->extend('beforeNextStep', $data, $form, $reservation);
        return $this->nextStep();
    }
319731
private function handlePostReset(Request $request, FormInterface $form)
    {
        $event = new AccessControlEvent($request);
        $username = $form->get('username')->getData();

        // Send a password request mail, if username exists.
        if ($username === null || $username === '') {
            $this->flashes()->error(Trans::__('general.phrase.please-provide-username'));
        } else {
            $this->password()->resetPasswordRequest($username, $request->getClientIp(), $event);
            $response = $this->redirectToRoute('login');
            $response->setVary('Cookies', false)->setMaxAge(0)->setPrivate();

            return $response;
        }

        return null;
    }
1270121
public function doSubmit($data, $form) {
		$controller = Controller::curr();

		$redirect = Director::baseURL() . $this->owner->URLSegment;

		if ((bool) Config::inst()->get('QuickFeedbackExtension', 'redirect_field') && isset($data['Redirect']) && Director::is_site_url($data['Redirect'])) {
			$redirect = Director::absoluteURL($data['Redirect'], true);
		}

		if (!$controller) {
			goto error;
		}

		$request = $controller->getRequest();

		if (!$request) {
			goto error;
		}

		$limit = (int) Config::inst()->get('QuickFeedbackExtension', 'rate_limit');

		$existing = Feedback::get()
			->filter('IP', $request->getIP())
			->sort('Created desc')
			->first();

		if ($existing) {
			$created = $existing->dbObject('Created');

			if (!$created) {
				goto error;
			}

			$seconds = abs(time() - strtotime($created->getValue()));
			$minutes = round($seconds / 60);

			if ($minutes <= $limit) {
				goto rate;
			}
		}

		$feedback = Feedback::create();
		$feedback->Rating = $data['Rating'];
		$feedback->Comment = $data['Comment'];
		$feedback->IP = $request->getIP();

		if (!empty($this->owner->ID)) {
			$feedback->PageID = $this->owner->ID;
		}

		if (!empty($this->owner->URLSegment)) {
			$feedback->URL = $this->owner->RelativeLink();
		}

		if ((bool) Config::inst()->get('QuickFeedbackExtension', 'redirect_field') && isset($data['Redirect'])) {
			$feedback->URL = $data['Redirect'];
		}

		$feedback->write();

		$form->sessionMessage(_t('QuickFeedback.ThanksMessage', 'Thanks for your comment!'),'good');
		return $this->owner->redirect($redirect . '?success=1#Form_QuickFeedbackForm');

		error:
			$form->sessionMessage(_t('QuickFeedback.ErrorMessage', 'An error occurred!'),'error');
			return $this->owner->redirect($redirect . '?error=1#Form_QuickFeedbackForm');

		rate:
			$form->sessionMessage(_t('QuickFeedback.RateMessage', 'Please wait a while before submitting!'),'error');
			return $this->owner->redirect($redirect . '?rate=1#Form_QuickFeedbackForm');
	}
1247442
public function saveFormIntoRecord($data, $form)
    {
        $record = parent::saveFormIntoRecord($data, $form);

        // Note: Don't publish if versioned, since that's a separate action
        $ownerIsVersioned = $record && $record->hasExtension(Versioned::class);
        $ownerIsPublishable = $record && $record->hasExtension(RecursivePublishable::class);
        if ($ownerIsPublishable && !$ownerIsVersioned) {
            /** @var RecursivePublishable $record */
            $record->publishRecursive();
        }

        return $record;
    }
134775
public function doAdd($data, $form)
    {
        if ($this->addMember($form)) {
            $form->sessionMessage(
                _t('MemberProfiles.MEMBERADDED', 'The new member has been added.'),
                'good'
            );
        }

        return $this->redirectBack();
    }
191103
public function post(string $url, $data, array $headers = [])
    {
        if (is_array($data)) {
            $headers['Content-type'] = self::FORM_CONTENT_TYPE;
        }

        $ctx = $this->getContext('POST', $data, $headers);
        $response = file_get_contents($url, false, $ctx);
        $this->saveCookies($http_response_header);

        return $response;
    }
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);
    }
1047367
public function doNext($data, $form)
    {
        $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
        $link = $this->getEditLink($this->getNextRecordID());
        return $this->redirect($link);
    }
454001
public function archive($data, $form)
    {
        $id = $data['ID'];
        /** @var SiteTree $record */
        $record = SiteTree::get()->byID($id);
        if (!$record || !$record->exists()) {
            throw new HTTPResponse_Exception("Bad record ID #$id", 404);
        }
        if (!$record->canArchive()) {
            return Security::permissionFailure();
        }

        // Archive record
        $record->doArchive();

        $this->getResponse()->addHeader(
            'X-Status',
            rawurlencode(_t(
                __CLASS__ . '.ARCHIVEDPAGE',
                "Archived page '{title}'",
                ['title' => $record->Title]
            ))
        );

        // Even if the record has been deleted from stage and live, it can be viewed in "archive mode"
        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
569579
public function doRegister($data, $form)
    {
        $r = new EventRegistration();
        $form->saveInto($r);

        $EventDetails = Event::get()->byID($r->EventID);

        if ($EventDetails->TicketsRequired) {
            $r->AmountPaid = ($r->AmountPaid/100);
        }
        $r->write();

        $from = Email::getAdminEmail();
        $to = $r->Email;
        $bcc = $EventDetails->RSVPEmail;
        $subject = "Event Registration - ".$EventDetails->Title." - ".date("d/m/Y H:ia");
        $body = "";

        $email = new Email($from, $to, $subject, $body, null, null, $bcc);
        $email->setTemplate('EventRegistration');
        $email->send();

        exit;
    }
956257
public function doArchive($data, $form)
    {
        /** @var Versioned|DataObject $record */
        $record = $this->getRecord();
        if (!$record->canArchive()) {
            return $this->httpError(403);
        }

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

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

        //when an item is deleted, redirect to the parent controller
        $controller = $this->getToplevelController();
        $controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh

        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
    }