Save changes to a valuelist

@param $slug
@param $postValues

@throws \Exception
961857
public function saveValuelist($slug, $postValues)
    {
        $valuelistObject = ValuelistFactory::createValuelistFromPostValues($postValues);

        $valuelists = $this->repository->valuelists;
        foreach ($valuelists as $key => $valuelist) {
            if ($valuelist->slug == $slug) {
                $valuelists[$key] = $valuelistObject;
            }
        }
        $this->repository->valuelists = $valuelists;
        $this->save();
    }
953574
public function Save($FormPostValues) {
      $Session = Gdn::Session();
      
      // Define the primary key in this model's table.
      $this->DefineSchema();
      
      // Add & apply any extra validation rules:
      $this->Validation->ApplyRule('Body', 'Required');
      $this->Validation->AddRule('MeAction', 'function:ValidateMeAction');
      $this->Validation->ApplyRule('Body', 'MeAction');
      $MaxCommentLength = Gdn::Config('Vanilla.Comment.MaxLength');
      if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) {
         $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength);
         $this->Validation->ApplyRule('Body', 'Length');
      }
      
      // Validate category permissions.
      $CategoryID = GetValue('CategoryID', $FormPostValues);
      if ($CategoryID > 0) {
         $Category = CategoryModel::Categories($CategoryID);
         if ($Category && !$Session->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', GetValue('PermissionCategoryID', $Category)))
            $this->Validation->AddValidationResult('CategoryID', 'You do not have permission to post in this category');
      }
      
      // Get the DiscussionID from the form so we know if we are inserting or updating.
      $DiscussionID = ArrayValue('DiscussionID', $FormPostValues, '');
      
      // See if there is a source ID.
      if (GetValue('SourceID', $FormPostValues)) {
         $DiscussionID = $this->SQL->GetWhere('Discussion', ArrayTranslate($FormPostValues, array('Source', 'SourceID')))->Value('DiscussionID');
         if ($DiscussionID)
            $FormPostValues['DiscussionID'] = $DiscussionID;
      } elseif (GetValue('ForeignID', $FormPostValues)) {
         $DiscussionID = $this->SQL->GetWhere('Discussion', array('ForeignID' => $FormPostValues['ForeignID']))->Value('DiscussionID');
         if ($DiscussionID)
            $FormPostValues['DiscussionID'] = $DiscussionID;
      }
      
      $Insert = $DiscussionID == '' ? TRUE : FALSE;
		$this->EventArguments['Insert'] = $Insert;
      
      if ($Insert) {
         unset($FormPostValues['DiscussionID']);
         // If no categoryid is defined, grab the first available.
         if (!GetValue('CategoryID', $FormPostValues) && !C('Vanilla.Categories.Use')) {
            $FormPostValues['CategoryID'] = GetValue('CategoryID', CategoryModel::DefaultCategory(), -1);
         }
            
         $this->AddInsertFields($FormPostValues);
         
         // The UpdateUserID used to be required. Just add it if it still is.
         if (!$this->Schema->GetProperty('UpdateUserID', 'AllowNull', TRUE)) {
            $FormPostValues['UpdateUserID'] = $FormPostValues['InsertUserID'];
         }
         
         // $FormPostValues['LastCommentUserID'] = $Session->UserID;
         $FormPostValues['DateLastComment'] = $FormPostValues['DateInserted'];
      } else {
         // Add the update fields.
         $this->AddUpdateFields($FormPostValues);
      }
      
      // Set checkbox values to zero if they were unchecked
      if (ArrayValue('Announce', $FormPostValues, '') === FALSE)
         $FormPostValues['Announce'] = 0;

      if (ArrayValue('Closed', $FormPostValues, '') === FALSE)
         $FormPostValues['Closed'] = 0;

      if (ArrayValue('Sink', $FormPostValues, '') === FALSE)
         $FormPostValues['Sink'] = 0;
		
		//	Prep and fire event
		$this->EventArguments['FormPostValues'] = &$FormPostValues;
		$this->EventArguments['DiscussionID'] = $DiscussionID;
		$this->FireEvent('BeforeSaveDiscussion');
         
      // Validate the form posted values
      $this->Validate($FormPostValues, $Insert);
      $ValidationResults = $this->ValidationResults();
      
      // If the body is not required, remove it's validation errors.
      $BodyRequired = C('Vanilla.DiscussionBody.Required', TRUE);
      if (!$BodyRequired && array_key_exists('Body', $ValidationResults))
         unset($ValidationResults['Body']);
      
      if (count($ValidationResults) == 0) {
         // If the post is new and it validates, make sure the user isn't spamming
         if (!$Insert || !$this->CheckForSpam('Discussion')) {
            // Get all fields on the form that relate to the schema
            $Fields = $this->Validation->SchemaValidationFields(); 
            
            // Get DiscussionID if one was sent
            $DiscussionID = intval(ArrayValue('DiscussionID', $Fields, 0));
            
            // Remove the primary key from the fields for saving
            $Fields = RemoveKeyFromArray($Fields, 'DiscussionID');
            
            $StoredCategoryID = FALSE;
            
            if ($DiscussionID > 0) {
               // Updating
               $Stored = $this->GetID($DiscussionID, DATASET_TYPE_ARRAY);
               
               // Clear the cache if necessary.
               if (GetValue('Announce', $Stored) != GetValue('Announce', $Fields)) {
                  $CacheKeys = array('Announcements');
                  $this->SQL->Cache($CacheKeys);
               }

               self::SerializeRow($Fields);
               $this->SQL->Put($this->Name, $Fields, array($this->PrimaryKey => $DiscussionID));

               SetValue('DiscussionID', $Fields, $DiscussionID);
               LogModel::LogChange('Edit', 'Discussion', (array)$Fields, $Stored);
               
               if (GetValue('CategoryID', $Stored) != GetValue('CategoryID', $Fields)) 
                  $StoredCategoryID = GetValue('CategoryID', $Stored);
               
            } else {
               // Inserting.
               if (!GetValue('Format', $Fields) || C('Garden.ForceInputFormatter'))
                  $Fields['Format'] = C('Garden.InputFormatter', '');
               
               if (C('Vanilla.QueueNotifications')) {
                  $Fields['Notified'] = ActivityModel::SENT_PENDING;
               }
               
               // Check for spam.
               $Spam = SpamModel::IsSpam('Discussion', $Fields);
            	if ($Spam)
                  return SPAM;
                  
               // Check for approval
					$ApprovalRequired = CheckRestriction('Vanilla.Approval.Require');
					if ($ApprovalRequired && !GetValue('Verified', Gdn::Session()->User)) {
               	LogModel::Insert('Pending', 'Discussion', $Fields);
               	return UNAPPROVED;
               }
					
               // Create discussion
               $DiscussionID = $this->SQL->Insert($this->Name, $Fields);
               $Fields['DiscussionID'] = $DiscussionID;
                  
               // Update the cache.
               if ($DiscussionID && Gdn::Cache()->ActiveEnabled()) {
                  $CategoryCache = array(
                     'LastDiscussionID' => $DiscussionID,
                     'LastCommentID' => NULL,
                     'LastTitle' => Gdn_Format::Text($Fields['Name']), // kluge so JoinUsers doesn't wipe this out.
                     'LastUserID' => $Fields['InsertUserID'],
                     'LastDateInserted' => $Fields['DateInserted'],
                     'LastUrl' => DiscussionUrl($Fields)
                  );
                  CategoryModel::SetCache($Fields['CategoryID'], $CategoryCache);
                  
                  // Clear the cache if necessary.
                  if (GetValue('Announce', $Fields)) {
                     Gdn::Cache()->Remove('Announcements');
                  }
               }
               
               // Update the user's discussion count.
               $this->UpdateUserDiscussionCount(Gdn::Session()->UserID);
               
               // Assign the new DiscussionID to the comment before saving.
               $FormPostValues['IsNewDiscussion'] = TRUE;
               $FormPostValues['DiscussionID'] = $DiscussionID;
               
               // Do data prep.
					$DiscussionName = ArrayValue('Name', $Fields, '');
               $Story = ArrayValue('Body', $Fields, '');
               $NotifiedUsers = array();
               
               $UserModel = Gdn::UserModel();
               $ActivityModel = new ActivityModel();
               
               if (GetValue('Type', $FormPostValues))
                  $Code = 'HeadlineFormat.Discussion.'.$FormPostValues['Type'];
               else
                  $Code = 'HeadlineFormat.Discussion';
               
               $HeadlineFormat = T($Code, '{ActivityUserID,user} started a new discussion: <a href="{Url,html}">{Data.Name,text}</a>');
               $Category = CategoryModel::Categories(GetValue('CategoryID', $Fields));
               $Activity = array(
                  'ActivityType' => 'Discussion',
                  'ActivityUserID' => $Fields['InsertUserID'],
                  'HeadlineFormat' => $HeadlineFormat,
                  'RecordType' => 'Discussion',
                  'RecordID' => $DiscussionID,
                  'Route' => DiscussionUrl($Fields),
                  'Data' => array(
                     'Name' => $DiscussionName,
                     'Category' => GetValue('Name', $Category)
                  )
               );
               
               // Allow simple fulltext notifications
               if (C('Vanilla.Activity.ShowDiscussionBody', FALSE))
                  $Activity['Story'] = $Story;
               
               // Notify all of the users that were mentioned in the discussion.
               $Usernames = array_merge(GetMentions($DiscussionName), GetMentions($Story));
               $Usernames = array_unique($Usernames);
               
               // Use our generic Activity for events, not mentions
               $this->EventArguments['Activity'] = $Activity;
               
               // Notifications for mentions
               foreach ($Usernames as $Username) {
                  $User = $UserModel->GetByUsername($Username);
                  if (!$User)
                     continue;
                  
                  // Check user can still see the discussion.
                  if (!$UserModel->GetCategoryViewPermission($User->UserID, GetValue('CategoryID', $Fields)))
                     continue;
                  
                  $Activity['HeadlineFormat'] = T('HeadlineFormat.Mention', '{ActivityUserID,user} mentioned you in <a href="{Url,html}">{Data.Name,text}</a>');
                  
                  $Activity['NotifyUserID'] = GetValue('UserID', $User);
                  $ActivityModel->Queue($Activity, 'Mention');
               }
                              
               // Notify everyone that has advanced notifications.
               if (!C('Vanilla.QueueNotifications')) {
                  try {
                     $Fields['DiscussionID'] = $DiscussionID;
                     $this->NotifyNewDiscussion($Fields, $ActivityModel, $Activity);
                  } catch(Exception $Ex) {
                     throw $Ex;
                  }
               }
               
               // Throw an event for users to add their own events.
               $this->EventArguments['Discussion'] = $Fields;
               $this->EventArguments['NotifiedUsers'] = $NotifiedUsers;
               $this->EventArguments['MentionedUsers'] = $Usernames;
               $this->EventArguments['ActivityModel'] = $ActivityModel;
               $this->FireEvent('BeforeNotification');

               // Send all notifications.
               $ActivityModel->SaveQueue();
            }
            
            // Get CategoryID of this discussion
            
            $Discussion = $this->GetID($DiscussionID, DATASET_TYPE_ARRAY);
            $CategoryID = GetValue('CategoryID', $Discussion, FALSE);
            
            // Update discussion counter for affected categories
            $this->UpdateDiscussionCount($CategoryID, $Insert ? $Discussion : FALSE);
            if ($StoredCategoryID)
               $this->UpdateDiscussionCount($StoredCategoryID);
				
				// Fire an event that the discussion was saved.
				$this->EventArguments['FormPostValues'] = $FormPostValues;
				$this->EventArguments['Fields'] = $Fields;
				$this->EventArguments['DiscussionID'] = $DiscussionID;
				$this->FireEvent('AfterSaveDiscussion');
         }
      }
      
      return $DiscussionID;
   }
