AnalysisFormHandler.php in Real-time SEO for Drupal 8.2
File
src/Form/AnalysisFormHandler.php
View source
<?php
namespace Drupal\yoast_seo\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\yoast_seo\EntityAnalyser;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AnalysisFormHandler implements EntityHandlerInterface {
use DependencySerializationTrait;
protected $entityAnalyser;
protected $messenger;
public function __construct(EntityAnalyser $entity_analyser, MessengerInterface $messenger) {
$this->entityAnalyser = $entity_analyser;
$this->messenger = $messenger;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($container
->get('yoast_seo.entity_analyser'), $container
->get('messenger'));
}
public function analysisSubmitAjax(array &$form, FormStateInterface $form_state) {
$form_state
->setTemporaryValue('entity_validated', FALSE);
$preview_entity = $form_state
->getFormObject()
->buildEntity($form, $form_state);
$preview_entity->in_preview = TRUE;
$entity_data = $this->entityAnalyser
->createEntityPreview($preview_entity);
$user_input = $form_state
->getUserInput();
if (!empty($user_input['path'][0]['alias'])) {
$entity_data['url'] = $user_input['path'][0]['alias'];
}
$this->messenger
->deleteAll();
$response = new AjaxResponse();
$response
->addCommand(new InvokeCommand('body', 'trigger', [
'updateSeoData',
$entity_data,
]));
return $response;
}
public function addAnalysisSubmit(array &$element, FormStateInterface $form_state) {
$triggeringElement = $form_state
->getTriggeringElement();
if ($triggeringElement !== NULL && end($triggeringElement['#parents']) === 'yoast_seo_preview_button') {
$form_state
->addRebuildInfo('copy', [
'#build_id' => TRUE,
'#action' => TRUE,
]);
}
$element['yoast_seo_preview_button'] = [
'#type' => 'button',
'#value' => t('Seo preview'),
'#attributes' => [
'class' => [
'yoast-seo-preview-submit-button',
],
'style' => 'display: none',
],
'#ajax' => [
'callback' => [
$this,
'analysisSubmitAjax',
],
],
];
}
}