Skip to main content

Using the Drupal Diff Component in Custom Forms

Drupal 8 comes with a Diff component in core. It's mainly used for showing changes to configuration or content revisions. However, it can be used in other ways too. Here are some quick steps to show how to use the Diff component in your custom forms or controllers.

by jibran.ijaz /

One way Drupal core uses the Diff component is to show the difference between 'Active' and 'Staged' config. See \Drupal\Core\Config\ConfigManager::diff for more details.

Recently, I was building a form where I had to show the diff between two versions of an entity. The Diff component is designed as a stand-alone component that can be used to show the diff between any two arrays or strings. So why not use that in our own forms?

Here's a quick example:

use Drupal\Component\Diff\Diff;
use Drupal\Core\Serialization\Yaml;

    $diffFormatter = \Drupal::service('diff.formatter');
    $from = explode("\n", Yaml::encode($current->toArray()));
    $to = explode("\n", Yaml::encode($revision->toArray()));
    $diff = new Diff($from, $to);
    $diffFormatter->show_header = FALSE;
    // Add the CSS for the inline diff.
    $form['#attached']['library'][] = 'system/diff';

    $form['diff'] = [
      '#type' => 'table',
      '#attributes' => [
        'class' => ['diff'],
      ],
      '#header' => [
        ['data' => t('From'), 'colspan' => '2'],
        ['data' => t('To'), 'colspan' => '2'],
      ],
      '#rows' => $diffFormatter->format($diff),
    ];

I hope this helps. Let me know how you have used the Diff component in your project in the comments!

Posted by jibran.ijaz
Senior Drupal Developer

Dated