5

My site allows users to upload images and add title and description to it. So I make a new class which extends ContentEntityBase. In its baseFieldDefinitions() method, I put an image field beside title and description fields:

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setRequired(TRUE);

I expect to see a file/image upload control in the add/edit form, but I don't see it. I see only the title and description textboxes.

I tried to find "create('image')" in all Drupal source code but didn't see any examples. So I don't know if creating an image field like this is the proper way or not?

5

See ...

$entity->getFieldDefinition('image')

'file_extensions' => string(16) "png gif jpg jpeg"
'file_directory' => string(31) "[date:custom:Y]-[date:custom:m]"

And edit

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setDescription(t('Image field'))
  ->setSettings([
    'file_directory' => 'IMAGE_FOLDER',
    'alt_field_required' => FALSE,
    'file_extensions' => 'png jpg jpeg',
  ])
 ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'default',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'label' => 'hidden',
    'type' => 'image_image',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);
2

Thanks Matt for your prompt answer. I don't want to build the entity form and the image widget manually. Found out that I need to call setDisplayOptions() and setDisplayOptions() in baseFieldDefinitions(), now it works:

$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setRequired(TRUE)
  ->setDisplayOptions('view', [
    'label'   => 'above',
    'type'    => 'image',
    'weight'  => 0,
  ])
  ->setDisplayOptions('form', [
    'type'    => 'image_image',
    'weight'  => 0,
  ]);
0

To create an image field you would use the form api like so:

$fields['image'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on the node page.'),
'#default_value' => $this->get('image'),
'#upload_location' => 'public://images/',
'#required' => TRUE,
);

You can learn more here https://api.drupal.org/api/drupal/elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.