class OrderCreateForm in Ubercart 8.4
Creates a new order and redirect to its edit screen.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\uc_order\Form\OrderCreateForm
Expanded class hierarchy of OrderCreateForm
1 string reference to 'OrderCreateForm'
- uc_order.routing.yml in uc_order/
uc_order.routing.yml - uc_order/uc_order.routing.yml
File
- uc_order/
src/ Form/ OrderCreateForm.php, line 16
Namespace
Drupal\uc_order\FormView source
class OrderCreateForm extends FormBase {
/**
* The mail manager service.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* Form constructor.
*
* @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The mail manager service.
*/
public function __construct(MailManagerInterface $mail_manager) {
$this->mailManager = $mail_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.mail'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'uc_order_create_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['customer_type'] = [
'#type' => 'radios',
'#options' => [
'search' => $this
->t('Search for an existing customer.'),
'create' => $this
->t('Create a new customer account.'),
'none' => $this
->t('No customer account required.'),
],
'#required' => TRUE,
'#default_value' => 'search',
'#ajax' => [
'callback' => [
$this,
'customerSelect',
],
'wrapper' => 'uc-order-customer',
'progress' => [
'type' => 'throbber',
],
],
];
$form['customer'] = [
'#prefix' => '<div id="uc-order-customer">',
'#suffix' => '</div>',
'#tree' => TRUE,
];
// Create form elements needed for customer search.
// Shown only when the 'Search for an existing customer.' radio is selected.
if (!$form_state
->hasValue('customer_type') || $form_state
->getValue('customer_type') == 'search') {
// Container for customer search fields.
$form['customer'] += [
'#type' => 'fieldset',
'#title' => $this
->t('Customer search'),
'#description' => $this
->t('Enter full or partial information in one or more of the following fields, then press the "Search" button. Search results will match all the provided information.'),
];
// Customer first name.
$form['customer']['first_name'] = [
'#type' => 'textfield',
'#title' => $this
->t('First name'),
'#size' => 24,
'#maxlength' => 32,
];
// Customer last name.
$form['customer']['last_name'] = [
'#type' => 'textfield',
'#title' => $this
->t('Last name'),
'#size' => 24,
'#maxlength' => 32,
];
// Customer e-mail address.
$form['customer']['email'] = [
'#type' => 'email',
'#title' => $this
->t('E-mail'),
'#size' => 24,
'#maxlength' => 96,
];
// Customer username.
$form['customer']['username'] = [
'#type' => 'textfield',
'#title' => $this
->t('Username'),
'#size' => 24,
'#maxlength' => 96,
];
$form['customer']['search'] = [
'#type' => 'button',
'#value' => $this
->t('Search'),
'#limit_validation_errors' => [],
'#submit' => [],
'#ajax' => [
'callback' => [
$this,
'customerSearch',
],
'wrapper' => 'uc-order-customer-results',
'progress' => [
'type' => 'throbber',
],
],
];
$form['customer']['uid'] = [
'#prefix' => '<div id="uc-order-customer-results">',
'#suffix' => '</div>',
];
// Search for existing customer by e-mail address.
if ($form_state
->getValue('customer')) {
$query = \Drupal::database()
->select('users_field_data', 'u')
->distinct();
$query
->leftJoin('uc_orders', 'o', 'u.uid = o.uid');
$query
->fields('u', [
'uid',
'name',
'mail',
])
->fields('o', [
'billing_first_name',
'billing_last_name',
'created',
])
->condition('u.uid', 0, '>')
->condition((new Condition('OR'))
->isNull('o.billing_first_name')
->condition('o.billing_first_name', \Drupal::database()
->escapeLike(trim($form_state
->getValue([
'customer',
'first_name',
]))) . '%', 'LIKE'))
->condition((new Condition('OR'))
->isNull('o.billing_last_name')
->condition('o.billing_last_name', \Drupal::database()
->escapeLike(trim($form_state
->getValue([
'customer',
'last_name',
]))) . '%', 'LIKE'))
->condition((new Condition('OR'))
->condition('o.primary_email', \Drupal::database()
->escapeLike(trim($form_state
->getValue([
'customer',
'email',
]))) . '%', 'LIKE')
->condition('u.mail', \Drupal::database()
->escapeLike(trim($form_state
->getValue([
'customer',
'email',
]))) . '%', 'LIKE'))
->condition('u.name', \Drupal::database()
->escapeLike(trim($form_state
->getValue([
'customer',
'username',
]))) . '%', 'LIKE')
->orderBy('o.created', 'DESC')
->range(0, $limit = 11);
$result = $query
->execute();
$options = [];
foreach ($result as $user) {
$name = '';
if (!empty($user->billing_first_name) && !empty($user->billing_last_name)) {
$name = $user->billing_first_name . ' ' . $user->billing_last_name . ' ';
}
// Options formatted as "First Last <email@example.com> (username)".
$options[$user->uid] = $name . '<' . $user->mail . '>' . ' (' . $user->name . ')';
}
$max = FALSE;
if (count($options) == $limit) {
array_pop($options);
$max = TRUE;
}
if (!empty($options)) {
// Display search results.
$form['customer']['uid'] += [
'#type' => 'radios',
'#title' => $this
->t('Select customer'),
'#description' => $max ? $this
->t('More than @limit results found. Refine your search to find other customers.', [
'@limit' => $limit - 1,
]) : '',
'#options' => $options,
'#default_value' => key($options),
];
}
else {
// No search results found.
$form['customer']['uid'] += [
'#markup' => '<p>' . $this
->t('Search returned no results.') . '</p>',
];
}
}
}
elseif ($form_state
->getValue('customer_type') == 'create') {
// Container for new customer information.
$form['customer'] += [
'#type' => 'fieldset',
'#title' => $this
->t('New customer details'),
];
// Customer e-mail address.
$form['customer']['email'] = [
'#type' => 'email',
'#title' => $this
->t('Customer e-mail address'),
'#size' => 24,
'#maxlength' => 96,
];
// Option to notify customer.
$form['customer']['sendmail'] = [
'#type' => 'checkbox',
'#title' => $this
->t('E-mail account details to customer.'),
];
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Create order'),
];
return $form;
}
/**
* Ajax callback: updates the customer selection fields.
*/
public function customerSelect(array $form, FormStateInterface $form_state) {
return $form['customer'];
}
/**
* Ajax callback: updates the customer search results.
*/
public function customerSearch(array $form, FormStateInterface $form_state) {
return $form['customer']['uid'];
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
switch ($form_state
->getValue('customer_type')) {
case 'search':
if (!$form_state
->hasValue([
'customer',
'uid',
])) {
$form_state
->setErrorByName('customer][uid', $this
->t('Please select a customer.'));
}
break;
case 'create':
$email = trim($form_state
->getValue([
'customer',
'email',
]));
$uid = \Drupal::database()
->query('SELECT uid FROM {users_field_data} WHERE mail LIKE :mail', [
':mail' => $email,
])
->fetchField();
if ($uid) {
$form_state
->setErrorByName('customer][mail', $this
->t('An account already exists for that e-mail.'));
}
break;
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
switch ($form_state
->getValue('customer_type')) {
case 'search':
$uid = $form_state
->getValue([
'customer',
'uid',
]);
break;
case 'create':
// Create new account.
$email = trim($form_state
->getValue([
'customer',
'email',
]));
$fields = [
'name' => uc_store_email_to_username($email),
'mail' => $email,
// @todo Replace the following line with:
// 'pass' => \Drupal::service('password_generator')->generate(),
// when Drupal 9.1 becomes the lowest-supported version of Drupal.
// @see https://www.drupal.org/project/ubercart/issues/3217319
'pass' => user_password(),
'status' => $this
->config('uc_cart.settings')
->get('new_customer_status_active') ? 1 : 0,
];
$account = User::create($fields);
$account
->save();
$uid = $account
->id();
if ($form_state
->getValue([
'customer',
'sendmail',
])) {
// Manually set the password so it appears in the e-mail.
$account->password = $fields['pass'];
$this->mailManager
->mail('user', 'register_admin_created', $email, uc_store_mail_recipient_langcode($email), [
'account' => $account,
], uc_store_email_from());
$this
->messenger()
->addMessage($this
->t('A welcome message has been e-mailed to the new user.'));
}
break;
default:
$uid = 0;
}
$order = Order::create([
'uid' => $uid,
'order_status' => uc_order_state_default('post_checkout'),
]);
$order
->save();
uc_order_comment_save($order
->id(), $this
->currentUser()
->id(), $this
->t('Order created by the administration.'), 'admin');
$form_state
->setRedirect('entity.uc_order.edit_form', [
'uc_order' => $order
->id(),
]);
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
OrderCreateForm:: |
protected | property | The mail manager service. | |
OrderCreateForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
OrderCreateForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
OrderCreateForm:: |
public | function | Ajax callback: updates the customer search results. | |
OrderCreateForm:: |
public | function | Ajax callback: updates the customer selection fields. | |
OrderCreateForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
OrderCreateForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
OrderCreateForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
OrderCreateForm:: |
public | function | Form constructor. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |