class UserForm in Ubercart 8.4
Creates or edits a file feature for a product.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\uc_file\Form\UserForm
Expanded class hierarchy of UserForm
File
- uc_file/
src/ Form/ UserForm.php, line 16
Namespace
Drupal\uc_file\FormView source
class UserForm extends FormBase {
/**
* The user account.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The datetime.time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* The date.formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Form constructor.
*
* @param \Drupal\Component\Datetime\TimeInterface $time
* The datetime.time service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date.formatter service.
*/
public function __construct(TimeInterface $time, DateFormatterInterface $date_formatter) {
$this->time = $time;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('datetime.time'), $container
->get('date.formatter'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'uc_file_user_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $account = NULL) {
$this->account = $account;
$form['file'] = [
'#type' => 'details',
'#title' => $this
->t('Administration'),
];
// Drop out early if we don't even have any files uploaded.
if (!\Drupal::database()
->queryRange('SELECT 1 FROM {uc_files}', 0, 1)
->fetchField()) {
$form['file']['file_message'] = [
'#prefix' => '<p>',
'#markup' => $this
->t('You must add files at the <a href=":url">Ubercart file download administration page</a> in order to attach them to a user.', [
':url' => Url::fromRoute('uc_file.downloads', [], [
'query' => [
'destination' => 'user/' . $account
->id() . '/edit',
],
])
->toString(),
]),
'#suffix' => '</p>',
];
return $form;
}
// Table displaying current downloadable files and limits.
$form['file']['download']['#theme'] = 'uc_file_hook_user_file_downloads';
$form['file']['download']['file_download']['#tree'] = TRUE;
$form['#attached']['library'][] = 'uc_file/uc_file.scripts';
$form['#attached']['library'][] = 'uc_file/uc_file.styles';
$downloadable_files = [];
$file_downloads = \Drupal::database()
->query('SELECT * FROM {uc_file_users} ufu INNER JOIN {uc_files} uf ON ufu.fid = uf.fid WHERE ufu.uid = :uid ORDER BY uf.filename ASC', [
':uid' => $account
->id(),
]);
$behavior = 0;
foreach ($file_downloads as $file_download) {
// Store a flat array so we can array_diff the ones already allowed when
// building the list of which can be attached.
$downloadable_files[$file_download->fid] = $file_download->filename;
$form['file']['download']['file_download'][$file_download->fid] = [
'fuid' => [
'#type' => 'value',
'#value' => $file_download->fuid,
],
'expiration' => [
'#type' => 'value',
'#value' => $file_download->expiration,
],
'remove' => [
'#type' => 'checkbox',
],
'filename' => [
'#markup' => $file_download->filename,
],
'expires' => [
'#markup' => $file_download->expiration ? $this->dateFormatter
->format($file_download->expiration, 'short') : $this
->t('Never'),
],
'time_polarity' => [
'#type' => 'select',
'#default_value' => '+',
'#options' => [
'+' => '+',
'-' => '-',
],
],
'time_quantity' => [
'#type' => 'textfield',
'#size' => 2,
'#maxlength' => 2,
],
'time_granularity' => [
'#type' => 'select',
'#default_value' => 'day',
'#options' => [
'never' => $this
->t('never'),
'day' => $this
->t('day(s)'),
'week' => $this
->t('week(s)'),
'month' => $this
->t('month(s)'),
'year' => $this
->t('year(s)'),
],
],
'downloads_in' => [
'#markup' => $file_download->accessed,
],
'download_limit' => [
'#type' => 'textfield',
'#maxlength' => 3,
'#size' => 3,
'#default_value' => $file_download->download_limit ? $file_download->download_limit : NULL,
],
'addresses_in' => [
'#markup' => count(unserialize($file_download->addresses)),
],
'address_limit' => [
'#type' => 'textfield',
'#maxlength' => 2,
'#size' => 2,
'#default_value' => $file_download->address_limit ? $file_download->address_limit : NULL,
],
];
// Incrementally add behaviors.
// @todo _uc_file_download_table_behavior($behavior++, $file_download->fid);
$form['#attached']['drupalSettings']['behavior'][$behavior++] = $file_download->fid;
// Store old values for comparing to see if we actually made any changes.
$less_reading =& $form['file']['download']['file_download'][$file_download->fid];
$less_reading['download_limit_old'] = [
'#type' => 'value',
'#value' => $less_reading['download_limit']['#default_value'],
];
$less_reading['address_limit_old'] = [
'#type' => 'value',
'#value' => $less_reading['address_limit']['#default_value'],
];
$less_reading['expiration_old'] = [
'#type' => 'value',
'#value' => $less_reading['expiration']['#value'],
];
}
// Create the list of files able to be attached to this user.
$available_files = [];
$files = \Drupal::database()
->query('SELECT * FROM {uc_files} ORDER BY filename ASC');
foreach ($files as $file) {
if (substr($file->filename, -1) != '/' && substr($file->filename, -1) != '\\') {
$available_files[$file->fid] = $file->filename;
}
}
// Dialog for uploading new files.
$available_files = array_diff($available_files, $downloadable_files);
if (count($available_files)) {
$form['file']['file_add'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#size' => 6,
'#title' => $this
->t('Add file'),
'#description' => [
'#markup' => $this
->t('Select a file to add as a download. Newly added files will inherit the settings at the <a href=":url">Ubercart products settings page</a>.', [
':url' => Url::fromRoute('uc_product.settings')
->toString(),
]),
],
'#options' => $available_files,
'#tree' => TRUE,
];
}
$form['file']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$edit = $form_state
->getValues();
// Determine if any downloads were modified.
if (isset($edit['file_download'])) {
foreach ((array) $edit['file_download'] as $key => $download_modification) {
// We don't care... it's about to be deleted.
if ($download_modification['remove']) {
continue;
}
if ($download_modification['download_limit'] < 0) {
$form_state
->setErrorByName('file_download][' . $key . '][download_limit', $this
->t('A negative download limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
}
if ($download_modification['address_limit'] < 0) {
$form_state
->setErrorByName('file_download][' . $key . '][address_limit', $this
->t('A negative address limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
}
// Some expirations don't need any validation...
if ($download_modification['time_granularity'] == 'never' || !$download_modification['time_quantity']) {
continue;
}
// Either use the current expiration, or if there's none,
// start from right now.
$new_expiration = _uc_file_expiration_date($download_modification, $download_modification['expiration']);
if ($new_expiration <= $this->time
->getRequestTime()) {
$form_state
->setErrorByName('file_download][' . $key . '][time_quantity', $this
->t('The date %date has already occurred.', [
'%date' => $this->dateFormatter
->format($new_expiration, 'short'),
]));
}
if ($download_modification['time_quantity'] < 0) {
$form_state
->setErrorByName('file_download][' . $key . '][time_quantity', $this
->t('A negative expiration quantity does not make sense. Use the polarity control to determine if the time should be added or subtracted.'));
}
}
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$edit = $form_state
->getValues();
// Check out if any downloads were modified.
if (isset($edit['file_download'])) {
foreach ((array) $edit['file_download'] as $fid => $download_modification) {
// Remove this user download?
if ($download_modification['remove']) {
uc_file_remove_user_file_by_id($this->account, $fid);
}
else {
// Calculate the new expiration.
$download_modification['expiration'] = _uc_file_expiration_date($download_modification, $download_modification['expiration']);
// Don't touch anything if everything's the same.
if ($download_modification['download_limit'] == $download_modification['download_limit_old'] && $download_modification['address_limit'] == $download_modification['address_limit_old'] && $download_modification['expiration'] == $download_modification['expiration_old']) {
continue;
}
// Renew. (Explicit overwrite.)
uc_file_user_renew($fid, $this->account, NULL, $download_modification, TRUE);
}
}
}
// Check out if any downloads were added. We pass NULL to file_user_renew,
// because this shouldn't be associated with a random product.
if (isset($edit['file_add'])) {
$file_config = $this
->config('uc_file.settings');
foreach ((array) $edit['file_add'] as $fid => $data) {
$download_modification['download_limit'] = $file_config
->get('download_limit_number');
$download_modification['address_limit'] = $file_config
->get('download_limit_addresses');
$download_modification['expiration'] = _uc_file_expiration_date([
'time_polarity' => '+',
'time_quantity' => $file_config
->get('duration_qty'),
'time_granularity' => $file_config
->get('duration_granularity'),
], $this->time
->getRequestTime());
// Renew. (Explicit overwrite.)
uc_file_user_renew($fid, $this->account, NULL, $download_modification, TRUE);
}
}
}
}
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. | |
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. | |
UserForm:: |
protected | property | The user account. | |
UserForm:: |
protected | property | The date.formatter service. | |
UserForm:: |
protected | property | The datetime.time service. | |
UserForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
UserForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
UserForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
UserForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
UserForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
UserForm:: |
public | function | Form constructor. |