Score:0

how to add the "alt" attribute to a "managed_file" type image field

kn flag

I have a custom form in drupal 9 where I am creating a managed_file type field to upload an image:

$form['footer']['logo'] = array(
  '#title' => 'Logo',
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_extensions' => ['png jpg jpeg'],
  ],
  '#description' => t('The valid formats are png, jpg, jpeg'),
  '#default_value' => $data['footer']['logo'] ?? '',
); 

And I need to add the "alt" attribute to the field and the user can add this information when uploading the image, however when I make the attempt to add it normally it doesn't work:

$form['footer']['logo'] = array(
  '#title' => 'Logo',
  '#type' => 'managed_file',
  '#alt' => 'Example'
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_extensions' => ['png jpg jpeg'],
  ],
  '#description' => t('The valid formats are png, jpg, jpeg'),
  '#default_value' => $data['footer']['logo'] ?? '',
); 

can anyone give me an idea how can I fix it?

cn flag
Managed file elements don’t have an alt (that’s an image field, different thing altogether). Add a separate text field for alt, and save/load its data alongside the file ID when you need to
Juan Carlos Osorio avatar
kn flag
Okay and maybe it would be easier to use a field of type "image" or something like that instead of using "managed_file"?
cn flag
Field widgets only work with entities, for manual forms you need to build it yourself
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.