Extension hook {@see DataObject::requireDefaultRecords}

@return void
489303
public function requireDefaultRecords()
    {
        if (!$this->supportsElemental()) {
            return;
        }

        $ownerClass = get_class($this->owner);
        $elementalAreas = $this->owner->getElementalRelations();
        $schema = $this->owner->getSchema();

        // There is no inbuilt filter for null values
        $where = [];
        foreach ($elementalAreas as $areaName) {
            $queryDetails = $schema->sqlColumnForField($ownerClass, $areaName . 'ID');
            $where[] = $queryDetails . ' IS NULL OR ' . $queryDetails . ' = 0' ;
        }

        foreach ($ownerClass::get()->where(implode(' OR ', $where)) as $elementalObject) {
            $elementalObject->ensureElementalAreasExist($elementalAreas)->write();
        }
    }
982219
private function fill_defaults()
	{
		if ( ! array_key_exists('ID', $this->attributes) ) {

			$this->attributes['post_type'] = $this->type;

			$this->attributes['post_status'] = $this->status;

		}
	}
1192098
public function requireDefaultRecords()
    {
        // Require Default Records (from parent):
        
        parent::requireDefaultRecords();
        
        // Create Default Folders:
        
        Folder::singleton()->createDefaultFolders();
        
        // Obtain App Instance:
        
        $app = self::instance();
        
        // Load Defaults:
        
        $app->loadDefaults();
        
        // Load Fixtures:
        
        $app->loadFixtures();
    }
76581
protected function getDefaultRecords()
    {
        $data = array(
            array(
                'ErrorCode' => 404,
                'Title' => _t('SilverStripe\\ErrorPage\\ErrorPage.DEFAULTERRORPAGETITLE', 'Page not found'),
                'Content' => _t(
                    'SilverStripe\\ErrorPage\\ErrorPage.DEFAULTERRORPAGECONTENT',
                    '<p>Sorry, it seems you were trying to access a page that doesn\'t exist.</p>'
                    . '<p>Please check the spelling of the URL you were trying to access and try again.</p>'
                )
            ),
            array(
                'ErrorCode' => 500,
                'Title' => _t('SilverStripe\\ErrorPage\\ErrorPage.DEFAULTSERVERERRORPAGETITLE', 'Server error'),
                'Content' => _t(
                    'SilverStripe\\ErrorPage\\ErrorPage.DEFAULTSERVERERRORPAGECONTENT',
                    '<p>Sorry, there was a problem with handling your request.</p>'
                )
            )
        );

        $this->extend('getDefaultRecords', $data);

        return $data;
    }
792488
public function import(array $definitions, array $records, array $defaultAttributes = [], $persist = true): array
    {
        $imported = [];
        $recordsByHandle = $this->getRecordsByHandle($records);
        foreach ($definitions as $handle => $definition) {
            $modelClass = $definition['class'];
            $converter = Craft::$app->controller->module->getConverter($modelClass);
            if ($converter) {
                $record = $this->findOrNewRecord($recordsByHandle, $definition, $handle);

                if ($converter->getRecordDefinition($record) === $definition) {
                    Schematic::info('- Skipping '.get_class($record).' '.$handle);
                } else {
                    $converter->setRecordAttributes($record, $definition, $defaultAttributes);
                    if ($persist) {
                        Schematic::info('- Saving '.get_class($record).' '.$handle);
                        if (!$converter->saveRecord($record, $definition)) {
                            Schematic::importError($record, $handle);
                        }
                    }
                }

                $imported[] = $record;
            }
            unset($recordsByHandle[$handle]);
        }

        if (Schematic::$force && $persist) {
            // Delete records not in definitions
            foreach ($recordsByHandle as $handle => $record) {
                $modelClass = get_class($record);
                Schematic::info('- Deleting '.get_class($record).' '.$handle);
                $converter = Craft::$app->controller->module->getConverter($modelClass);
                $converter->deleteRecord($record);
            }
        }

        return $imported;
    }
