commercetools-8.x-1.2-alpha1/src/Plugin/Block/CommercetoolsCatalogActionBlockBase.php
src/Plugin/Block/CommercetoolsCatalogActionBlockBase.php
<?php
declare(strict_types=1);
namespace Drupal\commercetools\Plugin\Block;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Defines a base block implementation for component blocks.
*/
abstract class CommercetoolsCatalogActionBlockBase extends CommercetoolsCatalogBlockBase {
/**
* {@inheritdoc}
*/
public function getBlockConfigKeys(): array {
$keys = parent::getBlockConfigKeys();
$keys[] = 'target_page';
return $keys;
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state): array {
$form = parent::blockForm($form, $form_state);
if (in_array('target_page', $this->getBlockConfigKeys())) {
$form['target_page'] = [
'#type' => 'textfield',
'#target_type' => 'node',
'#title' => $this->t('Target page'),
'#default_value' => $this->configuration['target_page'] ?? NULL,
'#description' => $this->t('The internal path where the user should be redirected to by the elements of this block. Empty value makes the block apply changes to the current page. If the path is set, the block will redirect users to the configured path, if the current path is different.'),
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function blockValidate($form, FormStateInterface $form_state) {
if (in_array('target_page', $this->getBlockConfigKeys())) {
$targetPage = $form_state->getValue('target_page');
// Skip if empty and not required.
if (!empty($targetPage)) {
try {
$url = Url::fromUserInput($targetPage);
// If you want to check if the resulting URL is valid, you could do:
if (!$url->isRouted() && !$url->isExternal()) {
// Fallback or error if it’s not recognized.
throw new \InvalidArgumentException('Invalid link.');
}
}
catch (\InvalidArgumentException) {
$form_state->setError($form['target_page'], $this->t('Invalid link. Please use an internal path or a valid URL.'));
}
}
}
}
}
