diff --git a/ajax_example/ajax_example.install b/ajax_example/ajax_example.install deleted file mode 100644 index 033516c..0000000 --- a/ajax_example/ajax_example.install +++ /dev/null @@ -1,56 +0,0 @@ - 'Stores example settings for nodes.', - 'fields' => [ - 'nid' => [ - 'type' => 'int', - 'unsigned' => TRUE, - 'not null' => TRUE, - 'default' => 0, - 'description' => 'The {node}.nid to store settings.', - ], - 'example_1' => [ - 'type' => 'int', - 'not null' => TRUE, - 'default' => 0, - 'description' => 'Node Form Example 1 checkbox', - ], - 'example_2' => [ - 'type' => 'varchar', - 'length' => 256, - 'not null' => FALSE, - 'default' => '', - 'description' => 'Node Form Example 2 textfield', - ], - ], - 'primary key' => ['nid'], - 'foreign keys' => [ - 'dnv_node' => [ - 'table' => 'node', - 'columns' => ['nid' => 'nid'], - ], - ], - ]; - return $schema; -} - -/** - * Add the new ajax_example_node_form_alter table. - */ -function ajax_example_update_7100() { - if (!db_table_exists('ajax_example_node_form_alter')) { - $schema = ajax_example_schema(); - db_create_table('ajax_example_node_form_alter', $schema['ajax_example_node_form_alter']); - return st('Created table ajax_example_node_form_alter'); - } -} diff --git a/ajax_example/ajax_example.links.menu.yml b/ajax_example/ajax_example.links.menu.yml index 914d35b..d5bd495 100644 --- a/ajax_example/ajax_example.links.menu.yml +++ b/ajax_example/ajax_example.links.menu.yml @@ -4,71 +4,73 @@ ajax_example.description: expanded: TRUE ajax_example.simplest: - title: 'Simplest AJAX Example' + title: 'Simplest AJAX example' route_name: 'ajax_example.simplest' parent: ajax_example.description + weight: 0 -ajax_example.autocheckboxes: - title: 'Generate checkboxes' - route_name: 'ajax_example.autocheckboxes' +ajax_example.submit-driven: + title: 'Submit-driven AJAX' + route_name: 'ajax_example.submit_driven_ajax' + parent: ajax_example.description + weight: 1 + +ajax_example.render-link: + title: 'AJAX link in a render array' + route_name: 'ajax_example.ajax_link_render' + parent: ajax_example.description + weight: 2 + +ajax_example.wizard-example: + title: 'Wizard example' + route_name: 'ajax_example.wizard' parent: ajax_example.description + weight: 2 + +ajax_example.wizard-examplenojs: + title: 'Wizard example w/JS turned off' + route_name: 'ajax_example.wizardnojs' + parent: ajax_example.description + weight: 3 + +ajax_example.autocomplete-user: + title: 'Autocomplete user with entity_autocomplete' + route_name: 'ajax_example.autocomplete_user' + parent: ajax_example.description + weight: 4 ajax_example.autotextfields: title: 'Generate textfields' route_name: 'ajax_example.autotextfields' parent: ajax_example.description - -ajax_example.submit-driven: - title: 'Submit-driven AJAX' - route_name: 'ajax_example.submit-driven-ajax' - parent: ajax_example.description + weight: 5 ajax_example.dependent-dropdown: title: 'Dependent dropdown' route_name: 'ajax_example.dependent_dropdown' parent: ajax_example.description + weight: 6 ajax_example.dependent-dropdown-degrades: title: 'Dependent dropdown degrades' route_name: 'ajax_example.dependent_dropdown_degrades' parent: ajax_example.description + weight: 7 ajax_example.dependent-dropdown-degrades-nojava: title: 'Dependent dropdown degrades w/JS turned off ' route_name: 'ajax_example.dependent_dropdown_degrades_nojava' parent: ajax_example.description + weight: 8 ajax_example.dynamic-dropdown: - title: 'Dynamic Sections (with graceful degradation)' + title: 'Dynamic sections with graceful degradation' route_name: 'ajax_example.dynamic_sections' parent: ajax_example.description + weight: 9 ajax_example.dynamic-dropdown-degrades-nojava-example: - title: 'Dynamic Sections (with graceful degradation) w/js turned off' + title: 'Dynamic sections with graceful degradation, w/js turned off' route_name: 'ajax_example.dynamic_sections_nojava' parent: ajax_example.description - -ajax_example.wizard-example: - title: 'AJAX Wizard Example' - route_name: 'ajax_example.wizard' - parent: ajax_example.description - -ajax_example.wizard-examplenojs: - title: 'AJAX Wizard Example w/JS turned off' - route_name: 'ajax_example.wizardnojs' - parent: ajax_example.description - -ajax_example.addmorenojs: - title: 'Add more button (with graceful degradation) w/JS turned off' - route_name: 'ajax_example.addmorenojs' - parent: ajax_example.description - -ajax_example.addmore: - title: 'AJAX Add more button' - route_name: 'ajax_example.addmore' - parent: ajax_example.description - -ajax_example.advanced: - title: 'AJAX framework commands' - route_name: 'ajax_example.advanced' - parent: ajax_example.description + weight: 10 diff --git a/ajax_example/ajax_example.module b/ajax_example/ajax_example.module index 11a7453..1c2a6de 100644 --- a/ajax_example/ajax_example.module +++ b/ajax_example/ajax_example.module @@ -21,88 +21,3 @@ /** * @} End of "defgroup ajax_example". */ - -/** - * Helper function to populate the first dropdown. - * - * This would normally be pulling data from the database. - * - * @return array - * Dropdown options. - */ -function _ajax_example_get_first_dropdown_options() { - return [ - 'String' => 'String', - 'Woodwind' => 'Woodwind', - 'Brass' => 'Brass', - 'Percussion' => 'Percussion', - ]; -} - -/** - * Helper function to populate the second dropdown. - * - * This would normally be pulling data from the database. - * - * @param string $key - * This will determine which set of options is returned. - * - * @return array - * Dropdown options - */ -function _ajax_example_get_second_dropdown_options($key = '') { - switch ($key) { - case 'String': - $options = [ - 'Violin' => 'Violin', - 'Viola' => 'Viola', - 'Cello' => 'Cello', - 'Double Bass' => 'Double Bass', - ]; - break; - - case 'Woodwind': - $options = [ - 'Flute' => 'Flute', - 'Clarinet' => 'Clarinet', - 'Oboe' => 'Oboe', - 'Bassoon' => 'Bassoon', - ]; - break; - - case 'Brass': - $options = [ - 'Trumpet' => 'Trumpet', - 'Trombone' => 'Trombone', - 'French Horn' => 'French Horn', - 'Euphonium' => 'Euphonium', - ]; - break; - - case 'Percussion': - $options = [ - 'Bass Drum' => 'Bass Drum', - 'Timpani' => 'Timpani', - 'Snare Drum' => 'Snare Drum', - 'Tambourine' => 'Tambourine', - ]; - break; - - default: - $options = ['none' => 'none']; - break; - } - return $options; -} - -/** - * Submit function for AjaxExampleDependentDropdownDegrades::prompt(). - */ - -/** - * Submit function for ajax_example_wizard. - * - * In AJAX this is only submitted when the final submit button is clicked, - * but in the non-javascript situation, it is submitted with every - * button click. - */ diff --git a/ajax_example/ajax_example.routing.yml b/ajax_example/ajax_example.routing.yml index 45d435b..a7310c0 100644 --- a/ajax_example/ajax_example.routing.yml +++ b/ajax_example/ajax_example.routing.yml @@ -9,49 +9,23 @@ ajax_example.description: ajax_example.simplest: path: 'examples/ajax-example/simplest' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleSimplest' - _title: 'Simplest AJAX Example' - requirements: - _permission: 'access content' - -ajax_example.progresssbar: - path: 'examples/ajax-example/progressbar' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleProgressBar' - _title: 'Progress bar' - requirements: - _permission: 'access content' - -ajax_example.progresssbarProgress: - path: 'examples/ajax_example/progressbar/progress/{time}' - defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::progressbarProgress' - _title: 'Progress bar Progress' - # We provide default value to both arguments. - time: '' - requirements: - _permission: 'access content' - -ajax_example.autocheckboxes: - path: 'examples/ajax-example/autocheckboxes' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAutocheckboxes' - _title: 'Generate checkboxes' + _form: '\Drupal\ajax_example\Form\Simplest' + _title: 'Simplest AJAX example' requirements: _permission: 'access content' ajax_example.autotextfields: path: 'examples/ajax-example/autotextfields' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAutotextfields' + _form: '\Drupal\ajax_example\Form\Autotextfields' _title: 'Generate textfields' requirements: _permission: 'access content' -ajax_example.submit-driven-ajax: +ajax_example.submit_driven_ajax: path: 'examples/ajax-example/submit-driven-ajax' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleSubmitDriven' + _form: '\Drupal\ajax_example\Form\SubmitDriven' _title: 'Submit-driven AJAX' requirements: _permission: 'access content' @@ -59,7 +33,7 @@ ajax_example.submit-driven-ajax: ajax_example.dependent_dropdown: path: 'examples/ajax-example/dependent-dropdown' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleDependentDropdown' + _form: '\Drupal\ajax_example\Form\DependentDropdown' _title: 'Dependent dropdown' requirements: _permission: 'access content' @@ -67,7 +41,7 @@ ajax_example.dependent_dropdown: ajax_example.dependent_dropdown_degrades: path: 'examples/ajax-example/dependent-dropdown-degrades' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleDependentDropdownDegrades' + _form: '\Drupal\ajax_example\Form\DependentDropdownDegrades' _title: 'Dependent dropdown degrades' requirements: _permission: 'access content' @@ -75,8 +49,8 @@ ajax_example.dependent_dropdown_degrades: ajax_example.dependent_dropdown_degrades_nojava: path: 'examples/ajax-example/dependent-dropdown-degrades-nojava/{no_js_use}' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleDependentDropdownDegrades' - _title: 'Dependent dropdown degrades w/JS turned off ' + _form: '\Drupal\ajax_example\Form\DependentDropdownDegrades' + _title: 'Dependent dropdown degrades w/JS turned off' no_js_use: TRUE requirements: _permission: 'access content' @@ -84,16 +58,16 @@ ajax_example.dependent_dropdown_degrades_nojava: ajax_example.dynamic_sections: path: 'examples/ajax-example/dynamic-sections' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleDependentDropdownDegrades' - _title: 'Dynamic Sections (with graceful degradation)' + _form: '\Drupal\ajax_example\Form\DependentDropdownDegrades' + _title: 'Dynamic sections with graceful degradation' requirements: _permission: 'access content' ajax_example.dynamic_sections_nojava: path: 'examples/ajax-example/dynamic-sections-nojava/{no_js_use}' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleDynamicSectionsDegrades' - _title: 'Dynamic Sections w/JS turned off' + _form: '\Drupal\ajax_example\Form\DynamicSectionsDegrades' + _title: 'Dynamic sections w/JS turned off' no_js_use: TRUE requirements: _permission: 'access content' @@ -101,94 +75,46 @@ ajax_example.dynamic_sections_nojava: ajax_example.wizard: path: 'examples/ajax-example/wizard' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleWizard' - _title: 'Wizard (with graceful degradation)' + _form: '\Drupal\ajax_example\Form\Wizard' + _title: 'Wizard with graceful degradation' requirements: _permission: 'access content' ajax_example.wizardnojs: path: 'examples/ajax-example/wizard-nojs/{no_js_use}' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleWizard' - _title: 'Wizard (with graceful degradation) w/JS turned off' + _form: '\Drupal\ajax_example\Form\Wizard' + _title: 'Wizard with graceful degradation, w/JS turned off' no_js_use: TRUE requirements: _permission: 'access content' -ajax_example.addmore: - path: 'examples/ajax-example/add-more' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAddMore' - _title: 'Add more button (with graceful degradation)' - requirements: - _permission: 'access content' - -ajax_example.addmorenojs: - path: 'examples/ajax-example/add-more-nojs/{no_js_use}' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAddMore' - _title: 'Add more button (with graceful degradation) w/JS turned off' - no_js_use: TRUE - requirements: - _permission: 'access content' - -ajax_example.advanced: - path: 'examples/ajax-example/advanced-commands' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAdvancedCommands' - _title: 'AJAX framework commands' - requirements: - _permission: 'access content' - -ajax_example.Ajaxlink: - path: 'examples/ajax-example/ajax-link' - defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::ajaxExampleRenderLink' - _title: 'Ajax Link (Renderable Array)' - requirements: - _permission: 'access content' - -ajax_example.Ajaxlinkrender: +ajax_example.ajax_link_render: path: 'examples/ajax-example/ajax-link-renderable' defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::ajaxExampleRenderLinkRa' - _title: 'Ajax Link (Renderable Array)' + _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::renderLinkRenderableArray' + _title: 'AJAX link from a render array' requirements: _permission: 'access content' -ajax_example.Ajaxlinkcall: - path: 'ajax_link_callback' - defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::ajaxLinkResponse' - requirements: - _permission: 'access content' - -ajax_example.AutocompleteSimplest: - path: 'examples/ajax_example/simple_autocomplete' - defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleAutocomplete' - _title: 'Autocomplete (simple)' - requirements: - _permission: 'access content, access user profiles' - -ajax_example.AutocompleteSimplestcallback: - path: 'examples/ajax_example/simple_user_autocomplete_callback' - defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::simpleUserAutocompleteCallback' - requirements: - _permission: 'access user profiles, access content' - -ajax_example.Autocompletenode: - path: 'examples/ajax_example/node_autocomplete' +# This route is for an AJAX callback. It is used by the AJAX system on +# ajax_example.ajax_link_render. It has a {nojs} parameter, which gives us +# a way to know whether the request is an AJAX request or is from some other +# source. +ajax_example.ajax_link_callback: + path: 'examples/ajax-example/ajax-link-callback/{nojs}' defaults: - _form: '\Drupal\ajax_example\Form\AjaxExampleUniqueComplete' - _title: 'Autocomplete (node with nid)' + _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::ajaxLinkCallback' + # We provide a default value for {nojs}, so that it can be an optional + # parameter. + nojs: 'nojs' requirements: _permission: 'access content' -ajax_example.Autocompletenodecallback: - path: 'examples/ajax_example/unique_node_autocomplete_callback' +ajax_example.autocomplete_user: + path: 'examples/ajax_example/user_autocomplete' defaults: - _controller: '\Drupal\ajax_example\Controller\AjaxExampleController::uniqueNodeAutocompleteCallback' + _form: '\Drupal\ajax_example\Form\EntityAutocomplete' + _title: 'Autocomplete users with entity_autocomplete.' requirements: _permission: 'access content' diff --git a/ajax_example/src/Controller/AjaxExampleController.php b/ajax_example/src/Controller/AjaxExampleController.php index 6ad8a18..3f596e0 100644 --- a/ajax_example/src/Controller/AjaxExampleController.php +++ b/ajax_example/src/Controller/AjaxExampleController.php @@ -2,16 +2,11 @@ namespace Drupal\ajax_example\Controller; -use Drupal\Component\Utility\SafeMarkup; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\AppendCommand; use Drupal\Core\Controller\ControllerBase; -use Drupal\Core\Database\Connection; -use Drupal\Core\Link; use Drupal\Core\Url; use Drupal\examples\Utility\DescriptionTemplateTrait; -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; /** @@ -21,23 +16,6 @@ class AjaxExampleController extends ControllerBase { use DescriptionTemplateTrait; - /** - * The database connection. - * - * @var \Drupal\Core\Database\Connection - */ - protected $connection; - - public static function create(ContainerInterface $container) { - return new static( - $container->get('database') - ); - } - - public function __construct(Connection $connection) { - $this->connection = $connection; - } - /** * {@inheritdoc} */ @@ -45,45 +23,6 @@ class AjaxExampleController extends ControllerBase { return 'ajax_example'; } - /** - * Get the progress bar execution status, as JSON. - * - * This is the menu handler for - * examples/ajax_example/progressbar/progress/$time. - * - * This function is our wholly arbitrary job that we're checking the status - * for. In this case, we're reading a system variable that is being updated by - * ajax_example_progressbar_callback(). - * - * We set up the AJAX progress bar to check the status every second, so this - * will execute about once every second. - * - * The progress bar JavaScript accepts two values: message and percentage. We - * set those in an array and in the end convert it JSON for sending back to - * the client-side JavaScript. - * - * @param int $time - * Timestamp. - * - * @return \Symfony\Component\HttpFoundation\JsonResponse - * JSON response to the AJAX request. - */ - public function progressbarProgress($time) { - $progress = [ - 'message' => t('Starting execute...'), - 'percentage' => -1, - ]; - - $completed_percentage = \Drupal::config('ajaxexample.settings')->get('example_progressbar_' . $time); - - if ($completed_percentage) { - $progress['message'] = t('Executing...'); - $progress['percentage'] = $completed_percentage; - } - - return new JsonResponse($progress); - } - /** * Demonstrates a clickable AJAX-enabled link using the 'use-ajax' class. * @@ -98,8 +37,7 @@ class AjaxExampleController extends ControllerBase { * * @ingroup ajax_example */ - public function ajaxExampleRenderLinkRa() { - + public function renderLinkRenderableArray() { $build['my_div'] = [ '#markup' => $this->t(' The link below has been rendered as an element with the #ajax property, so if @@ -108,43 +46,37 @@ of a normal page load. The URL also contains the "/nojs/" magic string, which is stripped if javascript is enabled, allowing the server code to tell by the URL whether JS was enabled or not, letting it do different things based on that.'), ]; + // We'll add a nice border element for our demo. $build['ajax_link'] = [ + '#type' => 'details', + '#title' => $this->t('This is the AJAX link'), + '#open' => TRUE, + ]; + // We build the AJAX link. + $build['ajax_link']['link'] = [ '#type' => 'link', - '#title' => t('Click here'), - // Note the /nojs portion of the href - if javascript is enabled, - // this part will be stripped from the path before it is called. - '#href' => 'ajax_link_callback/nojs/', - '#id' => 'ajax_link', - '#ajax' => [ - 'wrapper' => 'myDiv', - 'method' => 'html', - ], + '#title' => $this->t('Click me'), + // We have to ensure that Drupal's Ajax system is loaded. + '#attached' => ['library' => ['core/drupal.ajax']], + // We add the 'use-ajax' class so that Drupal's AJAX system can spring + // into action. + '#attributes' => ['class' => ['use-ajax']], + // The URL for this link element is the callback. In our case, it's route + // ajax_example.ajax_link_callback, which maps to ajaxLinkCallback() + // below. The route has a /{nojs} section, which is how the callback can + // know whether the request was made by AJAX or some other means where + // JavaScript won't be able to handle the result. If the {nojs} part of + // the path is replaced with 'ajax', then the request was made by AJAX. + '#url' => Url::fromRoute('ajax_example.ajax_link_callback', ['nojs' => 'ajax']), + ]; + // We provide a DIV that AJAX can append some text into. + $build['ajax_link']['destination'] = [ + '#type' => 'container', + '#attributes' => ['id' => ['ajax-example-destination-div']], ]; return $build; } - /** - * - */ - public function ajaxExampleRenderLink() { - $attachments['#attached']['library'][] = 'system/drupal.ajax'; - $explanation = $this->t(" -The link below has the use-ajax class applied to it, so if -javascript is enabled, ajax.js will try to submit it via an AJAX call instead -of a normal page load. The URL also contains the '/nojs/' magic string, which -is stripped if javascript is enabled, allowing the server code to tell by the -URL whether JS was enabled or not, letting it do different things based on that."); - $output = "
" . $explanation . "
"; - // The use-ajax class is special, so that the link will call without causing - // a page reload. Note the /nojs portion of the path - if javascript is - // enabled, this part will be stripped from the path before it is called. - $value = ['attributes' => ['class' => ['use-ajax']]]; - $url = Url::fromUri('internal:/ajax_link_callback/nojs/', $value); - $link = Link::fromTextAndUrl($this->t('Click here'), $url)->toString(); - $output .= "
$link
"; - return $output; - } - /** * Callback for link example. * @@ -152,7 +84,7 @@ URL whether JS was enabled or not, letting it do different things based on that. * If $type == 'ajax', it tells this function that ajax.js has rewritten * the URL and thus we are doing an AJAX and can return an array of commands. * - * @param string $type + * @param string $nojs * Either 'ajax' or 'nojs. Type is simply the normal URL argument to this * URL. * @@ -160,11 +92,13 @@ URL whether JS was enabled or not, letting it do different things based on that. * If $type == 'ajax', returns an array of AJAX Commands. * Otherwise, just returns the content, which will end up being a page. */ - public function ajaxLinkResponse($type = 'ajax') { - if ($type == 'ajax') { + public function ajaxLinkCallback($nojs = 'ajax') { + error_log($nojs); + // Determine whether the request is coming from AJAX or not. + if ($nojs == 'ajax') { $output = $this->t("This is some content delivered via AJAX"); $response = new AjaxResponse(); - $response->addCommand(new AppendCommand('#myDiv', $output)); + $response->addCommand(new AppendCommand('#ajax-example-destination-div', $output)); // See ajax_example_advanced.inc for more details on the available // commands and how to use them. @@ -176,114 +110,4 @@ URL whether JS was enabled or not, letting it do different things based on that. return $response; } - /** - * User autocomplete callback. - * - * It works simply by searching usernames (and of course in Drupal usernames - * are unique, so can be used for identifying a record.) - * - * The returned $matches array has - * * key: string which will be displayed once the autocomplete is selected - * * value: the value which will is displayed in the autocomplete pulldown. - * - * In the simplest cases (see - * drupal/ajax_example/form/AjaxExampleAutocomplete.php) - * these are the same, andnothing needs to be done. However, more complicated - * autocompletes require more work. Here we demonstrate the difference by - * displaying the UID along with the username in the dropdown. - * - * In the end, though, we'll be doing something with the value that ends up in - * the textfield, so it needs to uniquely identify the record we want to - * access. This is demonstrated in ajax_example_unique_autocomplete(). - * - * @param \Drupal\Core\Database\Connection $connection - * The database connection. - * @param string $string - * The string that will be searched. - * - * @return Symfony\Component\HttpFoundation\JsonResponse - * The JSON response to the AJAX request. - */ - public function simpleUserAutocompleteCallback(Connection $connection, $string = "") { - $matches = []; - - if ($string) { - - $result = $this->connection->select('users') - ->fields('users', ['name', 'uid']) - ->condition('name', $this->connection->like($string) . '%', 'LIKE') - ->range(0, 10) - ->execute(); - foreach ($result as $user) { - // In the simplest case (see user_autocomplete), the key and the value - // are the same. Here we'll display the uid along with the username in - // the dropdown. - $matches[] = ['value' => $user->name, 'label' => $user->uid]; - $matches[$user->name] = SafeMarkup::check_plain($user->name) . " (uid=$user->uid)"; - } - } - - return new JsonResponse($matches); - } - - /** - * Autocomplete callback for nodes by title. - * - * Searches for a node by title, but then identifies it by nid, so the actual - * returned value can be used later by the form. - * - * The returned $matches array has - * - key: The title, with the identifying nid in brackets, like "Some node - * title [3325]" - * - value: the title which will is displayed in the autocomplete pulldown. - * - * Note that we must use a key style that can be parsed successfully and - * unambiguously. For example, if we might have node titles that could have - * [3325] in them, then we'd have to use a more restrictive token. - * - * @param string $string - * The string that will be searched. - */ - public function uniqueNodeAutocompleteCallback($string = "") { - $matches = []; - if ($string) { - - $result = $this->connection->select('node') - ->fields('node', ['nid', 'title']) - ->condition('title', $this->connection->escapeLike($string) . '%', 'LIKE') - ->range(0, 10) - ->execute(); - foreach ($result as $node) { - $matches[$node->title . " [$node->nid]"] = SafeMarkup::check_plain($node->title); - } - } - - return new JsonResponse($matches); - } - - /* - * @todo: is this even in use? - */ - /* public function ajax_example_node_by_author_node_autocomplete_callback( - * $author_uid, $string = "") { - $this->connection = Connection::$connection; - $matches = []; - if ($author_uid > 0 && trim($string)) { - $db = Database::getConnection(); - $result = $db->select('node') - ->fields('node', ['nid', 'title']) - ->condition('uid', $author_uid) - ->condition('title', $db->escapeLike($string) . '%', 'LIKE') - ->range(0, 10) - ->execute(); - foreach ($result as $node) { - $matches[$node->title . " [$node->nid]"] = - SafeMarkup::check_plain($node->title); - } - } - - return new JsonResponse($matches); - } - */ - } diff --git a/ajax_example/src/Form/AjaxExampleAddMore.php b/ajax_example/src/Form/AjaxExampleAddMore.php deleted file mode 100644 index c43dc09..0000000 --- a/ajax_example/src/Form/AjaxExampleAddMore.php +++ /dev/null @@ -1,156 +0,0 @@ -t('non-js version'), $url)->toString(); - - // Prepare link for multiple arguments. - $urltwo = Url::fromUri('internal:/examples/ajax_example/add-more'); - $linktwo = Link::fromTextAndUrl($this->t('AJAX version'), $urltwo)->toString(); - $form['description'] = [ - '#markup' => t('This example shows an add-more and a remove-last button. The @link does it without page reloads; the @link2 is the same code but simulates a non-javascript environment, showing it with page reloads.', - ['@link' => $linktwo, '@link2' => $link]), - - ]; - - // Because we have many fields with the same values, we have to set - // #tree to be able to access them. - $form['#tree'] = TRUE; - $form['names_fieldset'] = [ - '#type' => 'fieldset', - '#title' => t('People coming to the picnic'), - // Set up the wrapper so that AJAX will be able to replace the fieldset. - '#prefix' => '
', - '#suffix' => '
', - ]; - - // Build the fieldset with the proper number of names. We'll use - // $form_state['num_names'] to determine the number of textfields to build. - $name_fields = $form_state->get('num_names'); - if (empty($name_fields)) { - $name_fields = 1; - $form_state->set('num_names', $name_fields); - } - $form['num_names'] = $name_fields; - for ($i = 0; $i < $name_fields; $i++) { - $form['names_fieldset']['name'][$i] = [ - '#type' => 'textfield', - '#title' => t('Name'), - ]; - } - $form['names_fieldset']['add_name'] = [ - '#type' => 'submit', - '#value' => t('Add one more'), - '#submit' => ['::ajax_example_add_more_add_one'], - '#ajax' => [ - 'callback' => '::prompt', - 'wrapper' => 'names-fieldset-wrapper', - ], - ]; - if ($form['num_names'] > 1) { - $form['names_fieldset']['remove_name'] = [ - '#type' => 'submit', - '#value' => t('Remove one'), - '#submit' => ['::ajax_example_add_more_remove_one'], - '#ajax' => [ - 'callback' => '::prompt', - 'wrapper' => 'names-fieldset-wrapper', - ], - ]; - } - $form['submit'] = [ - '#type' => 'submit', - '#value' => t('Submit'), - ]; - - // This simply allows us to demonstrate no-javascript use without - // actually turning off javascript in the browser. Removing the #ajax - // element turns off AJAX behaviors on that element and as a result - // ajax.js doesn't get loaded. - // For demonstration only! You don't need this. - if ($no_js_use) { - // Remove the #ajax from the above, so ajax.js won't be loaded. - if (!empty($form['names_fieldset']['remove_name']['#ajax'])) { - unset($form['names_fieldset']['remove_name']['#ajax']); - } - unset($form['names_fieldset']['add_name']['#ajax']); - } - - return $form; - } - - /** - * Callback for both ajax-enabled buttons. - * - * Selects and returns the fieldset with the names in it. - */ - public function prompt($form, $form_state) { - return $form['names_fieldset']; - } - - /** - * Submit handler for the "add-one-more" button. - * - * Increments the max counter and causes a rebuild. - */ - public function ajax_example_add_more_add_one($form, &$form_state) { - $name_field = $form_state->get('num_names'); - $add_button = $name_field + 1; - $form_state->set('num_names', $add_button); - $form_state->setRebuild(); - } - - /** - * Submit handler for the "remove one" button. - * - * Decrements the max counter and causes a form rebuild. - */ - public function ajax_example_add_more_remove_one($form, &$form_state) { - $name_field = $form_state->get('num_names'); - if ($name_field > 1) { - $remove_button = $name_field - 1; - $form_state->set('num_names', $remove_button); - } - $form_state->setRebuild(TRUE); - } - - /** - * Final submit handler. - * - * Reports what values were finally set. - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - $output = t('These people are coming to the picnic: @names', - [ - '@names' => implode(', ', $form_state->getValue(['names_fieldset', 'name'])), - ] - ); - // Sets a message to display to the user. - drupal_set_message($output); - } - -} diff --git a/ajax_example/src/Form/AjaxExampleAdvancedCommands.php b/ajax_example/src/Form/AjaxExampleAdvancedCommands.php deleted file mode 100644 index a4d1af8..0000000 --- a/ajax_example/src/Form/AjaxExampleAdvancedCommands.php +++ /dev/null @@ -1,443 +0,0 @@ - 'markup', - '#markup' => $this->t("
Demonstrates how AJAX commands can be used.
"), - ]; - - // Shows the 'after' command with a callback generating commands. - $form['after_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("This shows the Ajax 'after' command. Click to put something below the div that says 'Something can be inserted after this'"), - ]; - - $form['after_command_example_fieldset']['after_command_example'] = [ - '#value' => $this->t("AJAX 'After': Click to put something after the div"), - '#type' => 'submit', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_after_callback', - ], - '#suffix' => "
Something can be inserted after this
-
'After' Command Status: Unknown
", - ]; - - // Shows the 'alert' command. - $form['alert_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the AJAX 'alert' command. Click the button."), - ]; - $form['alert_command_example_fieldset']['alert_command_example'] = [ - '#value' => $this->t("AJAX 'Alert': Click to alert"), - '#type' => 'submit', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_alert_callback', - ], - ]; - - // Shows the 'append' command. - $form['append_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("This shows the Ajax 'append' command. Click to put something below the div that says 'Something can be inserted after this'"), - ]; - - $form['append_command_example_fieldset']['append_command_example'] = [ - '#value' => $this->t("AJAX 'Append': Click to append something"), - '#type' => 'submit', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_append_callback', - ], - '#suffix' => "
Something can be appended inside this div...
-
'After' Command Status: Unknown
", - ]; - - // Shows the 'before' command. - $form['before_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("This shows the Ajax 'before' command."), - ]; - - $form['before_command_example_fieldset']['before_command_example'] = [ - '#value' => $this->t("AJAX 'before': Click to put something before the div"), - '#type' => 'submit', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_before_callback', - ], - '#suffix' => "
Something can be inserted before this
-
'before' Command Status: Unknown
", - ]; - - // Shows the 'changed' command. - $form['changed_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the AJAX 'changed' command. If region is 'changed', it is marked with CSS. This example also puts an asterisk by changed content."), - ]; - - $form['changed_command_example_fieldset']['changed_command_example'] = [ - '#title' => $this->t("AJAX changed: If checked, div is marked as changed."), - '#type' => 'checkbox', - '#default_value' => FALSE, - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_changed_callback', - ], - '#suffix' => "
This div can be marked as changed or not.
-
Status: Unknown
", - ]; - - // Shows the AJAX 'css' command. - $form['css_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the AJAX 'css' command."), - ]; - - $form['css_command_example_fieldset']['css_command_example'] = [ - '#title' => $this->t("AJAX CSS: Choose the color you'd like the '#box' div to be."), - '#type' => 'select', - // '#default_value' => 'green',. - '#options' => ['green' => 'green', 'blue' => 'blue'], - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_css_callback', - ], - '#suffix' => "
box
-
Status: Unknown
", - ]; - - // Shows the AJAX 'data' command. But there is no use of this information, - // as this would require a javascript client to use the data. - $form['data_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the AJAX 'data' command."), - ]; - - $form['data_command_example_fieldset']['data_command_example'] = [ - '#title' => $this->t("AJAX data: Set a key/value pair on a selector."), - '#type' => 'textfield', - '#default_value' => 'color=green', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_data_callback', - ], - '#suffix' => "
This div should have key='time'/value='a time string' attached.
-
Status: Unknown
", - ]; - - // Shows the AJAX 'html' command. - $form['html_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the AJAX 'html' command."), - ]; - - $form['html_command_example_fieldset']['html_command_example'] = [ - '#title' => $this->t("AJAX html: Replace the HTML in a selector."), - '#type' => 'textfield', - '#default_value' => 'new value', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_html_callback', - ], - '#suffix' => "
Original contents
-
Status: Unknown
", - ]; - - // Shows the AJAX 'prepend' command. - $form['prepend_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("This shows the AJAX 'prepend' command. Click to put something below the div that says 'Something can be inserted after this'"), - ]; - - $form['prepend_command_example_fieldset']['prepend_command_example'] = [ - '#value' => $this->t("AJAX 'prepend': Click to prepend something"), - '#type' => 'submit', - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_prepend_callback', - ], - '#suffix' => "
Something can be prepended to this div...
-
'After' Command Status: Unknown
", - ]; - - // Shows the AJAX 'remove' command. - $form['remove_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Shows the Ajax 'remove' command."), - ]; - - $form['remove_command_example_fieldset']['remove_command_example'] = [ - '#title' => $this->t("AJAX 'remove': Check to remove text. Uncheck to add it back."), - '#type' => 'checkbox', - '#default_value' => FALSE, - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_remove_callback', - ], - '#suffix' => "
text to be removed
-
'After' Command Status: Unknown
", - ]; - - // Show off the AJAX 'restripe' command. Also shows classic AJAX replacement - // on the "how many rows" processing. - $form['restripe_command_example_fieldset'] = [ - '#type' => 'fieldset', - '#title' => $this->t("Demonstrates the Ajax 'restripe' command."), - ]; - - $options = range (-1, 10); - $options = array_shift($options); - $form['restripe_command_example_fieldset']['restripe_num_rows'] = [ - '#type' => 'select', - '#default_value' => - !empty($form_state->getValue('restripe_num_rows')) ? - $form_state->getValue('restripe_num_rows') : 1, - '#options' => $options, - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_restripe_num_rows', - 'method' => 'replace', - 'wrapper' => 'restripe_table', - ], - ]; - $form['restripe_command_example_fieldset']['restripe_restripe'] = [ - '#type' => 'submit', - '#value' => $this->t("Restripe the table"), - '#ajax' => [ - 'callback' => '::ajax_example_advanced_commands_restripe_callback', - ], - '#suffix' => "
- - -
first row
-
-
'Restripe' Command Status: Unknown
", - - ]; - - $form['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Submit'), - ]; - - return $form; - } - - /** - * Callback for 'after'. - * - * @see Drupal\Core\Ajax\AfterCommand; - */ - public function ajax_example_advanced_commands_after_callback($form, $form_state) { - $selector = '#after_div'; - $response = new AjaxResponse(); - $response->addCommand(new AfterCommand($selector, "New 'after'...")); - $response->addCommand(new ReplaceCommand("#after_status", "Updated after_command_example" . date('r') . "")); - return $response; - } - - /** - * Callback for 'alert'. - * - * @see Drupal\Core\Ajax\AlertCommand; - */ - public function ajax_example_advanced_commands_alert_callback($form, $form_state) { - $response = new AjaxResponse(); - $response->addCommand(new AlertCommand("Alert requested at " . date('r'))); - return $response; - } - - /** - * Callback for 'append'. - * - * @see Drupal\Core\Ajax\AppendCommand; - */ - public function ajax_example_advanced_commands_append_callback($form, $form_state) { - $selector = '#append_div'; - $response = new AjaxResponse(); - $response->addCommand(new AppendCommand($selector, "Stuff...")); - $response->addCommand(new ReplaceCommand("#append_status", "
Updated append_command_example " . date('r') . "
")); - return $response; - } - - /** - * Callback for 'before'. - * - * @see Drupal\Core\Ajax\BeforeCommand; - */ - public function ajax_example_advanced_commands_before_callback($form, $form_state) { - $selector = '#before_div'; - $response = new AjaxResponse(); - $response->addCommand(new BeforeCommand($selector, "New 'before'...")); - $response->addCommand(new ReplaceCommand("#before_status", "
Updated before_command_example " . date('r') . "
")); - - return $response; - } - - /** - * Callback for 'changed'. - * - * @see Drupal\Core\Ajax\ChangedCommand; - */ - public function ajax_example_advanced_commands_changed_callback($form, $form_state) { - $checkbox_value = $form_state->getValue('changed_command_example'); - $checkbox_value_string = $checkbox_value ? "TRUE" : "FALSE"; - $response = new AjaxResponse(); - if ($checkbox_value) { - $response->addCommand(new ChangedCommand('#changed_div', '#changed_div_mark_this')); - } - else { - $response->addCommand(new ReplaceCommand('#changed_div', "
This div can be marked as changed or not.
")); - } - $response->addCommand(new ReplaceCommand("#changed_status", "
Updated changed_command_example to $checkbox_value_string: " . date('r') . "
")); - return $response; - } - - /** - * Callback for 'css'. - * - * @see Drupal\Core\Ajax\AddCssCommand; - */ - public function ajax_example_advanced_commands_css_callback($form, $form_state) { - $selector = '#css_div'; - $color = $form_state->getValue('css_command_example'); - $response = new AjaxResponse(); - $response->addCommand(new AddCssCommand($selector, ['background-color' => $color])); - $response->addCommand(new ReplaceCommand("#css_status", "
Updated css_command_example to '{$color}' " . date('r') . "
")); - return $response; - } - - /** - * Callback for 'data'. - * - * @see Drupal\Core\Ajax\DataCommand - */ - public function ajax_example_advanced_commands_data_callback($form, $form_state) { - $selector = '#data_div'; - $text = $form_state->getValue('data_command_example'); - list($key, $value) = preg_split('/=/', $text); - - $response = new AjaxResponse(); - $response->addCommand(new DataCommand($selector, $key, $value)); - $response->addCommand(new ReplaceCommand("#data_status", "
Updated data_command_example with key=$key, value=$value; " . date('r') . "
")); - return $response; - } - - /** - * Callback for 'html'. - * - * @see Drupal\Core\Ajax\HtmlCommand - */ - public function ajax_example_advanced_commands_html_callback($form, $form_state) { - $text = $form_state->getValue('html_command_example'); - $response = new AjaxResponse(); - $response->addCommand(new HtmlCommand('#html_div', $text)); - $response->addCommand(new ReplaceCommand("#html_status", "
Updated html_command_example with text=$text; " . date('r') . "
")); - return $response; - } - - /** - * Callback for 'prepend'. - * - * @see Drupal\Core\Ajax\PrependCommand - */ - public function ajax_example_advanced_commands_prepend_callback($form, $form_state) { - $response = new AjaxResponse(); - $response->addCommand(new PrependCommand('#prepend_div', "Prepended Stuff...")); - $response->addCommand(new ReplaceCommand("#prepend_status", "
Updated prepend_command_example " . date('r') . "
")); - - return $response; - } - - /** - * Callback for 'remove'. - * - * @see Drupal\Core\Ajax\RemoveCommand - */ - public function ajax_example_advanced_commands_remove_callback($form, $form_state) { - $response = new AjaxResponse(); - $should_remove = $form_state->getValue('remove_command_example'); - $should_remove_string = $should_remove ? 'TRUE' : 'FALSE'; - if ($should_remove) { - $response->addCommand(new RemoveCommand('#remove_text')); - - } - else { - $response->addCommand(new HtmlCommand('#remove_div', "
text to be removed
")); - } - $response->addCommand(new ReplaceCommand("#remove_status", "
Updated remove_command_example (value={$should_remove_string} " . date('r') . "
")); - - return $response; - - } - - /** - * Callback for 'restripe'. - * - * Rebuilds the table with the selected number of rows. - */ - public function ajax_example_advanced_commands_restripe_num_rows($form, $form_state) { - $num_rows = $form_state->getValue('restripe_num_rows'); - $output = ""; - for ($i = 1; $i <= $num_rows; $i++) { - $output .= ""; - } - $output .= "
Row $i
"; - return $output; - } - - /** - * Callback for 'restripe'. - * - * @see Drupal\Core\Ajax\RestripeCommand - */ - public function ajax_example_advanced_commands_restripe_callback($form, $form_state) { - $response = new AjaxResponse(); - $response->addCommand(new RestripeCommand('#restripe_table')); - $response->addCommand(new ReplaceCommand("#restripe_status", "
Restriped table " . date('r') . "
")); - - return $response; - - } - - /** - * - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - } - -} diff --git a/ajax_example/src/Form/AjaxExampleAutocheckboxes.php b/ajax_example/src/Form/AjaxExampleAutocheckboxes.php deleted file mode 100644 index 3006624..0000000 --- a/ajax_example/src/Form/AjaxExampleAutocheckboxes.php +++ /dev/null @@ -1,94 +0,0 @@ -getValue('howmany_select')) ? $form_state->getValue('howmany_select') : 1; - $form['howmany_select'] = [ - '#title' => t('How many checkboxes do you want?'), - '#type' => 'select', - '#options' => [1 => 1, 2 => 2, 3 => 3, 4 => 4], - '#default_value' => $num_checkboxes, - '#ajax' => [ - 'callback' => '::prompt', - 'wrapper' => 'checkboxes-div', - // 'method' defaults to replaceWith, but valid values also include - // append, prepend, before and after. - // 'method' => 'replaceWith', - // 'effect' defaults to none. Other valid values are 'fade' and 'slide'. - // See AjaxExampleAutoTextfields for an example of 'fade'. - 'effect' => 'slide', - // 'speed' defaults to 'slow'. You can also use 'fast' - // or a number of milliseconds for the animation to last. - // 'speed' => 'slow', - // Don't show any throbber... - 'progress' => ['type' => 'none'], - ], - ]; - - $form['checkboxes_fieldset'] = [ - '#title' => t("Generated Checkboxes"), - // The prefix/suffix provide the div that we're replacing, named by - // #ajax['wrapper'] above. - '#prefix' => '
', - '#suffix' => '
', - '#type' => 'fieldset', - '#description' => $this->t('This is where we get automatically generated checkboxes'), - ]; - - for ($i = 1; $i <= $num_checkboxes; $i++) { - $form['checkboxes_fieldset']["checkbox$i"] = [ - '#type' => 'checkbox', - '#title' => "Checkbox $i", - ]; - } - - $form['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Submit'), - ]; - - return $form; - } - - /** - * {@inheritdoc} - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - } - - /** - * Callback for autocheckboxes. - * - * Callback element needs only select the portion of the form to be updated. - * Since #ajax['callback'] return can be HTML or a renderable array (or an - * array of commands), we can just return a piece of the form. - * See @link examples/ajax-example/advanced-commands for more details - * on AJAX framework commands. - * - * @return array - * Renderable array (the checkboxes fieldset) - */ - public function prompt($form, FormStateInterface $form_state) { - return $form['checkboxes_fieldset']; - } - -} diff --git a/ajax_example/src/Form/AjaxExampleAutocomplete.php b/ajax_example/src/Form/AjaxExampleAutocomplete.php deleted file mode 100644 index 37e3d35..0000000 --- a/ajax_example/src/Form/AjaxExampleAutocomplete.php +++ /dev/null @@ -1,44 +0,0 @@ - '
' . t("This example does a simplest possible autocomplete by username. You'll need a few users on your system for it to make sense.") . '
', - ]; - - $form['user'] = [ - '#type' => 'textfield', - '#title' => t('Choose a user (or a people, depending on your usage preference)'), - // The autocomplete path is provided in routing. - '#autocomplete_path' => 'examples/ajax_example/simple_user_autocomplete_callback', - ]; - - return $form; - } - - /** - * {@inheritdoc} - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - } - -} diff --git a/ajax_example/src/Form/AjaxExampleAutocompleteAuthor.php b/ajax_example/src/Form/AjaxExampleAutocompleteAuthor.php deleted file mode 100644 index bd1bf2e..0000000 --- a/ajax_example/src/Form/AjaxExampleAutocompleteAuthor.php +++ /dev/null @@ -1,157 +0,0 @@ - '
' . t("This example uses a user autocomplete to dynamically change a node title autocomplete using #ajax. - This is a way to get past the fact that we have no other way to provide context to the autocomplete function. - It won't work very well unless you have a few users who have created some content that you can search for.") . '
', - ]; - - $form['author'] = [ - '#type' => 'textfield', - '#title' => t('Choose the username that authored nodes you are interested in'), - // Since we just need simple user lookup, we can use the simplest function - // of them all, user_autocomplete(). - '#autocomplete_path' => 'user/autocomplete', - '#ajax' => [ - 'callback' => '::ajax_example_node_by_author_ajax_callback', - 'wrapper' => 'autocomplete-by-node-ajax-replace', - ], - ]; - - // This form element with autocomplete will be replaced by #ajax whenever - // the author changes, allowing the search to be limited by user. - $form['node'] = [ - '#type' => 'textfield', - '#title' => t('Choose a node by title'), - '#prefix' => '
', - '#suffix' => '
', - '#disabled' => TRUE, - ]; - - // When the author changes in the author field, we'll change the - // autocomplete_path to match. - if (!empty($form_state['values']['author'])) { - $author = user_load_by_name($form_state['values']['author']); - if (!empty($author)) { - $autocomplete_path = 'examples/ajax_example/node_by_author_autocomplete/' . $author->uid; - $form['node']['#autocomplete_path'] = $autocomplete_path; - $form['node']['#title'] = t('Choose a node title authored by %author', ['%author' => $author->name]); - $form['node']['#disabled'] = FALSE; - } - } - - $form['actions'] = [ - '#type' => 'actions', - ]; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => t('Submit'), - ]; - - return $form; - } - - /** - * {@inheritdoc} - */ - public function validateForm(array &$form, FormStateInterface $form_state) { - $title = $form_state['values']['node']; - $author = $form_state['values']['author']; - $matches = []; - - // We must have a valid user. - $account = user_load_by_name($author); - if (empty($account)) { - $form_state->setErrorByName($form['author'], t('You must choose a valid author username')); - return; - } - // This preg_match() looks for the last pattern like [33334] and if found - // extracts the numeric portion. - $result = preg_match('/\[([0-9]+)\]$/', $title, $matches); - if ($result > 0) { - // If $result is nonzero, we found a match and can use it as the index - // into $matches. - $nid = $matches[$result]; - // Verify that it's a valid nid. - $node = Node::load($nid); - if (empty($node)) { - $form_state->setErrorByName($form['node'], t('Sorry, no node with nid %nid can be found', ['%nid' => $nid])); - return; - } - // BUT: Not everybody will have javascript turned on, or they might hit - // ESC and not use the autocomplete values offered. In that case, we can - // attempt to come up with a useful value. This is not absolutely - // necessary, and we *could* just emit a form_error() as below. Here we'll - // find the *first* matching title and assume that is adequate. - else { - $db = Database::getConnection(); - $nid = $db->select('node') - ->fields('node', ['nid']) - ->condition('uid', $account->uid) - ->condition('title', $db->escapeLike($title) . '%', 'LIKE') - ->range(0, 1) - ->execute() - ->fetchField(); - } - - // Now, if we somehow found a nid, assign it to the node. If we failed, - // emit an error. - if (!empty($nid)) { - $form_state->setValue('node', $nid); - } - else { - $form_state->setErrorByName($form['node'], t('Sorry, no node starting with %title can be found', ['%title' => $title])); - } - - } - } - - /** - * AJAX callback for author form element. - */ - public function ajax_example_node_by_author_ajax_callback($form, $form_state) { - return $form['node']; - } - - /** - * {@inheritdoc} - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - $node = Node::load($form_state->getValue('node')); - $account = User::load($node->uid); - drupal_set_message(t('You found node %nid with title !title_link, authored by !user_link', - [ - '%nid' => $node->nid, - '!title_link' => l($node->title, 'node/' . $node->nid), - '!user_link' => theme('username', ['account' => $account]), - ] - )); - } - -} diff --git a/ajax_example/src/Form/AjaxExampleNodeFormAlter.php b/ajax_example/src/Form/AjaxExampleNodeFormAlter.php deleted file mode 100644 index 1d8e25d..0000000 --- a/ajax_example/src/Form/AjaxExampleNodeFormAlter.php +++ /dev/null @@ -1,159 +0,0 @@ -connection = $connection; - } - - /** - * {@inheritdoc} - */ - public function getFormId() { - return 'ajax_example_modeformalter'; - } - - /** - * {@inheritdoc} - */ - public function buildForm(array $form, FormStateInterface $form_state) { - $node = $form['#node']; - $form['ajax_example_1'] = [ - '#type' => 'checkbox', - '#title' => t('AJAX Example 1'), - '#description' => t('Enable to show second field.'), - '#default_value' => $node->ajax_example['example_1'], - '#ajax' => [ - 'callback' => '::ajax_example_form_node_callback', - 'wrapper' => 'ajax-example-form-node', - 'effect' => 'fade', - ], - ]; - $form['container'] = [ - '#prefix' => '
', - '#suffix' => '
', - ]; - - // If the state values exist and 'ajax_example_1' state value is 1 or - // if the state values don't exist and 'example1' variable is 1 then - // display the ajax_example_2 field. - if (!empty($form_state->getValue('ajax_example_1')) && $form_state->getValue('ajax_example_1') == 1 - || empty($form_state->getValue()) && $node->ajax_example['example_1']) { - - $form['container']['ajax_example_2'] = [ - '#type' => 'textfield', - '#title' => t('AJAX Example 2'), - '#description' => t('AJAX Example 2'), - '#default_value' => empty($form_state->getValue('ajax_example_2')) ? $node->ajax_example['example_2'] : $form_state->getValue('ajax_example_2'), - ]; - } - } - - /** - * Callback of ajax. - */ - public function ajax_example_form_node_callback($form, $form_state) { - return $form['container']; - } - - /** - * - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - $values = $form_state->getValue(); - // Move the new data into the node object. - $node->ajax_example['example_1'] = $values['ajax_example_1']; - // Depending on the state of ajax_example_1; it may not exist. - $node->ajax_example['example_2'] = isset($values['ajax_example_2']) ? $values['ajax_example_2'] : ''; - } - - /** - * - */ - public function ajax_example_node_prepare($node) { - if (empty($node->ajax_example)) { - // Set default values, since this only runs when adding a new node. - $node->ajax_example['example_1'] = 0; - $node->ajax_example['example_2'] = ''; - } - } - - /** - * Implements hook_node_load(). - * - * @see ajax_example_form_node_form_alter() - */ - public function ajax_example_node_load($nodes, $types) { - $result = $this->connection->query('SELECT * FROM {ajax_example_node_form_alter} WHERE nid IN(:nids)', [':nids' => array_keys($nodes)])->fetchAllAssoc('nid'); - - foreach ($nodes as &$node) { - $node->ajax_example['example_1'] - = isset($result[$node->nid]->example_1) ? - $result[$node->nid]->example_1 : 0; - $node->ajax_example['example_2'] - = isset($result[$node->nid]->example_2) ? - $result[$node->nid]->example_2 : ''; - } - } - - /** - * Implements hook_node_insert(). - * - * @see ajax_example_form_node_form_alter() - */ - public function ajax_example_node_insert($node) { - if (isset($node->ajax_example)) { - $this->connection->insert('ajax_example_node_form_alter') - ->fields([ - 'nid' => $node->nid, - 'example_1' => $node->ajax_example['example_1'], - 'example_2' => $node->ajax_example['example_2'], - ]) - ->execute(); - } - } - - /** - * Implements hook_node_update(). - * - * @see ajax_example_form_node_form_alter() - */ - public function ajax_example_node_update($node) { - if ($this->connection->select('ajax_example_node_form_alter', 'a')->fields('a')->condition('nid', $node->nid, '=')->execute()->fetchAssoc()) { - $this->connection->update('ajax_example_node_form_alter') - ->fields([ - 'example_1' => $node->ajax_example['example_1'], - 'example_2' => $node->ajax_example['example_2'], - ]) - ->condition('nid', $node->nid) - ->execute(); - } - else { - // Cleaner than doing it again. - ajax_example_node_insert($node); - } - } - - /** - * Implements hook_node_delete(). - * - * @see ajax_example_form_node_form_alter() - */ - public function ajax_example_node_delete($node) { - $this->connection->delete('ajax_example_node_form_alter') - ->condition('nid', $node->nid) - ->execute(); - } - -} diff --git a/ajax_example/src/Form/AjaxExampleProgressBar.php b/ajax_example/src/Form/AjaxExampleProgressBar.php deleted file mode 100644 index 8bdd599..0000000 --- a/ajax_example/src/Form/AjaxExampleProgressBar.php +++ /dev/null @@ -1,90 +0,0 @@ -getRequestTime(); - // We make a DIV which the progress bar can occupy. You can see this in use - // in ajax_example_progressbar_callback(). - $form['status'] = [ - '#title' => $this->t("progress-status"), - ]; - - $form['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Submit'), - '#ajax' => [ - // Here we set up our AJAX callback handler. - 'callback' => '::prompt', - // Tell FormAPI about our progress bar. - 'progress' => [ - 'type' => 'bar', - 'message' => $this->t('Execute..'), - // Have the progress bar access this URL path. - 'url' => Url::fromUri('internal:/examples/ajax_example/progressbar/progress/' . $form['time']), - // The time interval for the progress bar to check for updates. - 'interval' => 1000, - ], - ], - ]; - - return $form; - - } - - /** - * Our submit handler. - * - * This handler spends some time changing a variable and sleeping, and then - * finally returns a form element which marks the #progress-status DIV as - * completed. - * - * While this is occurring, ajax_example_progressbar_progress() will be called - * a number of times by the client-sid JavaScript, which will poll the - * variable being set here. - * - * @see \Drupal\ajax_example\Controller\AjaxExampleController::progressbarProgress - */ - public function prompt(array $form, FormStateInterface $form_state) { - $variable_name = 'example_progressbar_' . $form['time']; - $response = new AjaxResponse(); - $config = \Drupal::config('ajaxexample.settings'); - $config->set($variable_name, 10)->save(); - sleep(2); - $config->set($variable_name, 40)->save(); - sleep(2); - $config->set($variable_name, 70)->save(); - sleep(2); - $config->set($variable_name, 90)->save(); - sleep(2); - $response->addCommand(new HtmlCommand('#progress-status', $this->t('Executed.'))); - return $response; - } - - /** - * {@inheritdoc} - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - } - -} diff --git a/ajax_example/src/Form/AjaxExampleUniqueComplete.php b/ajax_example/src/Form/AjaxExampleUniqueComplete.php deleted file mode 100644 index 4ca6b8f..0000000 --- a/ajax_example/src/Form/AjaxExampleUniqueComplete.php +++ /dev/null @@ -1,108 +0,0 @@ - '
' . t("This example does a node autocomplete by title. The difference between this and a username autocomplete is that the node title may not be unique, so we have to use the nid for uniqueness, placing it in a parseable location in the textfield.") . '
', - ]; - - $form['node'] = [ - '#type' => 'textfield', - '#title' => $this->t('Choose a node by title'), - // The autocomplete path is provided in hook_menu in ajax_example.module. - '#autocomplete_path' => 'examples/ajax_example/unique_node_autocomplete_callback', - ]; - - $form['actions'] = [ - '#type' => 'actions', - ]; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Submit'), - ]; - - return $form; - } - - /** - * {@inheritdoc} - */ - public function validateForm(array &$form, FormStateInterface $form_state) { - $title = $form_state->getValue('node'); - $matches = []; - - // This preg_match() looks for the last pattern like [33334] and if found - // extracts the numeric portion. - $result = preg_match('/\[([0-9]+)\]$/', $title, $matches); - if ($result > 0) { - // If $result is nonzero, we found a match and can use it as the index - // into $matches. - $nid = $matches[$result]; - // Verify that it's a valid nid. - $node = Node::load($nid); - if (empty($node)) { - $form_state->setErrorByName($form['node'], t('Sorry, no node with nid %nid can be found', ['%nid' => $nid])); - return; - } - } - // BUT: Not everybody will have javascript turned on, or they might hit ESC - // and not use the autocomplete values offered. In that case, we can attempt - // to come up with a useful value. This is not absolutely necessary, and we - // *could* just emit a form_error() as below. - else { - $db = Database::getConnection(); - $nid = $db->select('node') - ->fields('node', ['nid']) - ->condition('title', $db->escapeLike($title) . '%', 'LIKE') - ->range(0, 1) - ->execute() - ->fetchField(); - } - - // Now, if we somehow found a nid, assign it to the node. If we failed, emit - // an error. - if (!empty($nid)) { - $form_state->setValue('node', $nid); - } - else { - $form_state->setErrorByName($form['node'], $this->t('Sorry, no node starting with %title can be found', ['%title' => $title])); - } - - } - - /** - * {@inheritdoc} - */ - public function submitForm(array &$form, FormStateInterface $form_state) { - $node = Node::load($form_state->getValue(['values', 'node'])); - drupal_set_message($this->t('You found node %nid with title %title', ['%nid' => $node->nid, '%title' => $node->title])); - } - -} diff --git a/ajax_example/src/Form/AjaxExampleAutotextfields.php b/ajax_example/src/Form/Autotextfields.php similarity index 97% rename from ajax_example/src/Form/AjaxExampleAutotextfields.php rename to ajax_example/src/Form/Autotextfields.php index d83a1e7..207ade4 100644 --- a/ajax_example/src/Form/AjaxExampleAutotextfields.php +++ b/ajax_example/src/Form/Autotextfields.php @@ -8,7 +8,7 @@ use Drupal\Core\Form\FormStateInterface; /** * Show/hide textfields based on AJAX-enabled checkbox clicks. */ -class AjaxExampleAutotextfields extends FormBase { +class Autotextfields extends FormBase { /** * {@inheritdoc} diff --git a/ajax_example/src/Form/AjaxExampleDependentDropdown.php b/ajax_example/src/Form/DependentDropdown.php similarity index 73% rename from ajax_example/src/Form/AjaxExampleDependentDropdown.php rename to ajax_example/src/Form/DependentDropdown.php index c2c9260..964f145 100644 --- a/ajax_example/src/Form/AjaxExampleDependentDropdown.php +++ b/ajax_example/src/Form/DependentDropdown.php @@ -8,7 +8,7 @@ use Drupal\Core\Form\FormStateInterface; /** * Repopulate a dropdown based on form state. */ -class AjaxExampleDependentDropdown extends FormBase { +class DependentDropdown extends FormBase { /** * {@inheritdoc} @@ -27,7 +27,7 @@ class AjaxExampleDependentDropdown extends FormBase { * are updated. */ public function buildForm(array $form, FormStateInterface $form_state) { - $options_first = _ajax_example_get_first_dropdown_options(); + $options_first = DependentDropdownDegrades::getFirstDropdownOptions(); // If we have a value for the first dropdown from $form_state['values'] we // use this both as the default value for the first dropdown and also as a // parameter to pass to the function that retrieves the options for the @@ -39,15 +39,15 @@ class AjaxExampleDependentDropdown extends FormBase { '#title' => $this->t('Instrument Type'), '#options' => $options_first, '#default_value' => $selected, - // Bind an ajax callback to the change event (which is the default for the - // select form type) of the first dropdown. It will replace the second - // dropdown when rebuilt. + // Bind an ajax callback to the change event (which is the default for the + // select form type) of the first dropdown. It will replace the second + // dropdown when rebuilt. '#ajax' => [ - // When 'event' occurs, Drupal will perform an ajax request in the - // background. Usually the default value is sufficient (eg. change for - // select elements), but valid values include any jQuery event, - // most notably 'mousedown', 'blur', and 'submit'. - // 'event' => 'change',. + // When 'event' occurs, Drupal will perform an ajax request in the + // background. Usually the default value is sufficient (eg. change for + // select elements), but valid values include any jQuery event, + // most notably 'mousedown', 'blur', and 'submit'. + // 'event' => 'change',. 'callback' => '::prompt', 'wrapper' => 'dropdown-second-replace', ], @@ -56,13 +56,13 @@ class AjaxExampleDependentDropdown extends FormBase { $form['dropdown_second'] = [ '#type' => 'select', '#title' => $options_first[$selected] . ' ' . $this->t('Instruments'), - // The entire enclosing div created here gets replaced when dropdown_first - // is changed. + // The entire enclosing div created here gets replaced when dropdown_first + // is changed. '#prefix' => '', - // When the form is rebuilt during ajax processing, the $selected variable - // will now have the new value and so the options will change. - '#options' => _ajax_example_get_second_dropdown_options($selected), + // When the form is rebuilt during ajax processing, the $selected variable + // will now have the new value and so the options will change. + '#options' => DependentDropdownDegrades::getSecondDropdownOptions($selected), '#default_value' => !empty($form_state->getValue('dropdown_second')) ? $form_state->getValue('dropdown_second') : '', ]; $form['submit'] = [ diff --git a/ajax_example/src/Form/AjaxExampleDependentDropdownDegrades.php b/ajax_example/src/Form/DependentDropdownDegrades.php similarity index 75% rename from ajax_example/src/Form/AjaxExampleDependentDropdownDegrades.php rename to ajax_example/src/Form/DependentDropdownDegrades.php index 719354e..9049cc9 100644 --- a/ajax_example/src/Form/AjaxExampleDependentDropdownDegrades.php +++ b/ajax_example/src/Form/DependentDropdownDegrades.php @@ -25,7 +25,7 @@ use Drupal\Core\Form\FormStateInterface; * ways to call this form, one normal ($no_js_use = FALSE) and one simulating * Javascript disabled ($no_js_use = TRUE). */ -class AjaxExampleDependentDropdownDegrades extends FormBase { +class DependentDropdownDegrades extends FormBase { /** * {@inheritdoc} @@ -34,11 +34,84 @@ class AjaxExampleDependentDropdownDegrades extends FormBase { return 'ajax_example_dependentdropdowndegrades'; } + /** + * Helper function to populate the first dropdown. + * + * This would normally be pulling data from the database. + * + * @return array + * Dropdown options. + */ + public static function getFirstDropdownOptions() { + return [ + 'String' => 'String', + 'Woodwind' => 'Woodwind', + 'Brass' => 'Brass', + 'Percussion' => 'Percussion', + ]; + } + + /** + * Helper function to populate the second dropdown. + * + * This would normally be pulling data from the database. + * + * @param string $key + * This will determine which set of options is returned. + * + * @return array + * Dropdown options + */ + public static function getSecondDropdownOptions($key = '') { + switch ($key) { + case 'String': + $options = [ + 'Violin' => 'Violin', + 'Viola' => 'Viola', + 'Cello' => 'Cello', + 'Double Bass' => 'Double Bass', + ]; + break; + + case 'Woodwind': + $options = [ + 'Flute' => 'Flute', + 'Clarinet' => 'Clarinet', + 'Oboe' => 'Oboe', + 'Bassoon' => 'Bassoon', + ]; + break; + + case 'Brass': + $options = [ + 'Trumpet' => 'Trumpet', + 'Trombone' => 'Trombone', + 'French Horn' => 'French Horn', + 'Euphonium' => 'Euphonium', + ]; + break; + + case 'Percussion': + $options = [ + 'Bass Drum' => 'Bass Drum', + 'Timpani' => 'Timpani', + 'Snare Drum' => 'Snare Drum', + 'Tambourine' => 'Tambourine', + ]; + break; + + default: + $options = ['none' => 'none']; + break; + } + return $options; + } + /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $no_js_use = FALSE) { - $options_first = _ajax_example_get_first_dropdown_options(); + $options_first = static::getFirstDropdownOptions(); // If we have a value for the first dropdown from $form_state['values'] we // use this both as the default value for the first dropdown and also as a @@ -99,7 +172,7 @@ class AjaxExampleDependentDropdownDegrades extends FormBase { // When the form is rebuilt during processing (either AJAX or multistep), // the $selected variable will now have the new value and so the options // will change. - '#options' => _ajax_example_get_second_dropdown_options($selected), + '#options' => static::getSecondDropdownOptions($selected), ]; $form['dropdown_second_fieldset']['submit'] = [ '#type' => 'submit', diff --git a/ajax_example/src/Form/AjaxExampleDynamicSectionsDegrades.php b/ajax_example/src/Form/DynamicSectionsDegrades.php similarity index 99% rename from ajax_example/src/Form/AjaxExampleDynamicSectionsDegrades.php rename to ajax_example/src/Form/DynamicSectionsDegrades.php index 607a174..6337468 100644 --- a/ajax_example/src/Form/AjaxExampleDynamicSectionsDegrades.php +++ b/ajax_example/src/Form/DynamicSectionsDegrades.php @@ -20,7 +20,7 @@ use Drupal\Core\Url; * The third $no_js_use argument is strictly for demonstrating operation * without javascript, without making the user/developer turn off javascript. */ -class AjaxExampleDynamicSectionsDegrades extends FormBase { +class DynamicSectionsDegrades extends FormBase { /** * {@inheritdoc} @@ -30,7 +30,7 @@ class AjaxExampleDynamicSectionsDegrades extends FormBase { } /** - * + * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $no_js_use = FALSE) { $url = Url::fromUri('internal:/examples/ajax-example/dynamic-sections-no_js'); diff --git a/ajax_example/src/Form/EntityAutocomplete.php b/ajax_example/src/Form/EntityAutocomplete.php new file mode 100644 index 0000000..53b0162 --- /dev/null +++ b/ajax_example/src/Form/EntityAutocomplete.php @@ -0,0 +1,126 @@ +get('entity_type.manager') + ); + $form->setStringTranslation($container->get('string_translation')); + return $form; + } + + /** + * Constructor. + * + * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager + * The entity type manager service. + */ + public function __construct(EntityTypeManagerInterface $entity_type_manager) { + $this->entityTypeManager = $entity_type_manager; + } + + /** + * {@inheritdoc} + */ + public function getFormId() { + return 'ajax_example_autocomplete_user'; + } + + /** + * {@inheritdoc} + */ + public function buildForm(array $form, FormStateInterface $form_state) { + $form['info'] = [ + '#markup' => '
' . t("This example uses the entity_autocomplete form " + . "element to select users. You'll need a few users on your system for " + . "it to make sense.") . '
', + ]; + + // Here we use the delightful entity_autocomplete form element. It allows us + // to consistently select entities. See https://www.drupal.org/node/2418529. + $form['users'] = [ + // A type of entity_autocomplete lets Drupal know it should autocomplete + // entities. + '#type' => 'entity_autocomplete', + // We can specify entity types to autocomplete. + '#target_type' => 'user', + // Specifying #tags as TRUE allows for multiple selections, separated by + // commas. + '#tags' => TRUE, + '#title' => t('Choose a user. Separate with commas.'), + ]; + + $form['actions'] = [ + '#type' => 'actions', + ]; + $form['actions']['submit'] = [ + '#type' => 'submit', + '#value' => $this->t('Submit'), + ]; + + return $form; + } + + /** + * {@inheritdoc} + * + * Here we validate and signal an error if there are no users selected. + */ + public function validateForm(array &$form, FormStateInterface $form_state) { + $state_users = $form_state->getValue('users'); + if (empty($state_users)) { + $form_state->setErrorByName('users', 'There were no users selected.'); + } + } + + /** + * {@inheritdoc} + * + * On submit, show the user the names of the users they selected. + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $state_users = $form_state->getValue('users'); + $users = []; + foreach ($state_users as $state_user) { + $uid = $state_user['target_id']; + $users[] = $this->entityTypeManager->getStorage('user')->load($uid)->getUsername(); + } + drupal_set_message('These are your users: ' . implode(' ', $users)); + } + +} diff --git a/ajax_example/src/Form/AjaxExampleSimplest.php b/ajax_example/src/Form/Simplest.php similarity index 96% rename from ajax_example/src/Form/AjaxExampleSimplest.php rename to ajax_example/src/Form/Simplest.php index b910fba..659d828 100644 --- a/ajax_example/src/Form/AjaxExampleSimplest.php +++ b/ajax_example/src/Form/Simplest.php @@ -6,9 +6,9 @@ use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; /** - * + * A relatively simple AJAX demonstration form. */ -class AjaxExampleSimplest extends FormBase { +class Simplest extends FormBase { /** * {@inheritdoc} diff --git a/ajax_example/src/Form/AjaxExampleSubmitDriven.php b/ajax_example/src/Form/SubmitDriven.php similarity index 96% rename from ajax_example/src/Form/AjaxExampleSubmitDriven.php rename to ajax_example/src/Form/SubmitDriven.php index f5297d5..c9f042c 100644 --- a/ajax_example/src/Form/AjaxExampleSubmitDriven.php +++ b/ajax_example/src/Form/SubmitDriven.php @@ -8,7 +8,7 @@ use Drupal\Core\Form\FormStateInterface; /** * Submit a form without a page reload. */ -class AjaxExampleSubmitDriven extends FormBase { +class SubmitDriven extends FormBase { /** * {@inheritdoc} diff --git a/ajax_example/src/Form/AjaxExampleWizard.php b/ajax_example/src/Form/Wizard.php similarity index 97% rename from ajax_example/src/Form/AjaxExampleWizard.php rename to ajax_example/src/Form/Wizard.php index c61d2e9..5a41802 100644 --- a/ajax_example/src/Form/AjaxExampleWizard.php +++ b/ajax_example/src/Form/Wizard.php @@ -12,7 +12,7 @@ use Drupal\Core\Ajax\HtmlCommand; /** * AJAX example wizard. */ -class AjaxExampleWizard extends FormBase { +class Wizard extends FormBase { /** * {@inheritdoc} @@ -96,13 +96,13 @@ class AjaxExampleWizard extends FormBase { * * @param array $form * Form API form. - * @param array $form_state + * @param \Drupal\Core\Form\FormStateInterface $form_state * Form API form. * * @return array * Form array. */ - public function prompt($form, $form_state) { + public function prompt(array $form, FormStateInterface $form_state) { return $form; } diff --git a/ajax_example/templates/description.html.twig b/ajax_example/templates/description.html.twig index 37e4d42..308ed68 100644 --- a/ajax_example/templates/description.html.twig +++ b/ajax_example/templates/description.html.twig @@ -5,9 +5,8 @@ Description text for the Ajax Example. #} {% set simple_ajax_example = path('ajax_example.simplest') %} -{% set ajax_generate_checkboxes = path('ajax_example.autocheckboxes') %} {% set ajax_generate_textfields = path('ajax_example.autotextfields') %} -{% set ajax_submit = path('ajax_example.submit-driven-ajax') %} +{% set ajax_submit = path('ajax_example.submit_driven_ajax') %} {% set ajax_dependent_dropdown = path('ajax_example.dependent_dropdown') %} {% set ajax_dependent_dropdown_degrade = path('ajax_example.dependent_dropdown_degrades') %} {% set ajax_dependent_dropdown_nojs = path('ajax_example.dependent_dropdown_degrades_nojava') %} @@ -15,15 +14,11 @@ Description text for the Ajax Example. {% set ajax_dynamic_dropdown_nojs = path('ajax_example.dynamic_sections_nojava') %} {% set ajax_wizard_example = path('ajax_example.wizard') %} {% set ajax_wizard_example_nojs = path('ajax_example.wizardnojs') %} -{% set ajax_addmore = path('ajax_example.addmore') %} -{% set ajax_addmore_nojs = path('ajax_example.addmorenojs') %} -{% set ajax_commands_example = path('ajax_example.advanced') %} {% trans %}

The AJAX example module provides many examples of AJAX including forms, links, and AJAX commands.

Simplest AJAX Example

-

Generate checkboxes

Generate textfields

Submit-driven AJAX

Dependent dropdown

@@ -33,7 +28,4 @@ Description text for the Ajax Example.

Dynamic Sections (with graceful degradation) w/js turned off

AJAX Wizard Example

AJAX Wizard Example w/JS turned off

-

AJAX Add more button

-

Add more button (with graceful degradation) w/JS turned off

-

AJAX framework commands

{% endtrans %} diff --git a/ajax_example/tests/src/Functional/AjaxExampleMenuTest.php b/ajax_example/tests/src/Functional/AjaxExampleMenuTest.php index 09cecd9..ab5b516 100644 --- a/ajax_example/tests/src/Functional/AjaxExampleMenuTest.php +++ b/ajax_example/tests/src/Functional/AjaxExampleMenuTest.php @@ -12,9 +12,6 @@ use Drupal\Tests\BrowserTestBase; * @group examples * * @ingroup ajax_example - * - * @todo Add more tests in - * https://www.drupal.org/project/examples/issues/2925368 */ class AjaxExampleMenuTest extends BrowserTestBase { @@ -23,6 +20,13 @@ class AjaxExampleMenuTest extends BrowserTestBase { */ public static $modules = ['ajax_example']; + /** + * The installation profile to use with this test. + * + * @var string + */ + protected $profile = 'minimal'; + /** * Tests links. */ @@ -34,18 +38,12 @@ class AjaxExampleMenuTest extends BrowserTestBase { $assertion = $this->assertSession(); - // Click all the submit and cancel buttons. - $routes = [ + // Routes with menu links, and their form buttons. + $routes_with_menu_links = [ 'ajax_example.description' => [], 'ajax_example.simplest' => [], - // @todo progress bar example is broken. - // 'ajax_example.progresssbar' => ['Submit'], - // @todo not found - // 'ajax_example.progresssbarProgress' => '', - // @todo not found. - // 'ajax_example.autocheckboxes' => '', + 'ajax_example.ajax_link_render' => [], 'ajax_example.autotextfields' => ['Click Me'], - 'ajax_example.submit-driven-ajax' => ['Submit'], 'ajax_example.dependent_dropdown' => ['Submit'], 'ajax_example.dependent_dropdown_degrades' => ['Choose', 'OK'], 'ajax_example.dependent_dropdown_degrades_nojava' => ['Choose', 'OK'], @@ -53,22 +51,24 @@ class AjaxExampleMenuTest extends BrowserTestBase { 'ajax_example.dynamic_sections_nojava' => ['Choose'], 'ajax_example.wizard' => ['Next step'], 'ajax_example.wizardnojs' => ['Next step'], - // @todo add-more has trouble with num_names. - // 'ajax_example.addmore' => ['Submit'], - // 'ajax_example.addmorenojs' => ['Submit'], - // @todo advanced-commands does not render. - // 'ajax_example.advanced' => ['Submit'], - // @todo ajax-link is broken. - // 'ajax_example.Ajaxlink' => [], - 'ajax_example.Ajaxlinkrender' => [], - 'ajax_example.Ajaxlinkcall' => [], - // @todo simple autocomplete is 403. - // 'ajax_example.AutocompleteSimplest' => [], - // 'ajax_example.AutocompleteSimplestcallback' => [], - 'ajax_example.Autocompletenode' => [], - 'ajax_example.Autocompletenodecallback' => [], + 'ajax_example.autocomplete_user' => ['Submit'], + ]; + + // Ensure the links appear in the tools menu sidebar. + $this->drupalGet(''); + foreach (array_keys($routes_with_menu_links) as $route) { + $assertion->linkByHrefExists(Url::fromRoute($route)->getInternalPath()); + } + + // All our routes with their form buttons. + $routes = [ + 'ajax_example.submit_driven_ajax' => ['Submit'], + 'ajax_example.ajax_link_render' => [], + 'ajax_example.ajax_link_callback' => [], ]; + // Go to all the routes and click all the buttons. + $routes = array_merge($routes_with_menu_links, $routes); foreach ($routes as $route => $buttons) { $path = Url::fromRoute($route); $this->drupalGet($path);