isNew example

foreach ($method_args as $method => $args) {
      $method_mock = $storage->expects($this->once())
        ->method($method);
      foreach ($args as $arg) {
        $method_mock->with($this->equalTo($arg));
      }
      call_user_func_array([$view_ui$method]$args);
    }

    $storage->expects($this->once())
      ->method('isNew');
    $view_ui->isNew();
  }

  /** * Tests the isLocked method. */
  public function testIsLocked() {
    $storage = $this->getMockBuilder('Drupal\views\Entity\View')
      ->setConstructorArgs([[], 'view'])
      ->getMock();
    $executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
      ->disableOriginalConstructor()
      
// Set the field value.     $entity->{$this->fieldName}->setValue($reference_field);

    // Load the target entities using EntityReferenceField::referencedEntities().     $entities = $entity->{$this->fieldName}->referencedEntities();

    // Test returned entities:     // - Deltas must be preserved.     // - Non-existent entities must not be retrieved in target entities result.     foreach ($target_entities as $delta => $target_entity) {
      if (!empty($target_entity)) {
        if (!$target_entity->isNew()) {
          // There must be an entity in the loaded set having the same id for           // the same delta.           $this->assertEquals($entities[$delta]->id()$target_entity->id());
        }
        else {
          // For entities that were not yet saved, there must an entity in the           // loaded set having the same label for the same delta.           $this->assertEquals($entities[$delta]->label()$target_entity->label());
        }
      }
      else {
        
public function view(EntityInterface $_entity$view_mode = 'full') {
    $page = $this->entityTypeManager
      ->getViewBuilder($_entity->getEntityTypeId())
      ->view($_entity$view_mode);

    $page['#pre_render'][] = [$this, 'buildTitle'];
    $page['#entity_type'] = $_entity->getEntityTypeId();
    $page['#' . $page['#entity_type']] = $_entity;

    // Add canonical and shortlink links if the entity has a canonical     // link template and is not new.     if ($_entity->hasLinkTemplate('canonical') && !$_entity->isNew()) {

      $url = $_entity->toUrl('canonical')->setAbsolute(TRUE);
      $page['#attached']['html_head_link'][] = [
        [
          'rel' => 'canonical',
          'href' => $url->toString(),
        ],
      ];

      // Set the non-aliased canonical path as a default shortlink.       $page['#attached']['html_head_link'][] = [
        [
$this->databaseDumpFiles = [
      __DIR__ . '/../../../fixtures/update/drupal-9.4.0.bare.standard.php.gz',
    ];
  }

  /** * Tests system_post_update_linkset_settings(). */
  public function testSystemPostUpdateLinksetSettings() {
    // Ensure config is not present.     $config = $this->config('system.feature_flags');
    $this->assertTrue($config->isNew());

    $this->runUpdates();

    // Confirm that config was created and the endpoint is disabled.     $updated_config = $this->config('system.feature_flags');
    $this->assertFalse($updated_config->isNew());
    $this->assertFalse($updated_config->get('linkset_endpoint'));
  }

}

  public function testIntegrationModuleReinstallation() {
    $default_config = 'config_integration_test.settings';
    $default_configuration_entity = 'config_test.dynamic.config_integration_test';

    // Install the config_test module we're integrating with.     \Drupal::service('module_installer')->install(['config_test']);

    // Verify the configuration does not exist prior to installation.     $config_static = $this->config($default_config);
    $this->assertTrue($config_static->isNew());
    $config_entity = $this->config($default_configuration_entity);
    $this->assertTrue($config_entity->isNew());

    // Install the integration module.     \Drupal::service('module_installer')->install(['config_integration_test']);
    $this->resetAll();

    // Verify that default module config exists.     \Drupal::configFactory()->reset($default_config);
    \Drupal::configFactory()->reset($default_configuration_entity);
    $config_static = $this->config($default_config);
    

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    if ($operation == 'delete' && $entity->isNew()) {
      return AccessResult::forbidden()->addCacheableDependency($entity);
    }
    if ($admin_permission = $this->entityType->getAdminPermission()) {
      return AccessResult::allowedIfHasPermission($account$admin_permission);
    }
    else {
      // No opinion.       return AccessResult::neutral();
    }
  }

  
    $form['#attributes']['class'][0] = 'block-' . Html::getClass($block->bundle()) . '-form';

    return $form;
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $block = $this->entity;

    $insert = $block->isNew();
    $block->save();
    $context = ['@type' => $block->bundle(), '%info' => $block->label()];
    $logger = $this->logger('block_content');
    $block_type = $this->getBundleEntity();
    $t_args = ['@type' => $block_type->label(), '%info' => $block->label()];

    if ($insert) {
      $logger->info('@type: added %info.', $context);
      $this->messenger()->addStatus($this->t('@type %info has been created.', $t_args));
    }
    else {
      

  public function onConfigSave(ConfigCrudEvent $event) {
    $saved_config = $event->getConfig();
    if ($saved_config->getName() == 'system.site' && $event->isChanged('default_langcode')) {
      $new_default_langcode = $saved_config->get('default_langcode');
      $default_language = $this->configFactory->get('language.entity.' . $new_default_langcode);
      // During an import the language might not exist yet.       if (!$default_language->isNew()) {
        $this->languageDefault->set(new Language($default_language->get()));
        $this->languageManager->reset();

        // Directly update language negotiation settings instead of calling         // language_negotiation_url_prefixes_update() to ensure that the code         // obeys the hook_update_N() restrictions.         $negotiation_config = $this->configFactory->getEditable('language.negotiation');
        $negotiation_changed = FALSE;
        $url_prefixes = $negotiation_config->get('url.prefixes');
        $old_default_langcode = $saved_config->getOriginal('default_langcode');
        if (empty($url_prefixes[$old_default_langcode])) {
          
/** * {@inheritdoc} */
  public function isDefaultRevision($new_value = NULL) {
    $return = $this->isDefaultRevision;
    if (isset($new_value)) {
      $this->isDefaultRevision = (bool) $new_value;
    }
    // New entities should always ensure at least one default revision exists,     // creating an entity without a default revision is an invalid state.     return $this->isNew() || $return;
  }

  /** * {@inheritdoc} */
  public function wasDefaultRevision() {
    /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
    $entity_type = $this->getEntityType();
    if (!$entity_type->isRevisionable()) {
      return TRUE;
    }

    
'id' => 'test_type',
      'label' => 'Test type',
      'source' => 'test',
    ]);

    /** @var \Drupal\field\Entity\FieldConfig $field */
    $field = $type->getSource()->createSourceField($type);
    /** @var \Drupal\field\Entity\FieldStorageConfig $field_storage */
    $field_storage = $field->getFieldStorageDefinition();

    // Test field storage.     $this->assertTrue($field_storage->isNew(), 'Field storage is saved automatically.');
    $this->assertFalse($field_storage->isLocked(), 'Field storage is not locked.');
    $this->assertSame('string', $field_storage->getType(), 'Field is not of correct type.');
    $this->assertSame('field_media_test_1', $field_storage->getName(), 'Incorrect field name is used.');
    $this->assertSame('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');

    // Test field.     $this->assertTrue($field->isNew(), 'Field is saved automatically.');
    $this->assertSame('field_media_test_1', $field->getName(), 'Incorrect field name is used.');
    $this->assertSame('string', $field->getType(), 'Field is of incorrect type.');
    $this->assertTrue($field->isRequired(), 'Field is not required.');
    $this->assertEquals('Test source', $field->label(), 'Incorrect label is used.');
    
use Symfony\Component\Validator\ConstraintValidator;

/** * Constraint validator for changing the menu settings in pending revisions. */
class MenuSettingsConstraintValidator extends ConstraintValidator {

  /** * {@inheritdoc} */
  public function validate($entity, Constraint $constraint) {
    if (isset($entity) && !$entity->isNew() && !$entity->isDefaultRevision()) {
      $defaults = menu_ui_get_menu_link_defaults($entity);

      // If the menu UI entity builder is not present and the menu property has       // not been set, do not attempt to validate the menu settings since they       // are not being modified.       if (!$values = $entity->menu) {
        return;
      }

      if (trim($values['title']) && !empty($values['menu_parent'])) {
        [$menu_name$parent] = explode(':', $values['menu_parent'], 2);
        

    $id = $value->target_id;
    // '0' or NULL are considered valid empty references.     if (empty($id)) {
      return;
    }
    /** @var \Drupal\Core\Entity\FieldableEntityInterface $referenced_entity */
    $referenced_entity = $value->entity;
    if ($referenced_entity) {
      $entity = $value->getEntity();
      $check_permission = TRUE;
      if (!$entity->isNew()) {
        $existing_entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
        $referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities();
        // Check permission if we are not already referencing the entity.         foreach ($referenced_entities as $ref) {
          if (isset($referenced_entities[$ref->id()])) {
            $check_permission = FALSE;
            break;
          }
        }
      }
      // We check that the current user had access to view any newly added
'#title' => $this->t('Menu name'),
      '#default_value' => $menu->id(),
      '#maxlength' => MenuStorage::MAX_ID_LENGTH,
      '#description' => $this->t('A unique name to construct the URL for the menu. It must only contain lowercase letters, numbers and hyphens.'),
      '#machine_name' => [
        'exists' => [$this, 'menuNameExists'],
        'source' => ['label'],
        'replace_pattern' => '[^a-z0-9-]+',
        'replace' => '-',
      ],
      // A menu's machine name cannot be changed.       '#disabled' => !$menu->isNew() || $menu->isLocked(),
    ];
    $form['description'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Administrative summary'),
      '#maxlength' => 512,
      '#default_value' => $menu->getDescription(),
    ];

    $form['langcode'] = [
      '#type' => 'language_select',
      '#title' => $this->t('Menu language'),
      

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('book.manager')
    );
  }

  /** * {@inheritdoc} */
  public function validate($entity, Constraint $constraint) {
    if (isset($entity) && !$entity->isNew() && !$entity->isDefaultRevision()) {
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original */
      $original = $this->bookManager->loadBookLink($entity->id(), FALSE) ?: [
        'bid' => 0,
        'weight' => 0,
      ];
      if (empty($original['pid'])) {
        $original['pid'] = -1;
      }

      if ($entity->book['bid'] != $original['bid']) {
        $this->context->buildViolation($constraint->message)
          

  public function form(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\user\UserInterface $account */
    $account = $this->entity;
    $user = $this->currentUser();
    $config = \Drupal::config('user.settings');
    $form['#cache']['tags'] = $config->getCacheTags();

    $language_interface = \Drupal::languageManager()->getCurrentLanguage();

    // Check for new account.     $register = $account->isNew();

    // For a new account, there are 2 sub-cases:     // $self_register: A user creates their own, new, account     // (path '/user/register')     // $admin_create: An administrator creates a new account for another user     // (path '/admin/people/create')     // If the current user is logged in and has permission to create users     // then it must be the second case.     $admin_create = $register && $account->access('create');
    $self_register = $register && !$admin_create;

    
Home | Imprint | This part of the site doesn't use cookies.