1

I am trying to create a custom drupal 8 form, that is going to allow user to enter his/her firstname, lastname and email address, and if the user enters these credentials, will be able to download the file that I will upload to cms. This is how my form looks like right now: enter image description here

namespace Drupal\whitepaper\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

class WhitePaperForm extends FormBase {

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

/**
 * {@inheritdoc}.
 */
   public function buildForm(array $form, FormStateInterface $form_state) {
  $form['iam'] = array(
   '#type' => 'select',
   '#title'=>t('I am:'),
   '#options' => array(
    'dentist' => t('Dentist'),
    'broker' => t('Broker'),
    'engineer' => t('Engineer'),
   ),
   '#required' => TRUE,
  );
  $form['fname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('First Name:'),
   '#required' => TRUE,
  );
  $form['lname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('Last Name:'),
   '#required' => TRUE,
  );
  $form['email'] = array(
   '#type' => 'email',
   '#title' => $this->t('Your .com email address.'),
   '#required' => TRUE,
  );
  $form['show'] = array(
   '#type' => 'submit',
   '#value' => $this->t('Download Whitepaper'),
  );

  return $form;
}


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

  if (strpos($form_state['values']['email'], '.com') === FALSE ) {
    $this->setFormError('email', $form_state, $this->t('This is not a .com email address.'));
  } 
 }

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

  drupal_set_message($this->t('Your email address is @email', array('@email' => $form_state['values']['email'])));
 }
}

Can anyone help with a block of code that if the inputs are valid, when the user click download paper button, will be able to download? I got really stuck and i guess my point of view is not helpful to solve this problem.Thank you advanced.

2 Answers 2

3

you can do this with the $form_state->response($response)

  $response = new BinaryFileResponse($file->getFileUri();
  $form_state->setResponse($response);
-1

You could add a redirect to your form, like:

$form['#redirect'][] = 'path/to/your/file.ext';

In submitForm the form values are valid !

So validateForm has to set errors to prevent the submission of the form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.