226571
protected function setRequiredFieldsConditional()
    {
        $requiredParamsIbanSwiftCode = ['iban', 'swift_code'];

        $requiredFieldsConditional = [
            'billing_country' => [
                'AE' => $requiredParamsIbanSwiftCode,
                'AT' => $requiredParamsIbanSwiftCode,
                'AU' => ['account_number', 'branch_code'],
                'BE' => $requiredParamsIbanSwiftCode,
                'BG' => ['iban'],
                'CA' => ['account_number', 'branch_code', 'bank_code', 'bank_name'],
                'CY' => $requiredParamsIbanSwiftCode,
                'CZ' => ['iban'],
                'DE' => $requiredParamsIbanSwiftCode,
                'DK' => ['account_number', 'bank_code'],
                'EE' => $requiredParamsIbanSwiftCode,
                'ES' => $requiredParamsIbanSwiftCode,
                'FI' => $requiredParamsIbanSwiftCode,
                'FR' => $requiredParamsIbanSwiftCode,
                'GB' => ['account_number', 'bank_code'],
                'GF' => $requiredParamsIbanSwiftCode,
                'GP' => $requiredParamsIbanSwiftCode,
                'GR' => $requiredParamsIbanSwiftCode,
                'HU' => ['account_number'],
                'IE' => $requiredParamsIbanSwiftCode,
                'IT' => $requiredParamsIbanSwiftCode,
                'LT' => $requiredParamsIbanSwiftCode,
                'LU' => $requiredParamsIbanSwiftCode,
                'LV' => $requiredParamsIbanSwiftCode,
                'MC' => $requiredParamsIbanSwiftCode,
                'MQ' => $requiredParamsIbanSwiftCode,
                'MT' => $requiredParamsIbanSwiftCode,
                'MX' => ['iban', 'bank_name'],
                'NL' => $requiredParamsIbanSwiftCode,
                'PL' => ['iban'],
                'PT' => $requiredParamsIbanSwiftCode,
                'RE' => $requiredParamsIbanSwiftCode,
                'SE' => ['iban'],
                'SI' => $requiredParamsIbanSwiftCode,
                'SK' => $requiredParamsIbanSwiftCode
            ]
        ];

        $this->requiredFieldsConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldsConditional);
    }
1328552
public function addConstraints()
    {
        $localValue = $this->farParent[$this->localKey];

        $this->performJoin();

        if (static::$constraints) {
            $this->query->where($this->getQualifiedFirstKeyName(), '=', $localValue);
        }
    }
1111625
private function _setDefaults()
    {
        if (!isset(self::$_template))
            self::_initializeDefaults();
        foreach (self::$_template as $k=>$v) {
            if ($k[0] != '_')
                $this->$k = $v;
        }
        return $this;
    }
724541
public function requireDefaultRecords() {
        parent::requireDefaultRecords();
        
        $defaultLangs=array_keys($this->defaultLanguages);
        $dbLangCount=SnippetLanguage::get()
                                        ->filter('Name', $defaultLangs)
                                        ->filter('UserLanguage', 0)
                                        ->Count();
        if($dbLangCount<count($defaultLangs)) {
            foreach($this->defaultLanguages as $name=>$data) {
                if(!SnippetLanguage::get()->find('Name', $name)) {
                    $lang=new SnippetLanguage();
                    $lang->Name=$name;
                    $lang->FileExtension=$data['Extension'];
                    $lang->HighlightCode=$data['HighlightCode'];
                    $lang->UserLanguage=false;
                    $lang->write();
                    
                    DB::alteration_message('Created snippet language "'.$name.'"', 'created');
                }
            }
        }
        
        
        //Look for config languages
        $configLanguages=CodeBank::config()->extra_languages;
        if(!empty($configLanguages)) {
            foreach($configLanguages as $language) {
                //Validate languages
                if(empty($language['Name']) || empty($language['FileName']) || empty($language['HighlightCode']) || empty($language['Brush'])) {
                    user_error('Invalid snippet user language found in config, user languages defined in config must contain a Name, FileName, HighlightCode and Brush file path', E_USER_WARNING);
                    continue;
                }
                
                
                $lang=SnippetLanguage::get()
                                            ->filter('Name', Convert::raw2sql($language['Name']))
                                            ->filter('HighlightCode', Convert::raw2sql($language['HighlightCode']))
                                            ->filter('UserLanguage', true)
                                            ->first();
                
                if(empty($lang) || $lang===false || $lang->ID<=0) {
                    if(Director::is_absolute($language['Brush']) || Director::is_absolute_url($language['Brush'])) {
                        user_error('Invalid snippet user language found in config, user languages defined in config must contain a path to the brush relative to the SilverStripe base ('.Director::baseFolder().')', E_USER_WARNING);
                        continue;
                    }
                    
                    if(preg_match('/\.js$/', $language['Brush'])==0) {
                        user_error('Invalid snippet user language found in config, user languages defined in config must be javascript files', E_USER_WARNING);
                        continue;
                    }
                    
                    
                    //Add language
                    $lang=new SnippetLanguage();
                    $lang->Name=$language['Name'];
                    $lang->FileExtension=$language['FileName'];
                    $lang->HighlightCode=$language['HighlightCode'];
                    $lang->BrushFile=$language['Brush'];
                    $lang->UserLanguage=true;
                    $lang->write();
                    
                    DB::alteration_message('Created snippet user language "'.$language['Name'].'"', 'created');
                }
            }
        }
    }
