Save the data from the policydoc form as a new policy document version.

@param stdClass $form data submitted from the {@link \tool_policy\form\policydoc} form.
@return \tool_policy\policy_version persistent
338234
public static function form_policydoc_update_new(stdClass $form) {
        global $DB;

        if (empty($form->policyid)) {
            throw new coding_exception('Invalid policy document ID');
        }

        $form = clone($form);

        $form->id = $DB->insert_record('tool_policy_versions', (new policy_version(0, (object) [
            'timecreated' => time(),
            'policyid' => $form->policyid,
        ]))->to_record());

        return static::form_policydoc_update_overwrite($form);
    }
69582
public function save()
    {

        $fields = array_except($this->attributes, ["_index", "_type", "_id", "_score"]);

        if ($this->exists()) {

            // Update the current document

            $this->newQuery()->id($this->getID())->update($fields);

        } else {

            // Check if model key exists in items

            if (array_key_exists("_id", $this->attributes)) {
                $created = $this->newQuery()->id($this->attributes["_id"])->insert($fields);
                $this->_id = $this->attributes["_id"];
            } else {
                $created = $this->newQuery()->insert($fields);
                $this->_id = $created->_id;
            }

            $this->setConnection($this->getConnection());
            $this->setIndex($created->_index);

            // Match earlier versions

            $this->_index = $created->_index;
            $this->_type = $this->type;

            $this->exists = true;
        }

        return $this;
    }
216185
public function form($form = null)
    {
        if (func_num_args() === 1) {
            $form = $form ?: [];
            $this->_form = $form;
            $this->set($form);
            return $this;
        }
        return $this->_form;
    }
331689
public function submit(Form $form)
    {
        return $this->request($form->getUri(), $form->getMethod(), $form->getPhpValues(), $form->getPhpFiles());
    }
148305
public function restore($data, $form)
    {
        if (!isset($data['ID']) || !is_numeric($data['ID'])) {
            return new HTTPResponse("Please pass an ID in the form content", 400);
        }

        $id = (int)$data['ID'];
        /** @var SiteTree $restoredPage */
        $restoredPage = Versioned::get_latest_version(SiteTree::class, $id);
        if (!$restoredPage) {
            return new HTTPResponse("SiteTree #$id not found", 400);
        }

        $restoredPage = $restoredPage->doRestoreToStage();

        $this->getResponse()->addHeader(
            'X-Status',
            rawurlencode(_t(
                __CLASS__ . '.RESTORED',
                "Restored '{title}' successfully",
                array('title' => $restoredPage->Title)
            ))
        );

        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
1279605
public function save(stdClass $submission, stdClass $data) {
        global $USER, $DB;

        $editoroptions = $this->get_edit_options();

        $data = file_postupdate_standard_editor($data,
                                                'onlinetext',
                                                $editoroptions,
                                                $this->assignment->get_context(),
                                                'assignsubmission_onlinetext',
                                                ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
                                                $submission->id);

        $onlinetextsubmission = $this->get_onlinetext_submission($submission->id);

        $fs = get_file_storage();

        $files = $fs->get_area_files($this->assignment->get_context()->id,
                                     'assignsubmission_onlinetext',
                                     ASSIGNSUBMISSION_ONLINETEXT_FILEAREA,
                                     $submission->id,
                                     'id',
                                     false);

        // Check word count before submitting anything.
        $exceeded = $this->check_word_count(trim($data->onlinetext));
        if ($exceeded) {
            $this->set_error($exceeded);
            return false;
        }

        $params = array(
            'context' => context_module::instance($this->assignment->get_course_module()->id),
            'courseid' => $this->assignment->get_course()->id,
            'objectid' => $submission->id,
            'other' => array(
                'pathnamehashes' => array_keys($files),
                'content' => trim($data->onlinetext),
                'format' => $data->onlinetext_editor['format']
            )
        );
        if (!empty($submission->userid) && ($submission->userid != $USER->id)) {
            $params['relateduserid'] = $submission->userid;
        }
        if ($this->assignment->is_blind_marking()) {
            $params['anonymous'] = 1;
        }
        $event = \assignsubmission_onlinetext\event\assessable_uploaded::create($params);
        $event->trigger();

        $groupname = null;
        $groupid = 0;
        // Get the group name as other fields are not transcribed in the logs and this information is important.
        if (empty($submission->userid) && !empty($submission->groupid)) {
            $groupname = $DB->get_field('groups', 'name', array('id' => $submission->groupid), MUST_EXIST);
            $groupid = $submission->groupid;
        } else {
            $params['relateduserid'] = $submission->userid;
        }

        $count = count_words($data->onlinetext);

        // Unset the objectid and other field from params for use in submission events.
        unset($params['objectid']);
        unset($params['other']);
        $params['other'] = array(
            'submissionid' => $submission->id,
            'submissionattempt' => $submission->attemptnumber,
            'submissionstatus' => $submission->status,
            'onlinetextwordcount' => $count,
            'groupid' => $groupid,
            'groupname' => $groupname
        );

        if ($onlinetextsubmission) {

            $onlinetextsubmission->onlinetext = $data->onlinetext;
            $onlinetextsubmission->onlineformat = $data->onlinetext_editor['format'];
            $params['objectid'] = $onlinetextsubmission->id;
            $updatestatus = $DB->update_record('assignsubmission_onlinetext', $onlinetextsubmission);
            $event = \assignsubmission_onlinetext\event\submission_updated::create($params);
            $event->set_assign($this->assignment);
            $event->trigger();
            return $updatestatus;
        } else {

            $onlinetextsubmission = new stdClass();
            $onlinetextsubmission->onlinetext = $data->onlinetext;
            $onlinetextsubmission->onlineformat = $data->onlinetext_editor['format'];

            $onlinetextsubmission->submission = $submission->id;
            $onlinetextsubmission->assignment = $this->assignment->get_instance()->id;
            $onlinetextsubmission->id = $DB->insert_record('assignsubmission_onlinetext', $onlinetextsubmission);
            $params['objectid'] = $onlinetextsubmission->id;
            $event = \assignsubmission_onlinetext\event\submission_created::create($params);
            $event->set_assign($this->assignment);
            $event->trigger();
            return $onlinetextsubmission->id > 0;
        }
    }
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;
    }
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');
	}
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();
    }
