/** * Test taxonomy functionality with nodes prior to 1970. */ function testTaxonomyLegacyNode() { // Posts an article with a taxonomy term and a date prior to 1970. $date = new DrupalDateTime('1969-01-01 00:00:00'); $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(); $edit['created[0][value][date]'] = $date->format('Y-m-d'); $edit['created[0][value][time]'] = $date->format('H:i:s'); $edit['body[0][value]'] = $this->randomMachineName(); $edit['field_tags[target_id]'] = $this->randomMachineName(); $this->drupalPostForm('node/add/article', $edit, t('Save and publish')); // Checks that the node has been saved. $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); $this->assertEqual($node->getCreatedTime(), $date->getTimestamp(), 'Legacy node was saved with the right date.'); }
/** * {@inheritdoc} */ public function setDateTime(DrupalDateTime $dateTime, $notify = TRUE) { $this->value = $dateTime->format('c'); // Notify the parent of any changes. if ($notify && isset($this->parent)) { $this->parent->onChange($this->name); } }
/** * Alter the default value for a date argument. * * @param object $argument * The argument object. * @param string $value * The default value created by the argument handler. */ function hook_date_default_argument_alter(&$argument, &$value) { $style_options = $style_options = $argument->view->display_handler->get_option('style_options'); if (!empty($style_options['track_date'])) { $default_date = new DrupalDateTime(); $value = $default_date->format($argument->arg_format); } }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form = parent::settingsForm($form, $form_state); $time = new DrupalDateTime(); $format_types = $this->dateFormatStorage->loadMultiple(); $options = []; foreach ($format_types as $type => $type_info) { $format = $this->dateFormatter->format($time->format('U'), $type); $options[$type] = $type_info->label() . ' (' . $format . ')'; } $form['format_type'] = array('#type' => 'select', '#title' => t('Date format'), '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."), '#options' => $options, '#default_value' => $this->getSetting('format_type')); return $form; }
/** * Specifies the start and end year to use as a date range. * * Handles a string like -3:+3 or 2001:2010 to describe a dynamic range of * minimum and maximum years to use in a date selector. * * Centers the range around the current year, if any, but expands it far enough * so it will pick up the year value in the field in case the value in the field * is outside the initial range. * * @param string $string * A min and max year string like '-3:+1' or '2000:2010' or '2000:+3'. * @param object $date * (optional) A date object to test as a default value. Defaults to NULL. * * @return array * A numerically indexed array, containing the minimum and maximum year * described by this pattern. */ protected static function datetimeRangeYears($string, $date = NULL) { $datetime = new DrupalDateTime(); $this_year = $datetime->format('Y'); list($min_year, $max_year) = explode(':', $string); // Valid patterns would be -5:+5, 0:+1, 2008:2010. $plus_pattern = '@[\\+|\\-][0-9]{1,4}@'; $year_pattern = '@^[0-9]{4}@'; if (!preg_match($year_pattern, $min_year, $matches)) { if (preg_match($plus_pattern, $min_year, $matches)) { $min_year = $this_year + $matches[0]; } else { $min_year = $this_year; } } if (!preg_match($year_pattern, $max_year, $matches)) { if (preg_match($plus_pattern, $max_year, $matches)) { $max_year = $this_year + $matches[0]; } else { $max_year = $this_year; } } // We expect the $min year to be less than the $max year. Some custom values // for -99:+99 might not obey that. if ($min_year > $max_year) { $temp = $max_year; $max_year = $min_year; $min_year = $temp; } // If there is a current value, stretch the range to include it. $value_year = $date instanceof DrupalDateTime ? $date->format('Y') : ''; if (!empty($value_year)) { $min_year = min($value_year, $min_year); $max_year = max($value_year, $max_year); } return array($min_year, $max_year); }
/** * Tests comment edit, preview, and save. */ function testCommentEditPreviewSave() { $web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'skip comment approval', 'edit own comments')); $this->drupalLogin($this->adminUser); $this->setCommentPreview(DRUPAL_OPTIONAL); $this->setCommentForm(TRUE); $this->setCommentSubject(TRUE); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.'); $edit = array(); $date = new DrupalDateTime('2008-03-02 17:23'); $edit['subject[0][value]'] = $this->randomMachineName(8); $edit['comment_body[0][value]'] = $this->randomMachineName(16); $edit['uid'] = $web_user->getUsername() . ' (' . $web_user->id() . ')'; $edit['date[date]'] = $date->format('Y-m-d'); $edit['date[time]'] = $date->format('H:i:s'); $raw_date = $date->getTimestamp(); $expected_text_date = format_date($raw_date); $expected_form_date = $date->format('Y-m-d'); $expected_form_time = $date->format('H:i:s'); $comment = $this->postComment($this->node, $edit['subject[0][value]'], $edit['comment_body[0][value]'], TRUE); $this->drupalPostForm('comment/' . $comment->id() . '/edit', $edit, t('Preview')); // Check that the preview is displaying the subject, comment, author and date correctly. $this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".'); $this->assertText($edit['subject[0][value]'], 'Subject displayed.'); $this->assertText($edit['comment_body[0][value]'], 'Comment displayed.'); $this->assertText($web_user->getUsername(), 'Author displayed.'); $this->assertText($expected_text_date, 'Date displayed.'); // Check that the subject, comment, author and date fields are displayed with the correct values. $this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.'); $this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.'); $this->assertFieldByName('uid', $edit['uid'], 'Author field displayed.'); $this->assertFieldByName('date[date]', $edit['date[date]'], 'Date field displayed.'); $this->assertFieldByName('date[time]', $edit['date[time]'], 'Time field displayed.'); // Check that saving a comment produces a success message. $this->drupalPostForm('comment/' . $comment->id() . '/edit', $edit, t('Save')); $this->assertText(t('Your comment has been posted.'), 'Comment posted.'); // Check that the comment fields are correct after loading the saved comment. $this->drupalGet('comment/' . $comment->id() . '/edit'); $this->assertFieldByName('subject[0][value]', $edit['subject[0][value]'], 'Subject field displayed.'); $this->assertFieldByName('comment_body[0][value]', $edit['comment_body[0][value]'], 'Comment field displayed.'); $this->assertFieldByName('uid', $edit['uid'], 'Author field displayed.'); $this->assertFieldByName('date[date]', $expected_form_date, 'Date field displayed.'); $this->assertFieldByName('date[time]', $expected_form_time, 'Time field displayed.'); // Submit the form using the displayed values. $displayed = array(); $displayed['subject[0][value]'] = (string) current($this->xpath("//input[@id='edit-subject-0-value']/@value")); $displayed['comment_body[0][value]'] = (string) current($this->xpath("//textarea[@id='edit-comment-body-0-value']")); $displayed['uid'] = (string) current($this->xpath("//input[@id='edit-uid']/@value")); $displayed['date[date]'] = (string) current($this->xpath("//input[@id='edit-date-date']/@value")); $displayed['date[time]'] = (string) current($this->xpath("//input[@id='edit-date-time']/@value")); $this->drupalPostForm('comment/' . $comment->id() . '/edit', $displayed, t('Save')); // Check that the saved comment is still correct. $comment_storage = \Drupal::entityManager()->getStorage('comment'); $comment_storage->resetCache(array($comment->id())); /** @var \Drupal\comment\CommentInterface $comment_loaded */ $comment_loaded = Comment::load($comment->id()); $this->assertEqual($comment_loaded->getSubject(), $edit['subject[0][value]'], 'Subject loaded.'); $this->assertEqual($comment_loaded->comment_body->value, $edit['comment_body[0][value]'], 'Comment body loaded.'); $this->assertEqual($comment_loaded->getOwner()->id(), $web_user->id(), 'Name loaded.'); $this->assertEqual($comment_loaded->getCreatedTime(), $raw_date, 'Date loaded.'); $this->drupalLogout(); // Check that the date and time of the comment are correct when edited by // non-admin users. $user_edit = array(); $expected_created_time = $comment_loaded->getCreatedTime(); $this->drupalLogin($web_user); // Web user cannot change the comment author. unset($edit['uid']); $this->drupalPostForm('comment/' . $comment->id() . '/edit', $user_edit, t('Save')); $comment_storage->resetCache(array($comment->id())); $comment_loaded = Comment::load($comment->id()); $this->assertEqual($comment_loaded->getCreatedTime(), $expected_created_time, 'Expected date and time for comment edited.'); $this->drupalLogout(); }
/** * Test default value functionality. */ function testDefaultValue() { // Create a test content type. $this->drupalCreateContentType(array('type' => 'date_content')); // Create a field storage with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'node', 'type' => 'datetime', 'settings' => array('datetime_type' => 'date'))); $field_storage->save(); $field = entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => 'date_content')); $field->save(); // Set now as default_value. $field_edit = array('default_value_input[default_date_type]' => 'now'); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', 'now', 'The default value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertEqual($config_entity['default_value'][0], array('default_date_type' => 'now', 'default_date' => 'now'), 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is today. $new_node = entity_create('node', array('type' => 'date_content')); $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Set an invalid relative default_value to test validation. $field_edit = array('default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => 'invalid date'); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); $this->assertText('The relative date value entered is invalid.'); // Set a relative default_value. $field_edit = array('default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => '+90 days'); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', 'relative', 'The default value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '+90 days', 'The relative default value is displayed in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertEqual($config_entity['default_value'][0], array('default_date_type' => 'relative', 'default_date' => '+90 days'), 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is +90 days. $new_node = entity_create('node', array('type' => 'date_content')); $expected_date = new DrupalDateTime('+90 days', DATETIME_STORAGE_TIMEZONE); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Remove default value. $field_edit = array('default_value_input[default_date_type]' => ''); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', '', 'The default value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default value is empty in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is not set. $new_node = entity_create('node', array('type' => 'date_content')); $this->assertNull($new_node->get($field_name)->value, 'Default value is not set'); }
/** * Creates a forum topic. * * @return string * The title of the newly generated topic. */ protected function createForumTopics($count = 5) { $topics = array(); $date = new DrupalDateTime(); $date->modify('-24 hours'); for ($index = 0; $index < $count; $index++) { // Generate a random subject/body. $title = $this->randomMachineName(20); $body = $this->randomMachineName(200); // Forum posts are ordered by timestamp, so force a unique timestamp by // changing the date. $date->modify('+1 minute'); $edit = array('title[0][value]' => $title, 'body[0][value]' => $body, 'created[0][value][date]' => $date->format('Y-m-d'), 'created[0][value][time]' => $date->format('H:i:s')); // Create the forum topic, preselecting the forum ID via a URL parameter. $this->drupalPostForm('node/add/forum', $edit, t('Save and publish'), array('query' => array('forum_id' => 1))); $topics[] = $title; } return $topics; }
/** * Returns day of week for a given date (0 = Sunday). * * @param mixed $date * (optional) A date object, timestamp, or a date string. * Defaults to NULL, which means use the current date. * * @return int * The number of the day in the week. */ public static function dayOfWeek($date = NULL) { if (!$date instanceof DrupalDateTime) { $date = new DrupalDateTime($date); } if (!$date->hasErrors()) { return $date->format('w'); } return NULL; }
/** * Test default value functionality. */ public function testDefaultValue() { // Create a test content type. $this->drupalCreateContentType(['type' => 'date_content']); // Create a field storage with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'node', 'type' => 'daterange', 'settings' => ['datetime_type' => DateRangeItem::DATETIME_TYPE_DATE]]); $field_storage->save(); $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'date_content']); $field->save(); // Set now as default_value. $field_edit = ['default_value_input[default_date_type]' => 'now', 'default_value_input[default_end_date_type]' => 'now']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', 'now', 'The default start value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '', 'The relative start default value is empty in instance settings page'); $this->assertOptionSelected('edit-default-value-input-default-end-date-type', 'now', 'The default end value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_end_date]', '', 'The relative end default value is empty in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertEqual($config_entity['default_value'][0], ['default_date_type' => 'now', 'default_date' => 'now', 'default_end_date_type' => 'now', 'default_end_date' => 'now'], 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is today. $new_node = Node::create(['type' => 'date_content']); $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->end_value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Set an invalid relative default_value to test validation. $field_edit = ['default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => 'invalid date', 'default_value_input[default_end_date_type]' => 'relative', 'default_value_input[default_end_date]' => '+1 day']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); $this->assertText('The relative start date value entered is invalid.'); $field_edit = ['default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => '+1 day', 'default_value_input[default_end_date_type]' => 'relative', 'default_value_input[default_end_date]' => 'invalid date']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); $this->assertText('The relative end date value entered is invalid.'); // Set a relative default_value. $field_edit = ['default_value_input[default_date_type]' => 'relative', 'default_value_input[default_date]' => '+45 days', 'default_value_input[default_end_date_type]' => 'relative', 'default_value_input[default_end_date]' => '+90 days']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', 'relative', 'The default start value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '+45 days', 'The relative default start value is displayed in instance settings page'); $this->assertOptionSelected('edit-default-value-input-default-end-date-type', 'relative', 'The default end value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_end_date]', '+90 days', 'The relative default end value is displayed in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertEqual($config_entity['default_value'][0], ['default_date_type' => 'relative', 'default_date' => '+45 days', 'default_end_date_type' => 'relative', 'default_end_date' => '+90 days'], 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is +90 days. $new_node = Node::create(['type' => 'date_content']); $expected_start_date = new DrupalDateTime('+45 days', DATETIME_STORAGE_TIMEZONE); $expected_end_date = new DrupalDateTime('+90 days', DATETIME_STORAGE_TIMEZONE); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->value, $expected_start_date->format(DATETIME_DATE_STORAGE_FORMAT)); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->end_value, $expected_end_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Remove default value. $field_edit = ['default_value_input[default_date_type]' => '', 'default_value_input[default_end_date_type]' => '']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name); $this->assertOptionSelected('edit-default-value-input-default-date-type', '', 'The default start value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_date]', '', 'The relative default start value is empty in instance settings page'); $this->assertOptionSelected('edit-default-value-input-default-end-date-type', '', 'The default end value is selected in instance settings page'); $this->assertFieldByName('default_value_input[default_end_date]', '', 'The relative default end value is empty in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->config('field.field.node.date_content.' . $field_name)->get(); $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is not set. $new_node = Node::create(['type' => 'date_content']); $this->assertNull($new_node->get($field_name)->value, 'Default value is not set'); // Set now as default_value for start date only. entity_get_form_display('node', 'date_content', 'default')->setComponent($field_name, ['type' => 'datetime_default'])->save(); $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE); $field_edit = ['default_value_input[default_date_type]' => 'now', 'default_value_input[default_end_date_type]' => '']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Make sure only the start value is populated on node add page. $this->drupalGet('node/add/date_content'); $this->assertFieldByName("{$field_name}[0][value][date]", $expected_date->format(DATETIME_DATE_STORAGE_FORMAT), 'Start date element populated.'); $this->assertFieldByName("{$field_name}[0][end_value][date]", '', 'End date element empty.'); // Set now as default_value for end date only. $field_edit = ['default_value_input[default_date_type]' => '', 'default_value_input[default_end_date_type]' => 'now']; $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_name, $field_edit, t('Save settings')); // Make sure only the start value is populated on node add page. $this->drupalGet('node/add/date_content'); $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Start date element empty.'); $this->assertFieldByName("{$field_name}[0][end_value][date]", $expected_date->format(DATETIME_DATE_STORAGE_FORMAT), 'End date element populated.'); }
/** * Parse date parts from an ISO date argument. * * Based on ISO 8601 date duration and time interval standards. * * Parses a value like 2006-01-01--2006-01-15, or 2006-W24, or @P1W. * Separate start and end dates or date and period with a double hyphen (--). * * The 'end' portion of the argument can be eliminated if it is the same as * the 'start' portion. Use @ instead of a date to substitute in the current * date and time. * * Use periods (P1H, P1D, P1W, P1M, P1Y) to get next hour/day/week/month/year * from now. Use date before P sign to get next hour/day/week/month/year from * that date. Use period then date to get a period that ends on the date. * * @see http://en.wikipedia.org/wiki/ISO_8601#Week_dates * @see http://en.wikipedia.org/wiki/ISO_8601#Duration */ function arg_parts($argument) { $values = array(); // Keep mal-formed arguments from creating errors. if (empty($argument) || is_array($argument)) { return array('date' => array(), 'period' => array()); } $fromto = explode('--', $argument); foreach ($fromto as $arg) { $parts = array(); if ($arg == '@') { $date = new DrupalDateTime(); $parts['date'] = date_parse($date->format(DATE_FORMAT_DATETIME)); } elseif (preg_match('/(\\d{4})?-?(W)?(\\d{1,2})?-?(\\d{1,2})?[T\\s]?(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?/', $arg, $matches)) { $date = array(); if (!empty($matches[1])) { $date['year'] = $matches[1]; } if (!empty($matches[3])) { if (empty($matches[2])) { $date['month'] = $matches[3]; } else { $date['week'] = $matches[3]; } } if (!empty($matches[4])) { $date['day'] = $matches[4]; } if (!empty($matches[5])) { $date['hour'] = $matches[5]; } if (!empty($matches[6])) { $date['minute'] = $matches[6]; } if (!empty($matches[7])) { $date['second'] = $matches[7]; } $parts['date'] = $date; } if (preg_match('/^P(\\d{1,4}[Y])?(\\d{1,2}[M])?(\\d{1,2}[W])?(\\d{1,2}[D])?([T]{0,1})?(\\d{1,2}[H])?(\\d{1,2}[M])?(\\d{1,2}[S])?/', $arg, $matches)) { $period = array(); if (!empty($matches[1])) { $period['year'] = str_replace('Y', '', $matches[1]); } if (!empty($matches[2])) { $period['month'] = str_replace('M', '', $matches[2]); } if (!empty($matches[3])) { $period['week'] = str_replace('W', '', $matches[3]); } if (!empty($matches[4])) { $period['day'] = str_replace('D', '', $matches[4]); } if (!empty($matches[6])) { $period['hour'] = str_replace('H', '', $matches[6]); } if (!empty($matches[7])) { $period['minute'] = str_replace('M', '', $matches[7]); } if (!empty($matches[8])) { $period['second'] = str_replace('S', '', $matches[8]); } $parts['period'] = $period; } $values[] = $parts; } return $values; }
/** * Test default value functionality. */ function testDefaultValue() { // Create a test content type. $this->drupalCreateContentType(array('type' => 'date_content')); // Create a field storage with settings to validate. $field_storage = entity_create('field_storage_config', array('name' => drupal_strtolower($this->randomMachineName()), 'entity_type' => 'node', 'type' => 'datetime', 'settings' => array('datetime_type' => 'date'))); $field_storage->save(); $instance = entity_create('field_instance_config', array('field_storage' => $field_storage, 'bundle' => 'date_content')); $instance->save(); // Set now as default_value. $instance_edit = array('default_value_input[default_date]' => 'now'); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_storage->name, $instance_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_storage->name); $this->assertRaw('<option value="now" selected="selected">The current date</option>', 'The default value is selected in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->container->get('config.factory')->get('field.instance.node.date_content.' . $field_storage->name)->get(); $this->assertEqual($config_entity['default_value'][0]['default_date'], 'now', 'Default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is today. $new_node = entity_create('node', array('type' => 'date_content')); $expected_date = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE); $this->assertEqual($new_node->get($field_storage->name)->offsetGet(0)->value, $expected_date->format(DATETIME_DATE_STORAGE_FORMAT)); // Remove default value. $instance_edit = array('default_value_input[default_date]' => ''); $this->drupalPostForm('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_storage->name, $instance_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/date_content/fields/node.date_content.' . $field_storage->name); $this->assertRaw('<option value="" selected="selected">' . t('- None -') . '</option>', 'The default value is selected in instance settings page'); // Check if default_date has been stored successfully. $config_entity = $this->container->get('config.factory')->get('field.instance.node.date_content.' . $field_storage->name)->get(); $this->assertTrue(empty($config_entity['default_value']), 'Empty default value has been stored successfully'); // Clear field cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that datetime field default value is today. $new_node = entity_create('node', array('type' => 'date_content')); $this->assertNull($new_node->get($field_storage->name)->offsetGet(0)->value, 'Default value is not set'); }
/** * {@inheritdoc} */ public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) { $default_value = parent::processDefaultValue($default_value, $entity, $definition); if (isset($default_value[0]['default_date_type'])) { // A default value should be in the format and timezone used for date // storage. $date = new DrupalDateTime($default_value[0]['default_date'], DATETIME_STORAGE_TIMEZONE); $storage_format = $definition->getSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT; $value = $date->format($storage_format); // We only provide a default value for the first item, as do all fields. // Otherwise, there is no way to clear out unwanted values on multiple value // fields. $default_value = array(array('value' => $value, 'date' => $date)); } return $default_value; }
/** * {@inheritdoc} */ public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) { // Explicitly call the base class so that we can get the default value // types. $default_value = FieldItemList::processDefaultValue($default_value, $entity, $definition); // Allow either the start or end date to have a default, but not require // defaults for both. if (!empty($default_value[0]['default_date_type']) || !empty($default_value[0]['default_end_date_type'])) { // A default value should be in the format and timezone used for date // storage. All-day ranges are stored the same as date+time ranges. We // only provide a default value for the first item, as do all fields. // Otherwise, there is no way to clear out unwanted values on multiple // value fields. $storage_format = $definition->getSetting('datetime_type') == DateRangeItem::DATETIME_TYPE_DATE ? DATETIME_DATE_STORAGE_FORMAT : DATETIME_DATETIME_STORAGE_FORMAT; $default_values = [[]]; if (!empty($default_value[0]['default_date_type'])) { $start_date = new DrupalDateTime($default_value[0]['default_date'], DATETIME_STORAGE_TIMEZONE); $start_value = $start_date->format($storage_format); $default_values[0]['value'] = $start_value; $default_values[0]['start_date'] = $start_date; } if (!empty($default_value[0]['default_end_date_type'])) { $end_date = new DrupalDateTime($default_value[0]['default_end_date'], DATETIME_STORAGE_TIMEZONE); $end_value = $end_date->format($storage_format); $default_values[0]['end_value'] = $end_value; $default_values[0]['end_date'] = $end_date; } $default_value = $default_values; } return $default_value; }