I am trying to get the values from an uploaded image inside a media entity during form submit.
Where my approach doesn’t work:
- When first uploading an image in the
media_image_add_form
form. - When editing an existing media entity and removing, then uploading a new image and trying to save.
My validation only works when editing and submitting an existing media entity (without changing the uploaded image file).
Here is my entire code for brevity, though it may be long, MYMODULE.module
:
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'media_image_add_form' || $form_id == 'media_image_edit_form') {
if ($form_state->getFormObject()->getEntity()->get("field_media_image")->entity) {
$form('#validate')() = '_MYMODULE_validate';
}
}
}
/**
* Validates submission values in the FORM_ID() form.
*/
function _MYMODULE_validate(array &$form, FormStateInterface $form_state) {
// $imageEntity = File::load($form_state->getValues()('field_media_image')(0)('fids')(0)); // Tried File::load here as well.
$imageField = $form_state->getFormObject()->getEntity()->get("field_media_image");
$imageEntity = $imageField->entity;
$imageFileSize = $imageEntity->getSize();
$imageFileMime = $imageEntity->getMimeType();
$imageFileName = $imageEntity->getFilename();
$isIssue = FALSE;
$showConditionalMessage = FALSE;
$ciuMessage = "";
$ignoreWarnings = $form_state->getValues()('field_ignore_warnings')('value'); // Field set on media image entity type.
// Conditional issue.
if ($ignoreWarnings === 0 && $imageFileMime === "image/jpeg" && $imageFileSize / 1000 > 150) {
$isIssue = TRUE;
$showConditionalMessage = TRUE;
$ciuMessage .= "<p>Conditional: This JPG file size is larger than 150kb, have you optimized this JPG image?</p>";
}
// Conditional issue.
if ($ignoreWarnings === 0 && $imageFileMime === "image/png" && $imageFileSize / 1000 > 200) {
$isIssue = TRUE;
$showConditionalMessage = TRUE;
$ciuMessage .= "<p>Conditional: This PNG file size is larger than 200kb, have you optimized this PNG image?</p>";
}
// Non-conditional issue.
if (strpos($imageFileName, ' ') !== false) {
$isIssue = TRUE;
$ciuMessage .= "<p>Filenames cannot contain spaces.</p>";
}
// Non-conditional issue.
if (strtolower($imageFileName) !== $imageFileName) {
$isIssue = TRUE;
$ciuMessage .= "<p>Filenames need to be in all lowercase.</p>";
}
if ($isIssue) {
if ($showConditionalMessage) {
$ciuMessage .= '<small>To ignore conditional errors, check the "Ignore conditional errors" checkbox below.</small>';
}
$form_state->setErrorByName('title', new FormattableMarkup($ciuMessage, ()));
}
}
One caveat for using hook_form_alter()
is that some of the errors are conditional, and I would like to provide a field on the media entity type to allow ignoring some of the errors.
How can I get the uploaded file/values in $form_state
when adding an image to a new media entity, or adding a new image to an existing media entity?