Skip to main content

Drupal 8

Displaying 1 - 9 of 9

Custom controller with JSON response

how to create a custom controller with JSON response in Drupal 8.

this might work on Drupal 9 and 10, but I never tested it on these versions.

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class JsonApiArticlesController
 * @package Drupal\mymodule\Controller
 */
class JsonApiArticlesController {

  /**
   * @return JsonResponse
   */
  public function index() {
    return new JsonResponse([ 'data' => $this->getData(), 'method' => 'GET', 'status'=> 200]);
  }

  /**
   * @return array
   */
  public function getData() {

    $result=[];
    $query = \Drupal::entityQuery('node')
      ->condition('type', 'article')
      ->sort('title', 'DESC');
    $nodes_ids = $query->execute();
    if ($nodes_ids) {
      foreach ($nodes_ids as $node_id) {
        $node = \Drupal\node\Entity\Node::load($node_id);
        $result[] = [
          "id" => $node->id(),
          "title" => $node->getTitle(),
        ];
      }
    }
    return $result;
  }
}
use Symfony\Component\HttpFoundation\JsonResponse;

// if you know the data to send when creating the response
$response = new JsonResponse(['data' => 123]);

// if you don't know the data to send or if you want to customize the encoding options
$response = new JsonResponse();
// ...
// configure any custom encoding options (if needed, it must be called before "setData()")
//$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
$response->setData(['data' => 123]);

// if the data to send is already encoded in JSON
$response = JsonResponse::fromJsonString('{ "data": 123 }');

Display Forms in a Modal Dialog

Display create a node in a modal dialog

By default when creating a node, the save action will redirect the user to another page but if we want to just close the modal dialog and leave the user on the same page we need to tell the form to do that.

For this we are going to alter the form and add an AJAX command letting Drupal know that we want to close the dialog as soon as the node is created.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;

/**
 * Implements hook_form_alter().
 */
function modal_form_example_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = '_modal_form_example_ajax_submit';
  $form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
  // in some cases this was needed:
  // $form['#attached']['library'][] = 'core/jquery.form';
  // $form['#attached']['library'][] = 'core/drupal.ajax';
}

/**
 * Close the Modal and redirect the user to the homepage.
 *
 * @param array $form
 *   The form that will be altered.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   FormState Object.
 */
function _modal_form_example_ajax_submit(array $form, FormStateInterface &$form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $form_state->setResponse($response);
}

Drush: how to Import and Export mySql database

Databases have the urge to grow, in some cases they are so big to manipulate, which means that import and export is imposible with the current tools like cPanel .

The Drush team created a tool which will help us to manipulate the database, which was defined in the settings configuration, regardless its size.

pay attention, most chance that import database will be available to files which ware created by export activity.

Advance Examples Which actually needed

This article is based on the O'Reilly article which is relevant to Drupal7 and some of it for Drupal8, but drupal did a lot of modifications since then, and I believe it's a good place to start with, but still should be modified to Drupal9 and on. from time to time I will fix this article and update it according to the last drupal version, you are all invited to send me remarks and suggestions.

These examples, I believe are most needed for the more advanced Drupal backend developer.

My development strategy recommendations are:

How to Send Mail from Module

Email support can be a very strong drupal capability.
You can create emails according to events, news, etc. with personalization and desired format and template.
In some cases, you need to define the email in a way that it will not appear as spam on the target email server.

Email on general drupal events like creating new articles are covered with the rules module and you don't need to program their email support.