cforge-2.0.x-dev/src/Plugin/Field/FieldWidget/ContactMeWidget.php
src/Plugin/Field/FieldWidget/ContactMeWidget.php
<?php
namespace Drupal\cforge\Plugin\Field\FieldWidget;
use \Drupal\cforge\Plugin\Field\FieldType\ContactMeItem;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Plugin implementation of the 'worth' widget.
*
* @FieldWidget(
* id = "cf_contactme",
* label = @Translation("Contact me"),
* field_types = {
* "cf_contactme"
* },
* multiple_values = false
* )
*/
class ContactMeWidget extends WidgetBase {
/**
* Returns the form for a single field widget.
*
* @see \Drupal\Core\Field\WidgetInterface
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$w = 0;
$element = [
'#title' => $this->t('Phone and social media handles.'),
'#description' => $this->t("Main phone can be made private, other info is visisble to all site members."),
'#type' => 'details',
'#open' => $items->getFieldDefinition()->isRequired(),
'#attributes'=> ['class' => ['channels']],
'#attached' => ['library' => ['cforge/social_media_icons']]
];
$this->availableChannels = array_filter($this->fieldDefinition->getSetting('channels')??[]);
foreach (ContactMeItem::CHANNELS as $channel => $info) {
if (in_array($channel, $this->availableChannels)) {
$element[$channel] = [
'#type' => 'textfield',
'#title' => new TranslatableMarkup($info['title']),
'#default_value' => $items->{$channel},
'#weight' => $w++
];
if (!empty($info['example'])) {
$element[$channel]['#placeholder'] = $info['example'];
}
if (!empty($info['regex'])) {
$element[$channel]['#pattern'] = $info['regex'];
}
if (!empty($info['prefix'])) {
$element[$channel]['#field_prefix'] = $info['prefix'];
}
if (!empty($info['phoneid'])) {
$this->dependsOnPhone($element, $channel);
}
}
}
$element['mob']['#required'] = $this->fieldDefinition->isRequired();
return $element;
}
/**
*
* @param array $element
* @param string $channel
*/
function dependsOnPhone(array &$element, string $channel) : void {
if (isset($element[$channel])) {
$element[$channel]['#states'] = [
'invisible' => [
':input[name="mob"]' => ['!value' => '']
]
];
if (in_array('mob', $this->availableChannels)) {
$element[$channel]['#options']['mob'] = $this->t('Mobile no.');
}
if (in_array('tel', $this->availableChannels)) {
$element[$channel]['#options']['tel'] = t('Other phone no.');
}
if ($element[$channel]['#options']) {
$element[$channel]['#type'] = 'select';
unset($element[$channel]['#field_prefix']);
$element[$channel]['#empty_option'] = $this->t('No');
}
}
}
}
