commercetools-8.x-1.2-alpha1/modules/commercetools_content/src/Form/ProductSearchForm.php
modules/commercetools_content/src/Form/ProductSearchForm.php
<?php
namespace Drupal\commercetools_content\Form;
use Drupal\commercetools_content\Service\CommercetoolsContentComponents;
use Drupal\Core\Form\BaseFormIdInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Defines a simple product search form for embedding in a block.
*/
class ProductSearchForm extends FormBase implements BaseFormIdInterface {
/**
* {@inheritdoc}
*/
public function getBaseFormId() {
return 'commercetools_content_product_search_form';
}
/**
* {@inheritdoc}
*/
public function getFormId() {
// Try to fix an error with several identical forms on the same page.
// @todo Remove after https://www.drupal.org/project/drupal/issues/2821852
static $index = 0;
return $this->getBaseFormId() . $index++;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
[$productListIndex] = $form_state->getBuildInfo()['args'];
$paramName = CommercetoolsContentComponents::getParamNameByIndex('search', $productListIndex);
$form[$paramName] = [
'#type' => 'textfield',
'#default_value' => $this->getRequest()->query->get($paramName),
'#size' => 15,
'#attributes' => ['placeholder' => t('Product search')],
];
$form['#attributes']['class'][] = 'search-form';
$form['#attributes']['class'][] = 'commercetools-product-search-form';
$form['#attributes']['class'][] = 'commercetools-content-product-search-form';
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => t('Search'),
'#button_type' => 'primary',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$query = $this->getRequest()->query->all();
// Reset page after applying new facets.
unset($query['page']);
[$productListIndex, $targetPage] = $form_state->getBuildInfo()['args'];
$paramName = CommercetoolsContentComponents::getParamNameByIndex('search', $productListIndex);
$query[$paramName] = $form_state->getValue($paramName);
$targetPage ??= Url::fromRoute('<current>');
$targetPage->setOption('query', array_filter($query));
$form_state->setRedirectUrl($targetPage);
}
}