611900
public function addImage($postValues)
    {
        $destinationPath = $this->getDestinationPath();

        $filename = $this->validateFilename($postValues['name'], $destinationPath);
        $destination = $destinationPath . DIRECTORY_SEPARATOR . $filename;

        if ('0' != $postValues['error']) {
            throw new \RuntimeException('Error uploading file. Error code: ' . $postValues['error']);
        }

        if (move_uploaded_file($postValues['tmp_name'], $destination)) {
            $imageResizer = new ImageResizer($this->getImageSet()->getImageSet());
            $fileNames = $imageResizer->applyImageSetToImage($destination);
            $fileNames['original'] = $filename;
            $imageObject = ImageFactory::createImageFromPostValues($postValues, $filename, $fileNames);

            $images = $this->repository->images;
            $images[] = $imageObject;
            $this->repository->images = $images;

            $this->save();

            return $imageObject;
        } else {
            throw new \RuntimeException('Error moving uploaded file');
        }
    }
932892
final public function saveValues() {
		// double check if we have collection object
		if (empty($this->collection_object)) {
			Throw new \Exception('You must provide collection object!');
		}
		$options = [
			'flag_delete_row' => $this->process_submit[self::BUTTON_SUBMIT_DELETE] ?? false,
			'skip_type_validation' => true,
			'skip_optimistic_lock' => $this->options['skip_optimistic_lock'] ?? false,
			'form_class' => $this->form_class,
			'max_records' => $this->misc_settings['max_records'] ?? [],
		];
		// we do not need to reload values from database because we locked them
		if ($this->values_loaded) {
			$options['original'] = $this->original_values;
		}
		$result = $this->collection_object->merge($this->values, $options);
		if (!$result['success']) {
			if (!empty($result['error'])) {
				foreach ($result['error'] as $v) {
					$this->error('danger', $v);
				}
			}
			// show warnings
			if (!empty($result['warning'])) {
				foreach ($result['warning'] as $v) {
					$this->error('warning', $v);
				}
			}
			$this->rollback = true;
			return false;
		} else { // if success
			// show warnings
			if (!empty($result['warning'])) {
				foreach ($result['warning'] as $v) {
					$this->error('warning', $v);
				}
			}
			// success messages
			if (!empty($result['deleted'])) { // deleted
				$this->values_deleted = true;
			} else if ($result['inserted']) { // inseted
				$this->values_inserted = true;
				// we must put serial columns back into values
				if (!empty($result['new_serials'])) {
					$this->new_serials = $result['new_serials'];
					$this->values = array_merge_hard($this->values, $result['new_serials']);
					$this->loadPk($this->values);
				}
			} else if (!empty($result['updated'])) { // updated
				$this->values_updated = true;
				// merge updated pk
				$this->pk = array_merge_hard($this->pk, $result['new_pk']);
			} else { // if no update/insert/delete we rollback
				$this->values_no_changes = true;
				return false;
			}
			return true;
		}
	}
