You are here

protected function RedirectForm::prepareEntity in Redirect 8

Prepares the entity object before the form is built first.

Overrides ContentEntityForm::prepareEntity

File

src/Form/RedirectForm.php, line 19

Class

RedirectForm

Namespace

Drupal\redirect\Form

Code

protected function prepareEntity() {

  /** @var \Drupal\redirect\Entity\Redirect $redirect */
  $redirect = $this->entity;
  if ($redirect
    ->isNew()) {

    // To pass in the query set parameters into GET as follows:
    // source_query[key1]=value1&source_query[key2]=value2
    $source_query = [];
    if ($this
      ->getRequest()
      ->get('source_query')) {
      $source_query = $this
        ->getRequest()
        ->get('source_query');
    }
    $redirect_options = [];
    $redirect_query = [];
    if ($this
      ->getRequest()
      ->get('redirect_options')) {
      $redirect_options = $this
        ->getRequest()
        ->get('redirect_options');
      if (isset($redirect_options['query'])) {
        $redirect_query = $redirect_options['query'];
        unset($redirect_options['query']);
      }
    }
    $source_url = urldecode($this
      ->getRequest()
      ->get('source'));
    if (!empty($source_url)) {
      $redirect
        ->setSource($source_url, $source_query);
    }
    $redirect_url = urldecode($this
      ->getRequest()
      ->get('redirect'));
    if (!empty($redirect_url)) {
      try {
        $redirect
          ->setRedirect($redirect_url, $redirect_query, $redirect_options);
      } catch (MatchingRouteNotFoundException $e) {
        $this
          ->messenger()
          ->addMessage($this
          ->t('Invalid redirect URL %url provided.', [
          '%url' => $redirect_url,
        ]), 'warning');
      }
    }
    $redirect
      ->setLanguage($this
      ->getRequest()
      ->get('language') ? $this
      ->getRequest()
      ->get('language') : Language::LANGCODE_NOT_SPECIFIED);
  }
}