View source
<?php
namespace Drupal\Tests\color_field\Kernel;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
class ColorFieldTypeTest extends FieldKernelTestBase {
public static $modules = [
'color_field',
];
protected function setUp() {
parent::setUp();
FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'color_field_type',
])
->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'bundle' => 'entity_test',
])
->save();
FieldStorageConfig::create([
'field_name' => 'field_hex',
'entity_type' => 'entity_test',
'type' => 'color_field_type',
'settings' => [
'format' => 'hexhex',
],
])
->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_hex',
'bundle' => 'entity_test',
'settings' => [
'opacity' => FALSE,
],
])
->save();
}
public function testTestItem() {
$entity = EntityTest::create();
$color = '#5BCEFA';
$lcolor = '5bcefa';
$opacity = 0.5;
$entity->field_test->color = $color;
$entity->field_test->opacity = $opacity;
$entity->field_hex->opacity = 5;
$entity->field_hex->color = $color;
$entity->name->value = $this
->randomMachineName();
$entity
->save();
$id = $entity
->id();
$entity = EntityTest::load($id);
$this
->assertInstanceOf(FieldItemListInterface::class, $entity->field_test, 'Field implements interface.');
$this
->assertInstanceOf(FieldItemInterface::class, $entity->field_test[0], 'Field item implements interface.');
$this
->assertEquals($color, $entity->field_test->color);
$this
->assertEquals($opacity, $entity->field_test->opacity);
$this
->assertEquals($color, $entity->field_test[0]->color);
$this
->assertEquals($lcolor, $entity->field_hex->color);
$this
->assertEquals('', $entity->field_hex->opacity);
$new_value = '#FFFFFF';
$entity->field_test->color = $new_value;
$this
->assertEquals($new_value, $entity->field_test->color);
$entity
->save();
$entity = EntityTest::load($id);
$this
->assertEquals($new_value, $entity->field_test->color);
$new_value = 'F5A9B8';
$entity->field_test->color = $new_value;
$this
->assertEquals($new_value, $entity->field_test->color);
$entity = EntityTest::create();
$entity->field_test
->generateSampleItems();
$this
->entityValidateAndSave($entity);
}
}