Handles actually adding a folder to the databsae
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {string} HTML to be rendered
320086
public function doAddFolder($data, Form $form) {
        //Existing Check
        $existingCheck=SnippetFolder::get()->filter('Name:nocase', Convert::raw2sql($data['Name']))->filter('LanguageID', intval($data['LanguageID']));
        
        if(array_key_exists('FolderID', $data)) {
            $existingCheck=$existingCheck->filter('ParentID', intval($data['FolderID']));
        }else {
            $existingCheck->filter('ParentID', 0);
        }
        
        if($existingCheck->Count()>0) {
            $form->sessionMessage(_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name'), 'bad');
            return $this->redirectBack();
        }
        
        
        $folder=new SnippetFolder();
        $folder->Name=$data['Name'];
        $folder->LanguageID=$data['LanguageID'];
        
        if(array_key_exists('ParentID', $data)) {
            $folder->ParentID=$data['ParentID'];
        }
        
        //Write the folder to the database
        $folder->write();
        
        
        //Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
        $next=$prev=null;
        $next=SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:GreaterThan', Convert::raw2sql($folder->Title))->first();
        if(!$next) {
            $prev=SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:LessThan', Convert::raw2sql($folder->Title))->reverse()->first();
        }
        
        
        //Setup js that will add the node to the tree
        $html=CodeBank_TreeNode::create($folder, '', false)->forTemplate().'</li>';
        $parentFolder=$folder->Parent();
        $outputData=array('folder-'.$folder->ID=>array(
                                            'html'=>$html,
                                            'ParentID'=>(!empty($parentFolder) && $parentFolder!==false && $parentFolder->ID!=0 ? 'folder-'.$folder->ParentID:'language-'.$folder->LanguageID),
                                            'NextID'=>($next ? 'folder-'.$next->ID:null),
                                            'PrevID'=>($prev ? 'folder-'.$prev->ID:null)
                                        ));
        
        Requirements::customScript('window.parent.updateCodeBankTreeNodes('.json_encode($outputData).');');
        
        
        //Re-render the form
        $form->setFields(new FieldList());
        $form->setActions(new FieldList());
        $form->setMessage(_t('CodeBank.FOLDER_ADDED', '_Folder added you may now close this dialog'), 'good');
        
        return $this->customise(array(
                                    'Content'=>' ',
                                    'Form'=>$form
                                ))->renderWith('CMSDialog');
    }
1172401
private function renderForm($form, $data = [])
    {
        // Check for tag name
        if ($form->tagName != 'form') {
            return $this;
        }

        // Set form values
        FormHelper::setValues($this->getHTMLHandler(), $form, $data['values']);

        return $this;
    }
1199114
function addFiles (formData, files) {
    var file, arr, key, i = 0, filename;

    for (key in files) {
        if (files.hasOwnProperty(key) && files[key]) {

            if (files[key] instanceof Array) {
                arr = files[key];
                filename = getFilename(arr[i]) || null;

                for (i = 0; i < arr.length; i += 1) {
                    formData.append(key + '[' + i + ']', arr[i]);
                }
            } else {
                file = files[key];
                filename = getFilename(file) || null;
                formData.append(key, file, filename);
            }
        }
    }
}
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;
    }
174900
public function doRegister($data, $form)
    {
        $r = new EventRegistration();
        $form->saveInto($r);
        $r->write();

        return "Thanks. We've received your registration.";
    }
142042
public function doDelete($data, Form $form) {
        $record=$this->currentPage();
    
        if($record->canDelete()) {
            Session::set('CodeBank.deletedSnippetID', $record->ID);
            $record->delete();
    
            $this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.SNIPPET_DELETED', '_Snippet has been deleted')));
        }else {
            $this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.PERMISSION_DENIED', '_Permission Denied')));
        }
        
        $this->redirect('admin/codeBank/');
        return $this->getResponseNegotiator()->respond($this->request);
    }