726591
protected function save($value, \WP_Post $post = null){
        switch( $this->field ){
            case 'post_meta':
                update_post_meta($post->ID, $this->name, $value);
                break;
            default:
                $post_id = intval($value);
                // TODO: Reconsider updating post row logic
                /** @var \wpdb $wpdb */
                global $wpdb;
                $wpdb->update($wpdb->posts, ['post_parent' => $post_id], ['ID' => $post->ID], ['%d'], ['%d']);
                clean_post_cache($post);
                break;
        }
    }
1341040
public function postProcessFormValues(array $formValues)
    {
        $settings = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            'Lightwerk.SurfCaptain');
        $driver = $settings['sources']['default']['driver'];
        $repositories = Arrays::trimExplode(',', $formValues['repositories']);
        // reset
        $this->distributionSettings['Lightwerk']['SurfCaptain']['sources']['default']['repositories'] = [];
        for ($i = 0; $i < count($repositories); $i++) {
            $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                'Lightwerk.SurfCaptain.sources.default.repositories.' . $i, $repositories[$i]);
        }
        $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
            'Lightwerk.SurfCaptain.sources.default.privateToken', $formValues['privateToken']);
        switch ($driver) {
            case 'GitHub':
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.accountName', 'git@github.com');
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.apiUrl', 'https://api.github.com/');
                break;
            case 'GitLab':
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.accountName', $formValues['accountName']);
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.apiUrl', $formValues['apiUrl']);
                break;
            case 'BitBucket':
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.accountName', $formValues['accountName']);
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.apiUrl', 'https://api.bitbucket.org/2.0/');
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.fallbackApiUrl', 'https://api.bitbucket.org/1.0/');
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.privateSecret', $formValues['privateSecret']);
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.accessToken', $formValues['accessToken']);
                $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings,
                    'Lightwerk.SurfCaptain.sources.default.accessSecret', $formValues['accessSecret']);
                break;
            default:
                throw new SetupException('Unknown driver ' . $driver, 1427623122);
        }
        $this->configurationSource->save(FLOW_PATH_CONFIGURATION . ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            $this->distributionSettings);
    }
