cloudinary-8.x-1.x-dev/modules/cloudinary_media_library_widget/src/Form/CloudinaryElementExampleForm.php
modules/cloudinary_media_library_widget/src/Form/CloudinaryElementExampleForm.php
<?php
namespace Drupal\cloudinary_media_library_widget\Form;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Markup;
/**
* Build an example form to show how to use cloudinary form element.
*/
class CloudinaryElementExampleForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'cloudinary_form_example';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['image'] = [
'#type' => 'cloudinary_media_library',
'#resource_type' => 'image',
'#title' => $this->t('Image'),
'#description' => $this->t('Choose an image from cloudinary media library.'),
];
$form['video'] = [
'#type' => 'cloudinary_media_library',
'#resource_type' => 'video',
'#title' => $this->t('Video'),
'#description' => $this->t('Choose a video from cloudinary media library.'),
];
$form['document'] = [
'#type' => 'cloudinary_media_library',
'#resource_type' => 'raw',
'#title' => $this->t('Document'),
'#description' => $this->t('Choose a document from cloudinary media library.'),
];
$form['assets'] = [
'#type' => 'cloudinary_media_library',
'#title' => $this->t('Asset (extended version)'),
'#extended' => TRUE,
'#description' => $this->t('Choose any asset from cloudinary media library.'),
];
$form['assets_with_preview'] = [
'#type' => 'cloudinary_media_library',
'#title' => $this->t('Asset with Preview'),
'#preview' => TRUE,
'#description' => $this->t('Choose any asset from cloudinary media library.'),
];
$form['multiple_assets_with_preview'] = [
'#type' => 'cloudinary_media_library',
'#title' => $this->t('Multiple Assets with Preview (extended version)'),
'#preview' => TRUE,
'#extended' => TRUE,
'#multiple' => TRUE,
'#cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'#description' => $this->t('Choose any asset from cloudinary media library.'),
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save and debug'),
'#button_type' => 'primary',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach (Element::children($form) as $child) {
if (isset($form[$child]['#type']) && $form[$child]['#type'] === 'cloudinary_media_library') {
if ($value = $form_state->getValue($child)) {
if (isset($value['value'])) {
if (!$value['value']) {
continue;
}
elseif ($form[$child]['#multiple']) {
unset($value['value']);
}
}
$this->messenger()->addStatus($this->t('Raw value of @label: @value', [
'@label' => $form[$child]['#title'],
'@value' => is_array($value) ? Markup::create('<pre>' . print_r($value, 1) . '</pre>') : $value,
]));
}
}
}
}
}
