/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $max = $field_definition->getSetting('max_length'); $values['value'] = $random->word(mt_rand(1, $max)); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $min = $field_definition->getSetting('min') ?: 0; $max = $field_definition->getSetting('max') ?: 999; $values['value'] = mt_rand($min, $max); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); if ($field_definition->getItemDefinition()->getSetting('link_type') & LinkItemInterface::LINK_EXTERNAL) { // Set of possible top-level domains. $tlds = array('com', 'net', 'gov', 'org', 'edu', 'biz', 'info'); // Set random length for the domain name. $domain_length = mt_rand(7, 15); switch ($field_definition->getSetting('title')) { case DRUPAL_DISABLED: $values['title'] = ''; break; case DRUPAL_REQUIRED: $values['title'] = $random->sentences(4); break; case DRUPAL_OPTIONAL: // In case of optional title, randomize its generation. $values['title'] = mt_rand(0, 1) ? $random->sentences(4) : ''; break; } $values['uri'] = 'http://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, sizeof($tlds) - 1)]; } else { $values['uri'] = 'base:' . $random->name(mt_rand(1, 64)); } return $values; }
/** * {@inheritdoc} */ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) { if ($operation == 'edit') { // Only users with the "administer comments" permission can edit // administrative fields. $administrative_fields = array('uid', 'status', 'created', 'date'); if (in_array($field_definition->getName(), $administrative_fields, TRUE)) { return AccessResult::allowedIfHasPermission($account, 'administer comments'); } // No user can change read-only fields. $read_only_fields = array('hostname', 'changed', 'cid', 'thread'); // These fields can be edited during comment creation. $create_only_fields = ['comment_type', 'uuid', 'entity_id', 'entity_type', 'field_name', 'pid']; if ($items && ($entity = $items->getEntity()) && $entity->isNew() && in_array($field_definition->getName(), $create_only_fields, TRUE)) { // We are creating a new comment, user can edit create only fields. return AccessResult::allowedIfHasPermission($account, 'post comments')->addCacheableDependency($entity); } // We are editing an existing comment - create only fields are now read // only. $read_only_fields = array_merge($read_only_fields, $create_only_fields); if (in_array($field_definition->getName(), $read_only_fields, TRUE)) { return AccessResult::forbidden(); } // If the field is configured to accept anonymous contact details - admins // can edit name, homepage and mail. Anonymous users can also fill in the // fields on comment creation. if (in_array($field_definition->getName(), ['name', 'mail', 'homepage'], TRUE)) { if (!$items) { // We cannot make a decision about access to edit these fields if we // don't have any items and therefore cannot determine the Comment // entity. In this case we err on the side of caution and prevent edit // access. return AccessResult::forbidden(); } /** @var \Drupal\comment\CommentInterface $entity */ $entity = $items->getEntity(); $commented_entity = $entity->getCommentedEntity(); $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous'); $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments'); $anonymous_access = AccessResult::allowedIf($entity->isNew() && $account->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT && $account->hasPermission('post comments'))->cachePerPermissions()->cacheUntilEntityChanges($entity)->cacheUntilEntityChanges($field_definition->getConfig($commented_entity->bundle()))->cacheUntilEntityChanges($commented_entity); return $admin_access->orIf($anonymous_access); } } if ($operation == 'view') { $entity = $items ? $items->getEntity() : NULL; // Admins can view any fields except hostname, other users need both the // "access comments" permission and for the comment to be published. The // mail field is hidden from non-admins. $admin_access = AccessResult::allowedIf($account->hasPermission('administer comments') && $field_definition->getName() != 'hostname')->cachePerPermissions(); $anonymous_access = AccessResult::allowedIf($account->hasPermission('access comments') && (!$entity || $entity->isPublished()) && !in_array($field_definition->getName(), array('mail', 'hostname'), TRUE))->cachePerPermissions(); if ($entity) { $anonymous_access->cacheUntilEntityChanges($entity); } return $admin_access->orIf($anonymous_access); } return parent::checkFieldAccess($operation, $field_definition, $account, $items); }
/** * {@inheritdoc} */ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) { // No user can edit the status of a file. Prevents saving a new file as // persistent before even validating it. if ($field_definition->getName() === 'status' && $operation === 'edit') { return AccessResult::forbidden(); } return parent::checkFieldAccess($operation, $field_definition, $account, $items); }
/** * {@inheritdoc} */ protected static function prepareTarget(FieldDefinitionInterface $field_definition) { // Only reference content entities. Configuration entities will need custom // targets. $type = $field_definition->getSetting('target_type'); if (!\Drupal::entityManager()->getDefinition($type)->isSubclassOf('\\Drupal\\Core\\Entity\\ContentEntityInterface')) { return; } return FieldTargetDefinition::createFromFieldDefinition($field_definition)->addProperty('target_id'); }
/** * {@inheritdoc} */ public static function isApplicable(FieldDefinitionInterface $field_definition) { $entity_form_display = entity_get_form_display($field_definition->getTargetEntityTypeId(), $field_definition->getTargetBundle(), 'default'); $widget = $entity_form_display->getRenderer($field_definition->getName()); $widget_id = $widget->getBaseId(); if ($field_definition->isList() && $widget_id == 'video_upload') { return TRUE; } return FALSE; }
/** * {@inheritdoc} */ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) { // Fields that are not implicitly allowed to administrative users. $explicit_check_fields = array('pass'); // Administrative users are allowed to edit and view all fields. if (!in_array($field_definition->getName(), $explicit_check_fields) && $account->hasPermission('administer users')) { return AccessResult::allowed()->cachePerPermissions(); } // Flag to indicate if this user entity is the own user account. $is_own_account = $items ? $items->getEntity()->id() == $account->id() : FALSE; switch ($field_definition->getName()) { case 'name': // Allow view access to anyone with access to the entity. Anonymous // users should be able to access the username field during the // registration process, otherwise the username and email constraints // are not checked. if ($operation == 'view' || $items && $account->isAnonymous() && $items->getEntity()->isAnonymous()) { return AccessResult::allowed()->cachePerPermissions(); } // Allow edit access for the own user name if the permission is // satisfied. if ($is_own_account && $account->hasPermission('change own username')) { return AccessResult::allowed()->cachePerPermissions()->cachePerUser(); } else { return AccessResult::forbidden(); } case 'preferred_langcode': case 'preferred_admin_langcode': case 'timezone': case 'mail': // Allow view access to own mail address and other personalization // settings. if ($operation == 'view') { return $is_own_account ? AccessResult::allowed()->cachePerUser() : AccessResult::forbidden(); } // Anyone that can edit the user can also edit this field. return AccessResult::allowed()->cachePerPermissions(); case 'pass': // Allow editing the password, but not viewing it. return $operation == 'edit' ? AccessResult::allowed() : AccessResult::forbidden(); case 'created': // Allow viewing the created date, but not editing it. return $operation == 'view' ? AccessResult::allowed() : AccessResult::forbidden(); case 'roles': case 'status': case 'access': case 'login': case 'init': return AccessResult::forbidden(); } return parent::checkFieldAccess($operation, $field_definition, $account, $items); }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $type = $field_definition->getSetting('datetime_type'); // Just pick a date in the past year. No guidance is provided by this Field // type. $timestamp = REQUEST_TIME - mt_rand(0, 86400 * 365); if ($type == DateTimeItem::DATETIME_TYPE_DATE) { $values['value'] = gmdate(DATETIME_DATE_STORAGE_FORMAT, $timestamp); } else { $values['value'] = gmdate(DATETIME_DATETIME_STORAGE_FORMAT, $timestamp); } return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $settings = $field_definition->getSettings(); $precision = rand(10, 32); $scale = rand(0, 2); $max = is_numeric($settings['max']) ?: pow(10, $precision - $scale) - 1; $min = is_numeric($settings['min']) ?: -pow(10, $precision - $scale) + 1; // @see "Example #1 Calculate a random floating-point number" in // http://php.net/manual/function.mt-getrandmax.php $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min); $values['value'] = self::truncateDecimal($random_decimal, $scale); return $values; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); $settings = $field_definition->getSettings(); if (empty($settings['max_length'])) { // Textarea handling $value = $random->paragraphs(); } else { // Textfield handling. $value = substr($random->sentences(mt_rand(1, $settings['max_length'] / 3), FALSE), 0, $settings['max_length']); } $values = array('value' => $value, 'summary' => $value, 'format' => filter_fallback_format()); return $values; }
/** * Builds an EntityQuery to get referenceable entities. * * @param string|null $match * (Optional) Text to match the label against. Defaults to NULL. * @param string $match_operator * (Optional) The operation the matching should be done with. Defaults * to "CONTAINS". * * @return \Drupal\Core\Entity\Query\QueryInterface * The EntityQuery object with the basic conditions and sorting applied to * it. */ public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') { $target_type = $this->fieldDefinition->getSetting('target_type'); $handler_settings = $this->fieldDefinition->getSetting('handler_settings'); $entity_type = \Drupal::entityManager()->getDefinition($target_type); $query = \Drupal::entityQuery($target_type); if (!empty($handler_settings['target_bundles'])) { $query->condition($entity_type->getKey('bundle'), $handler_settings['target_bundles'], 'IN'); } if (isset($match) && ($label_key = $entity_type->getKey('label'))) { $query->condition($label_key, $match, $match_operator); } // Add entity-access tag. $query->addTag($this->fieldDefinition->getSetting('target_type') . '_access'); // Add the Selection handler for // entity_reference_query_entity_reference_alter(). $query->addTag('entity_reference'); $query->addMetaData('field_definition', $this->fieldDefinition); $query->addMetaData('entity_reference_selection_handler', $this); // Add the sort option. $handler_settings = $this->fieldDefinition->getSetting('handler_settings'); if (!empty($handler_settings['sort'])) { $sort_settings = $handler_settings['sort']; if ($sort_settings['field'] != '_none') { $query->sort($sort_settings['field'], $sort_settings['direction']); } } return $query; }
/** * {@inheritdoc} */ public static function isApplicable(FieldDefinitionInterface $field_definition) { // This formatter is only available for entity types that have a view // builder. $target_type = $field_definition->getFieldStorageDefinition()->getSetting('target_type'); return \Drupal::entityManager()->getDefinition($target_type)->hasViewBuilderClass(); }
/** * {@inheritdoc} */ public static function settingsForm(FieldDefinitionInterface $field_definition) { $selection_handler_settings = $field_definition->getSetting('handler_settings'); // Merge in default values. $selection_handler_settings += array('filter' => array('type' => '_none')); // Add user specific filter options. $form['filter']['type'] = array('#type' => 'select', '#title' => t('Filter by'), '#options' => array('_none' => t('- None -'), 'role' => t('User role')), '#ajax' => TRUE, '#limit_validation_errors' => array(), '#default_value' => $selection_handler_settings['filter']['type']); $form['filter']['settings'] = array('#type' => 'container', '#attributes' => array('class' => array('entity_reference-settings')), '#process' => array('_entity_reference_form_process_merge_parent')); if ($selection_handler_settings['filter']['type'] == 'role') { // Merge in default values. $selection_handler_settings['filter'] += array('role' => NULL); $form['filter']['settings']['role'] = array('#type' => 'checkboxes', '#title' => t('Restrict to the selected roles'), '#required' => TRUE, '#options' => array_diff_key(user_role_names(TRUE), array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID)), '#default_value' => $selection_handler_settings['filter']['role']); } $form += parent::settingsForm($field_definition); return $form; }
/** * Check if a field on the entity type to update is a possible destination field. * * @todo Should this be on our FieldManager service? * * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition * Field definition on entity type to update to check. * @param \Drupal\Core\Field\FieldDefinitionInterface $source_field * Source field to check compatibility against. If none then check generally. * * @return bool */ protected function isDestinationFieldCompatible(FieldStorageDefinitionInterface $definition, FieldDefinitionInterface $source_field = NULL) { // @todo Create field definition wrapper class to treat FieldDefinitionInterface and FieldStorageDefinitionInterface the same. if ($definition instanceof BaseFieldDefinition && $definition->isReadOnly()) { return FALSE; } // Don't allow updates on updates! if ($definition->getType() == 'entity_reference') { if ($definition->getSetting('target_type') == 'scheduled_update') { return FALSE; } } if ($source_field) { $matching_types = $this->getMatchingFieldTypes($source_field->getType()); if (!in_array($definition->getType(), $matching_types)) { return FALSE; } // Check cardinality $destination_cardinality = $definition->getCardinality(); $source_cardinality = $source_field->getFieldStorageDefinition()->getCardinality(); // $destination_cardinality is unlimited. It doesn't matter what source is. if ($destination_cardinality != -1) { if ($source_cardinality == -1) { return FALSE; } if ($source_cardinality > $destination_cardinality) { return FALSE; } } switch ($definition->getType()) { case 'entity_reference': // Entity reference field must match entity target types. if ($definition->getSetting('target_type') != $source_field->getSetting('target_type')) { return FALSE; } // @todo Check bundles break; // @todo Other type specific conditions? } } return TRUE; }
/** * @covers ::massageFormValues */ public function testMassageFormValues() { $field_name = $this->randomMachineName(); $payment_id = mt_rand(); $this->fieldDefinition->expects($this->atLeastOnce())->method('getName')->willReturn($field_name); $form_state = $this->getMock(FormStateInterface::class); $form[$field_name]['widget']['target_id']['#value'] = $payment_id; $values = []; $expected_value = array('target_id' => $payment_id); $this->assertSame($expected_value, $this->sut->massageFormValues($values, $form, $form_state)); }
/** * Tests the match method. */ public function testMatch() { $this->field->expects($this->any())->method('getType')->will($this->returnValue('crap')); $this->contact->expects($this->any())->method('getFieldDefinitions')->will($this->returnValue(array('foo' => $this->field))); $this->pluginManager->expects($this->any())->method('hasDefinition')->will($this->returnValue(TRUE)); $this->matchHandler->expects($this->any())->method('match')->will($this->returnValue(array('42' => array('value' => 100)))); // $this->pluginManager->expects($this->once()) // ->method('createInstance') // ->will($this->returnValue($this->matchHandler)); // $ids = $this->engine->match($this->contact); // $this->assertEquals([], $ids); }
public function getOptions(FieldDefinitionInterface $field, $component) { $fs = $field->getFieldStorageDefinition()->getSettings(); $options = $fs[$component . '_options']; foreach ($options as $index => $opt) { if (preg_match('/^\\[vocabulary:([0-9a-z\\_]{1,})\\]/', trim($opt), $matches)) { unset($options[$index]); if ($this->termStorage && $this->vocabularyStorage) { $vocabulary = $this->vocabularyStorage->load($matches[1]); if ($vocabulary) { $max_length = isset($fs['max_length'][$component]) ? $fs['max_length'][$component] : 255; foreach ($this->termStorage->loadTree($vocabulary->id()) as $term) { if (Unicode::strlen($term->name) <= $max_length) { $options[] = $term->name; } } } } } } // Options could come from multiple sources, filter duplicates. $options = array_unique($options); if (isset($fs['sort_options']) && !empty($fs['sort_options'][$component])) { natcasesort($options); } $default = FALSE; foreach ($options as $index => $opt) { if (strpos($opt, '--') === 0) { unset($options[$index]); $default = trim(Unicode::substr($opt, 2)); } } $options = array_map('trim', $options); $options = array_combine($options, $options); if ($default !== FALSE) { $options = array('' => $default) + $options; } return $options; }
/** * {@inheritdoc} */ public function validateReferenceableEntities(array $ids) { $handler_settings = $this->fieldDefinition->getSetting('handler_settings'); $display_name = $handler_settings['view']['display_name']; $arguments = $handler_settings['view']['arguments']; $result = array(); if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) { // Get the results. $entities = $this->view->executeDisplay($display_name, $arguments); $result = array_keys($entities); } return $result; }
/** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $settings = $field_definition->getSettings(); $precision = $settings['precision'] ?: 10; $scale = $settings['scale'] ?: 2; // $precision - $scale is the number of digits on the left of the decimal // point. // The maximum number you can get with 3 digits is 10^3 - 1 --> 999. // The minimum number you can get with 3 digits is -1 * (10^3 - 1). $max = is_numeric($settings['max']) ?: pow(10, $precision - $scale) - 1; $min = is_numeric($settings['min']) ?: -pow(10, $precision - $scale) + 1; // Get the number of decimal digits for the $max $decimal_digits = self::getDecimalDigits($max); // Do the same for the min and keep the higher number of decimal digits. $decimal_digits = max(self::getDecimalDigits($min), $decimal_digits); // If $min = 1.234 and $max = 1.33 then $decimal_digits = 3 $scale = rand($decimal_digits, $scale); // @see "Example #1 Calculate a random floating-point number" in // http://php.net/manual/en/function.mt-getrandmax.php $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min); $values['value'] = self::truncateDecimal($random_decimal, $scale); return $values; }
/** * @covers ::formElementProcess */ public function testFormElementProcess() { $field_storage_definition = $this->getMock(FieldStorageDefinitionInterface::class); $this->fieldDefinition->expects($this->atLeastOnce())->method('getFieldStorageDefinition')->willReturn($field_storage_definition); $iterator = new \ArrayIterator([(object) ['plugin_configuration' => [], 'plugin_id' => $this->randomMachineName()]]); $items = $this->getMockBuilder(FieldItemList::class)->disableOriginalConstructor()->setMethods(['getIterator'])->getMock(); $items->expects($this->once())->method('getIterator')->willReturn($iterator); $element = ['#array_parents' => ['line_items'], '#items' => $items]; $form = []; $form_state = $this->getMock(FormStateInterface::class); $element = $this->sut->formElementProcess($element, $form_state, $form); $this->assertInternalType('array', $element); $this->arrayHasKey('array_parents', $element); $this->arrayHasKey('line_items', $element); }
/** * @covers ::viewElements */ public function testViewElements() { $entity_type_id = $this->randomMachineName(); $bundle = $this->randomMachineName(); $field_name = $this->randomMachineName(); $destination_url = $this->randomMachineName(); $currency_code = $this->randomMachineName(); $plugin_id = $this->randomMachineName(); $plugin_configuration = [$this->randomMachineName() => $this->randomMachineName()]; $plugin_id_property = $this->getMock(TypedDataInterface::class); $plugin_id_property->expects($this->once())->method('getValue')->willReturn($plugin_id); $plugin_configuration_property = $this->getMock(TypedDataInterface::class); $plugin_configuration_property->expects($this->once())->method('getValue')->willReturn($plugin_configuration); $map = [['plugin_id', $plugin_id_property], ['plugin_configuration', $plugin_configuration_property]]; $item = $this->getMockBuilder(PaymentFormFieldType::class)->disableOriginalConstructor()->getMock(); $item->expects($this->exactly(2))->method('get')->willReturnMap($map); $entity = $this->getMock(EntityInterface::class); $entity->expects($this->atLeastOnce())->method('bundle')->willReturn($bundle); $entity->expects($this->atLeastOnce())->method('getEntityTypeId')->willReturn($entity_type_id); $iterator = new \ArrayIterator([$item]); $items = $this->getMockBuilder(FieldItemList::class)->disableOriginalConstructor()->setMethods(['getEntity', 'getIterator'])->getMock(); $items->expects($this->atLeastOnce())->method('getEntity')->willReturn($entity); $items->expects($this->atLeastOnce())->method('getIterator')->willReturn($iterator); $this->fieldDefinition->expects($this->once())->method('getName')->willReturn($field_name); $this->fieldDefinition->expects($this->atLeastOnce())->method('getSetting')->with('currency_code')->willReturn($currency_code); $payment_type = $this->getMockBuilder(PaymentFormPaymentType::class)->disableOriginalConstructor()->getMock(); $payment_type->expects($this->once())->method('setEntityTypeId')->with($entity_type_id); $payment_type->expects($this->once())->method('setBundle')->with($bundle); $payment_type->expects($this->once())->method('setFieldName')->with($field_name); $payment_type->expects($this->once())->method('setDestinationUrl')->with($destination_url); $payment = $this->getMock(PaymentInterface::class); $payment->expects($this->once())->method('setCurrencyCode')->with($currency_code); $payment->expects($this->once())->method('getPaymentType')->willReturn($payment_type); $payment_line_item = $this->getMock(PaymentLineItemInterface::class); $this->paymentLineItemManager->expects($this->once())->method('createInstance')->with($plugin_id, $plugin_configuration)->willReturn($payment_line_item); $this->paymentStorage->expects($this->once())->method('create')->with(['bundle' => 'payment_form'])->willReturn($payment); $this->request->expects($this->atLeastOnce())->method('getUri')->willReturn($destination_url); $form = ['#foo' => $this->randomMachineName()]; $this->entityFormBuilder->expects($this->once())->method('getForm')->with($payment, 'payment_form')->willReturn($form); $this->assertSame($form, $this->sut->viewElements($items, 'en')); }
/** * {@inheritdoc} */ public function match(ContactInterface $contact, $property = 'value') { $ids = array(); $field = $this->field->getName(); $needle = $contact->get($field)->{$property}; if (!empty($needle)) { $this->query->condition('type', $contact->bundle()); if ($contact->id()) { $this->query->condition('contact_id', $contact->id(), '<>'); } if ($field instanceof FieldConfigInterface) { $field .= '.' . $property; } $this->query->condition($field, $needle, $this->getOperator($property)); $ids = $this->query->execute(); } // Get the score for this field/propery. $score = array($this->field->getName() . '.' . $property => $this->getScore($property)); // Returning an array holding the score as value and the contact id as key. return array_fill_keys($ids, $score); }
/** * {@inheritdoc} */ public function createPayment(FieldDefinitionInterface $field_definition) { /** @var \Drupal\payment\Entity\PaymentInterface $payment */ $payment = $this->entityManager->getStorage('payment')->create(['bundle' => 'payment_reference']); /** @var \Drupal\payment_reference\Plugin\Payment\Type\PaymentReference $payment_type */ $payment_type = $payment->getPaymentType(); $payment_type->setEntityTypeId($field_definition->getFieldStorageDefinition()->getTargetEntityTypeId()); $payment_type->setBundle($field_definition->getTargetBundle()); $payment_type->setFieldName($field_definition->getName()); $payment->setCurrencyCode($field_definition->getSetting('currency_code')); foreach ($field_definition->getSetting('line_items_data') as $line_item_data) { $line_item = $this->paymentLineItemManager->createInstance($line_item_data['plugin_id'], $line_item_data['plugin_configuration']); $payment->setLineItem($line_item); } return $payment; }
/** * {@inheritdoc} */ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) { /** @var \Drupal\comment\CommentInterface $entity */ $entity = $items->getEntity(); if ($operation == 'edit') { // Only users with the "administer comments" permission can edit // administrative fields. $administrative_fields = array('uid', 'status', 'created', 'date'); if (in_array($field_definition->getName(), $administrative_fields, TRUE)) { return AccessResult::allowedIfHasPermission($account, 'administer comments'); } // No user can change read-only fields. $read_only_fields = array('changed', 'hostname', 'uuid', 'cid', 'thread', 'comment_type', 'pid', 'entity_id', 'entity_type', 'field_name'); if (in_array($field_definition->getName(), $read_only_fields, TRUE)) { return AccessResult::forbidden(); } $commented_entity = $entity->getCommentedEntity(); $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous_contact'); // If the field is configured to accept anonymous contact details - admins // can edit name, homepage and mail. Anonymous users can also fill in the // fields on comment creation. if (in_array($field_definition->getName(), ['name', 'mail', 'homepage'], TRUE)) { $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments'); $anonymous_access = AccessResult::allowedIf($entity->isNew() && $account->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT && $account->hasPermission('post comments'))->cachePerRole()->cacheUntilEntityChanges($entity)->cacheUntilEntityChanges($field_definition->getConfig($commented_entity->bundle()))->cacheUntilEntityChanges($commented_entity); return $admin_access->orIf($anonymous_access); } } if ($operation == 'view') { // Admins can view any fields except hostname, other users need both the // "access comments" permission and for the comment to be published. The // mail field is hidden from non-admins. $admin_access = AccessResult::allowedIf($account->hasPermission('administer comments') && $field_definition->getName() != 'hostname')->cachePerRole(); $anonymous_access = AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished() && !in_array($field_definition->getName(), array('mail', 'hostname'), TRUE))->cacheUntilEntityChanges($entity)->cachePerRole(); return $admin_access->orIf($anonymous_access); } return parent::checkFieldAccess($operation, $field_definition, $account, $items); }
/** * {@inheritdoc} */ public function getPropertyDescription($property) { return $this->fieldDefinition->getItemDefinition()->getPropertyDefinition($property)->getDescription(); }
/** * {@inheritdoc} * Used in \Drupal\field\Tests\EntityReference\EntityReferenceAdminTest::testAvailableFormatters(). */ public static function isApplicable(FieldDefinitionInterface $field_definition) { // Returns FALSE if machine name of the field equals field_onewidgetfield. return $field_definition->getName() != "field_onewidgetfield"; }
/** * Control access to fields. * * This hook is invoked from * \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess() to let modules * grant or deny operations on fields. * * @param string $operation * The operation to be performed. See * \Drupal\Core\Access\AccessibleInterface::access() for possible values. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * @param \Drupal\Core\Session\AccountInterface $account * The user account to check. * @param \Drupal\Core\Field\FieldItemListInterface $items * (optional) The entity field object on which the operation is to be * performed. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ function hook_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Field\FieldItemListInterface $items = NULL) { if ($field_definition->getName() == 'field_of_interest' && $operation == 'edit') { return AccessResult::allowedIfHasPermission($account, 'update field of interest'); } return AccessResult::neutral(); }
/** * {@inheritdoc} */ public static function isApplicable(FieldDefinitionInterface $field_definition) { return $field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'user'; }
/** * {@inheritdoc} */ protected function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition) { $storage_definition = $field_definition->getFieldStorageDefinition(); $is_deleted = $this->storageDefinitionIsDeleted($storage_definition); $table_mapping = $this->getTableMapping(); $table_name = $table_mapping->getDedicatedDataTableName($storage_definition, $is_deleted); $revision_name = $table_mapping->getDedicatedRevisionTableName($storage_definition, $is_deleted); $revision_id = $this->entityType->isRevisionable() ? $entity->getRevisionId() : $entity->id(); $this->database->delete($table_name)->condition('revision_id', $revision_id)->execute(); if ($this->entityType->isRevisionable()) { $this->database->delete($revision_name)->condition('revision_id', $revision_id)->execute(); } }