Skip to content

Instantly share code, notes, and snippets.

@EclipseGc
Last active December 14, 2015 19:58
Show Gist options
  • Save EclipseGc/5140136 to your computer and use it in GitHub Desktop.
Save EclipseGc/5140136 to your computer and use it in GitHub Desktop.
<?php
use Drupal\Core\ContentNegotiation;
use Symfony\Component\HttpFoundation\Request;
class AjaxRequestCheck {
public function __construct(ContentNegotiation $negotiation, Request $request) {
$this->negotiation = $negotiation;
$this->request = $request;
}
public function isAjax() {
return bool $this->negotiation->getContentType($this->request) == 'ajax';
}
}
<?php
// In Drupal/Core/CoreBundle.php
$container->register('ajax_request_check', 'Drupal\Core\AjaxRequestCheck')
->setArgument(new Reference('content_negotiation'))
->setArgument(new Reference('request'));
<?php
use Drupal\Core\Form\FormInterface;
use Drupal\Core\ControllerInterface
class MyForm implements FormInterface, ControllerInterface {
public function __construct(AjaxRequestCheck $check) {
$this->check = $check;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('ajax_request_check')
);
}
public function buildForm(array $form, array &$form_state) {
$form['delete'] = array(
'#type' => 'submit',
'#value' => 'Delete',
);
if ($this->check->isAjax()) {
$form['delete']['#ajax']['callback'] = 'function_to_close_modal';
}
}
}
<?php
namespace Drupal\some;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SomekBundle extends Bundle {
/**
* Overrides \Symfony\Component\HttpKernel\Bundle\Bundle::build().
*/
public function build(ContainerBuilder $container) {
$container->register('some.form', 'Drupal\some\Routing\MyForm')
->setArgument(new Reference('ajax_request_check'));
}
}
some.form:
pattern: '/admin/config/some_form'
defaults:
_form: 'Drupal\some\Routing\MyForm'
requirements:
_permission: 'administer some form'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment