Skip to content

Instantly share code, notes, and snippets.

@tobytes
Created November 22, 2016 16:58
Show Gist options
  • Save tobytes/67a2c1fa9dfb78a2ce7f5a65b44c58c9 to your computer and use it in GitHub Desktop.
Save tobytes/67a2c1fa9dfb78a2ce7f5a65b44c58c9 to your computer and use it in GitHub Desktop.
Add File Form Elements
/**
* Adds the configured field from the file entity to form element.
*
* @param array $files
* Files which fields should be added.
* @param array $element
* Current form element.
* @param FormStateInterface $form_state
* Current state of the form.
*
* @return array
* The modified form element.
*/
protected static function addFileEntityFields(
array $files, array $element, FormStateInterface $form_state) {
foreach ($files as $fid => $file) {
// Add fieldset with inline entity fields.
$element[self::FORM_KEY] = array(
'#type' => 'fieldset',
'#title' => t('Inline fields'),
'#description' => t('Here you can edit custom fields of the file,
after it has been uploaded.'),
'#weight' => 10,
'#parents' => array(self::FORM_KEY, $fid),
);
$display = EntityFormDisplay::collectRenderDisplay($file, 'default');
$display->buildForm($file, $element[self::FORM_KEY], $form_state);
}
// Only display fields that are enabled in the widget config.
foreach (Element::children($element[self::FORM_KEY]) as $field) {
$config = $element['#' . self::CONFIG_KEY];
if (isset($config) && empty($config[$field])) {
$element[self::FORM_KEY][$field]['#access'] = FALSE;
}
}
return $element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment