How to get the image url to display it in my twig without and with node

213 Views Asked by At

I create a custom form then I retrieve the fields in a table then I return the table in a branch then I extract the contents of the branch in a variable which I put in a node.

and it does not show me the source of the image so I want to obtain the url saved in the database.

``In my form`
    $form['image1'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Image 1'),
      '#upload_location' => 'public://user/image/', 
      '#required' => FALSE,
      '#upload_validators' => [
        'file_validate_extensions' => ['jpg jpeg png gif'], 
        'file_validate_size' => [5 * 1024 * 1024],
      ],
    ];


`then i put information in $array`
    $form_array = array(
      'img1' => $form_state->getValue('image1'),
    );

`I put my array in html`
    $build = [
      '#type' => 'html',
      '#theme' => 'theme_project',
      '#form_array' => $form_array,
    ];

`i put my html in variable`
    $html = \Drupal::service('renderer')->renderPlain($build);

`i put in node then create it`
    $node = Node::create([
      'type' => 'name_content', 
      'title' => $form_state->getValue('form_titre'),
      'field_image1' => $form_state->getValue('image1'),
    ]);
    $node->save();

`twig file`
<img src={{ form_array.img1 }} style="width:100%">  

i try this but i no work

$file_url_generator=\Drupal::service('file_url_generator');
$image1 = $file_url_generator->generateAbsoluteString($form_state->getValue('field_image1'));
1

There are 1 best solutions below

0
Karmraj Zala On

If you would like to get the URL from an image that is trapped inside of a media entity however, you can either extract it using the aforementioned preprocess function like so:

function mytheme_preprocess_node(&$variables) {
 
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];
 
  $image_field = $node->get('field_background_image');
  if (!$image_field->isEmpty()) {
    $uri = $image_field->entity->get('field_media_image')->entity->uri->value;
    $variables['background_image_url'] = file_create_url($uri);
  }
}

In the node template, you can display it using

{{ background_image_url }}