page_tester-1.0.x-dev/src/Form/CreateCommentForm.php
src/Form/CreateCommentForm.php
<?php
namespace Drupal\page_tester\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\page_tester\PageTesterService;
use Drupal\Core\Form\FormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a confirmation form before clearing out the logs.
*
* @internal
*/
class CreateCommentForm extends FormBase {
protected $testId;
/**
* The page tester service.
*
* @var \Drupal\page_tester\PageTesterService
*/
protected $pageTesterService;
/**
* Constructs a new DeleteCommentConfirmForm.
*
* @param \Drupal\page_tester\PageTesterService $pageTesterService
* The page tester service.
*/
public function __construct(PageTesterService $pageTesterService) {
$this->pageTesterService = $pageTesterService;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('page_tester.pagetester_service')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'page_tester_create_comment';
}
/**
* {@inheritdoc}
*/
public function buildForm(
array $form,
FormStateInterface $form_state,
int $test_id = NULL,
int $test_number = NULL
) {
$form['test_id'] = [
'#type' => 'hidden',
'#value' => $test_id,
];
$form['test_number'] = [
'#type' => 'hidden',
'#value' => $test_number,
];
$form['comment'] = [
'#type' => 'textarea',
'#title' => $this->t('Comment'),
];
$form['actions'] = [
'#type' => 'actions',
'#attributes' => ['class' => ['container-inline']],
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if(
$form_state->hasValue('test_id') &&
$form_state->hasValue('test_number') &&
$form_state->hasValue('comment')
) {
$this->pageTesterService->setComment(
$form_state->getValue('test_id'),
$form_state->getValue('test_number'),
$form_state->getValue('comment')
);
$this->messenger()->addStatus($this->t('Comment created.'));
} else {
$this->messenger()->addStatus($this->t('Please fill in a comment.'));
}
$url = Url::fromUri(\Drupal::request()->headers->get('referer'));
if ($url) {
$form_state->setRedirectUrl($url);
}
}
}
