0

I've been working on creating a webform element programmatically. So far, I was able to set its maxlength and input_mask, but not its type. It is supposed to be a textfield. So, the maintainer pointed me to some example documents and I tried to copy it, to no avail. Below is my code to create it.

namespace Drupal\tckn_webform_component\Element;

use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;


/**
 * Provides a 'TCKN' element.
 *
 * @FormElement("tckn_webform_component")
 *  @see \Drupal\Core\Render\Element\FormElement
 *  @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21FormElement.php/class/FormElement
 *  @see \Drupal\Core\Render\Element\RenderElement
 *  @see https://api.drupal.org/api/drupal/namespace/Drupal%21Core%21Render%21Element
 *  @see \Drupal\webform_example_element\Element\WebformExampleElement
 */
class WebformTCKNElement extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#size' => 15,
      '#element_validate' => [
        [$class, 'validateWebformTCKNElement']
      ],
      '#pre_render' => [
        [$class, 'preRenderWebformTCKNElement']
      ],
      '#theme_wrappers' => ['form_element']
      ];
  }

  /**
   * Webform element validation for the TCKN element
   */

  public static function validateWebformTCKNElement(&$element, FormStateInterface $form_state, &$complete_form) {

  }

  /**
   * Prepares a #type 'text' render element for theme_element().
   */
  public static function preRenderWebformTCKNElement(array $element) {
    $element['#attributes']['type'] = 'text';
    Element::setAttributes($element, ['id', 'name', 'value', 'size', 'maxlength', 'placeholder']);
    static::setAttributes($element, ['form-text', 'webform-tckn-element']);
    return $element;
  }
}

What am I missing?

  • Your module is missing a corresponding "Form Element" (Drupal\tckn_webform_element\Element\WebformTCKNElement). cgit.drupalcode.org/tckn_webform_element/tree The Webform module now includes example modules for custom elements and composites. – jrockowitz Jul 31 '17 at 21:22
  • Oddly enough, I didn't need Form Element and it works beautifully. – Kartagis Aug 1 '17 at 3:28
  • @Kartagis, can you please explain how to create webforms programatically. I am stuck in it. I need to create webforms manually with 200+ elements. It would be helpful. – Pupil Nov 9 '17 at 12:06
  • Drupal 7 or Drupal 8? – Kartagis Nov 9 '17 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.