305334
public function addFile($postValues)
    {
        $destinationPath = $this->getDestinationPath();

        $filename = $this->validateFilename($postValues['name'], $destinationPath);
        $destination = $destinationPath . '/' . $filename;

        if ('0' != $postValues['error']) {
            throw new \RuntimeException('Error uploading file. Error code: ' . $postValues['error']);
        }

        if (move_uploaded_file($postValues['tmp_name'], $destination)) {
            $file = FileFactory::createFileFromPostValues($postValues, $filename);

            $files = $this->repository->files;
            $files[] = $file;
            $this->repository->files = $files;
            $this->save();
        } else {
            throw new \RuntimeException('Error moving uploaded file');
        }
        return $file;
    }
551003
public function onValueChanged(ValueChangedEvent $event)
    {
        // @todo Possible optimization: only track events for EmbedRoot entities,
        // what will save some memory when dealing with deeply nested embed structures.
        $this->changes->push($event);
        $this->propagateEntityChangedEvent($event);
    }
503411
public void save(Map<String, Object> changedValues) {
        operationDelegate.onSaveResource(IIOP_OPENJDK_SUBSYSTEM_TEMPLATE, null, changedValues,
                new CrudOperationDelegate.Callback() {
                    @Override
                    public void onSuccess(final AddressTemplate addressTemplate, final String name) {
                        Console.info(Console.MESSAGES.modified("IIOP Subsystem"));
                        refresh();
                    }

                    @Override
                    public void onFailure(final AddressTemplate addressTemplate, final String name, final Throwable t) {
                        Console.error(Console.MESSAGES.modificationFailed("IIOP Subsystem"), t.getMessage());
                        refresh();
                    }
                });
    }
