We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Writing custom form elements

Hi, I'm writing a new custom Element to use in Phalcon generated forms. This is my element code:

<?php
  namespace MyNameSpace\MyElementLocation;

  use Phalcon\Forms\Element;

  class Dummy extends Element
  {
    public function render($attributes = null)
    {
      $html = '<pre>' . print_r($attributes, true) . '</pre>';

      return $html;
    }
  }
?>

as you can see, it's only a test. To use it, I wrote this code:

<?php
  // namespace and other init stuff.

  class CustomElementTestForm extends Form
  {
    public function initialize($entity = null, $options = null)
    {
      $this->add(new Dummy('dummy', ['foo' => 'bar']));
    }
  }
?>

the problem is that the $attributes array in the custom element code contains no data, even i've used an array as function parameter in then test code ($html is always equal to '<pre></pre>')... suggestions on what I'm missing?



935
Accepted
answer

I'm guessing you're rendering the form element as follows:

$form = new CustomElementTestForm();
$form->render('dummy-el');

In order to get the default attributes you'll need to use $this->getAttributes() in the render method:

public function render($attributes = null)
{
    $html = '<pre>' . print_r($this->getAttributes(), true) . '</pre>';
    return $html;
}

The $attributes parameter contains attributes passed directly to the render method:

$form = new CustomElementTestForm();
$form->render('dummy-el', ['class' => 'my-class']);

A better solution would be to implement both of these options:

public function render($attributes = null)
{
    if(!$attributes) {
        $attributes = $this->getAttributes();
    }

    $html = '<pre>' . print_r($attributes, true) . '</pre>';

    return $html;
}


1.5k

Your "better solution" works great, thanks! In the meantime, I've uset custom tags to acheive the same result but using custom elements is better for a more consistent project design.