520949
protected function requireDefaultRecordFixture($defaultData)
    {
        $code = $defaultData['ErrorCode'];
        $page = ErrorPage::get()->filter('ErrorCode', $code)->first();
        $pageExists = !empty($page);
        if (!$pageExists) {
            $page = new ErrorPage($defaultData);
            $page->write();
            $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
        }

        // Check if static files are enabled
        if (!self::config()->enable_static_file) {
            return;
        }

        // Ensure this page has cached error content
        $success = true;
        if (!$page->hasStaticPage()) {
            // Update static content
            $success = $page->writeStaticPage();
        } elseif ($pageExists) {
            // If page exists and already has content, no alteration_message is displayed
            return;
        }

        if ($success) {
            DB::alteration_message(
                sprintf('%s error page created', $code),
                'created'
            );
        } else {
            DB::alteration_message(
                sprintf('%s error page could not be created. Please check permissions', $code),
                'error'
            );
        }
    }
11866
protected function setDefaultValue() : void
    {
        if (empty($this->defaultOptions['default'])) {
            return;
        }

        // If we have a default value from configuration, pass it through
        // processing for magic/dynamic values like dates and usernames.
        $eventName = (string)EventName::FIELD_HANDLER_DEFAULT_VALUE();
        $event = new Event($eventName, $this, [
            'default' => $this->defaultOptions['default']
        ]);

        $view = $this->config->getView();
        $view->getEventManager()->dispatch($event);

        // Only overwrite the default if any events were triggered
        $listeners = $view->getEventManager()->listeners($eventName);
        if (empty($listeners)) {
            return;
        }
        $this->defaultOptions['default'] = $event->result;
    }
1214260
public function populateDefaults()
    {
        if (!isset($this->Date) || $this->Date === null) {
            $this->Date = DBDatetime::now()->Format('y-MM-dd');
        }

        if (!isset($this->StartTime) || $this->StartTime === null) {
            $this->StartTime = '09:00:00';
        }

        if (!isset($this->EndTime) || $this->EndTime === null) {
            $this->EndTime = '17:00:00';
        }

        parent::populateDefaults();
    }
521450
protected function fillDataForEmpty()
    {
        // Fill list references if they are empty
        $fields = [];

        // Add fields for attributes
        foreach ($this->info->attributes as $attribute) {

            if ($attribute->hidden || ! $this->shouldAttributeBeDisplayedByDefault($attribute, $this->info)) {
                continue;
            }

            $fields[ $attribute->name ] = $this->makeModelShowFieldDataForAttributeData($attribute, $this->info);
        }

        // Add fields for relations?
        // Perhaps, though it may be fine to leave this up to manual configuration.
        // todo: consider


        $this->info->show->fields = $fields;
    }
1289050
protected function fillDataForEmpty()
    {
        // Fill field references if they are empty
        $fields = [];

        // Add columns for attributes
        foreach ($this->info->attributes as $attribute) {

            if ($attribute->hidden || ! $this->shouldAttributeBeEditableByDefault($attribute, $this->info)) {
                continue;
            }

            $fields[ $attribute->name ] = $this->makeModelFormFieldDataForAttributeData($attribute);
        }


        // Add fields for relations
        foreach ($this->info->relations as $relation) {

            $fields[ $relation->name ] = $this->makeModelFormFieldDataForRelationData($relation);
        }


        $this->info->form->fields = $fields;
    }
1257071
public function addConstraints()
    {
        if (static::$constraints)
        {
            $this->query->where($this->foreignKey, '=', $this->getParentKey());

            $this->query->whereNotNull($this->foreignKey);

            $this->query->where($this->rootKey, '=', $this->getRootKey());

            $this->query->whereNotNull($this->rootKey);

        }
    }
360011
private function ensureHrefDefaultsToNull()
    {
        if (!($this->database->tableExists('tl_metamodel_translatedurl'))) {
            return;
        }

        foreach ($this->database->listFields('tl_metamodel_translatedurl', true) as $field) {
            if ('href' == $field['name'] && $field['type'] != 'index') {
                // Already updated?
                if ('NOT NULL' === $field['null']) {
                    $this->database->execute(
                        'ALTER TABLE `tl_metamodel_translatedurl` CHANGE `href` `href` varchar(255) NULL;'
                    );
                    return;
                }
                // Found!
                break;
            }
        }
    }
296668
public function populateDefaults()
    {
        $defaults = $this->owner->config()->get('defaults');

        // Set if comments should be enabled by default
        if (isset($defaults['ProvideComments'])) {
            $this->owner->ProvideComments = $defaults['ProvideComments'];
        } else {
            $this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0;
        }

        // If moderation options should be configurable via the CMS then
        if (isset($defaults['ModerationRequired'])) {
            $this->owner->ModerationRequired = $defaults['ModerationRequired'];
        } elseif ($this->owner->getCommentsOption('require_moderation')) {
            $this->owner->ModerationRequired = 'Required';
        } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) {
            $this->owner->ModerationRequired = 'NonMembersOnly';
        } else {
            $this->owner->ModerationRequired = 'None';
        }

        // Set login required
        if (isset($defaults['CommentsRequireLogin'])) {
            $this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin'];
        } else {
            $this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0;
        }
    }