Skip to content

Applying Annotations ​

Annotations can be applied programmatically when building the schema, or via PHP attributes that the AttributeReader picks up.

Programmatic annotations ​

Pass annotations to any Edm constructor via the annotations parameter:

php
use LaravelUi5\OData\Edm\Annotation\Annotation;
use LaravelUi5\OData\Edm\Annotation\ConstantAnnotationValue;
use LaravelUi5\OData\Edm\Property\Property;
use LaravelUi5\OData\Edm\Type\EntityType;
use LaravelUi5\OData\Edm\Type\PrimitiveType;
use LaravelUi5\OData\Edm\EdmPrimitiveType;

// Annotate a property
$nameProp = new Property(
    name: 'name',
    type: new PrimitiveType(EdmPrimitiveType::String),
    annotations: [
        new Annotation(
            term: 'Org.OData.Core.V1.Description',
            value: new ConstantAnnotationValue('String', 'The product name'),
        ),
    ],
);

// Annotate an entity type
$productType = new EntityType(
    namespace: 'App.Products',
    name: 'Product',
    key: [$idProp],
    declaredProperties: [$idProp, $nameProp],
    annotations: [
        new Annotation(
            term: 'Org.OData.Core.V1.Description',
            value: new ConstantAnnotationValue('String', 'A product in the catalog'),
        ),
    ],
);

Annotation value types ​

Constant value — one expression and its literal. The first argument is the CSDL expression name, and it is written into $metadata as given: String, Bool, Int, Decimal, Date, EnumMember, or a path expression such as Path or PropertyPath. The literal is always a string.

php
new ConstantAnnotationValue('String', 'Hello World')   // String="Hello World"
new ConstantAnnotationValue('Bool', 'true')            // Bool="true"
new ConstantAnnotationValue('Path', 'name')            // Path="name"

Record value — an optional record type, followed by its property values:

php
use LaravelUi5\OData\Edm\Annotation\PropertyValue;
use LaravelUi5\OData\Edm\Annotation\RecordAnnotationValue;

new RecordAnnotationValue(
    'com.sap.vocabularies.UI.v1.HeaderInfoType',
    new PropertyValue('TypeName', new ConstantAnnotationValue('String', 'Product')),
    new PropertyValue('Title', new RecordAnnotationValue(
        'com.sap.vocabularies.UI.v1.DataField',
        new PropertyValue('Value', new ConstantAnnotationValue('Path', 'name')),
    )),
)

Collection value — an ordered list, passed as separate arguments:

php
use LaravelUi5\OData\Edm\Annotation\CollectionAnnotationValue;

new CollectionAnnotationValue(
    new RecordAnnotationValue(
        'com.sap.vocabularies.UI.v1.DataField',
        new PropertyValue('Value', new ConstantAnnotationValue('Path', 'name')),
        new PropertyValue('Label', new ConstantAnnotationValue('String', 'Product Name')),
    ),
    new RecordAnnotationValue(
        'com.sap.vocabularies.UI.v1.DataField',
        new PropertyValue('Value', new ConstantAnnotationValue('Path', 'price')),
        new PropertyValue('Label', new ConstantAnnotationValue('String', 'Price')),
    ),
)

Attribute-based annotations ​

Vocabulary term classes can be used as PHP attributes. When models are registered via discoverModel(), ModelDiscovery reads them from the model's class and attaches them to the EntityType and its properties. They then appear in the $metadata CSDL XML. Every annotation sits on the class; none needs a PHP property on the model.

Class-level annotations ​

Class-level annotations (applied to the model class) work directly:

php
use LaravelUi5\OData\Edm\Annotation\Path;
use LaravelUi5\OData\Vocabularies\Core\V1\Description;
use LaravelUi5\OData\Vocabularies\Ui\V1\DataField;
use LaravelUi5\OData\Vocabularies\Ui\V1\LineItem;
use LaravelUi5\OData\Vocabularies\Ui\V1\SelectionFields;

