closedquestion-8.x-3.x-dev/src/Form/ClosedQuestionForm.php
src/Form/ClosedQuestionForm.php
<?php
namespace Drupal\closedquestion\Form;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form handler for the closed question edit forms.
*
* @internal
*/
class ClosedQuestionForm extends ContentEntityForm {
/**
* The Current User object.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Constructs a form object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
*/
public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, AccountInterface $current_user, DateFormatterInterface $date_formatter) {
parent::__construct($entity_repository, $entity_type_bundle_info, $time);
$this->currentUser = $current_user;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.repository'),
$container->get('entity_type.bundle.info'),
$container->get('datetime.time'),
$container->get('current_user'),
$container->get('date.formatter')
);
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
/** @var \Drupal\closedquestion\Entity\ClosedQuestionInterface $entity */
$entity = $this->entity;
if ($this->operation == 'edit') {
$form['#title'] = $this->t('<em>Edit Closed Question</em> @title', [
'@title' => $entity->label(),
]);
}
// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = [
'#type' => 'hidden',
'#default_value' => $entity->getChangedTime(),
];
$form = parent::form($form, $form_state);
$form['status']['#group'] = 'footer';
// Closed question author information for administrators.
$form['author'] = [
'#type' => 'details',
'#title' => t('Authoring information'),
'#group' => 'advanced',
'#attributes' => [
'class' => ['closedquestion-form-author'],
],
'#weight' => 90,
'#optional' => TRUE,
];
if (isset($form['uid'])) {
$form['uid']['#group'] = 'author';
}
if (isset($form['created'])) {
$form['created']['#group'] = 'author';
}
// Call form submit function.
$form['#attributes']['onsubmit'] = 'CQ_beforesubmit();';
// Set parse_content property.
$form['parse_content'] = array(
'#type' => 'hidden',
'#default_value' => '',
'#input' => TRUE,
);
$path = drupal_get_path('module', 'closedquestion');
$form['#attached']['library'][] = 'core/jquery.ui.draggable';
$form['#attached']['library'][] = 'core/jquery.ui.resizable';
$form['#attached']['library'][] = 'core/jquery.ui.droppable';
$form['#attached']['library'][] = 'core/jquery.ui.sortable';
$form['#attached']['library'][] = 'closedquestion/closedquestion.form';
$form['#attached']['drupalSettings']['closedquestion']['xmlConfig'] = closedquestion_xml_config();
$form['#attached']['drupalSettings']['closedquestion']['basePath'] = base_path() . $path;
$form['#attached']['drupalSettings']['closedquestion']['xmlConfig']['basePath'] = $form['#attached']['drupalSettings']['closedquestion']['basePath'];
$form['#attached']['drupalSettings']['closedquestion']['language'] = $entity->language();
// Find all question templates, alphabetize them, and expose them
// to our JavaScript.
$templates = \Drupal::moduleHandler()->invokeAll('closedquestion_templates');
\Drupal::moduleHandler()->alter('closedquestion_templates', $templates);
uasort($templates, '_closedquestion_template_sort');
$form['#attached']['drupalSettings']['closedquestion']['templates'] = $templates;
$prefix = '
<div class="xmlJsonEditorTabs">
<a id="xmlJsonEditor_templates" class="xmlJsonEditor_inactiveTab" href="javascript:void(0)" onclick="CQ_ShowTemplates()">' . t('Choose a Template') . '</a>
<a id="xmlJsonEditor_tree" class="xmlJsonEditor_inactiveTab" href="javascript:void(0)" onclick="CQ_ShowTree()">' . t('Edit Question') . '</a>
<a id="xmlJsonEditor_xml" class="xmlJsonEditor_activeTab" href="javascript:void(0)" onclick="CQ_ShowXML()">' . t('Edit Source') . '</a>
</div>
<div id="body_field_wrapper">
<div class="xmlJsonEditor_container" id="xmlJsonEditor_container">
<div class="editor_structure_contents" id="editor_structure_contents">
<div id="xmlEditorAddContainer">
<div class="selectedNodeAddlist">
<label>Click to insert</label>
<ul id="selectedNodeAddlist"> </ul>
</div>
</div>
</div>
<table border=1 style="vertical-align:top;table-layout:fixed;" id="xmlJsonEditorTable">
<tr>
<td style="width:30%">
<div class="xmlJsonEditor_tree">
<div class="xmlJsonEditor_tree_container" id="xmlJsonEditor_tree_container"></div>
</div>
<!--<div class="xmlJsonEditor_divider" id="xmlJsonEditor_divider"></div>-->
</td>
<td style="width:70%;box-shadow: -1px 0px 3px gray;">
<div class="xmlJsonEditor_form_elements">
<h3 id="editor_values_legend">
<label>Edit selected item</label>
<controls>
<div id="selectedNodeRemoveContainer">
<a id="selectedNodeRemoveButton" href="javascript:void(0)"> <span class="fa fa-trash fa-lg"></span><br /><small>Remove</small></a>
<a id="selectedNodeCloneButton" href="javascript:void(0)"> <span class="fa fa-copy fa-lg"></span><br /><small>Clone</small></a>
</div>
</controls>
</h3>
<div class="xmlJsonEditor_form_container" id="xmlJsonEditor_editor">
</div>
</div>
</td>
</tr>
</table>
</div>
<div class="xmlJsonEditor_templates" id="xmlJsonEditor_template_container">
<h3>' . t('Which kind of question would you like to create?') . '</h3>';
// Generate a list of links, one for each template.
$template_links = [];
foreach ($templates as $id => $template) {
$template_links[$id] = array(
'title' => t($template['name']),
'url' => $url = Url::fromUserInput("#$id"),
// Store the template id in the fragment for our JS.
'attributes' => array(
'class' => array('cq-select-template'),
),
);
}
$template_links = [
'#theme' => 'links',
'#links' => $template_links,
];
$prefix .= render($template_links)->__toString();
$prefix .= '</div>';
$prefix = Markup::create($prefix);
$form['field_question_xml']['#prefix'] = render($prefix);
$form['field_question_xml']['#suffix'] = '</div>';
$form['field_question_xml'][0]['#wysiwyg'] = FALSE;
// Hide obsolete file attachment field if not used.
$attachment_field = $entity->get('field_attachments')->first()->getValue();
if (!$attachment_field) {
$form['field_attachments']['#access'] = FALSE;
}
return $form;
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$element = parent::actions($form, $form_state);
$entity = $this->entity;
$element['delete']['#access'] = $entity->access('delete');
$element['delete']['#weight'] = 100;
return $element;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->entity;
$insert = $entity->isNew();
$entity->save();
$entity_link = $entity->toLink($this->t('View'))->toString();
$context = ['%title' => $entity->label(), 'link' => $entity_link];
$t_args = ['%title' => $entity->toLink()->toString()];
if ($insert) {
$this->logger('closedquestion')->notice('Added %title.', $context);
$this->messenger()->addStatus($this->t('Closed Question %title has been created.', $t_args));
}
else {
$this->logger('closedquestion')->notice('Updated %title.', $context);
$this->messenger()->addStatus($this->t('Closed Question %title has been updated.', $t_args));
}
if ($entity->id()) {
$form_state->setValue('id', $entity->id());
$form_state->set('id', $entity->id());
$form_state->setRedirect('entity.closedquestion.collection');
}
else {
// In the unlikely case something went wrong on save, the entity will be
// rebuilt and entity form redisplayed the same way as in preview.
$this->messenger()->addError($this->t('The closed question could not be saved.'));
$form_state->setRebuild();
}
}
}
