I want to create a custom form similiar to the form from the ban module.

This is my form.

<?php

namespace Drupal\ipnotification\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\ipnotification\Ipnotification;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * IP notification form.
 */
class IpnotificationForm extends FormBase {

  /**
   * @var \Drupal\ipnotification\Ipnotificationp
   */
  protected $ipNotification;

  /**
   * Constructs a new Ipnotification object.
   *
   * @param \Drupal\ipnotification\Ipnotification $ipnotification
   */
  public function __construct(Ipnotification $ipnotification) {
    $this->ipNotification = $ipnotification;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('ipnotification.service')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ipnotification_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $ips = $this->ipNotification->findAllIps();
    $emails = $this->ipNotification->findAllEmails();
    $rowsips = array();
    $headerips = array($this->t('IP addresses to notify.'), $this->t('Operations'));
    $rowsemails = array();
    $headeremails = array($this->t('Emails addresses to notify.'), $this->t('Operations'));
    foreach ($ips as $ip) {
      $row = array();
      $row[] = $ip;
      $links = array();
      $links['delete'] = array(
        'title' => $this->t('Delete'),
        'url' => Url::fromRoute('ipnotification.delete', ['ip' => $ip]),
      );
      $row[] = array(
        'data' => array(
          '#type' => 'operations',
          '#links' => $links,
        ),
      );
      $rowsips[] = $row;
    }

    foreach ($emails as $email) {
      $row = array();
      $row[] = $email;
      $links = array();
      $links['delete'] = array(
        'title' => $this->t('Delete'),
        'url' => Url::fromRoute('ipnotification.delete', ['email' => $email]),
      );
      $row[] = array(
        'data' => array(
          '#type' => 'operations',
          '#links' => $links,
        ),
      );
      $rowsemails[] = $row;
    }

    $form['ip'] = array(
      '#title' => $this->t('IP address'),
      '#type' => 'textfield',
      '#size' => 48,
      '#maxlength' => 40,
      '#defaul_value' => '',
      '#description' => $this->t('Enter IP addresse'),
    );
    $form['email'] = array(
      '#title' => $this->t('Email address'),
      '#type' => 'textfield',
      '#size' => 48,
      '#defaul_value' => '',
      '#description' => $this->t('Enter email address'),
    );
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    );

    $form['ip_to_notify_table'] = array(
      '#type' => 'table',
      '#header' => $headerips,
      '#rows' => $rowsips,
      '#empty' => $this->t('No IP addresses to watch.'),
      '#weight' => 120,
    );

    $form['email_to_notify_table'] = array(
      '#type' => 'table',
      '#header' => $headeremails,
      '#rows' => $rowsemails,
      '#empty' => $this->t('No email addresses to watch.'),
      '#weight' => 120,
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $ip = trim($form_state->getValue('ip'));
    $email = trim($form_state->getValue('email'));
    $this->ipNotification->storeIp($ip);
    $this->ipNotification->storeEmail($email);
    drupal_set_message($this->t('The IP address/es %ip and the email adress/es %email have been saved to watch', array('%ip' => $ip, '%email' => $email)));
  }

}

This is the delete form:

<?php

namespace Drupal\ipnotification\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\ipnotification\Ipnotification;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * IP notification form.
 */
class IpnotificationDelete extends ConfirmFormBase  {

  /**
   * @var string ip.
   */
  protected $ip;

  /**
   * @var string email.
   */
  protected $email;

  /**
   * @var \Drupal\ipnotification\Ipnotificationp
   */
  protected $ipNotification;

  /**
   * Constructs a new Ipnotification object.
   *
   * @param \Drupal\ipnotification\Ipnotification $ipnotification
   */
  public function __construct(Ipnotification $ipnotification) {
    $this->ipNotification = $ipnotification;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('ipnotification.service')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ipnotification_delete_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    if ($this->ip) {
      return $this->t('Are you sure you don\'t want to notify about the behaviour of %ip?', array('%ip' => $this->ip));
    }
    elseif ($this->email) {
      return $this->t('Are you sure you don\'t want to notify about the behaviour of %email?', array('%email' => $this->email));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Delete');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('ipnotification.admin_page');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!in_array($this->ip, $this->ipNotification->findAllIps()) ||
        !in_array($this->email, $this->ipNotification->findAllEmails())) {
      throw new NotFoundHttpException();
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->ip) {
      $this->ipNotification->deleteIP($this->ip);
      $this->logger('user')->notice('Deleted %ip', array('%ip' => $this->ip));
      drupal_set_message($this->t('The IP address %ip was deleted.', array('%ip' => $this->ip)));
    }
    elseif ($this->email) {
      $this->ipNotification->deleteEmail($this->email);
      $this->logger('user')->notice('Deleted %email', array('%email' => $this->email));
      drupal_set_message($this->t('The email address %email was deleted.', array('%email' => $this->email)));
    }
    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}

And this is the routing.yml:

ipnotification.admin_page:
  path: '/admin/config/people/ipnotification/{default_ip}'
  defaults:
    _form: '\Drupal\ipnotification\Form\IpnotificationForm'
    _title: 'IP notification'
    default_ip: ''
  requirements:
    _permission: 'IP notification'

ipnotification.delete:
  path: '/admin/config/people/ipnotification/delete/{ip}'
  defaults:
    _form: '\Drupal\ipnotification\Form\IpnotificationDelete'
    _title: 'Delete IP/Email address'
  requirements:
    _permission: 'IP notification'

Exception: Object of type stdClass cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 449 of core/lib/Drupal/Core/Template/TwigExtension.php).
__TwigTemplate_95f11765bf36ab497483c979b0fab5f4ce748de1c7befb97555a9f4b2529179d->doDisplay(Array, Array) (Line: 382)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 350)
Twig_Template->display(Array) (Line: 361)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/themes/classy/templates/dataset/table.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('table', Array) (Line: 435)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 149)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Comments

Insasse created an issue. See original summary.

Insasse’s picture

Issue summary: View changes
Insasse’s picture

cilefen’s picture

When does the exception happen?

Insasse’s picture

The exception happen when I try to go the admin page.

cilefen’s picture

If it is when the form loads, the issue will be in buildForm(). It seems like one of the variables in your form array is or contains an object that does not have a __toString or a toString method. Put a breakpoint on the $form return and inspect them.

Insasse’s picture

@cliefen thanks for your answer.

I had to change fetchAll() to fetchAssoc() in my SQL statement :) now all is fine.

cilefen’s picture

Component: Bartik theme » render system
Category: Bug report » Support request
Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.