/** * Returns a readonly span containing the correct value. * * @param array $properties * * @return string */ public function Field($properties = array()) { $source = ArrayLib::flatten($this->getSource()); $values = $this->getValueArray(); // Get selected values $mapped = array(); foreach ($values as $value) { if (isset($source[$value])) { $mapped[] = $source[$value]; } } // Don't check if string arguments are matching against the source, // as they might be generated HTML diff views instead of the actual values if ($this->value && is_string($this->value) && empty($mapped)) { $mapped = array(trim($this->value)); $values = array(); } if ($mapped) { $attrValue = implode(', ', array_values($mapped)); $attrValue = Convert::raw2xml($attrValue); $inputValue = implode(', ', array_values($values)); } else { $attrValue = '<i>(' . _t('FormField.NONE', 'none') . ')</i>'; $inputValue = ''; } $properties = array_merge($properties, array('AttrValue' => DBField::create_field('HTMLFragment', $attrValue), 'InputValue' => $inputValue)); return parent::Field($properties); }
public function __construct($controller, $name, $fields = null, $actions = null, $validator = null) { if (!$fields) { $helpHtml = _t('MemberImportForm.Help1', '<p>Import users in <em>CSV format</em> (comma-separated values).' . ' <small><a href="#" class="toggle-advanced">Show advanced usage</a></small></p>'); $helpHtml .= _t('MemberImportForm.Help2', '<div class="advanced">' . '<h4>Advanced usage</h4>' . '<ul>' . '<li>Allowed columns: <em>%s</em></li>' . '<li>Existing users are matched by their unique <em>Code</em> property, and updated with any new values from ' . 'the imported file.</li>' . '<li>Groups can be assigned by the <em>Groups</em> column. Groups are identified by their <em>Code</em> property, ' . 'multiple groups can be separated by comma. Existing group memberships are not cleared.</li>' . '</ul>' . '</div>'); $importer = new MemberCsvBulkLoader(); $importSpec = $importer->getImportSpec(); $helpHtml = sprintf($helpHtml, implode(', ', array_keys($importSpec['fields']))); $fields = new FieldList(new LiteralField('Help', $helpHtml), $fileField = new FileField('CsvFile', DBField::create_field('HTMLFragment', _t('SecurityAdmin_MemberImportForm.FileFieldLabel', 'CSV File <small>(Allowed extensions: *.csv)</small>')))); $fileField->getValidator()->setAllowedExtensions(array('csv')); } if (!$actions) { $action = new FormAction('doImport', _t('SecurityAdmin_MemberImportForm.BtnImport', 'Import from CSV')); $action->addExtraClass('btn btn-secondary-outline ss-ui-button'); $actions = new FieldList($action); } if (!$validator) { $validator = new RequiredFields('CsvFile'); } parent::__construct($controller, $name, $fields, $actions, $validator); Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/vendor.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/MemberImportForm.js'); Requirements::css(FRAMEWORK_ADMIN_DIR . '/client/dist/styles/bundle.css'); $this->addExtraClass('cms'); $this->addExtraClass('import-form'); }
/** * Create a new Decimal field. * * @param string $name * @param int $wholeSize * @param int $decimalSize * @param float|int $defaultValue */ public function __construct($name = null, $wholeSize = 9, $decimalSize = 2, $defaultValue = 0) { $this->wholeSize = is_int($wholeSize) ? $wholeSize : 9; $this->decimalSize = is_int($decimalSize) ? $decimalSize : 2; $this->defaultValue = number_format((double) $defaultValue, $decimalSize); parent::__construct($name); }
public function testCasting() { $htmlString = """; $textString = '"'; $htmlField = DBField::create_field('HTMLFragment', $textString); $this->assertEquals($textString, $htmlField->forTemplate()); $this->assertEquals($htmlString, $htmlField->obj('HTMLATT')->forTemplate()); $this->assertEquals('%22', $htmlField->obj('URLATT')->forTemplate()); $this->assertEquals('%22', $htmlField->obj('RAWURLATT')->forTemplate()); $this->assertEquals($htmlString, $htmlField->obj('ATT')->forTemplate()); $this->assertEquals($textString, $htmlField->obj('RAW')->forTemplate()); $this->assertEquals('\\"', $htmlField->obj('JS')->forTemplate()); $this->assertEquals($htmlString, $htmlField->obj('HTML')->forTemplate()); $this->assertEquals($htmlString, $htmlField->obj('XML')->forTemplate()); $textField = DBField::create_field('Text', $textString); $this->assertEquals($htmlString, $textField->forTemplate()); $this->assertEquals($htmlString, $textField->obj('HTMLATT')->forTemplate()); $this->assertEquals('%22', $textField->obj('URLATT')->forTemplate()); $this->assertEquals('%22', $textField->obj('RAWURLATT')->forTemplate()); $this->assertEquals($htmlString, $textField->obj('ATT')->forTemplate()); $this->assertEquals($textString, $textField->obj('RAW')->forTemplate()); $this->assertEquals('\\"', $textField->obj('JS')->forTemplate()); $this->assertEquals($htmlString, $textField->obj('HTML')->forTemplate()); $this->assertEquals($htmlString, $textField->obj('XML')->forTemplate()); }
public function testNice() { $time = DBField::create_field('Time', '17:15:55'); $this->assertEquals('5:15pm', $time->Nice()); Config::inst()->update('SilverStripe\\ORM\\FieldType\\DBTime', 'nice_format', 'H:i:s'); $this->assertEquals('17:15:55', $time->Nice()); }
public function testSafelyCast() { $field1 = new OptionsetField('Options', 'Options', array(1 => 'One', 2 => 'Two & Three', 3 => DBField::create_field('HTMLText', 'Four & Five & Six'))); $fieldHTML = (string) $field1->Field(); $this->assertContains('One', $fieldHTML); $this->assertContains('Two & Three', $fieldHTML); $this->assertNotContains('Two & Three', $fieldHTML); $this->assertContains('Four & Five & Six', $fieldHTML); $this->assertNotContains('Four & Five & Six', $fieldHTML); }
/** * Main BBCode parser method. This takes plain jane content and * runs it through so many filters * * @return DBField */ public function parse() { // Convert content to plain text $this->content = DBField::create_field('HTMLFragment', $this->content)->Plain(); $p = new SSHTMLBBCodeParser(); $this->content = $p->qparse($this->content); unset($p); if ($this->config()->allow_smilies) { $smilies = array('#(?<!\\w):D(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/grin.gif'> ", '#(?<!\\w):\\)(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/smile.gif'> ", '#(?<!\\w):-\\)(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/smile.gif'> ", '#(?<!\\w):\\((?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/sad.gif'> ", '#(?<!\\w):-\\((?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/sad.gif'> ", '#(?<!\\w):p(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/tongue.gif'> ", '#(?<!\\w)8-\\)(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/cool.gif'> ", '#(?<!\\w):\\^\\)(?!\\w)#i' => " <img src='" . BBCodeParser::smilies_location() . "/confused.gif'> "); $this->content = preg_replace(array_keys($smilies), array_values($smilies), $this->content); } // Ensure to return cast value return DBField::create_field('HTMLFragment', $this->content); }
public function testExists() { // True exists $this->assertTrue(DBField::create_field('StringFieldTest_MyStringField', true)->exists()); $this->assertTrue(DBField::create_field('StringFieldTest_MyStringField', '0')->exists()); $this->assertTrue(DBField::create_field('StringFieldTest_MyStringField', '1')->exists()); $this->assertTrue(DBField::create_field('StringFieldTest_MyStringField', 1)->exists()); $this->assertTrue(DBField::create_field('StringFieldTest_MyStringField', 1.1)->exists()); // false exists $this->assertFalse(DBField::create_field('StringFieldTest_MyStringField', false)->exists()); $this->assertFalse(DBField::create_field('StringFieldTest_MyStringField', '')->exists()); $this->assertFalse(DBField::create_field('StringFieldTest_MyStringField', null)->exists()); $this->assertFalse(DBField::create_field('StringFieldTest_MyStringField', 0)->exists()); $this->assertFalse(DBField::create_field('StringFieldTest_MyStringField', 0.0)->exists()); }
public function FieldList() { $items = parent::FieldList()->toArray(); $count = 0; $newItems = array(); foreach ($items as $item) { if ($this->value == $item->getValue()) { $firstSelected = true; $checked = true; } else { $firstSelected = false; $checked = false; } $itemID = $this->ID() . '_' . ++$count; // @todo Move into SelectionGroup_Item.ss template at some point. $extra = array("RadioButton" => DBField::create_field('HTMLFragment', FormField::create_tag('input', array('class' => 'selector', 'type' => 'radio', 'id' => $itemID, 'name' => $this->name, 'value' => $item->getValue(), 'checked' => $checked, 'aria-labelledby' => "title-{$itemID}"))), "RadioLabel" => DBField::create_field('HTMLFragment', FormField::create_tag('label', array('id' => "title-{$itemID}", 'for' => $itemID), $item->getTitle())), "Selected" => $firstSelected); $newItems[] = $item->customise($extra); } return new ArrayList($newItems); }
public function __construct($controller, $name, $fields = null, $actions = null, $validator = null) { if (!$fields) { $helpHtml = _t('GroupImportForm.Help1', '<p>Import one or more groups in <em>CSV</em> format (comma-separated values).' . ' <small><a href="#" class="toggle-advanced">Show advanced usage</a></small></p>'); $helpHtml .= _t('GroupImportForm.Help2', '<div class="advanced">' . '<h4>Advanced usage</h4>' . '<ul>' . '<li>Allowed columns: <em>%s</em></li>' . '<li>Existing groups are matched by their unique <em>Code</em> value, and updated with any new values from the ' . 'imported file</li>' . '<li>Group hierarchies can be created by using a <em>ParentCode</em> column.</li>' . '<li>Permission codes can be assigned by the <em>PermissionCode</em> column. Existing permission codes are not ' . 'cleared.</li>' . '</ul>' . '</div>'); $importer = new GroupCsvBulkLoader(); $importSpec = $importer->getImportSpec(); $helpHtml = sprintf($helpHtml, implode(', ', array_keys($importSpec['fields']))); $fields = new FieldList(new LiteralField('Help', $helpHtml), $fileField = new FileField('CsvFile', DBField::create_field('HTMLFragment', _t('SecurityAdmin_MemberImportForm.FileFieldLabel', 'CSV File <small>(Allowed extensions: *.csv)</small>')))); $fileField->getValidator()->setAllowedExtensions(array('csv')); } if (!$actions) { $action = new FormAction('doImport', _t('SecurityAdmin_MemberImportForm.BtnImport', 'Import from CSV')); $action->addExtraClass('ss-ui-button'); $actions = new FieldList($action); } if (!$validator) { $validator = new RequiredFields('CsvFile'); } parent::__construct($controller, $name, $fields, $actions, $validator); $this->addExtraClass('cms'); $this->addExtraClass('import-form'); }
public function getHTMLFragments($gridField) { $modelClass = $gridField->getModelClass(); $parentID = 0; if ($this->currentID) { $modelObj = DataObject::get_by_id($modelClass, $this->currentID); if ($modelObj->hasMethod('getParent')) { $parent = $modelObj->getParent(); } elseif ($modelObj->ParentID) { $parent = $modelObj->Parent(); } if ($parent) { $parentID = $parent->ID; } // Attributes $attrs = array_merge($this->attributes, array('href' => sprintf($this->linkSpec, $parentID), 'class' => 'cms-panel-link ss-ui-button font-icon-level-up no-text grid-levelup')); $attrsStr = ''; foreach ($attrs as $k => $v) { $attrsStr .= " {$k}=\"" . Convert::raw2att($v) . "\""; } $forTemplate = new ArrayData(array('UpLink' => DBField::create_field('HTMLFragment', sprintf('<a%s></a>', $attrsStr)))); return array('before' => $forTemplate->renderWith('Includes/GridFieldLevelup')); } }
public function getHTMLFragments($gridField) { $modelClass = $gridField->getModelClass(); $parentID = 0; if (!$this->currentID) { return null; } $modelObj = DataObject::get_by_id($modelClass, $this->currentID); $parent = null; if ($modelObj->hasMethod('getParent')) { $parent = $modelObj->getParent(); } elseif ($modelObj->ParentID) { $parent = $modelObj->Parent(); } if ($parent) { $parentID = $parent->ID; } // Attributes $attrs = array_merge($this->attributes, array('href' => sprintf($this->linkSpec, $parentID), 'class' => 'cms-panel-link ss-ui-button font-icon-level-up no-text grid-levelup')); $linkTag = FormField::create_tag('a', $attrs); $forTemplate = new ArrayData(array('UpLink' => DBField::create_field('HTMLFragment', $linkTag))); $template = SSViewer::get_templates_by_class($this, '', __CLASS__); return array('before' => $forTemplate->renderWith($template)); }
/** * The process() method handles the "meat" of the template processing. * * It takes care of caching the output (via {@link Cache}), as well as * replacing the special "$Content" and "$Layout" placeholders with their * respective subtemplates. * * The method injects extra HTML in the header via {@link Requirements::includeInHTML()}. * * Note: You can call this method indirectly by {@link ViewableData->renderWith()}. * * @param ViewableData $item * @param array|null $arguments Arguments to an included template * @param ViewableData $inheritedScope The current scope of a parent template including a sub-template * @return DBHTMLText Parsed template output. */ public function process($item, $arguments = null, $inheritedScope = null) { SSViewer::$topLevel[] = $item; $template = $this->chosen; $cacheFile = TEMP_FOLDER . "/.cache" . str_replace(array('\\', '/', ':'), '.', Director::makeRelative(realpath($template))); $lastEdited = filemtime($template); if (!file_exists($cacheFile) || filemtime($cacheFile) < $lastEdited) { $content = file_get_contents($template); $content = $this->parseTemplateContent($content, $template); $fh = fopen($cacheFile, 'w'); fwrite($fh, $content); fclose($fh); } $underlay = array('I18NNamespace' => basename($template)); // Makes the rendered sub-templates available on the parent item, // through $Content and $Layout placeholders. foreach (array('Content', 'Layout') as $subtemplate) { $sub = null; if (isset($this->subTemplates[$subtemplate])) { $sub = $this->subTemplates[$subtemplate]; } elseif (!is_array($this->templates)) { $sub = ['type' => $subtemplate, $this->templates]; } elseif (!array_key_exists('type', $this->templates) || !$this->templates['type']) { $sub = array_merge($this->templates, ['type' => $subtemplate]); } if ($sub) { $subtemplateViewer = clone $this; // Disable requirements - this will be handled by the parent template $subtemplateViewer->includeRequirements(false); // Select the right template $subtemplateViewer->setTemplate($sub); if ($subtemplateViewer->exists()) { $underlay[$subtemplate] = $subtemplateViewer->process($item, $arguments); } } } $output = $this->includeGeneratedTemplate($cacheFile, $item, $arguments, $underlay, $inheritedScope); if ($this->includeRequirements) { $output = Requirements::includeInHTML($output); } array_pop(SSViewer::$topLevel); // If we have our crazy base tag, then fix # links referencing the current page. $rewrite = SSViewer::config()->get('rewrite_hash_links'); if ($this->rewriteHashlinks && $rewrite) { if (strpos($output, '<base') !== false) { if ($rewrite === 'php') { $thisURLRelativeToBase = "<?php echo \\SilverStripe\\Core\\Convert::raw2att(preg_replace(\"/^(\\\\/)+/\", \"/\", \$_SERVER['REQUEST_URI'])); ?>"; } else { $thisURLRelativeToBase = Convert::raw2att(preg_replace("/^(\\/)+/", "/", $_SERVER['REQUEST_URI'])); } $output = preg_replace('/(<a[^>]+href *= *)"#/i', '\\1"' . $thisURLRelativeToBase . '#', $output); } } return DBField::create_field('HTMLFragment', $output); }
public function __construct($name = null, $defaultVal = 0) { $this->defaultVal = $defaultVal ? 1 : 0; parent::__construct($name); }
/** * Writes a subset of changes for a specific table to the given manipulation * * @param string $baseTable Base table * @param string $now Timestamp to use for the current time * @param bool $isNewRecord Whether this should be treated as a new record write * @param array $manipulation Manipulation to write to * @param string $class Class of table to manipulate */ protected function prepareManipulationTable($baseTable, $now, $isNewRecord, &$manipulation, $class) { $schema = $this->getSchema(); $table = $schema->tableName($class); $manipulation[$table] = array(); // Extract records for this table foreach ($this->record as $fieldName => $fieldValue) { // we're not attempting to reset the BaseTable->ID // Ignore unchanged fields or attempts to reset the BaseTable->ID if (empty($this->changed[$fieldName]) || $table === $baseTable && $fieldName === 'ID') { continue; } // Ensure this field pertains to this table $specification = $schema->fieldSpec($class, $fieldName, DataObjectSchema::DB_ONLY | DataObjectSchema::UNINHERITED); if (!$specification) { continue; } // if database column doesn't correlate to a DBField instance... $fieldObj = $this->dbObject($fieldName); if (!$fieldObj) { $fieldObj = DBField::create_field('Varchar', $fieldValue, $fieldName); } // Write to manipulation $fieldObj->writeToManipulation($manipulation[$table]); } // Ensure update of Created and LastEdited columns if ($baseTable === $table) { $manipulation[$table]['fields']['LastEdited'] = $now; if ($isNewRecord) { $manipulation[$table]['fields']['Created'] = empty($this->record['Created']) ? $now : $this->record['Created']; $manipulation[$table]['fields']['ClassName'] = $this->class; } } // Inserts done one the base table are performed in another step, so the manipulation should instead // attempt an update, as though it were a normal update. $manipulation[$table]['command'] = $isNewRecord ? 'insert' : 'update'; $manipulation[$table]['id'] = $this->record['ID']; $manipulation[$table]['class'] = $class; }
public function testATT() { $data = DBField::create_field('Text', '"this is a test"'); $this->assertEquals($data->ATT(), '"this is a test"'); }
public function testStringFieldsWithMultibyteData() { $plainFields = array('Varchar', 'Text'); $htmlFields = array('HTMLVarchar', 'HTMLText', 'HTMLFragment'); $allFields = array_merge($plainFields, $htmlFields); $value = 'üåäöÜÅÄÖ'; foreach ($allFields as $stringField) { $stringField = DBField::create_field($stringField, $value); for ($i = 1; $i < mb_strlen($value); $i++) { $expected = mb_substr($value, 0, $i) . '...'; $this->assertEquals($expected, $stringField->LimitCharacters($i)); } } $value = '<p>üåäö&ÜÅÄÖ</p>'; foreach ($htmlFields as $stringField) { $stringObj = DBField::create_field($stringField, $value); // Converted to plain text $this->assertEquals('üåäö&ÜÅÄ...', $stringObj->LimitCharacters(8)); // But which will be safely cast in templates $this->assertEquals('üåäö&ÜÅÄ...', $stringObj->obj('LimitCharacters', [8])->forTemplate()); } $this->assertEquals('ÅÄÖ', DBField::create_field('Text', 'åäö')->UpperCase()); $this->assertEquals('åäö', DBField::create_field('Text', 'ÅÄÖ')->LowerCase()); $this->assertEquals('<P>ÅÄÖ</P>', DBField::create_field('HTMLFragment', '<p>åäö</p>')->UpperCase()); $this->assertEquals('<p>åäö</p>', DBField::create_field('HTMLFragment', '<p>ÅÄÖ</p>')->LowerCase()); }
public function testShortCodeParsedInTemplateHelpers() { $parser = ShortcodeParser::get('HTMLTextTest'); $parser->register('shortcode', function ($arguments, $content, $parser, $tagName, $extra) { return 'Replaced short code with this. <a href="home">home</a>'; }); ShortcodeParser::set_active('HTMLTextTest'); /** @var DBHTMLText $field */ $field = DBField::create_field('HTMLText', '<p>[shortcode]</p>'); $this->assertEquals('<p>Replaced short code with this. <a href="home">home</a></p>', $field->HTMLATT()); $this->assertEquals('%3Cp%3EReplaced+short+code+with+this.+%3Ca+href%3D%22home%22%3Ehome%3C%2Fa%3E%3C%2Fp%3E', $field->URLATT()); $this->assertEquals('%3Cp%3EReplaced%20short%20code%20with%20this.%20%3Ca%20href%3D%22home%22%3Ehome%3C%2Fa%3E%3C%2Fp%3E', $field->RAWURLATT()); $this->assertEquals('<p>Replaced short code with this. <a href="home">home</a></p>', $field->ATT()); $this->assertEquals('<p>Replaced short code with this. <a href="home">home</a></p>', $field->RAW()); $this->assertEquals('\\x3cp\\x3eReplaced short code with this. \\x3ca href=\\"home\\"\\x3ehome\\x3c/a\\x3e\\x3c/p\\x3e', $field->JS()); $this->assertEquals('<p>Replaced short code with this. <a href="home">home</a></p>', $field->HTML()); $this->assertEquals('<p>Replaced short code with this. <a href="home">home</a></p>', $field->XML()); $this->assertEquals('Repl...', $field->LimitCharacters(4, '...')); $this->assertEquals('Replaced...', $field->LimitCharactersToClosestWord(10, '...')); $this->assertEquals('Replaced...', $field->LimitWordCount(1, '...')); $this->assertEquals('<p>replaced short code with this. <a href="home">home</a></p>', $field->LowerCase()); $this->assertEquals('<P>REPLACED SHORT CODE WITH THIS. <A HREF="HOME">HOME</A></P>', $field->UpperCase()); $this->assertEquals('Replaced short code with this. home', $field->Plain()); Config::nest(); Config::inst()->update('SilverStripe\\Control\\Director', 'alternate_base_url', 'http://example.com/'); $this->assertEquals('<p>Replaced short code with this. <a href="http://example.com/home">home</a></p>', $field->AbsoluteLinks()); Config::unnest(); $this->assertEquals('Replaced short code with this.', $field->LimitSentences(1)); $this->assertEquals('Replaced short code with this.', $field->FirstSentence()); $this->assertEquals('Replaced short...', $field->Summary(2)); $this->assertEquals('Replaced short code with this. home', $field->FirstParagraph()); $this->assertEquals('Replaced <span class="highlight">short</span> <span class="highlight">code</span> with this. home', $field->ContextSummary(500, 'short code')); ShortcodeParser::set_active('default'); }
/** * Generate a new DBFile instance using the given callback if it hasn't been created yet, or * return the existing one if it has. * * @param string $variant name of the variant to create * @param callable $callback Callback which should return a new tuple as an array. * This callback will be passed the backend, filename, hash, and variant * This will not be called if the file does not * need to be created. * @return DBFile The manipulated file */ public function manipulate($variant, $callback) { // Verify this manipulation is applicable to this instance if (!$this->exists()) { return null; } // Build output tuple $filename = $this->getFilename(); $hash = $this->getHash(); $existingVariant = $this->getVariant(); if ($existingVariant) { $variant = $existingVariant . '_' . $variant; } // Skip empty files (e.g. Folder does not have a hash) if (empty($filename) || empty($hash)) { return null; } // Create this asset in the store if it doesn't already exist, // otherwise use the existing variant $store = Injector::inst()->get('AssetStore'); $result = null; if (!$store->exists($filename, $hash, $variant)) { $result = call_user_func($callback, $store, $filename, $hash, $variant); } else { $result = array('Filename' => $filename, 'Hash' => $hash, 'Variant' => $variant); } // Callback may fail to perform this manipulation (e.g. resize on text file) if (!$result) { return null; } // Store result in new DBFile instance /** @var DBFile $file */ $file = DBField::create_field('DBFile', $result); return $file->setOriginal($this); }
/** * Cast an arbitrary value with the help of a $castingDefinition. * * @todo refactor this into GridFieldComponent * * @param mixed $value * @param string|array $castingDefinition * * @return mixed */ public function getCastedValue($value, $castingDefinition) { $castingParams = array(); if (is_array($castingDefinition)) { $castingParams = $castingDefinition; array_shift($castingParams); $castingDefinition = array_shift($castingDefinition); } if (strpos($castingDefinition, '->') === false) { $castingFieldType = $castingDefinition; $castingField = DBField::create_field($castingFieldType, $value); return call_user_func_array(array($castingField, 'XML'), $castingParams); } list($castingFieldType, $castingMethod) = explode('->', $castingDefinition); $castingField = DBField::create_field($castingFieldType, $value); return call_user_func_array(array($castingField, $castingMethod), $castingParams); }
public function testNativeName() { $l = DBField::create_field('Locale', 'de_DE'); $this->assertEquals($l->getNativeName(), 'Deutsch'); }
/** * @param array $attrs * @return DBHTMLText */ public function getAttributesHTML($attrs = null) { $excludeKeys = is_string($attrs) ? func_get_args() : null; if (!$attrs || is_string($attrs)) { $attrs = $this->attributes; } // Remove empty or excluded values foreach ($attrs as $key => $value) { if ($excludeKeys && in_array($key, $excludeKeys) || !$value && $value !== 0 && $value !== '0') { unset($attrs[$key]); continue; } } // Create markkup $parts = array(); foreach ($attrs as $name => $value) { $parts[] = $value === true ? "{$name}=\"{$name}\"" : "{$name}=\"" . Convert::raw2att($value) . "\""; } return DBField::create_field('HTMLFragment', implode(' ', $parts)); }
public function __construct($name = null, $defaultVal = 0) { $this->defaultVal = is_int($defaultVal) ? $defaultVal : 0; parent::__construct($name); }
/** * Show the "login" page * * For multiple authenticators, Security_MultiAuthenticatorLogin is used. * See getTemplatesFor and getIncludeTemplate for how to override template logic * * @return string|SS_HTTPResponse Returns the "login" page as HTML code. */ public function login() { // Check pre-login process if ($response = $this->preLogin()) { return $response; } // Get response handler $controller = $this->getResponseController(_t('Security.LOGIN', 'Log in')); // if the controller calls Director::redirect(), this will break early if (($response = $controller->getResponse()) && $response->isFinished()) { return $response; } $forms = $this->GetLoginForms(); if (!count($forms)) { user_error('No login-forms found, please use Authenticator::register_authenticator() to add one', E_USER_ERROR); } // Handle any form messages from validation, etc. $messageType = ''; $message = $this->getLoginMessage($messageType); // We've displayed the message in the form output, so reset it for the next run. Session::clear('Security.Message'); // only display tabs when more than one authenticator is provided // to save bandwidth and reduce the amount of custom styling needed if (count($forms) > 1) { $content = $this->generateLoginFormSet($forms); } else { $content = $forms[0]->forTemplate(); } // Finally, customise the controller to add any form messages and the form. $customisedController = $controller->customise(array("Content" => DBField::create_field('HTMLFragment', $message), "Message" => DBField::create_field('HTMLFragment', $message), "MessageType" => $messageType, "Form" => $content)); // Return the customised controller return $customisedController->renderWith($this->getTemplatesFor('login')); }
/** * Test import with manual column mapping and custom column names */ public function testLoadWithCustomHeaderAndRelation() { $loader = new CsvBulkLoader('CsvBulkLoaderTest_Player'); $filepath = $this->getCurrentAbsolutePath() . '/CsvBulkLoaderTest_PlayersWithCustomHeaderAndRelation.csv'; $file = fopen($filepath, 'r'); $compareCount = $this->getLineCount($file); fgetcsv($file); // pop header row $compareRow = fgetcsv($file); $loader->columnMap = array('first name' => 'FirstName', 'bio' => 'Biography', 'bday' => 'Birthday', 'teamtitle' => 'Team.Title', 'teamsize' => 'Team.TeamSize', 'salary' => 'Contract.Amount'); $loader->hasHeaderRow = true; $loader->relationCallbacks = array('Team.Title' => array('relationname' => 'Team', 'callback' => 'getTeamByTitle')); $results = $loader->load($filepath); // Test that right amount of columns was imported $this->assertEquals(1, $results->Count(), 'Test correct count of imported data'); // Test of augumenting existing relation (created by fixture) $testTeam = DataObject::get_one('CsvBulkLoaderTest_Team', null, null, '"Created" DESC'); $this->assertEquals('20', $testTeam->TeamSize, 'Augumenting existing has_one relation works'); // Test of creating relation $testContract = DataObject::get_one('CsvBulkLoaderTest_PlayerContract'); $testPlayer = DataObject::get_one("CsvBulkLoaderTest_Player", array('"CsvBulkLoaderTest_Player"."FirstName"' => 'John')); $this->assertEquals($testPlayer->ContractID, $testContract->ID, 'Creating new has_one relation works'); // Test nested setting of relation properties $contractAmount = DBField::create_field('Currency', $compareRow[5])->RAW(); $this->assertEquals($testPlayer->Contract()->Amount, $contractAmount, 'Setting nested values in a relation works'); fclose($file); }
/** * Return a {@link Form} instance allowing a user to * add links in the TinyMCE content editor. * * @return Form */ public function LinkForm() { $siteTree = TreeDropdownField::create('internal', _t('HTMLEditorField.PAGE', "Page"), 'SilverStripe\\CMS\\Model\\SiteTree', 'ID', 'MenuTitle', true); // mimic the SiteTree::getMenuTitle(), which is bypassed when the search is performed $siteTree->setSearchFunction(array($this, 'siteTreeSearchCallback')); $numericLabelTmpl = '<span class="step-label"><span class="flyout">%d</span><span class="arrow"></span>' . '<strong class="title">%s</strong></span>'; $form = new Form($this->controller, "{$this->name}/LinkForm", new FieldList($headerWrap = new CompositeField(new LiteralField('Heading', sprintf('<h3 class="htmleditorfield-mediaform-heading insert">%s</h3>', _t('HTMLEditorField.LINK', 'Insert Link')))), $contentComposite = new CompositeField(OptionsetField::create('LinkType', DBField::create_field('HTMLFragment', sprintf($numericLabelTmpl, '1', _t('HTMLEditorField.LINKTO', 'Link to'))), array('internal' => _t('HTMLEditorField.LINKINTERNAL', 'Page on the site'), 'external' => _t('HTMLEditorField.LINKEXTERNAL', 'Another website'), 'anchor' => _t('HTMLEditorField.LINKANCHOR', 'Anchor on this page'), 'email' => _t('HTMLEditorField.LINKEMAIL', 'Email address'), 'file' => _t('HTMLEditorField.LINKFILE', 'Download a file')), 'internal'), LiteralField::create('Step2', '<div class="step2">' . sprintf($numericLabelTmpl, '2', _t('HTMLEditorField.DETAILS', 'Details')) . '</div>'), $siteTree, TextField::create('external', _t('HTMLEditorField.URL', 'URL'), 'http://'), EmailField::create('email', _t('HTMLEditorField.EMAIL', 'Email address')), $fileField = UploadField::create('file', _t('HTMLEditorField.FILE', 'File')), TextField::create('Anchor', _t('HTMLEditorField.ANCHORVALUE', 'Anchor')), TextField::create('Subject', _t('HTMLEditorField.SUBJECT', 'Email subject')), TextField::create('Description', _t('HTMLEditorField.LINKDESCR', 'Link description')), CheckboxField::create('TargetBlank', _t('HTMLEditorField.LINKOPENNEWWIN', 'Open link in a new window?')), HiddenField::create('Locale', null, $this->controller->Locale))), new FieldList()); $headerWrap->setName('HeaderWrap'); $headerWrap->addExtraClass('CompositeField composite cms-content-header form-group--no-label '); $contentComposite->setName('ContentBody'); $contentComposite->addExtraClass('ss-insert-link content'); $fileField->setAllowedMaxFileNumber(1); $form->unsetValidator(); $form->loadDataFrom($this); $form->addExtraClass('htmleditorfield-form htmleditorfield-linkform cms-mediaform-content'); $this->extend('updateLinkForm', $form); return $form; }
public function __construct($name = null, $defaultVal = 0) { $this->defaultVal = is_float($defaultVal) ? $defaultVal : (double) 0; parent::__construct($name); }
public function testFormatFromSettings() { $memberID = $this->logInWithPermission(); $member = DataObject::get_by_id('SilverStripe\\Security\\Member', $memberID); $member->DateFormat = 'dd/MM/YYYY'; $member->write(); $fixtures = array('2000-12-31' => '31/12/2000', '31-12-2000' => '31/12/2000', '31/12/2000' => '31/12/2000', '2014-04-01' => '01/04/2014'); foreach ($fixtures as $from => $to) { $date = DBField::create_field('Date', $from); // With member $this->assertEquals($to, $date->FormatFromSettings($member)); // Without member $this->assertEquals($to, $date->FormatFromSettings()); } }
/** * @return String */ public function Locale() { return DBField::create_field('Locale', i18n::get_locale()); }
/** * Mock the system date temporarily, which is useful for time-based unit testing. * Use {@link clear_mock_now()} to revert to the current system date. * Caution: This sets a fixed date that doesn't increment with time. * * @param DBDatetime|string $datetime Either in object format, or as a DBDatetime compatible string. * @throws Exception */ public static function set_mock_now($datetime) { if ($datetime instanceof DBDatetime) { self::$mock_now = $datetime; } elseif (is_string($datetime)) { self::$mock_now = DBField::create_field('Datetime', $datetime); } else { throw new InvalidArgumentException('DBDatetime::set_mock_now(): Wrong format: ' . $datetime); } }