1038401
public function save($data, $form)
    {
        $request = $this->getRequest();
        $className = $this->config()->get('tree_class');

        // Existing or new record?
        $id = $data['ID'];
        if (is_numeric($id) && $id > 0) {
            $record = DataObject::get_by_id($className, $id);
            if ($record && !$record->canEdit()) {
                return Security::permissionFailure($this);
            }
            if (!$record || !$record->ID) {
                $this->httpError(404, "Bad record ID #" . (int)$id);
            }
        } else {
            if (!singleton($this->config()->get('tree_class'))->canCreate()) {
                return Security::permissionFailure($this);
            }
            $record = $this->getNewItem($id, false);
        }

        // save form data into record
        $form->saveInto($record, true);
        $record->write();
        $this->extend('onAfterSave', $record);
        $this->setCurrentPageID($record->ID);

        $message = _t(__CLASS__ . '.SAVEDUP', 'Saved.');
        if ($this->getSchemaRequested()) {
            $schemaId = Controller::join_links($this->Link('schema/DetailEditForm'), $id);
            // Ensure that newly created records have all their data loaded back into the form.
            $form->loadDataFrom($record);
            $form->setMessage($message, 'good');
            $response = $this->getSchemaResponse($schemaId, $form);
        } else {
            $response = $this->getResponseNegotiator()->respond($request);
        }

        $response->addHeader('X-Status', rawurlencode($message));
        return $response;
    }
