1

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.

1 Answer 1

1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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