/** * {@inheritdoc} * * When the $operation is 'add' then the $entity is of type 'profile_type', * otherwise $entity is of type 'profile'. */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { $account = $this->prepareUser($account); $user_page = \Drupal::request()->attributes->get('user'); // Some times, operation edit is called update. // Use edit in any case. if ($operation == 'update') { $operation = 'edit'; } // Check that if profile type has require roles, the user the profile is // being added to has any of the required roles. if ($entity->getEntityTypeId() == 'profile') { $profile_roles = ProfileType::load($entity->bundle())->getRoles(); $user_roles = $entity->getOwner()->getRoles(TRUE); if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) { return AccessResult::forbidden(); } } elseif ($entity->getEntityTypeId() == 'profile_type') { $profile_roles = $entity->getRoles(); $user_roles = User::load($user_page->id())->getRoles(TRUE); if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) { return AccessResult::forbidden(); } } if ($account->hasPermission('bypass profile access')) { return AccessResult::allowed()->cachePerPermissions(); } elseif ($operation == 'add' && ($user_page->id() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->id() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->id() . ' profile')) || $operation != 'add' && ($entity->getOwnerId() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->getType() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->getType() . ' profile'))) { return AccessResult::allowed()->cachePerPermissions(); } else { return AccessResult::forbidden()->cachePerPermissions(); } }
/** * Invokes the implementation. */ public function invoke(EntityInterface $entity) { if ($entity->getEntityTypeId() == 'payment_method_configuration') { $manager = $this->paymentMethodManager; } elseif ($entity->getEntityTypeId() == 'payment_status') { $manager = $this->paymentStatusManager; } if (isset($manager) && $manager instanceof CachedDiscoveryInterface) { $manager->clearCachedDefinitions(); } }
/** * {@inheritdoc} */ public function getTranslationAccess(EntityInterface $entity, $op) { // @todo Move this logic into a translation access controller checking also // the translation language and the given account. $entity_type = $entity->getEntityType(); $translate_permission = TRUE; // If no permission granularity is defined this entity type does not need an // explicit translate permission. $current_user = \Drupal::currentUser(); if (!$current_user->hasPermission('translate any entity') && ($permission_granularity = $entity_type->getPermissionGranularity())) { $translate_permission = $current_user->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}"); } return $translate_permission && $current_user->hasPermission("{$op} content translations"); }
/** * Assert that a field has the expected values in an entity. * * This function only checks a single column in the field values. * * @param EntityInterface $entity * The entity to test. * @param $field_name * The name of the field to test * @param $expected_values * The array of expected values. * @param $langcode * (Optional) The language code for the values. Defaults to * \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT. * @param $column * (Optional) The name of the column to check. Defaults to 'value'. */ function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') { // Re-load the entity to make sure we have the latest changes. \Drupal::entityManager()->getStorage($entity->getEntityTypeId())->resetCache(array($entity->id())); $e = entity_load($entity->getEntityTypeId(), $entity->id()); $field = $values = $e->getTranslation($langcode)->{$field_name}; // Filter out empty values so that they don't mess with the assertions. $field->filterEmptyItems(); $values = $field->getValue(); $this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.'); foreach ($expected_values as $key => $value) { $this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', array('@value' => $value))); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\entity_clone\EntityClone\EntityCloneInterface $entity_clone_handler */ $entity_clone_handler = $this->entityTypeManager->getHandler($this->entityTypeDefinition->id(), 'entity_clone'); if ($this->entityTypeManager->hasHandler($this->entityTypeDefinition->id(), 'entity_clone_form')) { $entity_clone_form_handler = $this->entityTypeManager->getHandler($this->entityTypeDefinition->id(), 'entity_clone_form'); } $properties = []; if (isset($entity_clone_form_handler) && $entity_clone_form_handler) { $properties = $entity_clone_form_handler->getNewValues($form_state); } $cloned_entity = $entity_clone_handler->cloneEntity($this->entity, $this->entity->createDuplicate(), $properties); drupal_set_message($this->stringTranslationManager->translate('The entity <em>@entity (@entity_id)</em> of type <em>@type</em> was cloned', [ '@entity' => $this->entity->label(), '@entity_id' => $this->entity->id(), '@type' => $this->entity->getEntityTypeId(), ])); if ($cloned_entity && $cloned_entity->hasLinkTemplate('canonical')) { $form_state->setRedirect($cloned_entity->toUrl() ->getRouteName(), $cloned_entity->toUrl()->getRouteParameters()); } $form_state->setRedirect('<front>'); }
/** * {@inheritdoc} */ public function access(EntityInterface $entity, $operation, $langcode = LanguageInterface::LANGCODE_DEFAULT, AccountInterface $account = NULL, $return_as_object = FALSE) { $account = $this->prepareUser($account); if (($return = $this->getCache($entity->uuid(), $operation, $langcode, $account)) !== NULL) { // Cache hit, no work necessary. return $return_as_object ? $return : $return->isAllowed(); } // Invoke hook_entity_access() and hook_ENTITY_TYPE_access(). Hook results // take precedence over overridden implementations of // EntityAccessControlHandler::checkAccess(). Entities that have checks that // need to be done before the hook is invoked should do so by overriding // this method. // We grant access to the entity if both of these conditions are met: // - No modules say to deny access. // - At least one module says to grant access. $access = array_merge($this->moduleHandler()->invokeAll('entity_access', array($entity, $operation, $account, $langcode)), $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', array($entity, $operation, $account, $langcode))); $return = $this->processAccessHookResults($access); // Also execute the default access check except when the access result is // already forbidden, as in that case, it can not be anything else. if (!$return->isForbidden()) { $return = $return->orIf($this->checkAccess($entity, $operation, $langcode, $account)); } $result = $this->setCache($return, $entity->uuid(), $operation, $langcode, $account); return $return_as_object ? $result : $result->isAllowed(); }
/** * {@inheritdoc} */ public function formElement(EntityInterface $entity) { $form = []; if ($this->entityTypeManager->getDefinition($entity->getEntityTypeId())->getKey('label')) { $form['label'] = array( '#type' => 'textfield', '#title' => $this->translationManager->translate('New Label'), '#maxlength' => 255, '#required' => TRUE, ); } $form['id'] = array( '#type' => 'machine_name', '#title' => $this->translationManager->translate('New Id'), '#maxlength' => 255, '#required' => TRUE, ); // If entity must have a prefix // (e.g. entity_form_mode, entity_view_mode, ...). if (method_exists($entity, 'getTargetType')) { $form['id']['#field_prefix'] = $entity->getTargetType() . '.'; } if (method_exists($entity, 'load')) { $form['id']['#machine_name'] = [ 'exists' => get_class($entity) . '::load', ]; } return $form; }
/** * {@inheritdoc} */ public function checkAccess(EntityInterface $entity, Route $route, AccountInterface $account, $operation, $graph_name) { if (!$entity) { return FALSE; } // For now, we only have the view operation but this is not the only // operation so we will check anyway. $map = ['view' => 'view all graphs']; $entity_type_id = $entity->getEntityTypeId(); $type_map = ['view' => "view {$entity_type_id} {$graph_name} graph"]; // If the operation is not supported, do not allow access. if (!isset($map[$operation]) || !isset($type_map[$operation])) { return FALSE; } // @todo: This probably needs to be cached manually creating a cid. // @see: \Drupal\node\Access\NodeRevisionAccessCheck::checkAccess(). // @todo: This needs also to check cache for cached permission. // @see: \Drupal\Core\Entity\EntityAccessControlHandler::access(). $has_permission = $account->hasPermission($map[$operation]) || $account->hasPermission($type_map[$operation]); $access = $has_permission ? AccessResult::allowed() : AccessResult::neutral(); $arguments = [$entity, $operation, $account, $graph_name]; $access_array = array_merge([$access], $this->moduleHandler->invokeAll('entity_graph_access', $arguments), $this->moduleHandler->invokeAll($entity_type_id . '_graph_access', $arguments)); $return = $this->processAccessHookResults($access_array); return $return->isAllowed(); }
/** * Creates an instance wrapping the given entity. * * @param \Drupal\Core\Entity\EntityInterface|null $entity * The entity object to wrap. * * @return static */ public static function createFromEntity(EntityInterface $entity) { $definition = EntityDataDefinition::create()->setEntityTypeId($entity->getEntityTypeId())->setBundles([$entity->bundle()]); $instance = new static($definition); $instance->setValue($entity); return $instance; }
/** * {@inheritdoc} */ public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = array()) { $form_object = $this->entityManager->getFormObject($entity->getEntityTypeId(), $operation); $form_object->setEntity($entity); $form_state = (new FormState())->setFormState($form_state_additions); return $this->formBuilder->buildForm($form_object, $form_state); }
/** * Check if a provided entity is of a specific type and bundle. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to check the bundle and type of. * @param string $type * The type to check for. * @param string $bundle * The bundle to check for. * * @return bool * TRUE if the provided entity is of the provided type and bundle. */ protected function doEvaluate(EntityInterface $entity, $type, $bundle) { $entity_type = $entity->getEntityTypeId(); $entity_bundle = $entity->bundle(); // Check to see whether the entity's bundle and type match the specified // values. return $entity_bundle == $bundle && $entity_type == $type; }
/** * {@inheritdoc} */ protected function alterBuild(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) { $entity_type_id = $entity->getEntityTypeId(); if ($entity instanceof ContentEntityInterface && $entity->isDefaultRevision() || !$entity->getEntityType()->isRevisionable()) { $build['#contextual_links'][$entity_type_id] = ['route_parameters' => [$entity_type_id => $entity->id()]]; } else { $build['#contextual_links'][$entity_type_id . '_revision'] = ['route_parameters' => [$entity_type_id => $entity->id(), $entity_type_id . '_revision' => $entity->getRevisionId()]]; } }
/** * {@inheritdoc} */ public function getForm(EntityInterface $entity, $operation = 'default', array $form_state = array()) { $form_object = $this->entityManager->getFormObject($entity->getEntityTypeId(), $operation); $form_object->setEntity($entity); $form_state['build_info']['callback_object'] = $form_object; $form_state['build_info']['base_form_id'] = $form_object->getBaseFormID(); $form_state['build_info'] += array('args' => array()); return $this->formBuilder->buildForm($form_object, $form_state); }
/** * Initialize the form state and the entity before the first form build. */ protected function init(FormStateInterface $form_state) { // Flag that this form has been initialized. $form_state->set('entity_form_initialized', TRUE); // Prepare the entity to be presented in the entity form. $this->prepareEntity(); // Invoke the prepare form hooks. $this->prepareInvokeAll('entity_prepare_form', $form_state); $this->prepareInvokeAll($this->entity->getEntityTypeId() . '_prepare_form', $form_state); }
public function create(EntityInterface $entity) { if (!isset($entity->xmlsitemap)) { $entity->xmlsitemap = array(); if ($entity->id() && ($link = $this->load($entity->getEntityTypeId(), $entity->id()))) { $entity->xmlsitemap = $link; } } $settings = xmlsitemap_link_bundle_load($entity->getEntityTypeId(), $entity->bundle()); $uri = $entity->url(); $entity->xmlsitemap += array('type' => $entity->getEntityTypeId(), 'id' => (string) $entity->id(), 'subtype' => $entity->bundle(), 'status' => $settings['status'], 'status_default' => $settings['status'], 'status_override' => 0, 'priority' => $settings['priority'], 'priority_default' => $settings['priority'], 'priority_override' => 0, 'changefreq' => isset($settings['changefreq']) ? $settings['changefreq'] : 0); $url = $entity->url(); // The following values must always be checked because they are volatile. $entity->xmlsitemap['loc'] = $uri; $entity->xmlsitemap['access'] = isset($url) && $entity->access('view', $this->anonymousUser); $language = $entity->language(); $entity->xmlsitemap['language'] = !empty($language) ? $language->getId() : LanguageInterface::LANGCODE_NOT_SPECIFIED; return $entity->xmlsitemap; }
/** * Converts role names into og roles by adding the appropriate prefix. * * This function does not test if the entity is a group. It merely serves as * a name conversion method. * * @param array $roles * An array of roles to convert names. * @param \Drupal\Core\Entity\EntityInterface $group * The group entity. * * @return array * An array with the converted names. */ protected function convertOgRoleNamesToIds(array $roles, EntityInterface $group) { $role_prefix = $group->getEntityTypeId() . '-' . $group->bundle() . '-'; foreach ($roles as $key => $role) { // What is called a "collection owner" or a "solution owner" in Joinup, is // known as an "administrator" in OG. $role = $role === 'owner' ? 'administrator' : $role; $roles[$key] = $role_prefix . $role; } return $roles; }
/** * Test registration type deletion. */ function testRegistrationTypeAPIDelete() { // Associate event with registration type. $this->event->{EventManagerInterface::FIELD_REGISTRATION_TYPE}->appendItem(['target_id' => $this->registration_type->id()]); $this->event->save(); $this->assertEqual(1, $this->countEventRegistrationTypeReferences($this->event->getEntityTypeId(), $this->registration_type->id()), 'One reference exists to this registration type'); $registration[0] = $this->createRegistration($this->event, $this->registration_type->id()); $this->registration_type->delete(); $this->assertIdentical(0, count(Registration::loadMultiple()), 'Registrations no longer exist'); $this->assertEqual(0, $this->countEventRegistrationTypeReferences($this->event->getEntityTypeId(), $this->registration_type->id()), 'No references from event entities to this registration type'); }
/** * Initialize the form state and the entity before the first form build. */ protected function init(FormStateInterface $form_state) { // Add the controller to the form state so it can be easily accessed by // module-provided form handlers there. $form_state['controller'] = $this; // Prepare the entity to be presented in the entity form. $this->prepareEntity(); // Invoke the prepare form hooks. $this->prepareInvokeAll('entity_prepare_form', $form_state); $this->prepareInvokeAll($this->entity->getEntityTypeId() . '_prepare_form', $form_state); }
/** * {@inheritdoc} */ public function buildLinks(EntityInterface $entity = NULL) { $links = array(); $printable_settings = $this->configFactory->get('printable.settings'); // Build the array of links to be added to the entity. foreach ($this->printableFormatManager->getDefinitions() as $key => $definition) { $links[$key] = array('title' => $definition['title'], 'url' => Url::fromRoute('printable.show_format.' . $entity->getEntityTypeId(), array('printable_format' => $key, 'entity' => $entity->id()))); // Add target "blank" if the configuration option is set. if ($printable_settings->get('open_target_blank') && ($key == 'print' or !$printable_settings->get('save_pdf'))) { $links[$key]['attributes']['target'] = '_blank'; } } return $links; }
/** * {@inheritdoc} */ public function access(EntityInterface $entity, $operation, AccountInterface $account = NULL, $return_as_object = FALSE) { $result = AccessResult::neutral(); $account = $this->prepareUser($account); // $account = workflow_current_user($account); /* @var $transition WorkflowTransitionInterface */ $transition = $entity; // This is only for Edit/Delete transition. For Add/create, use createAccess. switch ($entity->getEntityTypeId()) { case 'workflow_transition': case 'workflow_scheduled_transition': switch ($operation) { case 'update': $is_owner = WorkflowManager::isOwner($account, $transition); $type_id = $transition->getWorkflowId(); if ($account->hasPermission("bypass {$type_id} workflow_transition access")) { $result = AccessResult::allowed()->cachePerPermissions(); } elseif ($account->hasPermission("edit any {$type_id} workflow_transition")) { $result = AccessResult::allowed()->cachePerPermissions(); } elseif ($is_owner && $account->hasPermission("edit own {$type_id} workflow_transition")) { $result = AccessResult::allowed()->cachePerPermissions(); } return $return_as_object ? $result : $result->isAllowed(); break; case 'delete': // The delete operation is not defined for Transitions. $result = AccessResult::forbidden(); break; case 'revert': // @see workflow_operations. // @see workflow_operations. default: $type_id = $transition->getWorkflowId(); $result = parent::access($entity, $account, $return_as_object); //if ($account->hasPermission("bypass $type_id workflow_transition access")) { // $result = AccessResult::allowed()->cachePerPermissions(); //} break; } // End of switch ($operation). break; case 'workflow_config_transition': workflow_debug(__FILE__, __FUNCTION__, __LINE__, $account->id(), $transition->getOwnerId()); // @todo D8-port: still test this snippet. break; } $result = parent::access($entity, $operation, $account, TRUE)->cachePerPermissions(); return $return_as_object ? $result : $result->isAllowed(); }
/** * Render the token tree for the specified entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which the token tree should be rendered. * * @return array * Render array of the token tree for the $entity. * * @see static::entityLoad */ protected function renderTokenTree(EntityInterface $entity) { $this->moduleHandler()->loadInclude('token', 'pages.inc'); $entity_type = $entity->getEntityTypeId(); $token_type = $this->entityMapper->getTokenTypeForEntityType($entity_type); $options = ['flat' => TRUE, 'values' => TRUE, 'data' => [$token_type => $entity]]; $token_tree = [$token_type => ['tokens' => $this->treeBuilder->buildTree($token_type, $options)]]; // foreach ($tree as $token => $token_info) { // if (!isset($token_info['value']) && !empty($token_info['parent']) && !isset($tree[$token_info['parent']]['value'])) { // continue; // } // } $build['tokens'] = ['#type' => 'token_tree_table', '#show_restricted' => FALSE, '#skip_empty_values' => TRUE, '#token_tree' => $token_tree, '#columns' => ['token', 'value'], '#empty' => $this->t('No tokens available.')]; return $build; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // The revision timestamp will be updated when the revision is saved. Keep // the original one for the confirmation message. $this->revision = $this->prepareRevision($this->revision); if ($this->revision instanceof RevisionLogInterface) { $original_revision_timestamp = $this->revision->getRevisionCreationTime(); $this->revision->setRevisionLogMessage($this->t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)])); drupal_set_message(t('@type %title has been reverted to the revision from %revision-date.', ['@type' => $this->getBundleLabel($this->revision), '%title' => $this->revision->label(), '%revision-date' => $this->dateFormatter->format($original_revision_timestamp)])); } else { drupal_set_message(t('@type %title has been reverted', ['@type' => $this->getBundleLabel($this->revision), '%title' => $this->revision->label()])); } $this->revision->save(); $this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]); $form_state->setRedirect("entity.{$this->revision->getEntityTypeId()}.version_history", [$this->revision->getEntityTypeId() => $this->revision->id()]); }
/** * Determines if the user specified has access to report the entity. * * @param \Drupal\core\Entity\EntityInterface $entity * The entity to check access for * @param $form_id string * The form that is protected for this entity. * @param \Drupal\Core\Session\AccountInterface $account * The account to use. If null, use the current user. * * @return \Drupal\Core\Access\AccessResultInterface */ public static function accessReport($entity, $form_id, $account = NULL) { // Check if the user has access to this comment. $result = $entity->access('edit', $account, TRUE)->andIf($entity->access('update', $account, TRUE)); if (!$result->isAllowed()) { return $result; } // Check if this entity type is protected. $form_entity = \Drupal::entityManager()->getStorage('mollom_form')->load($form_id); if (empty($form_entity)) { return new AccessResultForbidden(); } // Check any specific report access callbacks. $forms = FormController::getProtectableForms(); $info = $forms[$form_id]; if (empty($info)) { // Orphan form protection. return new AccessResultForbidden(); } $report_access_callbacks = []; $access_permissions = []; // If there is a 'report access callback' add it to the list. if (isset($info['report access callback']) && function_exists($info['report access callback']) && !in_array($info['report access callback'], $report_access_callbacks)) { $report_access_callbacks[] = $info['report access callback']; } else { if (isset($info['report access']) && !in_array($info['report access'], $access_permissions)) { $access_permissions += $info['report access']; } } foreach ($report_access_callbacks as $callback) { if (!$callback($entity->getEntityTypeId(), $entity->id())) { return new AccessResultForbidden(); } } foreach ($access_permissions as $permission) { if (empty($account)) { $account = \Drupal::currentUser(); } if (!$account->hasPermission($permission)) { return new AccessResultForbidden(); } } return new AccessResultAllowed(); }
/** * {@inheritdoc} */ public function access(EntityInterface $entity, $operation, AccountInterface $account = NULL, $return_as_object = FALSE) { $result = AccessResult::neutral(); $account = $user = workflow_current_user($account); // This is only for Edit/Delete transition. For Add/create, use createAccess. switch ($entity->getEntityTypeId()) { case 'workflow_transition': case 'workflow_scheduled_transition': /* @var $transition WorkflowTransitionInterface */ $transition = $entity; switch ($operation) { case 'revert': $is_owner = WorkflowManager::isOwner($user, $transition); $type_id = $transition->getWorkflowId(); if ($transition->getFromSid() == $transition->getToSid()) { // No access for same state transitions. $result = AccessResult::forbidden(); } elseif ($user->hasPermission("revert any {$type_id} workflow_transition")) { // OK, add operation. $result = AccessResult::allowed(); } elseif ($is_owner && $user->hasPermission("revert own {$type_id} workflow_transition")) { // OK, add operation. $result = AccessResult::allowed(); } else { // No access. $result = AccessResult::forbidden(); } break; default: $result = parent::access($entity, $operation, $account, $return_as_object)->cachePerPermissions(); break; } // End of switch ($operation). break; // case // case default: // $entity_type $result = AccessResult::forbidden(); } // End of switch($entity->getEntityTypeId()). return $return_as_object ? $result : $result->isAllowed(); }
/** * Return an Ajax dialog command for editing a referenced entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * An entity being edited. * * @return \Drupal\Core\Ajax\AjaxResponse * An Ajax response with a command for opening or closing the dialog * containing the edit form. */ public function entityBrowserEdit(EntityInterface $entity) { // Build the entity edit form. $form_object = $this->entityManager()->getFormObject($entity->getEntityTypeId(), 'edit'); $form_object->setEntity($entity); $form_state = (new FormState())->setFormObject($form_object)->disableRedirect(); // Building the form also submits. $form = $this->formBuilder()->buildForm($form_object, $form_state); // Return a response, depending on whether it's successfully submitted. if (!$form_state->isExecuted()) { // Return the form as a modal dialog. $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; $title = $this->t('Edit entity @entity', ['@entity' => $entity->label()]); $response = AjaxResponse::create()->addCommand(new OpenModalDialogCommand($title, $form, ['width' => 800])); return $response; } else { // Return command for closing the modal. return AjaxResponse::create()->addCommand(new CloseModalDialogCommand()); } }
/** * Responds to entity GET requests. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object. * * @return \Drupal\rest\ResourceResponse * The response containing the entity with its accessible fields. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException */ public function get(EntityInterface $entity) { if (!$entity->access('view')) { throw new AccessDeniedHttpException(); } $fields = $entity->getFields(); $display_id = $entity->getEntityTypeId() . '.' . $entity->bundle() . '.restx'; // Remove hidden fields (Display mode 'default'). $view_display = \Drupal::entityManager()->getStorage('entity_view_display')->load($display_id); if ($view_display) { $content = $view_display->get('content'); foreach ($fields as $field_name => $field) { if (!$field->access('view') || substr($field_name, 0, 6) === 'field_' && !isset($content[$field_name])) { unset($fields[$field_name]); } } } $output = array('data' => $fields); $response = new ResourceResponse($output, ResourceResponse::HTTP_OK); $response->addCacheableDependency($output); return $response; }
/** * {@inheritdoc} */ public function access(EntityInterface $entity, $operation, $langcode = LanguageInterface::LANGCODE_DEFAULT, AccountInterface $account = NULL) { $account = $this->prepareUser($account); if (($access = $this->getCache($entity->uuid(), $operation, $langcode, $account)) !== NULL) { // Cache hit, no work necessary. return $access; } // Invoke hook_entity_access() and hook_ENTITY_TYPE_access(). Hook results // take precedence over overridden implementations of // EntityAccessController::checkAccess(). Entities that have checks that // need to be done before the hook is invoked should do so by overriding // this method. // We grant access to the entity if both of these conditions are met: // - No modules say to deny access. // - At least one module says to grant access. $access = array_merge($this->moduleHandler()->invokeAll('entity_access', array($entity, $operation, $account, $langcode)), $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', array($entity, $operation, $account, $langcode))); if (($return = $this->processAccessHookResults($access)) === NULL) { // No module had an opinion about the access, so let's the access // controller check create access. $return = (bool) $this->checkAccess($entity, $operation, $langcode, $account); } return $this->setCache($return, $entity->uuid(), $operation, $langcode, $account); }
/** * {@inheritdoc} */ public function delete(EntityInterface $entity) { $this->database->delete('comment_entity_statistics')->condition('entity_id', $entity->id())->condition('entity_type', $entity->getEntityTypeId())->execute(); }
/** * Builds the renderable view of an entity. * * Entities postpone the composition of their renderable arrays to #pre_render * functions in order to maximize cache efficacy. This means that the full * renderable array for an entity is constructed in drupal_render(). Some * tests require the complete renderable array for an entity outside of the * drupal_render process in order to verify the presence of specific values. * This method isolates the steps in the render process that produce an * entity's renderable array. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to prepare a renderable array for. * @param string $view_mode * (optional) The view mode that should be used to build the entity. * @param null $langcode * (optional) For which language the entity should be prepared, defaults to * the current content language. * @param bool $reset * (optional) Whether to clear the cache for this entity. * @return array * * @see drupal_render() */ protected function drupalBuildEntityView(EntityInterface $entity, $view_mode = 'full', $langcode = NULL, $reset = FALSE) { $ensure_fully_built = function (&$elements) use(&$ensure_fully_built) { // If the default values for this element have not been loaded yet, populate // them. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) { $elements += \Drupal::service('element_info')->getInfo($elements['#type']); } // Make any final changes to the element before it is rendered. This means // that the $element or the children can be altered or corrected before the // element is rendered into the final text. if (isset($elements['#pre_render'])) { foreach ($elements['#pre_render'] as $callable) { $elements = call_user_func($callable, $elements); } } // And recurse. $children = Element::children($elements, TRUE); foreach ($children as $key) { $ensure_fully_built($elements[$key]); } }; $render_controller = $this->container->get('entity.manager')->getViewBuilder($entity->getEntityTypeId()); if ($reset) { $render_controller->resetCache(array($entity->id())); } $build = $render_controller->view($entity, $view_mode, $langcode); $ensure_fully_built($build); return $build; }
/** * Alter entity operations. * * @param array $operations * Operations array as returned by * \Drupal\Core\Entity\EntityListBuilderInterface::getOperations(). * @param \Drupal\Core\Entity\EntityInterface $entity * The entity on which the linked operations will be performed. */ function hook_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) { // Alter the title and weight. $operations['translate']['title'] = t('Translate @entity_type', array('@entity_type' => $entity->getEntityTypeId())); $operations['translate']['weight'] = 99; }