1286265
public function render(string $view = null, array $data = [], string $formAction = ''): string
    {
        if (!$this->_data) {
            return '';
        }

        return $this->_data->setPath($formAction)->appends($data)->render($view)->toHtml();
    }
1047367
public function doNext($data, $form)
    {
        $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
        $link = $this->getEditLink($this->getNextRecordID());
        return $this->redirect($link);
    }
1246499
public function doAddMockData($data, $form)
    {
        $this->owner->record->fill(array(
            'only_empty' => true,
            'include_relations' => false,
            'download_images' => false
        ));

        Controller::curr()->getResponse()->addHeader("X-Pjax", "Content");
        $link = Controller::join_links($this->owner->gridField->Link(), "item", $this->owner->record->ID);
        return Controller::curr()->redirect($link);
    }
1114594
public function doUpdatePayment($data, $form)
    {
        $session = $this
            ->getRequest()
            ->getSession();

        $session->set(
            "Checkout.PaymentMethodID",
            $data["PaymentMethodID"]
        );        
        
        return $this->redirectBack();        
    }
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;
    }
425087
public function filterSucceeded(Form $form)
	{
		if ($this->snippets_set) {
			return;
		}

		$values = $form->getValues();

		if ($this->getPresenter()->isAjax()) {
			if (isset($form['group_action']['submit']) && $form['group_action']['submit']->isSubmittedBy()) {
				return;
			}
		}

		/**
		 * Per page
		 */
		$this->saveSessionData('_grid_per_page', $values->per_page);
		$this->per_page = $values->per_page;

		/**
		 * Inline edit
		 */
		if (isset($form['inline_edit']) && isset($form['inline_edit']['submit']) && isset($form['inline_edit']['cancel'])) {
			$edit = $form['inline_edit'];

			if ($edit['submit']->isSubmittedBy() || $edit['cancel']->isSubmittedBy()) {
				$id = $form->getHttpData(Form::DATA_LINE, 'inline_edit[_id]');
				$primary_where_column = $form->getHttpData(
					Form::DATA_LINE,
					'inline_edit[_primary_where_column]'
				);

				if ($edit['submit']->isSubmittedBy() && !$edit->getErrors()) {
					$this->inlineEdit->onSubmit($id, $values->inline_edit);
					$this->getPresenter()->payload->_datagrid_inline_edited = $id;
					$this->getPresenter()->payload->_datagrid_name = $this->getName();
				} else {
					$this->getPresenter()->payload->_datagrid_inline_edit_cancel = $id;
					$this->getPresenter()->payload->_datagrid_name = $this->getName();
				}

				if ($edit['submit']->isSubmittedBy() && !empty($this->inlineEdit->onCustomRedraw)) {
					$this->inlineEdit->onCustomRedraw();
				} else {
					$this->redrawItem($id, $primary_where_column);
					$this->redrawControl('summary');
				}

				return;
			}
		}

		/**
		 * Inline add
		 */
		if (isset($form['inline_add']) && isset($form['inline_add']['submit']) && isset($form['inline_add']['cancel'])) {
			$add = $form['inline_add'];

			if ($add['submit']->isSubmittedBy() || $add['cancel']->isSubmittedBy()) {
				if ($add['submit']->isSubmittedBy() && !$add->getErrors()) {
					$this->inlineAdd->onSubmit($values->inline_add);

					if ($this->getPresenter()->isAjax()) {
						$this->getPresenter()->payload->_datagrid_inline_added = true;
					}
				}

				return;
			}
		}

		/**
		 * Filter itself
		 */
		$values = $values['filter'];

		foreach ($values as $key => $value) {
			/**
			 * Session stuff
			 */
			if ($this->remember_state && $this->getSessionData($key) != $value) {
				/**
				 * Has been filter changed?
				 */
				$this->page = 1;
				$this->saveSessionData('_grid_page', 1);
			}

			$this->saveSessionData($key, $value);

			/**
			 * Other stuff
			 */
			$this->filter[$key] = $value;
		}

		if (!empty($values)) {
			$this->saveSessionData('_grid_has_filtered', 1);
		}

		if ($this->getPresenter()->isAjax()) {
			$this->getPresenter()->payload->_datagrid_sort = [];

			foreach ($this->columns as $key => $column) {
				if ($column->isSortable()) {
					$this->getPresenter()->payload->_datagrid_sort[$key] = $this->link('sort!', [
						'sort' => $column->getSortNext(),
					]);
				}
			}
		}

		$this->reload();
	}
