Skip to content

Instantly share code, notes, and snippets.

@featuriz
Created February 1, 2022 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save featuriz/50ab3d2d4af7395015a822372bbddb4e to your computer and use it in GitHub Desktop.
Save featuriz/50ab3d2d4af7395015a822372bbddb4e to your computer and use it in GitHub Desktop.
// Drupal 9 Custom Moduel Form file field with upload, validate and move and save.
<?php
namespace Drupal\careerjobs\Form;
use Drupal\Core\Database\Database;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\file\Entity\File;
class CareerjobsForm extends FormBase {
protected static array $file_ext = ['pdf doc docx'];
protected static int $file_size = 2048000000;
/**
* @inheritDoc
*/
public function getFormId(): string {
return 'careerjobs_form';
}
/**
* @inheritDoc
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['#attributes']['enctype'] = 'multipart/form-data';
/** @var \Drupal\node\Entity\Node $node */
$node = \Drupal::routeMatch()->getParameter('node');
$nid = 0;
if ($node instanceof \Drupal\node\NodeInterface) {
$nid = $node->id();
}
$form['name'] = [
'#title' => t('Name'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('Your name.'),
'#required' => TRUE,
];
$form['email'] = [
'#title' => t('Email Address'),
'#type' => 'email',
'#size' => 25,
'#description' => t('Your email address for us to contact.'),
'#required' => TRUE,
];
$form['phone'] = [
'#title' => t('Contact Number'),
'#type' => 'tel',
'#size' => 25,
'#description' => t('Your contact phone number.'),
'#required' => TRUE,
'#pattern' => '[+]?[1-9][0-9]{9,14}',
];
$form['cover_letter'] = [
'#title' => t('Cover Letter'),
'#type' => 'textarea',
'#maxlength' => 5000,
'#rows' => 5,
'#description' => t('Write something about yourself.'),
'#required' => FALSE,
];
$form['resume_upload'] = [
'#title' => t('Upload your Resume file'),
'#type' => 'managed_file',
'#upload_location' => 'public://careerjobs/resume/',
'#multiple' => FALSE,
'#description' => t('Allowed extensions: pdf doc docx. \\n Filesize <= 2MB'),
'#upload_validators' => [
'file_validate_extensions' => self::$file_ext,
'file_validate_size' => [self::$file_size],
],
'#required' => FALSE,
'#validated' => TRUE,
'#attached' => [
'library' => [],
],
];
$form['terms'] = [
'#type' => 'checkbox',
'#title' => t('By using this form you agree with the storage and handling of your data by this website.'),
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Apply'),
'#attributes' => ['class' => ['btn btn-success']],
];
$form['nid'] = [
'#type' => 'hidden',
'#value' => $nid,
];
return $form;
}
/**
* @inheritDoc
*/
public function validateForm(array &$form, FormStateInterface $form_state):void {
//EMAIL
$terms = $form_state->getValue('terms');
if (!$terms) {
$form_state->setErrorByName('terms', $this->t('You must accept our terms first!'));
}
// NAME
$name_len = strlen($form_state->getValue('name'));
if ($name_len < 3) {
$form_state->setErrorByName('name', $this->t('Name must have at-least 3 characters long.'));
}
elseif ($name_len > 25) {
$form_state->setErrorByName('name', $this->t('Name can\'t be more than 25 characters.'));
}
//EMAIL
$value = $form_state->getValue('email');
if ($value == !\Drupal::service('email.validator')->isValid($value)) {
$form_state->setErrorByName('email', t('The email address %mail is not valid.', ['%mail' => $value]));
}
/** @var \Drupal\node\Entity\Node $node */
$node = \Drupal::routeMatch()->getParameter('node');
// Check if email already is set for this node
$select = Database::getConnection()->select('fz__careerjobs', 'r');
$select->fields('r', ['nid']);
// $select->condition('nid', $node->id());
$select->condition('nid', 1);
$select->condition('mail', $value);
$results = $select->execute();
if (!empty($results->fetchCol())) {
// We found a row with this nid and email.
$form_state->setErrorByName('email', t('The address %mail is already subscribed to this list.', ['%mail' => $value]));
}
// PHONE
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $form_state->getValue('phone'))) {
$form_state->setErrorByName('phone', $this->t('Invalid phone number.'));
}
// COVER_LETTER
$cover_letter_len = strlen($form_state->getValue('cover_letter'));
if ($cover_letter_len != NULL && $cover_letter_len < 10) {
$form_state->setErrorByName('cover_letter', $this->t('Too small, please make it long.'));
}
elseif ($cover_letter_len != NULL && $cover_letter_len > 5000) {
$form_state->setErrorByName('cover_letter', $this->t('Too long, please make it short.'));
}
// FILE => Handled in buildForm itself.
}
/**
* @inheritDoc
*/
public function submitForm(array &$form, FormStateInterface $form_state):void {
// $this->messenger()->addMessage(t('Submit form.'));
$files = $form_state->getValue('resume_upload');
$file = reset($files);
// dpm($file);
$fileName = NULL;
if (!empty($file)) {
$fileName = $this->saveFile($file);
}
try {
// $this->messenger()->addMessage(t('The form is working.'));
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
\Drupal::database()->insert('fz__careerjobs')
->fields([
'name' => $form_state->getValue('name'),
'mail' => $form_state->getValue('email'),
'phone' => $form_state->getValue('phone'),
'cover_letter' => $form_state->getValue('cover_letter'),
'resume' => $fileName,
'nid' => $form_state->getValue('nid'),
'uid' => $user->id(),
'created' => time(),
])
->execute();
$this->messenger()
->addMessage(t('Thankyou for your interest, you are on the list for this job.'));
} catch (\Exception $e) {
$this->messenger()
->addError(t('Error occured while saving your data!'));
}
}
private function saveFile($files) {
try {
$file = File::load(reset($files));
$file->setTemporary();
$ext = pathinfo($file->getFileUri(), PATHINFO_EXTENSION);
$file_name = "CareerJob_" . (new \DateTime())->format("dmYHisv") . '.' . $ext;
$file->setFilename($file_name);
$file->save();
$fx = \Drupal::service('file.repository')
->move($file, 'public://careerjobs/resume/' . $file_name);
return \Drupal::service('file_url_generator')
->generateString($fx->getFileUri());
} catch (EntityStorageException $e) {
$this->messenger()
->addError(t('Error while processing your file on save. Please report us or try again later.'));
}
return NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment