-1

I am trying to store data entered in the drupal custom form in order to display it in next page using session.

For the first time it is running perfectly, but for the second time it contains the same value in session which was entered previously.

After clearing caches (admin/config/development/performance/clear caches) it is working for the first time, retains the same problem.

/**
 * @file
 * Contains \Drupal\resume\Form\PaymentForm.
 */
namespace Drupal\resume\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\SessionManager;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManagerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;


class PaymentForm extends FormBase {

    /**
* @var \Drupal\user\PrivateTempStoreFactory
*/
protected $tempStoreFactory;

/**
* @var \Drupal\Core\Session\SessionManagerInterface
*/
private $sessionManager;

/**
* @var \Drupal\Core\Session\AccountInterface
*/
private $currentUser;

/**
* @var \Drupal\user\PrivateTempStore
*/
protected $store;

public function getFormId() {
    return 'payment_form';
}

public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;

    $this->store = $this->tempStoreFactory->get('mymodule.storename');
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('user.private_tempstore'),
        $container->get('session_manager'),
        $container->get('current_user')
    );
}

  public function buildForm(array $form, FormStateInterface $form_state) {

if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
    $_SESSION['session_started'] = true;
    $this->sessionManager->start();
}


$form['pay_first_name'] = array(
    '#type' => 'textfield',
    '#title' => ('First Name'),
);

$form['pay_last_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
);

$form['address'] = array(
    '#type' => 'textfield',
    '#title' => ('address'),
);


$form['email_id'] = array(
    '#type' => 'textfield',
    '#title' => t('email_id'),
);

$form['actions']['#type'] = 'actions';
$form['actions']['payment_submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('payment'),
  '#button_type' => 'primary',
);
return $form;
}


  public function submitForm(array &$form, FormStateInterface $form_state) {

  $payment_array['first_name'] = $form_state->getValue('pay_first_name');
  $payment_array['last_name'] = $form_state->getValue('pay_last_name');
  $payment_array['line1'] = $form_state->getValue('address');
  $payment_array['email'] = $form_state->getValue('email_id');

  $session = \Drupal::service('user.private_tempstore')->get('resume');
  $session->set('payment_details', $payment_array);
    $form_state->setRedirect('payment_redirect.form');
    return;
  }
}
2
  • Do you clear the session after a successful purchase? Otherwise the data will persist until your session expires (by default approx. 2 weeks). Commented Jul 1, 2017 at 12:34
  • I have tried that too, Even though it is not refreshing. Code : $session = \Drupal::request(); $session->getSession()->clear(); Thanks in advance Commented Jul 1, 2017 at 14:13

1 Answer 1

2

What you store in $session is not a session. A private tempstore is a different kind of storage for large amount of data, too big to have it preloaded in memory.

If you want to store a small amount of data, that does not exceed a few Megabytes, then use a session. You find the session attached to the request object:

$session = \Drupal::request()->getSession();

In a form you can get the session from the injected request stack. Use $session->set() and $session->get() to store:

  public function submitForm(array &$form, FormStateInterface $form_state) {

    $session = $this->getRequest()->getSession();
    $session->set('payment_details', $payment_array);

  }

and retrieve the data:

  public function buildForm(array $form, FormStateInterface $form_state) {

    $session = $this->getRequest()->getSession();
    $payment_array = $session->get('payment_details', []);

    // make sure the form is not cached and this code is run on every request
    $form['#cache']['max-age'] = 0;

  }

You don't need to start the session. This is done by Drupal in the background for each request:

When finishing the response, Drupal checks if there is new session data and then starts a session to store the data (which implies setting a cookie). When the user with the session cookie comes back, then the session is restored from the database and is attached to the request.

More info Drupal 8 and Session Management

17
  • Is there any library should be used for this?? I have tried this but while submitting the from it displays "website encounters an error"... Thanks in advance. Commented Jul 1, 2017 at 14:33
  • No, only the two lines of code, no services or libraries necessary. The request stack is already injected by extending FormBase. The error could be a typo, enable full error messages in /admin/config/development/logging
    – 4uk4
    Commented Jul 1, 2017 at 14:39
  • The website encountered an unexpected error. Please try again later. Error: Call to a member function getCurrentRequest() on null in Drupal\resume\Form\PaymentForm->submitForm() (line 128 of modules/resume/src/Form/PaymentForm.php). Commented Jul 1, 2017 at 15:01
  • Found the problem, the request stack is not set when you run submit. By using getRequest() it should work, see the edit.
    – 4uk4
    Commented Jul 1, 2017 at 15:11
  • Same problem.... Error: Call to a member function getRequest() on null in Drupal\resume\Form\PaymentForm->submitForm() (line 128 of modules/resume/src/Form/PaymentForm.php). Commented Jul 1, 2017 at 15:26

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.