#[Description('A product in the catalog')]
#[SelectionFields(['name', 'category'])]
#[LineItem([
    new DataField(value: new Path('name'), label: 'Product'),
    new DataField(value: new Path('category')),
    new DataField(value: new Path('price')),
])]
class Product extends Model
{
    // ...
}

These are placed on the <EntityType> element in $metadata.

Records and collections of records since 4.0 ​

A UI.LineItem is a collection of records, one per column or button. Each record is an object of its vocabulary type: DataField for a column, DataFieldForAction for a button, DataFieldWithUrl for a link. The term takes a list of them and writes each as <Record Type="…">, with only the fields you set:

php
use LaravelUi5\OData\Vocabularies\Ui\V1\CriticalityType;
use LaravelUi5\OData\Vocabularies\Ui\V1\DataFieldForAction;

#[LineItem([
    new DataField(value: new Path('status'), criticality: CriticalityType::Positive),
    new DataFieldForAction(action: 'App.Products.approve', label: 'Approve'),
])]

Three rules hold for every record class and every term with fields:

  • Pass the fields by name. Each field, its own or inherited from the base type, is a named, optional parameter, in the order the vocabulary declares them. A positional call breaks when a vocabulary grows.
  • A required field fails loud when the schema is built, not at the call. Leaving out DataFieldForAction's action throws a LogicException that names the field. A field with a default, such as Inline, is not required.
  • A plain value where the vocabulary wants a record fails loud too. #[LineItem(['name'])] throws instead of writing columns UI5 cannot read.
changed in 4.0`#[LineItem(['name', 'price'])]` used to be accepted and wrote a collection of strings, in which UI5 finds no columns. Write a `DataField` per column.

Annotating a column since 4.0 ​

A vocabulary attribute written directly on the class annotates the entity type. To annotate one column, name it with #[ODataAnnotate] and pass the terms as objects:

php
use LaravelUi5\OData\Service\Discovery\Attributes\ODataAnnotate;
use LaravelUi5\OData\Vocabularies\Common\V1\Label;
use LaravelUi5\OData\Vocabularies\Core\V1\Description;
use LaravelUi5\OData\Vocabularies\Ui\V1\Hidden;
use LaravelUi5\OData\Vocabularies\Ui\V1\SelectionFields;

#[Description('A product in the catalog')]
#[SelectionFields(['name', 'category'])]
#[ODataAnnotate('name', new Label('Product Name'), new Description('The display name of the product'))]
#[ODataAnnotate('category', new Label('Category'))]
#[ODataAnnotate('internal_flags', new Hidden())]
class Product extends Model
{
}

The attribute repeats, once per column or as often as you like for the same one, and takes any number of terms. A qualifier goes on the term: new Label('Short', qualifier: 'Tile'). The named property must be one the entity type declares — a column the model serializes, or a computed property — otherwise discovery fails loud while the schema is built.

changed in 4.0Column annotations used to sit on a PHP 8.4 hooked property that delegated to Eloquent's attribute bag. That idiom is gone with the property attributes; move each term into an `#[ODataAnnotate]` on the class and delete the hooked property.

Annotating columns across models since 4.0 ​

A package that knows something about columns of many models binds a ColumnAnnotationResolverInterface. Discovery asks it once per declared column, with the model class and the column name:

php
use LaravelUi5\OData\Service\Contracts\ColumnAnnotationResolverInterface;
use LaravelUi5\OData\Vocabularies\Core\V1\IsLanguageDependent;

final class TranslatedColumns implements ColumnAnnotationResolverInterface
{
    public function annotations(string $modelClass, string $column): array
    {
        return in_array($column, Translations::fieldsOf($modelClass), true)
            ? [new IsLanguageDependent()]
            : [];
    }
}

// in a service provider
$this->app->bind(ColumnAnnotationResolverInterface::class, TranslatedColumns::class);

The default answers nothing. On the same term and qualifier the model's own #[ODataAnnotate] wins, because it is local to one model. Like the facet resolver, there is one binding, not a chain, and it runs when the schema is built: a service cached with odata:cache keeps what it saw then.

How discovery wires it ​

