BuyItNowForm.php in Ubercart 8.4
File
uc_product/src/Form/BuyItNowForm.php
View source
<?php
namespace Drupal\uc_product\Form;
use Drupal\Core\Form\BaseFormIdInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
class BuyItNowForm extends FormBase implements BaseFormIdInterface {
protected $nid;
public function __construct($nid) {
$this->nid = $nid;
}
public function getBaseFormId() {
return 'uc_product_buy_it_now_form';
}
public function getFormId() {
return 'uc_product_buy_it_now_form_' . $this->nid;
}
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
$query = $this
->getRequest()->query
->all();
$form['#action'] = Url::fromRoute('<current>')
->setOptions([
'query' => $query,
])
->toString();
$form['nid'] = [
'#type' => 'value',
'#value' => $node
->id(),
];
$form['node'] = [
'#type' => 'value',
'#value' => $node,
];
$form['qty'] = [
'#type' => 'value',
'#value' => 1,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Add to cart'),
];
uc_form_alter($form, $form_state, $this
->getFormId());
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if (!$form_state
->getRedirect()) {
$data = \Drupal::moduleHandler()
->invokeAll('uc_add_to_cart_data', [
$form_state
->getValues(),
]);
$msg = $this
->config('uc_cart.settings')
->get('add_item_msg');
$cart = \Drupal::service('uc_cart.manager')
->get();
$redirect = $cart
->addItem($form_state
->getValue('nid'), $form_state
->getValue('qty'), $data, $msg);
if (isset($redirect)) {
$form_state
->setRedirectUrl($redirect);
}
}
}
}
Classes
Name |
Description |
BuyItNowForm |
Defines a simple form for adding a product to the cart. |