How to call a function in a form from another form? I have 2 forms: distribution_inscription_table_form and distribution_inscription_for_user_form in the same custom module (amap).  

namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionTableForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_table_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    some code...
    $rows = $this-&gt;_listEnrolments();
    some code...
    return $form;
  }
  public function _listEnrolments() {
    some code...
    return $rows;
  }
  public function validateForm(array &amp;$form, FormStateInterface $form_state) {
    some code...
  }
  public function submitForm(array &amp;$form, FormStateInterface $form_state) {
    some code...
  }
}


namespace Drupal\amap\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DistributionInscriptionForUserForm extends FormBase {
  public function getFormId() {
    return 'distribution_inscription_for_user_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $rows = ????_listEnrolments(); &lt;--------
    return $form;
  }
}


As they share a significant part of code; I put this code in a public function _listEnrolments located in the first form.
How can I call this function from the other form?
I created amap.services.yml  

services:
  listenrolments:
    class: Drupal\amap\ListEnrolments
    arguments: []


and ListEnrolments.php  

&lt;?php
namespace Drupal\amap;
class ListEnrolments {
  public function __construct() {
  }
  public function list() {
    some code...
    return $rows;
    }
}


and in my two forms, inserted  

$rows = \Drupal::service('listenrolments')-&gt;list();


at the right place.
And it works!