本文整理汇总了PHP中DBField类的典型用法代码示例。如果您正苦于以下问题:PHP DBField类的具体用法?PHP DBField怎么用?PHP DBField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBField类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setValue
/**
* Remember the classname and the ID for the given $dbField
* @param DBField $dbField
* @param $value
* @param null $record
*/
public static function setValue(DBField $dbField, $value, $record = null)
{
$canEdit = Controller::curr() instanceof Page_Controller && Controller::curr()->data()->canEdit();
if (!$canEdit) {
$canEdit = is_object($record) && in_array(get_class($record), self::$EditableClasses) && method_exists($record, 'canEdit') && $record->canEdit();
}
if ($canEdit && $record && is_object($record) && $dbField->getName()) {
$dbField->makeEditable = true;
$dbField->editClassName = $record->ClassName;
$dbField->editID = $record->ID;
}
}
示例2: getEventsAction
public function getEventsAction(SS_HTTPRequest $request)
{
// Search date
$date = DBField::create_field("SS_Datetime", $request->param("SearchDate"));
if (!$date->getValue()) {
$date = SS_Datetime::now();
}
// Get event data
$cache = SS_Cache::factory(self::EVENTS_CACHE_NAME);
$cacheKey = $date->Format('Y_m_d');
if ($result = $cache->load($cacheKey)) {
$data = unserialize($result);
} else {
$data = EventsDataUtil::get_events_data_for_day($date);
$cache->save(serialize($data), $cacheKey);
}
// Get init data
if ($request->param("GetAppConfig")) {
$cache = SS_Cache::factory(self::CONFIG_CACHE_NAME);
$cacheKey = 'APP_CONFIG';
if ($result = $cache->load($cacheKey)) {
$configData = unserialize($result);
} else {
$configData = AppConfigDataUtil::get_config_data();
$cache->save(serialize($configData), $cacheKey);
}
$data['appConfig'] = $configData;
}
return $this->sendResponse($data);
}
示例3: GlobalNav
public function GlobalNav()
{
Requirements::css(Controller::join_links(GlobalNavSiteTreeExtension::get_toolbar_hostname(), Config::inst()->get('GlobalNav', 'css_path')));
$html = DBField::create_field('HTMLText', $this->globalNav);
$html->setOptions(array('shortcodes' => false));
return $html;
}
示例4: getPostContent
/**
* @return HTMLText
*/
public function getPostContent($post)
{
$text = isset($post->text) ? $post->text : '';
$text = preg_replace('/(https?:\\/\\/[a-z0-9\\.\\/]+)/i', '<a href="$1" target="_blank">$1</a>', $text);
$result = DBField::create_field('HTMLText', $text);
return $result;
}
示例5: parse
/**
* Parses the snippet short code
* @example [snippet id=123]
* @example [snippet id=123 version=456]
*/
public static function parse($arguments, $content = null, $parser = null)
{
//Ensure ID is pressent in the arguments
if (!array_key_exists('id', $arguments)) {
return '<p><b><i>' . _t('CodeBankShortCode.MISSING_ID_ATTRIBUTE', '_Short Code missing the id attribute') . '</i></b></p>';
}
//Fetch Snippet
$snippet = Snippet::get()->byID(intval($arguments['id']));
if (empty($snippet) || $snippet === false || $snippet->ID == 0) {
return '<p><b><i>' . _t('CodeBankShortCode.SNIPPET_NOT_FOUND', '_Snippet not found') . '</i></b></p>';
}
//Fetch Text
$snippetText = $snippet->SnippetText;
//If the version exists fetch it, and replace the text with that of the version
if (array_key_exists('version', $arguments)) {
$version = $snippet->Version(intval($arguments['version']));
if (empty($version) || $version === false || $version->ID == 0) {
$snippetText = $version->Text;
}
}
//Load CSS Requirements
Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shCore.css');
Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shCoreDefault.css');
Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shThemeDefault.css');
//Load JS Requirements
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
Requirements::javascript(CB_DIR . '/javascript/external/syntaxhighlighter/brushes/shCore.js');
Requirements::javascript(CB_DIR . '/javascript/external/syntaxhighlighter/brushes/' . self::getBrushName($snippet->Language()->HighlightCode) . '.js');
Requirements::javascriptTemplate(CB_DIR . '/javascript/CodeBankShortCode.template.js', array('ID' => $snippet->ID), 'snippet-highlightinit-' . $snippet->ID);
//Render the snippet
$obj = new ViewableData();
return $obj->renderWith('CodeBankShortCode', array('ID' => $snippet->ID, 'Title' => $snippet->getField('Title'), 'Description' => $snippet->getField('Description'), 'SnippetText' => DBField::create_field('Text', $snippetText), 'HighlightCode' => strtolower($snippet->Language()->HighlightCode)));
}
示例6: testLoadWithCustomHeaderAndRelation
/**
* Test import with manual column mapping and custom column names
*/
function testLoadWithCustomHeaderAndRelation()
{
$loader = new CsvBulkLoader('CsvBulkLoaderTest_Player');
$filepath = Director::baseFolder() . '/sapphire/tests/dev/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", "FirstName = 'John'");
$this->assertEquals($testPlayer->ContractID, $testContract->ID, 'Creating new has_one relation works');
// Test nested setting of relation properties
$contractAmount = DBField::create('Currency', $compareRow[5])->RAW();
$this->assertEquals($testPlayer->Contract()->Amount, $contractAmount, 'Setting nested values in a relation works');
fclose($file);
}
示例7: handlePost
protected function handlePost(array $data, $settings = [])
{
$post = ['ID' => isset($data['id']) && isset($data['id']['videoId']) ? $data['id']['videoId'] : '0', 'Author' => isset($data['snippet']) && isset($data['snippet']['channelTitle']) ? \FormField::name_to_label($data['snippet']['channelTitle']) : '', 'AuthorID' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? $data['snippet']['channelId'] : 0, 'AuthorURL' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? \Controller::join_links($this->url, 'channel', $data['snippet']['channelId']) : '', 'Title' => isset($data['snippet']) && isset($data['snippet']['title']) ? $data['snippet']['title'] : '', 'Content' => isset($data['snippet']) && isset($data['snippet']['description']) ? $this->textParser()->text($data['snippet']['description']) : '', 'Priority' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? strtotime($data['snippet']['publishedAt']) : 0, 'Posted' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? \DBField::create_field('SS_Datetime', strtotime($data['snippet']['publishedAt'])) : null];
if (isset($data['snippet']) && isset($data['snippet']['thumbnails'])) {
if (isset($data['snippet']['thumbnails']['high']) && isset($data['snippet']['thumbnails']['high']['url'])) {
$post['Cover'] = $data['snippet']['thumbnails']['high']['url'];
} else {
if (isset($data['snippet']['thumbnails']['medium']) && isset($data['snippet']['thumbnails']['medium']['url'])) {
$post['Cover'] = $data['snippet']['thumbnails']['medium']['url'];
} else {
if (isset($data['snippet']['thumbnails']['default']) && isset($data['snippet']['thumbnails']['default']['url'])) {
$post['Cover'] = $data['snippet']['thumbnails']['default']['url'];
}
}
}
}
if ($post['ID']) {
$params = (array) singleton('env')->get('Youtube.video_params');
if (isset($settings['videoParams'])) {
$params = array_merge($params, (array) $settings['videoParams']);
}
$params['v'] = $post['ID'];
$post['Link'] = \Controller::join_links($this->url, 'watch', '?' . http_build_query($params));
$this->setFromEmbed($post);
}
if (isset($post['ObjectDescription']) && $post['ObjectDescription'] == $post['Content']) {
unset($post['ObjectDescription']);
}
if (isset($post['Description']) && $post['Description'] == $post['Content']) {
unset($post['Description']);
}
return $post;
}
示例8: Dates
function Dates()
{
Requirements::themedCSS('archivewidget');
$results = new DataObjectSet();
$container = BlogTree::current();
$ids = $container->BlogHolderIDs();
$stage = Versioned::current_stage();
$suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
$monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
$yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
$sqlResults = DB::query("\n\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
if ($this->ShowLastYears == 0) {
$cutOffYear = 0;
} else {
$cutOffYear = (int) date("Y") - $this->ShowLastYears;
}
$years = array();
if (Director::get_current_page()->ClassName == 'BlogHolder') {
$urlParams = Director::urlParams();
$yearParam = $urlParams['ID'];
$monthParam = $urlParams['OtherID'];
} else {
$date = new DateTime(Director::get_current_page()->Date);
$yearParam = $date->format("Y");
$monthParam = $date->format("m");
}
if ($sqlResults) {
foreach ($sqlResults as $sqlResult) {
$isMonthDisplay = true;
$year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
$isMonthDisplay = $year > $cutOffYear;
// $dateFormat = 'Month'; else $dateFormat = 'Year';
$monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
$month = $isMonthDisplay ? $monthVal : 1;
$date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
if ($isMonthDisplay) {
$link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
} else {
$link = $container->Link('date') . '/' . $sqlResult['Year'];
}
if ($isMonthDisplay || !$isMonthDisplay && !in_array($year, $years)) {
$years[] = $year;
$current = false;
$children = new DataObjectSet();
$LinkingMode = "link";
if ($isMonthDisplay && $yearParam == $year && $monthParam == $month || !$isMonthDisplay && $yearParam == $year) {
$LinkingMode = "current";
$current = true;
if ($this->ShowChildren && $isMonthDisplay) {
$filter = $yearclause . ' = ' . $year . ' AND ' . $monthclause . ' = ' . $month;
$children = DataObject::get('BlogEntry', $filter, "Date DESC");
}
}
$results->push(new ArrayData(array('Date' => $date, 'Year' => $year, 'Link' => $link, 'NoMonth' => !$isMonthDisplay, 'LinkingMode' => $LinkingMode, 'Children' => $children)));
unset($children);
}
}
}
return $results;
}
示例9: Field
public function Field($properties = array())
{
$content = '';
Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
Requirements::javascript(FRAMEWORK_DIR . "/javascript/ToggleField.js");
if ($this->startClosed) {
$this->addExtraClass('startClosed');
}
$valforInput = $this->value ? Convert::raw2att($this->value) : "";
$rawInput = Convert::html2raw($valforInput);
if ($this->charNum) {
$reducedVal = substr($rawInput, 0, $this->charNum);
} else {
$reducedVal = DBField::create_field('Text', $rawInput)->{$this->truncateMethod}();
}
// only create togglefield if the truncated content is shorter
if (strlen($reducedVal) < strlen($rawInput)) {
$content = <<<HTML
\t\t\t<div class="readonly typography contentLess" style="display: none">
\t\t\t\t{$reducedVal}
\t\t\t\t <a href="#" class="triggerMore">{$this->labelMore}</a>
\t\t\t</div>
\t\t\t<div class="readonly typography contentMore">
\t\t\t\t{$this->value}
\t\t\t\t <a href="#" class="triggerLess">{$this->labelLess}</a>
\t\t\t</div>\t
\t\t\t<br />
\t\t\t<input type="hidden" name="{$this->name}" value="{$valforInput}" />
HTML;
} else {
$this->dontEscape = true;
$content = parent::Field();
}
return $content;
}
示例10: Tweets
public function Tweets()
{
$twitterApp = TwitterApp::get()->first();
if (!$twitterApp) {
return null;
}
$siteConfig = SiteConfig::current_site_config();
$twitter = $twitterApp->getTwitter();
$twitter->setAccess(new OAuthToken($twitterApp->TwitterAccessToken, $twitterApp->TwitterAccessSecret));
if ($twitter->hasAccess()) {
$result = $twitter->api("1.1/statuses/user_timeline.json", "GET", array("screen_name" => $this->TwitterHandle, "count" => $this->NumberOfTweets));
if ($result->statusCode() == 200) {
$rawTweets = json_decode($result->body(), true);
if (count($rawTweets) > 0) {
$tweets = new ArrayList();
foreach ($rawTweets as $tweet) {
// Parse tweet links, users and hashtags.
$parsed = preg_replace("#(^|[\n ])([\\w]+?://[\\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" target=\"_blank\">\\2</a>'", $tweet['text']);
$parsed = preg_replace("#(^|[\n ])@([A-Za-z0-9\\_]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" target=\"_blank\">@\\2</a>'", $parsed);
$parsed = preg_replace("#(^|[\n ])\\#([A-Za-z0-9]*)#ise", "'\\1<a href=\"http://www.twitter.com/search?q=\\2\" target=\"_blank\">#\\2</a>'", $parsed);
$t = new ArrayData(array());
$t->Tweet = DBField::create_field("HTMLText", $parsed, "Tweet");
$t->TweetDate = DBField::create_field("SS_Datetime", strtotime($tweet['created_at']));
$t->TweetLink = DBField::create_field("Varchar", "http://www.twitter.com/" . rawurlencode($tweet['user']['screen_name']) . "/status/" . rawurlencode($tweet['id_str']));
$tweets->push($t);
}
return $tweets;
}
}
}
return null;
}
示例11: Form
function Form()
{
$fields = new FieldSet();
$source = array();
$fields->push(new HeaderField('Header', _t('RemoveOrphanedPagesTask.HEADER', 'Remove all orphaned pages task')));
$fields->push(new LiteralField('Description', $this->description));
$orphans = $this->getOrphanedPages($this->orphanedSearchClass);
if ($orphans) {
foreach ($orphans as $orphan) {
$latestVersion = Versioned::get_latest_version($this->orphanedSearchClass, $orphan->ID);
$latestAuthor = DataObject::get_by_id('Member', $latestVersion->AuthorID);
$stageRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Stage', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
$liveRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Live', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
$label = sprintf('<a href="admin/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>', $orphan->ID, $orphan->Title, $orphan->ID, DBField::create('Date', $orphan->LastEdited)->Nice(), $latestAuthor ? $latestAuthor->Title : 'unknown', $liveRecord ? 'is published' : 'not published');
$source[$orphan->ID] = $label;
}
}
if ($orphans && $orphans->Count()) {
$fields->push(new CheckboxSetField('OrphanIDs', false, $source));
$fields->push(new LiteralField('SelectAllLiteral', sprintf('<p><a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'checked\'); return false;">%s</a> ', _t('RemoveOrphanedPagesTask.SELECTALL', 'select all'))));
$fields->push(new LiteralField('UnselectAllLiteral', sprintf('<a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'\'); return false;">%s</a></p>', _t('RemoveOrphanedPagesTask.UNSELECTALL', 'unselect all'))));
$fields->push(new OptionSetField('OrphanOperation', _t('RemoveOrphanedPagesTask.CHOOSEOPERATION', 'Choose operation:'), array('rebase' => _t('RemoveOrphanedPagesTask.OPERATION_REBASE', sprintf('Rebase selected to a new holder page "%s" and unpublish. None of these pages will show up for website visitors.', $this->rebaseHolderTitle())), 'remove' => _t('RemoveOrphanedPagesTask.OPERATION_REMOVE', 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)')), 'rebase'));
$fields->push(new LiteralField('Warning', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.DELETEWARNING', 'Warning: These operations are not reversible. Please handle with care.'))));
} else {
$fields->push(new LiteralField('NotFoundLabel', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.NONEFOUND', 'No orphans found'))));
}
$form = new Form($this, 'Form', $fields, new FieldSet(new FormAction('doSubmit', _t('RemoveOrphanedPagesTask.BUTTONRUN', 'Run'))));
if (!$orphans || !$orphans->Count()) {
$form->makeReadonly();
}
return $form;
}
示例12: testToDialect
public function testToDialect()
{
$expression = Expression::containsIp(IpRange::create('127.0.0.1-127.0.0.5'), IpAddress::create('127.0.0.3'));
$this->assertEquals("'127.0.0.3' <<= '127.0.0.1-127.0.0.5'", $expression->toDialectString(PostgresDialect::me()));
$expression = Expression::containsIp(DBField::create('range'), '192.168.1.1');
$this->assertEquals('\'192.168.1.1\' <<= "range"', $expression->toDialectString(PostgresDialect::me()));
}
示例13: testNice
public function testNice()
{
$time = DBField::create_field('Time', '17:15:55');
$this->assertEquals('5:15pm', $time->Nice());
Config::inst()->update('Time', 'nice_format', 'H:i:s');
$this->assertEquals('17:15:55', $time->Nice());
}
示例14: onBeforeWrite
function onBeforeWrite()
{
parent::onBeforeWrite();
if (!$this->DispatchedOn) {
$this->DispatchedOn = DBField::create_field('Date', date('Y-m-d'));
}
}
示例15: renderRows
protected function renderRows($rows, ArrayIterator $splitcontent, &$pos = -1)
{
$output = "";
$rownumber = 0;
foreach ($rows as $row) {
if ($row->cols) {
$columns = array();
foreach ($row->cols as $col) {
$nextcontent = $splitcontent->current();
$isholder = !isset($col->rows);
if ($isholder) {
$splitcontent->next();
//advance iterator if there are no sub-rows
$pos++;
//wrap split content in a HTMLText object
$dbObject = DBField::create_field('HTMLText', $nextcontent, "Content");
$dbObject->setOptions(array("shortcodes" => true));
$nextcontent = $dbObject;
}
$width = $col->width ? (int) $col->width : 1;
//width is at least 1
$columns[] = new ArrayData(array("Width" => $width, "EnglishWidth" => $this->englishWidth($width), "Content" => $isholder ? $nextcontent : $this->renderRows($col->rows, $splitcontent, $pos), "IsHolder" => $isholder, "GridPos" => $pos, "ExtraClasses" => isset($col->extraclasses) ? $col->extraclasses : null));
}
$output .= ArrayData::create(array("Columns" => new ArrayList($columns), "RowNumber" => (string) $rownumber++, "ExtraClasses" => isset($row->extraclasses) ? $row->extraclasses : null))->renderWith($this->template);
} else {
//every row should have columns!!
}
}
return $output;
}