I'm using PHP 7.4 with Drupal 9.4.5.
Hello, i'm new using Drupal programmatically and i'm trying to make a simple form that would allow me to insert an input and tell me if the inserted input exist, if it does, give me the name related to that input.
To make it clearer :
I have an entity called inscription which are people with : name, email and a code.
When entering the code on my form, i want to get the name related to that person.
My problem is, i can't manage to connect the form to my entity, i tried using Storage to do it.
$inscription = \Drupal::entityTypeManager()->getStorage('inscription')->loadByProperties(['code' => $form_state->getValue('code')]);
/** @var \Drupal\Mymodule\InscriptionInterface $inscription */
$inscription = $this->getEntity();
<?php
namespace Drupal\timeline_inscription\Form;
use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\PageCache\ResponsePolicyInterface;
use Drupal\timeline_inscription\InscriptionInterface;
use Drupal\timeline_inscription\Entity\Inscription;
use Drupal\timeline_inscription\InscriptionManager;
/**
* Provides a Mymodule form.
*/
class ControleForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'Mymodule_controle';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['code'] = [
'#type' => 'textfield',
'#title' => $this->t('Controle Check'),
'#required' => TRUE,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (mb_strlen($form_state->getValue('code')) < 12) {
$form_state->setErrorByName('name', $this->t('Code must be at least 12 characters'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// If the code exist in my entity .
if ($form_state->getValue('code') == 'rcA4DEVNc1h9mukP') {
$this->messenger()->addStatus($this->t('This code exist, name related to it :getValue('name') !'));
}
else {
$this->messenger()->addStatus($this->t('This code doesn't exist'));
}
$form_state->setRedirect('timeline_inscription.controle');
}
}
Or perhaps i need to use an EntityForm to do this ? I'm really confused.
Thanks a lot.