No extra registration needed. When you call discoverModel(), ModelDiscovery automatically:

  1. Reads class-level vocabulary attributes via AttributeReader::readClass()
  2. Collects each column's terms from the bound ColumnAnnotationResolverInterface and the model's #[ODataAnnotate] attributes, the attribute winning on the same term and qualifier
  3. Passes the annotations to EntityType and Property constructors
  4. The CsdlSerializer serializes them into the $metadata XML
php
protected function configure(EdmBuilderInterface $builder): EdmBuilderInterface
{
    $this->discoverModel(Product::class);

    return $builder
        ->namespace('App.Products')
        ->useVocabulary(Vocabulary::Core)
        ->useVocabulary(Vocabulary::UI)
        ->useVocabulary(Vocabulary::Common);
}

Reading attributes manually ​

For advanced use cases outside of model discovery, use AttributeReader directly:

php
use LaravelUi5\OData\Service\Discovery\AttributeReader;

$reader = new AttributeReader();

// Class-level annotations
$annotations = $reader->readClass(new ReflectionClass(Product::class));

// Parameter-level annotations (for function parameters)
$annotations = $reader->readParameter($reflectionParameter);

The AttributeReader only picks up attributes that implement TypedAnnotationInterface. Other PHP attributes (routing, validation, ORM) are silently ignored. changed in 4.0readProperty() is removed with the hooked-property idiom.

Path values ​

Some terms do not carry a fixed value. Their value is read per entity from another property. The currency of an amount is the typical case: one row is in EUR, the next in JPY. A Path expresses this:

php
use LaravelUi5\OData\Edm\Annotation\Path;
use LaravelUi5\OData\Vocabularies\Measures\V1\ISOCurrency;

#[ODataAnnotate('amount', new ISOCurrency(new Path('currency')))]
class Order extends Model {}

The path may point at a column or at a computed property — the tenant's base currency, say, when the row stores none.

This is written as <Annotation Term="Org.OData.Measures.V1.ISOCurrency" Path="currency"/>. In programmatic annotations the equivalent is new ConstantAnnotationValue('Path', 'currency'), or (new Path('currency'))->toAnnotationValue().

Every generated term and every record field accepts a Path in place of its value since 4.0, an enumeration included: new FieldControl(new Path('fieldControl')) reads the field control per row, the common case in UI5.

A term or field whose type is itself a model path (Edm.PropertyPath, Edm.NavigationPropertyPath and their kin) takes two forms. A string is written as the path itself, PropertyPath="iso", which is what CSDL defines for these types. A Path is written as a value path, Path="iso". CSDL does not allow that form for path types (§14.4.1), but some SAP clients read exactly that: CodeList.StandardCode is one. Use the string unless a client needs the value path.

Annotating the entity container ​

Service-wide terms target the entity container. Call annotateContainer() in configure(). It takes generated terms or plain Annotations:

php
use LaravelUi5\OData\Edm\Vocabularies\Vocabulary;
use LaravelUi5\OData\Vocabularies\CodeList\V1\CurrencyCodes;

protected function configure(EdmBuilderInterface $builder): EdmBuilderInterface
{
    $this->annotateContainer(
        new CurrencyCodes(url: '../[email protected]/$metadata', collectionPath: 'Currencies'),
    );

    return $builder
        ->namespace($this->namespace())
        ->useVocabulary(Vocabulary::CodeList);
}

The annotations are written inline in <EntityContainer>, and odata:cache keeps them.

Code lists for currencies and units ​

UI5's sap.ui.model.odata.type.Currency and Unit format each row with the decimals of its currency or unit. They look those decimals up in a code list that the service announces. Three pieces make it work. The decimals of a currency then come from the code list, not from a fixed Scale:

1. The business property points at its code. Use Measures.ISOCurrency for an amount and Measures.Unit for a quantity, each as a path to the property that holds the code.

2. The container points at the code list. CodeList.CurrencyCodes and CodeList.UnitsOfMeasure name the service (url) and the entity set (collectionPath). UI5 resolves a relative url against the service's own URL. The code list may live in the same service or in a separate one that every app shares. UI5 loads each list once per page, even when several models point at it.

