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.

Tags

Have Any Project in Mind?

If you want to do something in Drupal maybe you can hire me.

Either for consulting, development or maintenance of Drupal websites.