Pascal Pivaty
Pascal Pivaty

Reputation: 97

How to add the alt and title fields in an image field of a custom entity in drupal 8

I created a custom entity with an image field. But I can not display the alt and title fields.

Here is my code:

$fields['main_img'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Main image of the hardware'))
  ->setSettings([
    'file_directory' => 'hardware',
    'file_extensions' => 'png jpg jpeg',
  ])
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'image',
    'weight' => -30,
  ))
  ->setDisplayOptions('form', array(
    'label' => 'above',
    'type' => 'image_image',
    'weight' => -30,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Could you tell me how to display the alt and title fields of my image and maybe someone knows where the documentation is for doing that because I can not find it?

Thank you all

Upvotes: 0

Views: 1127

Answers (2)

Pascal Pivaty
Pascal Pivaty

Reputation: 97

Thank Dmytro.

I feel a little stupid but it's life.

It was enough to add 'alt_field_required' => FALSE and 'title_field' => TRUE in setSettings.

But as title and alt is displayed that when we download an image I thought it did not work.

A day of lost!

Upvotes: 0

Dmytro Sukhovoy
Dmytro Sukhovoy

Reputation: 992

I loaded one of my node field definitions with $node->getFieldDefinitions():

enter image description here

I believe you can try something like this:

  ->setDisplayOptions('form', array(
    'label' => 'above',
    'type' => 'image_image',
    'weight' => -30,
    'settings' => [
      'alt_field' => TRUE,
      'alt_field_required' => TRUE, //optional
      'title_field' => TRUE,
      'title_field_required' => TRUE, //optional
    ],
  ))

Upvotes: 1

Related Questions