public function LinkItemTest::testLinkItem

Tests using entity fields of the link field type.

File

drupal/core/modules/link/lib/Drupal/link/Tests/LinkItemTest.php, line 54
Contains \Drupal\link\Tests\LinkItemTest.

Class

LinkItemTest
Tests the new entity API for the link field type.

Namespace

Drupal\link\Tests

Code

public function testLinkItem() {

  // Create entity.
  $entity = entity_create('entity_test', array());
  $url = 'http://www.drupal.org';
  $title = $this
    ->randomName();
  $class = $this
    ->randomName();
  $entity->field_test->url = $url;
  $entity->field_test->title = $title;
  $entity->field_test
    ->get('attributes')
    ->set('class', $class);
  $entity->name->value = $this
    ->randomName();
  $entity
    ->save();

  // Verify that the field value is changed.
  $id = $entity
    ->id();
  $entity = entity_load('entity_test', $id);
  $this
    ->assertTrue($entity->field_test instanceof FieldInterface, 'Field implements interface.');
  $this
    ->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
  $this
    ->assertEqual($entity->field_test->url, $url);
  $this
    ->assertEqual($entity->field_test[0]->url, $url);
  $this
    ->assertEqual($entity->field_test->title, $title);
  $this
    ->assertEqual($entity->field_test[0]->title, $title);
  $this
    ->assertEqual($entity->field_test->attributes['class'], $class);

  // Verify changing the field value.
  $new_url = 'http://drupal.org';
  $new_title = $this
    ->randomName();
  $new_class = $this
    ->randomName();
  $entity->field_test->url = $new_url;
  $entity->field_test->title = $new_title;
  $entity->field_test
    ->get('attributes')
    ->set('class', $new_class);
  $this
    ->assertEqual($entity->field_test->url, $new_url);
  $this
    ->assertEqual($entity->field_test->title, $new_title);
  $this
    ->assertEqual($entity->field_test->attributes['class'], $new_class);

  // Read changed entity and assert changed values.
  $entity
    ->save();
  $entity = entity_load('entity_test', $id);
  $this
    ->assertEqual($entity->field_test->url, $new_url);
  $this
    ->assertEqual($entity->field_test->title, $new_title);
  $this
    ->assertEqual($entity->field_test->attributes['class'], $new_class);
}