1349379
protected function getValidationData(Form $form)
    {
        // If parent has metadata
        $parent = $form->getParent();
        if ($parent && null !== $parent->getConfig()->getDataClass()) {
            $classMetadata = $metadata = $this->getMetadataFor($parent->getConfig()->getDataClass());
            if ($classMetadata->hasPropertyMetadata($form->getName())) {
                $metadata = $classMetadata->getPropertyMetadata($form->getName());
                /** @var PropertyMetadata $item */
                foreach ($metadata as $item) {
                    $this->composeValidationData(
                        $parentData,
                        $item->getConstraints(),
                        $getters = !empty($item->getters) ? (array)$item->getters : array()
                    );
                }
            }
        }
        // If has own metadata
        if (null !== $form->getConfig()->getDataClass()) {
            $metadata = $this->getMetadataFor($form->getConfig()->getDataClass());
            $this->composeValidationData(
                $ownData,
                $metadata->getConstraints(),
                $getters = !empty($metadata->getters) ? (array)$metadata->getters : array()
            );
        }
        // If has constraints in a form element
        $this->composeValidationData(
            $formData,
            (array)$form->getConfig()->getOption('constraints'),
            array()
        );

        $result = array();
        $groups = $this->getValidationGroups($form);

        if (!empty($parentData)) {
            $parentData['groups'] = $this->getValidationGroups($parent);
            $result['parent']     = $parentData;
        }
        if (!empty($ownData)) {
            $ownData['groups'] = $groups;
            $result['entity']  = $ownData;
        }
        if (!empty($formData)) {
            $formData['groups'] = $groups;
            $result['form']     = $formData;
        }

        return $result;
    }
514536
public function updateEditForm(Form $form)
    {
        Requirements::javascript('symbiote/silverstripe-advancedworkflow:client/dist/js/advancedworkflow.js');
        /** @var WorkflowService $service */
        $service = singleton(WorkflowService::class);
        /** @var DataObject|WorkflowApplicable $record */
        $record = $form->getRecord();
        $active = $service->getWorkflowFor($record);

        if ($active) {
            $fields = $form->Fields();
            $current = $active->CurrentAction();
            $wfFields = $active->getWorkflowFields();

            $allowed = array_keys($wfFields->saveableFields());
            $data = [];
            foreach ($allowed as $fieldName) {
                $data[$fieldName] = $current->$fieldName;
            }

            $fields->findOrMakeTab(
                'Root.WorkflowActions',
                _t('Workflow.WorkflowActionsTabTitle', 'Workflow Actions')
            );
            $fields->addFieldsToTab('Root.WorkflowActions', $wfFields);

            $form->loadDataFrom($data);

            // Set the form to readonly if the current user doesn't have permission to edit the record, and/or it
            // is in a state that requires review
            if (!$record->canEditWorkflow() && !$fields->isReadonly()) {
                $fields->makeReadonly();
            }

            $this->owner->extend('updateWorkflowEditForm', $form);
        }
    }
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));
    }
776862
public static function signup_form($mform) {
        if ($url = static::get_embed_url()) {
            $mform->addElement('header', 'policyagreement', get_string('policyagreement'), '');
            $mform->setExpanded('policyagreement');
            $mform->addElement('static', 'policylink', '', '<a href="' . $url .
                '" onclick="this.target=\'_blank\'">' . get_string('policyagreementclick') . '</a>');
            $mform->addElement('checkbox', 'policyagreed', get_string('policyaccept'));
            $mform->addRule('policyagreed', get_string('policyagree'), 'required', null, 'client');
        }
    }
8774
public function save($validate = true)
    {
        // if document already in db and not modified - skip this method
        if (!$this->isSaveRequired()) {
            return $this;
        }

        if ($validate) {
            $this->validate();
        }

        // handle beforeSave event
        if ($this->triggerEvent(self::EVENT_NAME_BEFORE_SAVE)->isCancelled()) {
            return $this;
        }

        // write document
        if ($this->isStored()) {
            $this->internalUpdate();
        } else {
            $this->internalInsert();
        }

        // handle afterSave event
        $this->triggerEvent(self::EVENT_NAME_AFTER_SAVE);

        // set document unmodified
        $this->apply();
        
        return $this;
    }
87766
public static function populateForm(Form $form)
	{
		if (static::$builder === null)
		{
			static::setBuilder(new V1Model);

			static::$builder->setWrapperElement(null);
		}

		$elements = static::$builder->generate(get_called_class());

		return $form->setContents($elements);
	}
360211
public function setForm($form)
    {
        // Associate Fields with Form:
        
        $this->honeypot->setForm($form);
        $this->timestamp->setForm($form);
        
        // Call Parent Method:
        
        return parent::setForm($form);
    }