You are here

class DbtngExampleAddForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/dbtng_example/src/Form/DbtngExampleAddForm.php \Drupal\dbtng_example\Form\DbtngExampleAddForm

Form to add a database entry, with all the interesting fields.

Hierarchy

Expanded class hierarchy of DbtngExampleAddForm

Related topics

1 string reference to 'DbtngExampleAddForm'
dbtng_example.routing.yml in dbtng_example/dbtng_example.routing.yml
dbtng_example/dbtng_example.routing.yml

File

dbtng_example/src/Form/DbtngExampleAddForm.php, line 19

Namespace

Drupal\dbtng_example\Form
View source
class DbtngExampleAddForm implements FormInterface, ContainerInjectionInterface {
  use StringTranslationTrait;
  use MessengerTrait;

  /**
   * Our database repository service.
   *
   * @var \Drupal\dbtng_example\DbtngExampleRepository
   */
  protected $repository;

  /**
   * The current user.
   *
   * We'll need this service in order to check if the user is logged in.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   *
   * We'll use the ContainerInjectionInterface pattern here to inject the
   * current user and also get the string_translation service.
   */
  public static function create(ContainerInterface $container) {
    $form = new static($container
      ->get('dbtng_example.repository'), $container
      ->get('current_user'));

    // The StringTranslationTrait trait manages the string translation service
    // for us. We can inject the service here.
    $form
      ->setStringTranslation($container
      ->get('string_translation'));
    $form
      ->setMessenger($container
      ->get('messenger'));
    return $form;
  }

  /**
   * Construct the new form object.
   */
  public function __construct(DbtngExampleRepository $repository, AccountProxyInterface $current_user) {
    $this->repository = $repository;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'dbtng_add_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];
    $form['message'] = [
      '#markup' => $this
        ->t('Add an entry to the dbtng_example table.'),
    ];
    $form['add'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Add a person entry'),
    ];
    $form['add']['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#size' => 15,
    ];
    $form['add']['surname'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Surname'),
      '#size' => 15,
    ];
    $form['add']['age'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Age'),
      '#size' => 5,
      '#description' => $this
        ->t("Values greater than 127 will cause an exception. Try it - it's a great example why exception handling is needed with DTBNG."),
    ];
    $form['add']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Verify that the user is logged-in.
    if ($this->currentUser
      ->isAnonymous()) {
      $form_state
        ->setError($form['add'], $this
        ->t('You must be logged in to add values to the database.'));
    }

    // Confirm that age is numeric.
    if (!intval($form_state
      ->getValue('age'))) {
      $form_state
        ->setErrorByName('age', $this
        ->t('Age needs to be a number'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Gather the current user so the new record has ownership.
    $account = $this->currentUser;

    // Save the submitted entry.
    $entry = [
      'name' => $form_state
        ->getValue('name'),
      'surname' => $form_state
        ->getValue('surname'),
      'age' => $form_state
        ->getValue('age'),
      'uid' => $account
        ->id(),
    ];
    $return = $this->repository
      ->insert($entry);
    if ($return) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Created entry @entry', [
        '@entry' => print_r($entry, TRUE),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DbtngExampleAddForm::$currentUser protected property The current user.
DbtngExampleAddForm::$repository protected property Our database repository service.
DbtngExampleAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
DbtngExampleAddForm::create public static function We'll use the ContainerInjectionInterface pattern here to inject the current user and also get the string_translation service. Overrides ContainerInjectionInterface::create
DbtngExampleAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DbtngExampleAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DbtngExampleAddForm::validateForm public function Form validation handler. Overrides FormInterface::validateForm
DbtngExampleAddForm::__construct public function Construct the new form object.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.