139987
private static function createBrickObject($postValues, $title, $slug)
    {
        $brickObject = new \stdClass();
        $brickObject->title = $title;
        $brickObject->slug = StringUtil::slugify($title);
        $brickObject->brickSlug = $postValues['brickBricks'][$slug];
        $brickObject->multiple = ($postValues['brickMultiples'][$slug] === 'true');

        return $brickObject;
    }
655175
public function init()
    {
        // Update slug
        $slug = Helpers::urlize($this->getModel()->getSlug());
        $this->getModel()->setSlug($slug);

        // Check forbidden slugs
        if (in_array($slug, $this->forbidden_slugs)) {
            throw new PosttypeException(Translate::t('posttype.errors.slug_is_forbidden'));
        }

        // Update args on post types except reserved ones
        if (!in_array($slug, $this->reserved_slugs)) {
            // Check if post type already exists
            if (post_type_exists($slug)) {
                throw new PosttypeException(Translate::t('posttype.errors.slug_already_exists'));
            }

            $args = $this->getModel()->getArgs();
            $labels = $this->getModel()->getLabels();

            // Initialize plural and singular vars
            $labels['name'] = isset($labels['name']) ? $labels['name'] : '';
            $labels['singular_name'] = isset($labels['singular_name']) ? $labels['singular_name'] : '';

            // Check label for all except reserved ones
            if (empty($labels['name']) || empty($labels['singular_name'])) {
                throw new PosttypeException(Translate::t('posttype.errors.term_is_not_defined'));
            }

            $args = array_merge($this->defaultArgs(), $args);
            $args['labels'] = array_merge(
                $this->defaultLabels($labels['name'], $labels['singular_name']),
                $labels
            );

            // Update PosttypeModel args
            $this->getModel()->setArgs($args);
            $this->getModel()->setLabels($labels);
        }

        // Register post type
        $this->register();
    }
172449
public void updatePostMetaValue(final long postId, final String metaKey, final String metaValue) throws SQLException {

      Meta currMeta = selectPostMetaValue(postId, metaKey);
      if(currMeta == null) {
         Connection conn = null;
         PreparedStatement stmt = null;
         Timer.Context ctx = metrics.setPostMetaTimer.time();
         try {
            conn = connectionSupplier.getConnection();
            stmt = conn.prepareStatement(insertPostMetaSQL);
            stmt.setLong(1, postId);
            stmt.setString(2, metaKey);
            stmt.setString(3, metaValue);
            stmt.executeUpdate();
         } finally {
            ctx.stop();
            SQLUtil.closeQuietly(conn, stmt);
         }
      } else {
         Connection conn = null;
         PreparedStatement stmt = null;
         Timer.Context ctx = metrics.setPostMetaTimer.time();
         try {
            conn = connectionSupplier.getConnection();
            stmt = conn.prepareStatement(updatePostMetaValueSQL);
            stmt.setString(1, metaValue);
            stmt.setString(2, metaKey);
            stmt.setLong(3, postId);
            stmt.executeUpdate();
         } finally {
            ctx.stop();
            SQLUtil.closeQuietly(conn, stmt);
         }
      }
   }
