Custom Text Line Field Type - adamwojs/formatted-textline GitHub Wiki

adamwojs/ibexa-formatted-textline provides an abstract implementation for the field types which value is represented as string e.g postal code, phone number, e-mail, isbn

Example

The following example shows how to build the Postal Code field type. The accepted format is DD-DDD where the D is any digit e.g. 31-916 (it's format used in Poland).

1. Create Field Type Definition

<?php

declare(strict_types=1);

namespace App\FieldType\PostalCode;

use AdamWojs\IbexaFormattedTextLineBundle\FieldType\FormattedTextLine\Type as FormattedTextLineType;

final class Type extends FormattedTextLineType
{
    public function getFieldTypeIdentifier(): string
    {
        return 'postalcode';
    }
}

2. Provide AdamWojs\IbexaFormattedTextLineBundle\FieldType\FormattedTextLine\Format implementation

<?php

declare(strict_types=1);

namespace App\FieldType\PostalCode;

use AdamWojs\IbexaFormattedTextLineBundle\FieldType\FormattedTextLine\Format;
use eZ\Publish\API\Repository\Values\ContentType\FieldDefinition;

final class Format implements Format
{
    private const PATTERN = '/^[0-9]{2}-[0-9]{3}$/';

    public function validate(FieldDefinition $fieldDefinition, string $text): bool
    {
        // Validate value against pattern here !
        return preg_match(self::PATTERN, $text) !== 0;
    }

    public function getMask(FieldDefinition $fieldDefinition): ?string
    {
        return '00-000';
    }

    public function getExamples(FieldDefinition $fieldDefinition): array
    {
        return ['40-079', '31-123'];
    }
}

3. Configure services

Add the following services definitions:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    app.field_type.postalcode:
        class: App\FieldType\PostalCode\Type
        arguments:
            $format: '@app.field_type.postalcode.format'
        tags:
            - { name: ezplatform.field_type, alias: postalcode }

    app.field_type.postalcode.format:
        class: App\FieldType\PostalCode\Format

    app.field_type.postalcode.converter:
        class: AdamWojs\IbexaFormattedTextLineBundle\Persistence\Legacy\Converter\TextLineConverter
        tags:
            - { name: ezplatform.field_type.legacy_storage.converter, alias: postalcode }

    app.field_type.postalcode.indexable:
        class: AdamWojs\IbexaFormattedTextLineBundle\FieldType\FormattedTextLine\SearchField
        tags:
            - { name: ezplatform.field_type.indexable, alias: postalcode }

    app.field_type.postalcode.form_mapper.value:
        class: AdamWojs\IbexaFormattedTextLineBundle\Form\Mapper\FormattedTextLine\FieldValueFormMapper
        arguments:
            $format: '@app.field_type.postalcode.format'
        tags:
            - { name: ezplatform.field_type.form_mapper.value, fieldType: postalcode }