572586
public function renderForm(Form $form)
	{
		foreach ($form as $element)
		{
			$this->render($element);
		}

		$tableRender = new SimpleTable();
		$tableContent = $tableRender->renderTable($this->table);

		return Html::tag('form', $form->getAttributes(), $tableContent);
	}
950038
public function doAddTags($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 = [];
        }

        $tags_list = (isset($data['Tags'])) ? $data['Tags'] : [];
        
        try {
            foreach ($tags_list as $tag_name) {
                if (!empty($tag_name)) {
                    $tag = ContactTag::get()->find("Title", $tag_name);
                    if (!$tag) {
                        $tag = ContactTag::create([
                            "Title" => $tag_name
                        ]);
                        $tag->write();
                    }

                    foreach ($ids as $record_id) {
                        $record = DataObject::get_by_id($className, $record_id);
                        
                        if ($record->hasMethod("Tags")) {
                            $record->Tags()->add($tag);
                            $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 (count($tags_list)) {
            $message = "Added " . count($return) . " contacts to tags '" . implode(",",$tags_list) . "'";
        } 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);
    }
1121950
function submitFormData(params, cb) {
  var resourcePath = config.addURIParams("/appforms/forms/:id/submitFormData", params);
  var method = "POST";
  var data = params.submission;

  params.resourcePath = resourcePath;
  params.method = method;
  params.data = data;

  mbaasRequest.app(params, cb);
}
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');
	}
586424
public function AddForm() {
        $sng=singleton('Snippet');
        $fields=$sng->getCMSFields();
        $validator=$sng->getCMSValidator();
        
        $actions=new FieldList(
                                FormAction::create('doAdd', _t('CodeBank.CREATE', '_Create'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true)
                            );
        
        $form=CMSForm::create($this, 'AddForm', $fields, $actions)->setHTMLID('Form_AddForm');
        $form->setValidator($validator);
        $form->disableDefaultAction();
        $form->addExtraClass('cms-add-form cms-edit-form');
        $form->setResponseNegotiator($this->getResponseNegotiator());
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
        $form->addExtraClass('center '.$this->BaseCSSClasses());
        $form->setAttribute('data-pjax-fragment', 'CurrentForm');
        
        
        //Handle Language id in url
        if($this->request->getVar('LanguageID')) {
            $langField=$form->Fields()->dataFieldByName('LanguageID');
            if($langField && $langField->Value()=='') {
                $langField->setValue(intval(str_replace('language-', '', $this->request->getVar('LanguageID'))));
            }
        }
        
        
        //Handle folder id in url (or post)
        if($this->request->getVar('FolderID')) {
            $folder=SnippetFolder::get()->byID(intval($this->request->getVar('FolderID')));
            if(!empty($folder) && $folder!==false && $folder->ID!=0) {
                $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID);
                $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation());
                $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID));
            }
        }else if($this->request->postVar('FolderID')) {
            $folder=SnippetFolder::get()->byID(intval($this->request->postVar('FolderID')));
            if(!empty($folder) && $folder!==false && $folder->ID!=0) {
                $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID);
                $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation());
                $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID));
            }
        }
        
        
        $this->extend('updateAddForm', $form);
        
        
        //Display message telling user to run dev/build because the version numbers are out of sync
        if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
            $form->insertBefore(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
        }else if($this->hasOldTables()) {
            $form->insertBefore(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
        }
        
        $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
        
        
        Requirements::javascript(CB_DIR.'/javascript/CodeBank.EditForm.js');
        
        return $form;
    }