Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Using the Drupal Diff Component in Custom Forms

Parent Feed: 

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.

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

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web