Score:1

Render responsive image inside form fields programmatically

cn flag

I am trying to figure out how to render a responsive image programmatically inside a form field. I am doing maintenance in a code on my current job, and sometimes there are form fields using the '#markup' property. Now I need to change all images to be responsive.

The code example:

$form['markup1'] = [
     '#markup' => '<div class="rating_reminder"><img src="'.file_create_url($order->campaign_id->entity->product_id->entity->image->entity->getFileUri()).'"><div>'
];

It is very hard to find anything explaining how to use responsive images that are in code in PHP.

I'll be very grateful if you can help me.

Score:1
cn flag

Build render elements instead of HTML markup:

$form['markup1'] = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['rating_reminder'],
  ],
  'image' => [
    '#type' => 'responsive_image',
    '#responsive_image_style_id' => 'big',
    '#uri' => $order->campaign_id->entity->product_id->entity->image->entity->getFileUri(),
    '#attributes' => [
      'alt' => $order->campaign_id->entity->product_id->entity->image->alt,
    ],
  ],
];

Available render elements: https://api.drupal.org/api/drupal/elements

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.