Render form widget inside a custom form

I’m trying to use the Image Widget Crop inside a form API. I followed the example module but there’s no explanation how to do it after a file is uploaded.

My form is set like the code below. It works with page reload but not when the file is uploaded, also the widget it’s not attached to field image, if I remove the image the widget remains in the form with the image loaded previously.

<?php  $fid = isset($produto) ? $produto->field_produto_img->getValue()[0]['target_id'] : NULL; $upload_location = DrupalfieldEntityFieldConfig::loadByName('node', 'produto', 'field_produto_img'); $form['image'] = [   '#type' => 'managed_file',   '#title' => t('Selecione a imagem do produto'),   '#description' => t('Extensões permitidas: png jpg jpeg'),   '#upload_location' => 'public://' . $this->token->replace($upload_location->getSetting('file_directory')),   '#theme' => 'image_widget',   '#preview_image_style' => 'medium',   '#upload_validators' => [     'file_validate_extensions' => ['png jpg jpeg'],     'file_validate_size' => [512000],   ],   '#default_value' => !empty($fid) ? [$fid] : NULL, ];  if ($fid) {   $form['image_crop'] = [     '#type' => 'image_crop',     '#title' => t('Cortar imagem'),     '#file' => DrupalfileEntityFile::load($fid),     '#crop_type_list' => ['crop_type_produto'],     '#crop_preview_image_style' => 'crop_thumbnail',     '#show_default_crop' => TRUE,     '#show_crop_area' => FALSE,     '#warn_mupltiple_usages' => TRUE,   ]; } ?> 

I tried to follow the instructions of the official repo https://github.com/drupal-media/image_widget_crop#configuration, but I had no success.

I’m able to configure the theme after the file is uploaded. I tried to add the custom element image_crop but it didn’t work.

<?php function my_theme_preprocess_image_widget(&$variables) {   $element = $variables['element'];    $variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));    if (!empty($element['fids']['#value'])) {     $file = reset($element['#files']);     $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';     $file_variables = array(       'style_name' => $element['#preview_image_style'],       'uri' => $file->getFileUri(),     );      // Determine image dimensions.     if (isset($element['#value']['width']) && isset($element['#value']['height'])) {       $file_variables['width'] = $element['#value']['width'];       $file_variables['height'] = $element['#value']['height'];     } else {       $image = Drupal::service('image.factory')->get($file->getFileUri());       if ($image->isValid()) {         $file_variables['width'] = $image->getWidth();         $file_variables['height'] = $image->getHeight();       }       else {         $file_variables['width'] = $file_variables['height'] = NULL;       }     }      $element['preview'] = array(       '#weight' => -10,       '#theme' => 'image_style',       '#width' => $file_variables['width'],       '#height' => $file_variables['height'],       '#style_name' => $file_variables['style_name'],       '#uri' => $file_variables['uri'],     );      // Store the dimensions in the form so the file doesn't have to be     // accessed again. This is important for remote files.     $element['width'] = array(       '#type' => 'hidden',       '#value' => $file_variables['width'],     );     $element['height'] = array(       '#type' => 'hidden',       '#value' => $file_variables['height'],     );   }    $variables['data'] = array();   foreach (DrupalCoreRenderElementElement::children($element) as $child) {     $variables['data'][$child] = $element[$child];   } } ?> 

Any help is welcome, thanks!

Sponsored by SupremePR
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Render form widget inside a custom form

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.