DEV Community

Mahmoud Sayed
Mahmoud Sayed

Posted on

Drupal Seed Data

Seed Data
You use seeding to provide initial values for lookup lists,
for demo purposes, proof of concepts and of course for development.

To modules\custom\my_module\src we add a directory called SeedData. We add a file
called SeedDataGenerator.php to modules\custom\offer\src\SeedData.
The class will for now just create a dummy user.

<?php

namespace Drupal\my_module\SeedData;

use Drupal\user\Entity\User;
use Drush\Drush;

/**
 * SeedDataGenerator.
 *
 * @package Drupal\my_module
 */
class SeedDataGenerator {

  /**
   * Function to create a seed data.
   *
   * @param string $entity
   *   The type of entity that needs to be created.
   *
   * @return null|int
   *   The number of entities created.
   */
  public function generate(string $entity){
    $count = 0;
    switch ($entity) {
      case 'user':
        $count = $this->seedUser();
        break;
    }
    return $count;
  }

  /**
   * @return int
   *   The number of users created.
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  private function seedUser() {
    $count = 0;

    $user = User::create();
    $user->setUsername('testUser');
    $user->setPassword('P@ssw0rd');
    $user->activate();
    $user->enforceIsNew();
    Drush::output()->writeln('<comment>Creating user test</comment>' );
    if ($user->save()) {
      $count++;
    }
    return $count;
  }
}

Enter fullscreen mode Exit fullscreen mode

Proceed with adding a drush command that will trigger the class:
Add custom/my_module/src/Commands/SeedGeneratorCommand.php and configure
further. The final file looks like this:

<?php

namespace Drupal\my_module\Commands;

use Drupal\my_module\SeedData\SeedDataGenerator;
use Drush\Commands\DrushCommands;
use Drush\Drush;

/**
 * Class SeedGeneratorCommand.
 *
 * @package Drupal\my_module\Commands
 */
class SeedGeneratorCommand extends DrushCommands {

  /**
   * Runs the mymoduleCreateSeeds command.
   *
   * @command mymodule-create-seeds
   * @aliases mymodulecs
   * @usage drush mymodule-create-seeds
   * Display 'Seed data created'
   */
  public function mymoduleCreateSeeds():void {
    $seed = new SeedDataGenerator();
    $count = $seed->generate('user');
    Drush::output()->writeln('<info>'. $count . ' user(s) created</info>' );
  }

}

Enter fullscreen mode Exit fullscreen mode

One more thing. Add a file custom/my_module/my_module.services.yml and add:

services:
  offer.commands:
    class: Drupal\offer\Commands\SeedGeneratorCommand
    tags:
      - { name: drush.command }
Enter fullscreen mode Exit fullscreen mode

That’s it! Clear cache and see if our system has registered our command

$drush offer-create-seeds
Enter fullscreen mode Exit fullscreen mode

References:

Top comments (0)