686201
public function save_post($post_id, \WP_Post $post ){
        // Skip auto save
        if( wp_is_post_revision($post) || wp_is_post_autosave($post) ){
            return;
        }
        // Check Nonce
        if( !$this->verify_nonce() ){
            return;
        }
        // O.K., let's save
        foreach( $this->loop_fields() as $field ){
            try{
                if( is_wp_error($field) ){
                    /** @var \WP_Error $field */
                    throw new \Exception($field->get_error_message(), $field->get_error_code());
                }
                if( !$this->is_override_field($field->name) ){
                    /** @var \WPametu\UI\Field\Base $field */
                    $field->update($this->input->post($field->name), $post);
                }
            }catch ( \Exception $e ){
                $this->prg->addErrorMessage($e->getMessage());
            }

        }
    }
918172
public function addDocumentType($postValues)
    {
        $documentTypeObject = DocumentTypeFactory::createDocumentTypeFromPostValues($postValues);

        $documentTypes = $this->repository->documentTypes;
        $documentTypes[] = $documentTypeObject;
        $this->repository->documentTypes = $documentTypes;

        $this->save();
    }
1204027
public function saveSitemapItem($slug, $postValues)
    {
        $sitemapObject = SitemapItemFactory::createSitemapItemFromPostValues($postValues);

        $sitemap = $this->repository->sitemap;
        foreach ($sitemap as $key => $sitemapItem) {
            if ($sitemapItem->slug == $slug) {
                $sitemap[$key] = $sitemapObject;
            }
        }
        $this->repository->sitemap = $sitemap;
        $this->save();
    }
952144
public function postProcessFormValues(array $formValues)
    {
        if (empty($formValues['defaultDeploymentPath']) === false) {
            $this->distributionSettings = Arrays::setValueByPath(
                $this->distributionSettings,
                'Lightwerk.SurfCaptain.frontendSettings.defaultDeploymentPath',
                $formValues['defaultDeploymentPath']
            );
        }
        if (empty($formValues['defaultUser']) === false) {
            $this->distributionSettings = Arrays::setValueByPath(
                $this->distributionSettings,
                'Lightwerk.SurfCaptain.frontendSettings.defaultUser',
                $formValues['defaultUser']
            );
        }
        $this->configurationSource->save(
            FLOW_PATH_CONFIGURATION . ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            $this->distributionSettings
        );
    }
931067
public function InsertForApproval($FormPostValues, $Options = array()) {
      $RoleIDs = C('Garden.Registration.ApplicantRoleID');
      if (!$RoleIDs) {
         throw new Exception(T('The default role has not been configured.'), 400);
      }

      // Define the primary key in this model's table.
      $this->DefineSchema();

      // Add & apply any extra validation rules:
      $this->Validation->ApplyRule('Email', 'Email');

      // Make sure that the checkbox val for email is saved as the appropriate enum
      if (array_key_exists('ShowEmail', $FormPostValues))
         $FormPostValues['ShowEmail'] = ForceBool($FormPostValues['ShowEmail'], '0', '1', '0');
      
      if (array_key_exists('Banned', $FormPostValues))
         $FormPostValues['Banned'] = ForceBool($FormPostValues['Banned'], '0', '1', '0');

      $this->AddInsertFields($FormPostValues);

      if ($this->Validate($FormPostValues, TRUE)) {
         // Check for spam.
         $Spam = SpamModel::IsSpam('Registration', $FormPostValues);
         if ($Spam) {
            $this->Validation->AddValidationResult('Spam', 'You are not allowed to register at this time.');
            return;
         }

         $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above)
         $Username = ArrayValue('Name', $Fields);
         $Email = ArrayValue('Email', $Fields);
         $Fields = $this->Validation->SchemaValidationFields(); // Only fields that are present in the schema
         $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);

         if (!$this->ValidateUniqueFields($Username, $Email))
            return FALSE;

         // Define the other required fields:
         $Fields['Email'] = $Email;
         $Fields['Roles'] = (array)$RoleIDs;

         // And insert the new user
         $UserID = $this->_Insert($Fields, $Options);
      } else {
         $UserID = FALSE;
      }
      return $UserID;
   }