USING DRUPAL DIFF COMPONENT IN CUSTOM FORMS

Drupal 8 comes with a Diff component in core. It is mainly used to display configuration changes or content revisions. However, it can be used in other ways as well. 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 'Staging' settings. See \Drupal\Core\Config\ConfigManager::diff for more details.

Recently, I was creating a form where I needed to show the difference between two versions of an entity. The Diff component is designed as a standalone component that can be used to show the difference between two arrays or strings. So why not use that in our 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.

Need a Drupal Expert?

Senior Drupal developer, freelance, specialized in what's hardest: migrations, multilingual sites, SaaS platforms and Stripe integration. I leverage AI to cut delivery times and costs, with expert review on every line of code.

No agency, no middlemen. Direct contact with the one who does the work.