3. The code-list set annotates its key. The set has exactly one key, the code. On that key go Common.UnitSpecificScale (the decimals), Common.Text (the display name) and, optionally, CodeList.StandardCode, each as a path:

php
use LaravelUi5\OData\Edm\Annotation\Path;
use LaravelUi5\OData\Service\Discovery\Attributes\ODataAnnotate;
use LaravelUi5\OData\Service\Discovery\Attributes\ODataEntity;
use LaravelUi5\OData\Vocabularies\CodeList\V1\StandardCode;
use LaravelUi5\OData\Vocabularies\Common\V1\Text;
use LaravelUi5\OData\Vocabularies\Common\V1\UnitSpecificScale;

#[ODataEntity(name: 'Currency', entitySet: 'Currencies')]
#[ODataAnnotate(
    'code',
    new UnitSpecificScale(new Path('decimals')),
    new Text(new Path('name')),
    new StandardCode(new Path('iso')),
)]
class Currency extends Model
{
    protected $primaryKey = 'code';
    protected $keyType = 'string';
    public $incrementing = false;
}

Things to know:

  • UnitSpecificScale must never be null. UI5 ignores such an entry, treats the code as unknown, and renders the amount empty.
  • StandardCode takes a Path, not a string. OpenUI5 reads it as a value path (…StandardCode/$Path). The string form, PropertyPath="iso", is the one CSDL defines for the term's type, and UI5 finds no standard code in it.
  • The set is delivered unpaged. UI5 requests it with $select and without $top or Prefer, and loads only the first page it gets — every later code then renders empty. odata.pagination.default is 200 out of the box, so mark a code-list set that is a custom entity set with UnpagedEntitySetInterface since 5.1: the server then never pages it, whatever the configuration and the client's Prefer say. See Pagination.
  • The text follows Accept-Language. UI5 sends the UI language in this header. It sends no sap-language parameter unless the app puts one into its service URL.
  • Input is not checked against the code's decimals by default. Currency and Unit default to preserveDecimals: true, so too many decimals are accepted. To reject them, bind with formatOptions: {preserveDecimals: false}. A fixed Scale on a plain Edm.Decimal is enforced without that (see Type facets).

Vocabulary references ​

When annotations use terms from external vocabularies (Core, UI, Common, etc.), the $metadata document must include the corresponding <edmx:Reference> elements so that clients can resolve the term definitions.

For any of the 12 built-in vocabularies, use useVocabulary() with the Vocabulary enum:

php
use LaravelUi5\OData\Edm\Vocabularies\Vocabulary;

protected function configure(EdmBuilderInterface $builder): EdmBuilderInterface
{
    $builder
        ->useVocabulary(Vocabulary::Core)
        ->useVocabulary(Vocabulary::UI);

    // ... entity types, sets, etc.
    return $builder->namespace($this->namespace());
}

Available enum cases: Core, Validation, Measures, Aggregation, Authorization, Capabilities, Common, UI, Analytics, Communication, CodeList since 4.0, PersonalData — one for each vocabulary whose classes ship.

For vocabularies outside the built-in set, use addReference() directly:

php
use LaravelUi5\OData\Edm\IncludedSchema;
use LaravelUi5\OData\Edm\Reference;

$builder->addReference(new Reference(
    uri: 'https://example.com/vocabularies/Custom.xml',
    includes: [new IncludedSchema(namespace: 'com.example.Custom.v1', alias: 'Custom')],
));

Each vocabulary whose terms you use needs its own reference. Without it the annotations will still appear in the XML, but clients may not be able to interpret them.

Where annotations appear ​

Annotations are serialized into the $metadata CSDL XML document:

xml
<EntityType Name="Product">
  <Annotation Term="Org.OData.Core.V1.Description" String="A product in the catalog"/>
  <Property Name="name" Type="Edm.String">
    <Annotation Term="com.sap.vocabularies.Common.v1.Label" String="Product Name"/>
  </Property>
</EntityType>

UI5 clients can read these annotations through the OData V4 metadata model for table columns, form fields, filter fields and value helps. SAP Fiori Elements (SAPUI5) configures them automatically.