Giter Club home page Giter Club logo

laminas-form's Introduction

laminas-form

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

laminas-form is intended primarily as a bridge between your domain models and the View Layer. It composes a thin layer of objects representing form elements, an InputFilter, and a small number of methods for binding data to and from the form and attached objects.

Installation

Run the following to install this library:

$ composer require laminas/laminas-form

Documentation

Browse the documentation online at https://docs.laminas.dev/laminas-form/

Support

laminas-form's People

Contributors

akrabat avatar bakura10 avatar carnage avatar cgmartin avatar dasprid avatar davidwindell avatar driehle avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar gsteel avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mimmi20 avatar mwillbanks avatar ocramius avatar pine3ree avatar ralphschindler avatar renovate[bot] avatar richardjennings avatar samsonasik avatar sgehrig avatar shreef avatar slamdunk avatar thestanislav avatar thomasweidner avatar weierophinney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laminas-form's Issues

Impossible to disable escaping of select option labels

At this point it seems to be impossible to disable HTML escaping of select option labels. Here is an entry point into the code for the current HEAD in the master branch. There's no difference to the develop branch at this point.

Why is the possibility to disable HTML escaping important, you might ask? It has become quiet common to use unicode emojis and other non alphanumerical characters in the web. This counts also for select option labels. Theoretically it's possible to include these characters directly into the labels without using entities but the problem is that this is often impractical.

In my case I have a dynamic set of FontAwesome icons that I want to include in my option labels. I can assign the FontAwesome font via CSS to the select element and then include the unicode characters in the label, e.g. . Using the FontAwesome font this becomes a retweet icon.

But it would be so much easier just to be able to use the unicode entities as in this post on StackOverflow (link to solution).

Any pros and cons are welcome!


Originally posted by @netbrothers-tr at zendframework/zend-form#183

Feature/number parse option for number form element

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7084
User: @fabiocarneiro
Created On: 2014-12-29T23:31:45Z
Updated At: 2015-03-18T16:40:04Z
Body
Add a NumberParse option to number form element, plus set the default locale to "en" since the html5 number form element always return in this locale.


Comment

User: @Ocramius
Created On: 2014-12-30T00:10:59Z
Updated At: 2014-12-30T00:10:59Z
Body
As usual, asking for tests.


Comment

User: @fabiocarneiro
Created On: 2014-12-30T06:49:22Z
Updated At: 2014-12-30T08:52:11Z
Body
@Ocramius Sorry, forgot to add WIP to the title, i was still working on dat.

Don't know if that will be enough. I thought about creating one test for each NumberFormatter style option, but i'm not sure if this should be tested here.

Also there is no coverage for the lazy load ifs early return in getFilters and getValidators. I don't know how to fix it.


Comment

User: @Ocramius
Created On: 2014-12-30T17:53:53Z
Updated At: 2014-12-30T17:53:53Z
Body
@fabiocarneiro lazy-loading is usually tested with aggressive mocking


Comment

User: @fabiocarneiro
Created On: 2014-12-30T19:31:33Z
Updated At: 2014-12-30T19:44:37Z
Body
@Ocramius, please elaborate, if possible with example. I have no idea what aggressive mocking is.


Comment

User: @Ocramius
Created On: 2014-12-30T19:34:29Z
Updated At: 2014-12-30T19:34:29Z
Body

there is no coverage for the lazy load ifs early return in getFilters and getValidators

This suggests that getFilters and getValidators are not being called unless strictly needed, right? You can eventually mock out those methods and expect them to never be called.

If this is not what you were meaning, then please comment the exact lines of code where you think any lazy loading should happen.


Comment

User: @fabiocarneiro
Created On: 2014-12-30T19:39:53Z
Updated At: 2014-12-30T19:40:52Z
Body
In my coverage report, it is complaining about the lack of coverage in https://github.com/zendframework/zf2/pull/7084/files#diff-05c525e17bf373c935a48e1e7b117c40R102 and https://github.com/zendframework/zf2/pull/7084/files#diff-05c525e17bf373c935a48e1e7b117c40R52
calling the method twice would make the coverage to pass, but that's not a real test, right? to make sure the early return is working propertly there i would have to make sure the filter/validator objects generated in the first call are the same ones returned in the second call.


Comment

User: @Ocramius
Created On: 2014-12-30T19:42:36Z
Updated At: 2014-12-30T19:42:36Z
Body
That doesn't require mocking: a test that asserts that the result of that
operation is the same over multiple calls is enough.

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/

On 30 December 2014 at 20:39, Fábio Carneiro [email protected]
wrote:

In my coverage report, it is complaining about
https://github.com/zendframework/zf2/pull/7084/files#diff-05c525e17bf373c935a48e1e7b117c40R102
and
https://github.com/zendframework/zf2/pull/7084/files#diff-05c525e17bf373c935a48e1e7b117c40R52
calling the method twice would make the coverage to pass, but that's not a
real test, right? to make sure the early return is working propertly there
i would have to make sure the filter/validator objects generated in the
first call are the same ones returned in the second call.


Reply to this email directly or view it on GitHub
zendframework/zendframework#7084 (comment).


Comment

User: @fabiocarneiro
Created On: 2014-12-30T19:47:12Z
Updated At: 2014-12-30T19:47:12Z
Body
Yes @Ocramius, i got that. The problem is "how"? serialize?


Comment

User: @Ocramius
Created On: 2014-12-30T19:53:50Z
Updated At: 2014-12-30T19:53:50Z
Body
assertSame? :-)


Comment

User: @fabiocarneiro
Created On: 2014-12-30T20:02:58Z
Updated At: 2014-12-30T20:29:40Z
Body
$this->assertSame($this->getFilters(), $this->getFilters());
$this->assertSame(serialize($this->getFilters()), serialize($this->getFilters()));
??

EDIT:
nvm, i read the assertSame internals, it uses ===

php > var_dump([new StdClass, new StdClass] == [new StdClass, new StdClass]); 
bool(true)
php > var_dump([new StdClass, new StdClass] === [new StdClass, new StdClass]);
bool(false)

Comment

User: @weierophinney
Created On: 2015-02-09T22:25:07Z
Updated At: 2015-02-09T22:25:07Z
Body

We are trying to decouple components, whereas this is adding more coupling between them.

True, but Zend\Form is essentially an integration component already, as it has dependencies on Zend\InputFilter (and, by extension, Zend\Filter and Zend\Validator), and, to a degree, Zend\View (as it provides helpers).

That said, we've explicitly not had Zend\InputFilter depend on Zend\I18n, and I'm not understanding why the NumberParse filter is a requirement of the Number element. @fabiocarneiro : is this class unusable without the filter? or just unusable for your use case?

There are other possibilities here:

  • Add a Form subcomponent in the Zend\I18n namespace, and have an i18n-specific extension there.
  • Offer it in a personal library/package

I'm not saying definitively that we won't merge it, but I'd really like to know the use case, and we definitely need to consider the dependency.


Comment

User: @fabiocarneiro
Created On: 2015-02-16T00:27:38Z
Updated At: 2015-02-16T00:27:38Z
Body
@weierophinney :D! In my use case, it made sense to me to have automatically parsed numbers, and the zf2 feature that does that is the NumberParse filter, which belongs to Zend\i18n.

Of course we could rely in php intl directly, but IMHO that's worse than relying in Zend\i18n.

After this PR, i had a talk with @Ocramius on IRC and we both agreed that it would be more inteligent to move this logic to another repo, like the Zend\i18n component, which already has Zend\InputFilter features, but i didn't have more time to work on that since i'm running with company things and then this issue is stuck here.

That said, some time ago I had another issue (which i don't remember exacly what was right now) and i came back in this same dependency from Zend\Form, and then I considered it important again.


Comment

User: @weierophinney
Created On: 2015-03-18T16:40:04Z
Updated At: 2015-03-18T16:40:04Z
Body
I'm removing the 2.4 milestone at this time. Solutions for the short term include, as noted above, creating your own i18n-specific implementation, and wiring it into your project.

Long term, we can touch base again after the repository split, and see if this should belong in the Zend\I18n repo instead.



Originally posted by @GeeH at zendframework/zend-form#96

`Form/Fieldset` dependency on `FormInterface`

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7192
User: @claytondaley
Created On: 2015-02-06T16:14:35Z
Updated At: 2015-11-06T21:02:59Z
Body
I'm trying to build an extensible HTML table generator and want to provide HTML table builders a comparable experience -- infrastructure and syntax -- to form construction. Obviously, I don't need a bunch of the form infrastructure (input filters or validation) so I expected to extend Fieldset instead of Form.

As I worked my way through this possibility, I discovered that the type hint for Fieldset->prepareElement() is actually FormInterface per an inheritance from ElementPrepareAwareInterface. Obviously, any class that extends Fieldset will not meet this requirement. I'm trying to find out if this dependency is really obligatory or if you'd consider a BC-incompatible reduction to FieldsetInterface.

In favor of reducing this requirement to FieldsetInterface:

  • FieldsetInterface is the interface that actually extends ElementPrepareAwareInterface
  • FieldsetInterface is inherited by all forms so this would be transparent to most users
  • Unless I missed something, none of the prepareElement implementations in Zend/Form depend on methods in Form but not in the Fieldset.
  • Makes Fieldset usable in isolation. The only other "Form" dependency is the Form/Factory which is really a common factory -- and appears to be so out of convenience not obligation.

In favor of staying at FormInterface:

  • BC break
  • Custom code may require a method from the FormInterface in their PrepareElement calls.
  • Form and Fieldset share a common Factory so they'd still be "coupled". As mentioned above, this appears to be a matter of convenience not coupling.

Comment

User: @claytondaley
Created On: 2015-02-07T23:22:23Z
Updated At: 2015-02-07T23:22:23Z
Body
Incidentally, get/setFormFactory has similar (possibly worse) issues.

  • The factory needs to be available in Fieldset because it supports factory-backed extension to the fieldset.
  • The methods is defined in FromFactoryAwareInterface which is included in FieldsetInterface and used in Fieldset
  • However, the hint for @returns is Form.

Presumably, the right hint is FieldsetInterface. At minimum, a change to FormInterface would be consistent with a previously accepted change -- #3526.

In the long run (maybe ZF3), it'd be better to clean up names (FormFactoryAwareInterface) and split (but extend) the factories so they're easier to inherit.


Comment

User: @claytondaley
Created On: 2015-03-24T18:08:00Z
Updated At: 2015-03-24T18:08:06Z
Body
closed by #7344


Comment

User: @weierophinney
Created On: 2015-03-28T20:34:00Z
Updated At: 2015-03-28T20:34:00Z
Body
Re-opening; reverted #7344 due to the BC breaks it introduces.



Originally posted by @GeeH at zendframework/zend-form#93

Conditional Elements + Conditional InputFilter Feature request or documentation request if functionality already exists

Given a form that is defined as an array data structure and constructed using the factory and outputting the rendered content using the Form View Helper ... how would one go about adding in conditional elements and their respective Filters and Validators?

Sample:
Regular fieldsets
--> Elements / fieldsets
--> Radio button
------> Option A
------------> Show the conditional fieldset / element(s) for option A.
------> Option B
------------> Show the conditional fieldset / element(s) for option B.


Originally posted by @jackdpeterson at zendframework/zend-form#155

Element::init is called before Element::setOptions when using Zend\Form\Factory but not when using FormElementManager

How can you initialize if you don't have the options?

This is closely related to zendframework/zend-form#138

Code to reproduce the issue

use Zend\Form\Factory;
use Zend\Form\Element;
use Zend\Form\FormElementManager\FormElementManagerV3Polyfill;
use Zend\ServiceManager\ServiceManager;

class MyElement extends Element
{
    public function init()
    {
        echo "init\n";
    }

    public function setOptions($options)
    {
        echo "setOptions\n"
    }
}

// scenario 1, incorrect
// same as calling $this->add() inside a fieldset
$factory = new Factory();
$factory->create([
    'type' => MyElement::class,
    'options' => [
        'my_option' => true
    ]
]);

echo "\n";

// scenario 2, correct
$formElementManager = new FormElementManagerV3Polyfill(new ServiceManager());
$countrySelect = $formElementManager->get(MyElement::class, [
    'my_option' => true
]);

Expected results

setOptions
init

setOptions
init

Actual results

init
setOptions

setOptions
init

Workaround

There are several different workarounds:

  • Don't use Zend\Form\Factory. This means don't use $this->add() in a fieldset. Write factories which initialize elements and fieldsets.
  • Manually call ->init() again on the element after it's been created
  • Implement ElementPrepareAwareInterface instead of InitializableInterface (adds an unused dependency from Element to Fieldset)
  • Apply the 1-line fix to Zend\Form\Factory:
- $element = $this->getFormElementManager()->get($type);
+ $element = $this->getFormElementManager()->get($type, $spec['options'] ?? []);

Proper fix

I don't see a coherent solution which doesn't involve overhauling how stuff works.

If you move towards constructor injection this would break many factories people wrote.

Zend\ServiceManager\Initializer\InitializerInterface does not support passing options. If it did you could move the setOptions() logic to there with little BC break.

(DelgatorFactoryInterface does support passing options but you'd have to register it for every element).


Originally posted by @Erikvv at zendframework/zend-form#221

OpenTag Helper - allow "itemprop", "itemscope" and "itemtype" for microdata as attributes

I tried to add some microdata to my form:

$form->setAttributes([
    'itemprop' => 'potentialAction',
    'itemscope' => 'itemscope',
    'itemtype' => 'http://schema.org/SearchAction'
]);

This does not work, as the specified attributes are not added if I render the form's open tag:

$this->form()->openTag($form);

Any workaround to get this specific attributes working?


Originally posted by @koseduhemak at zendframework/zend-form#179

Error binding with validation group setted

Version 2.6.2 broke for me... In this line https://github.com/zendframework/zend-form/blob/master/src/Form.php#L365 you're looking for $validationGroup[<field>], but I'm using setValidationGroup(field1, field2, field3) or even setValidationGroup(array(field1, field2, field3)), in this case array will be as above:

array(
    0 => 'field1",
    1 => 'field2",
    2 => 'field3",
)

And this will broke the code!


Originally posted by @guilherme-santos at zendframework/zend-form#124

Make form element manager a regular service

This is a bc break but will improve performance.

The form element manager is currently registered as a services listener, which means it can interrogate Module classes for form element service definitions at bootstrap; but this also means that it is instantiated on EVERY page load even when no forms are rendered in that request.

If we make it a regular service it will not be able to register the getFormElementConfig method against a module but will still be able to read form elements from the config. As a regular service it will only be instantiated when it is requested from the service manager.


Originally posted by @carnage at zendframework/zend-form#56

Troublesome attribute value gets cleared silently.

This code in AbstractHelper.php has the effect of silently failing:

        try {
            $escapedAttribute = $escapeAttr($value);
            $strings[] = sprintf('%s="%s"', $escape($key), $escapedAttribute);
        } catch (EscaperException $x) {
            // If an escaper exception happens, escape only the key, and use a blank value.
            $strings[] = sprintf('%s=""', $escape($key));
        }

Some problem with my attribute value was resulting in an exception and thus a blank value, as intended by the above code. I would have much preferred seeing the exception, instead of having to trace it down to this bit of code.


Originally posted by @bitwombat at zendframework/zend-form#236

Custom element factory not called

Hello,

I've followed this guide https://zendframework.github.io/zend-form/advanced/#handling-dependencies but i cant get it work.

module.config.php

<?php
...
    'form_elements' => array(
        'factories' => array(
            \Base\File\FileElement::class => \Base\File\FileElementFactory::class
        )
    ),
...

FileElementFactory

<?php

namespace Base\File;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class FileElementFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config = $container->get('Config');

        $dir = $config['upload']; // Contain "myDir"

        if (!is_dir($dir)) {
            mkdir($dir);
        }

        var_dump('im call');

        return new FileElement($dir);
    }
}

FileElement

<?php
namespace Base\File;

use Zend\InputFilter\InputProviderInterface;

class FileElement extends \Zend\Form\Element\File implements InputProviderInterface
{
    private $dir;

    public function __construct($dir)
    {
        $this->dir = $dir;
    }

    public function getInputSpecification()
    {
        $validators = [
            ['name'    => 'FileUploadFile'],
        ];

        return array(
            'name'       => $this->getName(),
            'required'   => false,
            'validators' => $validators,
            'filters'  => [
                [
                    'name' => 'FileRenameUpload',
                    'options' => [
                        'target'=> $this->dir,
                        'useUploadName'=>false,
                        'useUploadExtension'=>false,
                        'overwrite'=>false,
                        'randomize'=>true
                    ]
                ]
            ],
            'options' => array(
                'label' => 'Fichier',
            ),
            'attributes' => array(
                'id' => 'file',
                'class'=> 'form-control'
            ),
        );
    }
}

Form

<?php
namespace StatementsSuppliers\Form;

use Zend\Form\Form;
use Base\File\FileElement;
use Zend\Stdlib\InitializableInterface;

class StatementsSuppliersForm extends Form implements InitializableInterface
{
    public function init()
    {
        $this->add([
            'type' => FileElement::class,
            'name' => 'filename',
            'options' => array(
                'label' => 'File',
            ),
            'attributes' => array(
                'id' => 'file',
                'class'=> 'form-control'
            )
        ]);
    }
}

Controller

<?php
namespace StatementsSuppliers\Controller;

use StatementsSuppliers\Form\StatementsSuppliersForm;
use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    /**
     * @var StatementsSuppliersForm
     */
    private $statementsSuppliersForm;

    public function __construct(StatementsSuppliersForm $statementsSuppliersForm)
    {
        $this->statementsSuppliersForm = $statementsSuppliersForm;
    }

    public function addAction()
    {
        $this->statementsSuppliersForm->init();

        var_dump($this->statementsSuppliersForm->getElements());exit;
    }
}

Actual output

array(1) {
  ["filename"]=>
  object(Base\File\FileElement)#854 (8) {
    ["dir":"Base\File\FileElement":private]=>
    string(11) "fileelement"
    ["attributes":protected]=>
    array(4) {
      ["type"]=>
      string(4) "file"
      ["name"]=>
      string(8) "filename"
      ["id"]=>
      string(4) "file"
      ["class"]=>
      string(12) "form-control"
    }
    ["label":protected]=>
    string(7) "Fichier"
    ["labelAttributes":protected]=>
    array(0) {
    }
    ["labelOptions":protected]=>
    array(0) {
    }
    ["messages":protected]=>
    array(0) {
    }
    ["options":protected]=>
    array(1) {
      ["label"]=>
      string(7) "Fichier"
    }
    ["value":protected]=>
    NULL
  }
}

Expected output

string(7) "im call"
array(1) {
  ["filename"]=>
  object(Base\File\FileElement)#854 (8) {
    ["dir":"Base\File\FileElement":private]=>
    string(11) "myDir"
    ["attributes":protected]=>
    array(4) {
      ["type"]=>
      string(4) "file"
      ["name"]=>
      string(8) "filename"
      ["id"]=>
      string(4) "file"
      ["class"]=>
      string(12) "form-control"
    }
    ["label":protected]=>
    string(7) "Fichier"
    ["labelAttributes":protected]=>
    array(0) {
    }
    ["labelOptions":protected]=>
    array(0) {
    }
    ["messages":protected]=>
    array(0) {
    }
    ["options":protected]=>
    array(1) {
      ["label"]=>
      string(7) "Fichier"
    }
    ["value":protected]=>
    NULL
  }
}

composer show

zendframework/zend-authentication            2.5.3             provides an API for authentication and includes c...
zendframework/zend-cache                     2.7.2             provides a generic way to cache any data
zendframework/zend-code                      2.6.3             provides facilities to generate arbitrary code us...
zendframework/zend-component-installer       1.1.x-dev 960fc8a Composer plugin for automating component registra...
zendframework/zend-config                    3.1.0             provides a nested object property based user inte...
zendframework/zend-console                   2.6.0
zendframework/zend-debug                     2.5.1
zendframework/zend-developer-tools           1.1.1             Module for developer and debug tools for use with...
zendframework/zend-di                        2.6.1
zendframework/zend-dom                       2.6.0             provides tools for working with DOM documents and...
zendframework/zend-escaper                   2.5.2
zendframework/zend-eventmanager              3.2.0             Trigger and listen to events within a PHP applica...
zendframework/zend-file                      2.7.1
zendframework/zend-filter                    2.7.2             provides a set of commonly needed data filters
zendframework/zend-form                      2.10.2
zendframework/zend-http                      2.6.0             provides an easy interface for performing Hyper-T...
zendframework/zend-hydrator                  2.2.2
zendframework/zend-i18n                      2.7.4
zendframework/zend-inputfilter               2.7.4
zendframework/zend-json                      3.0.0             provides convenience methods for serializing nati...
zendframework/zend-loader                    2.5.1
zendframework/zend-log                       2.9.2             component for general purpose logging
zendframework/zend-mail                      2.8.0             provides generalized functionality to compose and...
zendframework/zend-mime                      2.6.1
zendframework/zend-modulemanager             2.8.0
zendframework/zend-mvc                       3.1.0
zendframework/zend-mvc-i18n                  1.0.0
zendframework/zend-mvc-plugin-flashmessenger 1.0.0
zendframework/zend-mvc-plugin-identity       1.0.0
zendframework/zend-paginator                 2.7.0
zendframework/zend-permissions-acl           2.6.0             provides a lightweight and flexible access contro...
zendframework/zend-router                    3.0.2
zendframework/zend-servicemanager            3.3.0
zendframework/zend-session                   2.8.0             manage and preserve session data, a logical compl...
zendframework/zend-stdlib                    3.1.0
zendframework/zend-test                      3.1.0
zendframework/zend-uri                       2.5.2             a component that aids in manipulating and validat...
zendframework/zend-validator                 2.9.2             provides a set of commonly needed validators
zendframework/zend-view                      2.9.0             provides a system of helpers, output filters, and...
zfcampus/zf-development-mode                 3.1.0             Zend Framework development mode script

Thanks in advance !


Originally posted by @fezfez at zendframework/zend-form#174

Form annotations don't work on PHP 7

I've narrowed the problem down the the Zend-code dependency. I don't know if there is any way we can fix this for PHP 7; perhaps a documentation update warning of this fact. The fix I assume is going to be to upgrade to Zend-code 3 which has PHP 7 support. Turns out even Zend code 3.0.0 isn't sufficient


Originally posted by @carnage at zendframework/zend-form#51

MultiCheckbox custom message for validation not working

I have an issue happening only for a MultiCheckbox Element, with ZF 2.4.9.

In my form, I create two elements : a text field and a MultiCheckbox field, with this code :

$this->add(array(
    'name' => 'name',
    'type' => 'Text'
));

$value_options = array(
//...
);

$this->add(array(
    'type' => 'Zend\Form\Element\MultiCheckbox',
    'name' => 'equipments',
    'options' => array(
        'value_options' => $value_options,
    )
));

Then, I had the following filter validators :

$this->add(array(
    'name' => 'name',
    'required' => true,
    'validators' => array(
        array(
            'name' => 'Zend\Validator\NotEmpty',
            'options' => array(
               'messages' => array(
                   \Zend\Validator\NotEmpty::IS_EMPTY => 'Please set a name.',
                )
            )
        ),
    ),
));

$this->add(array(
    'name' => 'equipments',
    'required' => true,
    'validators' => array(
        array(
           'name' => 'Zend\Validator\NotEmpty',
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Please select at least one equipment.',
                )
            )
        )
    ),
));

In the end, if I submit my form with no value in any field, two error messages are displayed : Please set a name, which is the good one for name, but for equipments, the default error message is displaying : Value is required and can't be empty.

There must be a problem somewhere when choosing to display the message.


Originally posted by @chougron at zendframework/zend-form#177

Cannot add element label attributes via factory

Issue

When I try to add a form element to a form using an array configuration, I cannot add the label attributes via the configuration even despite the base element supporting that method.

E.g.

$form = new Form();
$form->add([
    'type' => Element\Select::class,
    'name' => 'option',
    'options' => [
        'label' => 'Option'
    ],
    'attributes' => [
        'class' => 'form__control'
    ],
    'label_attributes' => [
        'class' => 'form__labell'
    ]
]);

Solution

Under the configureElement method in Laminas\Form\Factory, add the additional lines:-

        $label_attributes = isset($spec['label_attributes']) ? $spec['label_attributes'] : null;

        ...

        if (is_array($label_attributes) || $label_attributes instanceof Traversable || $label_attributes instanceof ArrayAccess) {
            $element->setLabelAttributes($label_attributes);
        }

Annotations: Use Annotation to build Fieldset don't preserve Validator/filter

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7686
User: @gregGit
Created On: 2016-03-14T13:33:17Z
Updated At: 2016-03-15T00:15:27Z
Body
I'm using Form Annotation in a project with DoctrineORM 2.0. So i wan't to have all my fields specifications in my entities including the Validator/Filter for each element.
When i need to use an entity, i first build a form (without annotation) and add to this blank form a fieldset representing an entity which i build with annotation. By this way i can more than one entities fieldset on the same form (and collection if i need it).
Then i realise there is a pb with this method, because as the entities Form is a fieldset, all validators/filter are loose (they are not applied to the form).

It's not really a bug because input filters applies only to form, not to fieldset. But for me it's logical and pratical to define ZF2 Validator/Filter and entity's column specification (ie a varchar(20) not null column need to have StringLength and Required validator's).

The following simple exemple illustrate the problem :

Using a new skeleton application with doctrine common, i build a very simple class :

<?php

namespace Application\Form;

use Zend\Form\Annotation as Form;
/**
 * @Form\Name("test")
 */
class Test 
{
    /**
     * @var string
     *
     * @Form\Attributes({"type":"text", "required":true})
     * @Form\Options({"label":"Max 5 car field :"})
     * @Form\Required(true)
     * @Form\Filter({"name": "StripTags"})
     * @Form\Filter({"name": "StringTrim"})
     * @Form\Validator({"name":"StringLength", "options":{"encoding" : "UTF-8","min":1, "max":5}})
     */
    private $max5field;

}

Then in Index controller, i add the folowing

public function testAction() {

        $builder = new \Zend\Form\Annotation\AnnotationBuilder();
        $form = $builder->createForm(new \Application\Form\Test());
        $form->setAttribute('method', 'POST');
        $form->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit',
                'value' => 'OK',
                'id' => 'submitbutton',
            ),
        ));

        $result="";
        $request = $this->getRequest();
        if ($request->isPost()) {

           $form->setData($request->getPost());
            if ($form->isValid()) {
                $result="Form is Valid";
            } else {
                $result = print_r($form->getMessages(), true);
            }
        }
        return new ViewModel(array('form'=>$form, 'result'=>$result));
    }

And finally the view test.phtml only contains :

<?php echo $this->form($form);
echo $result;
?>

By this all is ok, validator and filter are applied.

Now i want to use the same in a fieldset, so in controller i build form like this :

        $builder = new \Zend\Form\Annotation\AnnotationBuilder();
        $form=new \Zend\Form\Form();
        $fieldset = $builder->createForm(new \Application\Form\Test());
        $form->add($fieldset);
        ....

With this no validator/filter are applied even if i had the annotation @Form\Type("\Zend\Form\Fieldset")

So if you use annotation to build a fieldset, validator/filter applyed to fieldset elements are ignored.

Regarding to ZF2 FormFactory code it seem to be "normal" because prepareAndInjectInputFilter method is only call in configureForm method.

To be complete, my workaround is to create a new Form Factroy (wich extend Zend/Form/Factory) and redefine configureFieldset like this :

public function configureFieldset(FieldsetInterface $fieldset, $spec)
    {
       $fieldset=parent::configureFieldset($fieldset, $spec);
       $fieldset->input_filter_factory= $spec['input_filter'];
       return $fieldset;
    }

This factory is used by my annotationBuilder (using setFormFactory method)

Then all my Entities Fieldset Classes implement inputFilterProvider and the get method is :

   public function getInputFilterSpecification()
    {
        if (isset($this->input_filter_factory)){
            return $this->input_filter_factory;
        }        
        else {
            return array();
        }
    }

Then it works as i want, Validator/Filter defined in the entity annotation are set in the form using the fieldset.



Originally posted by @GeeH at zendframework/zend-form#87

function prepareBindData creates data in return array when nested fieldset empty

The prepareBindData(...) {...} function creates data in the resulting $data array when a fieldset is prepared, which as a child fieldset.

I used Doctrine, so maybe it was the combination, but it had me stumped for quite a while.

Function in Form.php is as follows:

protected function prepareBindData(array $values, array $match)
{
    $data = [];
    foreach ($values as $name => $value) {
        if (! array_key_exists($name, $match)) {
            continue;
        }
        if (is_array($value) && is_array($match[$name])) {
            $data[$name] = $this->prepareBindData($value, $match[$name]);
        } else {
            $data[$name] = $value;
        }
    }
    return $data;
}

I've updated it to the following:

protected function prepareBindData(array $values, array $match)
{
    $data = [];
    foreach ($values as $name => $value) {
        if (! array_key_exists($name, $match)) {
            continue;
        }

        if (is_array($value) && is_array($match[$name])) {
            if (!empty(array_filter($value))) {
                $data[$name] = $this->prepareBindData($value, $match[$name]);
            }
        } else {
            $data[$name] = $value;
        }
    }
    return $data;
}

Adding the if (!empty(array_filter($value)) { ... } check ensures that the key is not added to the $data array when the $value is completely empty. As it stands, this can happen, and in my situation it did happen. The reason for it to happen is that $value, an array, contains at least 1 other array. This array in turn may not contain any values, but may contain keys. If it has keys, the first array (parent) is added because it's seen as not empty, though it has no values.

In combination with Doctrine 2 it the tries to create a child element, which in my case resulted in database restriction errors, which is never pretty.

P.s. - First bug report. Not sure how to update this to a PR or something similar. Definitely no idea on how to create test cases for this.

P.p.s. - As test data I've included a screenshot of received data. It's from a "Product" form. A Product may have 0 or more "ProductDetail" Entities (so it's a Collection), 0 or more "Price" Entities and may or may not have "Stock". In my situation it always attempted to create a "Stock" Entity. The proposed code change fixes the issue when the form gets validated after receiving the data in the image below.

image


Originally posted by @rkeet at zendframework/zend-form#173

Accessing fieldset and legend for radio buttons

An element's label can get attributes, e.g. class. Theoretically this behavior is also possible for radio buttons. But the setLabelAttributes(['class' => 'my_class']) called on a Zend\Form\Element\Radio object sets the attribute(-s) for the input elements and not for the container-element.

And it's not possible to access the fieldset or the legend element, that are "hard-coded" in the Zend\Form\View\Helper\FormRow. (Also the maintaining of a custom view helper for the 135 rows long FormRow#render(...) is not easy.)

It would be nice to be able to set the fieldset's and legend's attributes of radio buttons / multi_checkbox'es (and generally of all elements, affected by this code).

An example of a situation, when it's need, is makring elements as required using the :before CSS pseudo-class. For text fields it can be managed by setting the class attribute for the label. For radio's an access to the fieldset and/or at least to the legend is needed.


Originally posted by @automatix at zendframework/zend-form#129

problem with form validation

I use a form to validate the input of my json rest api, but an exception occurs when i get a value that is not an array for a fieldset. Here an example:

All fine:
{
"article": {
"id": 1
}
}

All fine:
{
}

Exception in inputfilter
{
"article": null
}

Validationgroup is array("article" => array("id"))

How to allow article to be anything and get a validation error if its not an array with a valid id?


Originally posted by @sneps85 at zendframework/zend-form#44

Documentation around `FormElementManager->get()`

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7305
User: @claytondaley
Created On: 2015-03-10T15:31:30Z
Updated At: 2015-11-06T20:55:08Z
Body
I was using Custom Form elements in my application so I started to work through all the tips in the Advanced Form guide. Despite implementing all of these points, I was still getting an error. Thanks to a reference example, I found that I could resolve my errors with one additional change not documented in the guide:

You must also define the form (not just the custom elements) inside form_elements rather than service_manager otherwise init() is not run

If this is a requirement, it would be helpful to add it to the guide. If this should not be a requirement, I may need to submit a bug report.



Originally posted by @GeeH at zendframework/zend-form#92

isValid() must be called after bind() to populate Collection elements in bound object

The documentation suggests following workflow with a form :

class MyObject {
 public $id;
 public $items = [];
}

class SubObjectFieldset extends Fieldset
{
    public function __construct( $name = null, $options = [] )
    {
        parent::__construct('items');

        $this->setHydrator(new \Zend\Hydrator\ObjectProperty());

        $this->add([
            'name' => 'id',
            'type' => 'hidden',
        ]);

        $this->add([
            'name' => ’title',
            'type' => ’text',
        ]);
    }
}

class ObjectForm extends Form
{
    public function __construct( $name = null, $options = [])
    {
        parent::__construct($name, $options);

        $this->setObject( new Object() );
        $this->setHydrator( new \Zend\Hydrator\ObjectProperty() );

        $this->add([
            'name' => 'id',
            'type' => 'hidden',
        ]);

        $this->add([
            'name' => 'items',
            'type' => 'Zend\Form\Element\Collection',
            'options' => [
                'target_element' => [
                    'type' => SubObjectFieldset::class,
                ]
            ]
        ]);
...
    }
}

$o = $db->getObject();

$f = new MyForm();
$f->bind($o);

$data = $request->getPost();
if ( !$f->setData($data)->isValid() ) {
… do something
}

// at this point it is expected $o has been populated with post $data
// but it doesn’t happen
$db->saveObject($o); 

setData() call updates only MyObject->id, but not MyObject->items, even though $data provides respective values. If workflow is changed as following, then MyObject->items updated as well

$o = $db->getObject();

$f = new MyForm();
$f->bind($o);
$f->isValid(); // <— add validation here

$data = $request->getPost();
if ( !$f->setData($data)->isValid() ) {
… do something
}

// now $o has been populated with received data
$db->saveObject($o);

Originally posted by @isharfme at zendframework/zend-form#137

"ComposedObject" Annotation does not add inputSpec to element configuration

I noticed, that my form was not validating correctly. After some digging in code, I found, that although inputSpec is properly set in ElementAnnotationsListener::handleComposedObjectAnnotation, it gets ignored in AnnotationBuilder::configureElement

So here is what I found was causing it, and how I fixed it (although I am not sure, if that is correct):
AnnotationBulder.php:

    protected function configureElement($annotations, $reflection, $formSpec, $filterSpec)
    {
        // If the element is marked as exclude, return early
        if ($this->checkForExclude($annotations)) {
            return;
        }

        $events = $this->getEventManager();
        $name   = $this->discoverName($annotations, $reflection);

        $elementSpec = new ArrayObject([
            'flags' => [],
            'spec'  => [
                'name' => $name
            ],
        ]);
        $inputSpec = new ArrayObject([
            'name' => $name,
        ]);

        $params = [
            'name'        => $name,
            'elementSpec' => $elementSpec,
            'inputSpec'   => $inputSpec,  // Before the fix, this would not change its vallue
            'formSpec'    => $formSpec,
            'filterSpec'  => $filterSpec,
        ];
        foreach ($annotations as $annotation) {
            $params['annotation'] = $annotation;
// -> This causes ElementAnnotationsListener::handleComposedObjectAnnotation to configure the element
            $events->trigger(__FUNCTION__, $this, $params);
        }
        // Rest of the code is omitted (not relevant)
    }

ElementAnnotationsListener.php:

public function handleComposedObjectAnnotation($e)
    {
        $annotation = $e->getParam('annotation');
        if (!$annotation instanceof ComposedObject) {
            return;
        }

        $class             = $annotation->getComposedObject();
        $annotationManager = $e->getTarget();
        $specification     = $annotationManager->getFormSpecification($class);

        $name        = $e->getParam('name');
        $elementSpec = $e->getParam('elementSpec');

        if ($annotation->isCollection()) {
// Omitted, not relevant
        } else {
            // Compose input filter into parent input filter
            $inputFilter = $specification['input_filter'];
            if (!isset($inputFilter['type'])) {
                $inputFilter['type'] = 'Zend\InputFilter\InputFilter';
            }

// So here is what causes the problem:
// For some reason setting inputSpec like this causes it to be ignored in AnnotationBuilder::configureElement
//            $e->setParam('inputSpec', $inputFilter);
// This seems to work, now the composed object receives the correct inputSpec
            /** @var ArrayObject $inputSpec */
            $inputSpec = $e->getParam('inputSpec');
            $inputSpec->exchangeArray($inputFilter);

            unset($specification['input_filter']);
// Rest of the code is omitted, not relevant
        }
    }

I don't believe that this is expected behavior, because every other aspect of the element configuration can be set in ElementAnnotationsListener::handleComposedObjectAnnotation.


Originally posted by @prendit at zendframework/zend-form#125

Force input type also on attributes in Form\Factory

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7172
User: @Martin-P
Created On: 2015-01-31T00:36:54Z
Updated At: 2015-11-06T20:07:59Z
Body
I think there should be some refactoring of adding elements to Zend\Form, because inputs can be represented by different classes (duplicate code).

$form = new \Zend\Form\Form();
$form->add(array(
    'name' => 'password',
    'type' => 'password',
));

This adds an <input type="password" /> which is represented by an instance of Zend\Form\Element\Password. When rendering it uses view helper Zend\Form\View\Helper\FormPassword.

However this code:

$form = new \Zend\Form\Form();
$form->add(array(
    'name' => 'password',
    'attributes' => array(
        'type' => 'password',
    ),
));

adds an <input type="password" /> which is represented by an instance of Zend\Form\Element. When rendering it uses view helper Zend\Form\View\Helper\FormInput.

Because there are 2 ways to create an <input type="password" /> and 2 different classes and 2 different view helpers are used for each way, whenever there is a bug in a form element it possibly needs fixing in 2 places like in #2613 and #7171.

In Zend\Form\Factory line 108 there is a check for the type key:

 $type = isset($spec['type']) ? $spec['type'] : 'Zend\Form\Element';

Ideally when adding an element to Zend\Form the check should also include checking the attributes array for a type key. With that check an <input type="password" /> will always be represented by an instance of Zend\Form\Element\Password and as a consequence will always be rendered by Zend\Form\View\Helper\FormPassword.

This also applies to all other types of <input />, but to explain the issue I only used <input type="password" /> here.


Comment

User: @jaapio
Created On: 2015-01-31T10:31:32Z
Updated At: 2015-01-31T10:31:32Z
Body
In some cases this could be useful. For example custom elements without a viewhelper could be rendered as a default element. But still have different behavior inside the element class.


Comment

User: @Martin-P
Created On: 2015-01-31T11:43:35Z
Updated At: 2015-01-31T11:43:35Z
Body
I can see the use for Zend\Form\Element, but as far as I can see now it would be better to declare it as an abstract class and only use instances of Zend\Form\Element\* for the predefined elements.



Originally posted by @GeeH at zendframework/zend-form#94

Form label translated two times using view helper form row

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7551
User: @phpManiac77
Created On: 2015-05-25T14:27:23Z
Updated At: 2015-11-06T21:54:22Z
Body
In the method Zend\Form\View\Helper\FormRow::render() lines 129-134 explicit label translation is done.

On line 122 the label helper is obtained (normally an instance of Zend\Form\View\Helper\FormLabel) where label tranlslation is done again with the already translated label value.



Originally posted by @GeeH at zendframework/zend-form#90

Nested forms each with input filter, sub form input filter not added

If you nest forms and the main form uses an input filter then the sub form is completely ignored, no matter if the sub form uses an input filter or not. You have to explicitly add the input filter of the sub form to the main form's input filter.

// main form with one element
$mainForm = new \Zend\Form\Form('mainForm');
$mainElem = new \Zend\Form\Element\Text('mainElem');
$mainForm->add($mainElem);

// sub form with one element
$subForm = new \Zend\Form\Form('subForm');
$subElem = new \Zend\Form\Element\Text('subElem');
$subForm->add($subElem);

$mainForm->add($subForm);

$data = ['mainElem' => 'foo', 'subForm' => ['subElem' => 'foobar']];
$mainForm->setData($data);
if ($mainForm->isValid()) {
    echo '<pre>', var_dump($mainForm->getData()), '</pre>';
}

Output is as expected

array(2) {
    ["mainElem"]=>
  NULL
  ["subForm"]=>
  array(1) {
        ["subElem"]=>
    NULL
  }
}

Now if you add input filter to both forms:

$mainForm->getInputFilter()->add([ 'required' => false ], $mainElem->getName());
// ...
$subForm->getInputFilter()->add([ 'required' => false ], $subElem->getName());

The output is not as expected:

array(1) {
    ["mainElem"]=>
  NULL
}

While this makes sense, because the main form is checked and its input filter does not know anything about the sub form or its input filter. On the other hand this is highly annoying because a working form (sub form) - either with input filter or without - is working standalone but not working while used as a sub form.

Fieldsets are no alternative to build nested forms, because they have no input filter assigned.

Workaround / "Solution":

$mainForm->getInputFilter()->add($subForm->getInputFilter(), $subForm->getName());

I would suggest a better / automatic solution within the add() method of \Zend\Form\Form but I'm not sure if this is a good solution. But maybe someone has a better idea?

(This is not a question, more a feature request) (I'm talking about ZF 2.4.10)

-Cheers


Originally posted by @antiphp at zendframework/zend-form#111

Applying filters to form elements with i18n validators on rendering with form view helpers

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7511
User: @berturion
Created On: 2015-05-11T08:54:59Z
Updated At: 2015-11-06T21:38:46Z
Body
Hello,
I am facing a problem when rendering forms containing existing values that have i18n input filters.

Here is an example with a Float:
1 - I fill a form with a float in french format (comma as decimal separator) and submit it
2 - The form validates the float in french format => OK
3 - I reopen the form to edit the float using FormRow view helper
4 - The float is rendered in english format (dot as decimal separator)
5 - If I submit the form as is, with no modification, the float field get an input validation error because the float has been redered in english format => KO

My question is: Why couldn't we set a 'filters' option in the form element declaration and render it correctly in the FormRow View Helper and others (applying the filters before rendering) like this?

    $this->add(array(
        'name' => 'price',
        'type' => 'text',
        'options' => array(

        ),
        'filters' => array(
            array(
                'name' => 'NumberFormat',
                'locale' => 'fr_FR',
                'style' => \NumberFormatter::DECIMAL
            )
        ),
    ));

In that way, we could render i18n form values in the same way as they should be entered.

What do you think ?

EDIT:

The workaround I found is this:

$price = $form->get('price');
$origValue = $price->getValue();
$price->setValue($this->numberFormat($origValue, \NumberFormatter::DECIMAL, \NumberFormatter::TYPE_DEFAULT, 'fr_FR'));
echo $this->formRow($price);

But I would really want to reduce view scripts and be able to use this simple line:

$this->formRow($form->get($price))


Originally posted by @GeeH at zendframework/zend-form#91

Collection/Fieldset problem after update 2.2.x to 2.5

Hi,

Zend Framework updated to the version 2.5, then came to me mainly problems with collections.
At an earlier version 2.2.x all it worked normally but now I have a problem.

Debugging code form, specifically the data from the form, I found two types of data received.

2.2.x:

'descriptionTabs' => 
    array (size=2)
      0 => 
        array (size=5)
          'id' => int 1
          'name' => string 'raz' (length=3)
          'position' => int 0
          'content' => string '<p>22222222222222222</p>' (length=24)
          '_translation' => 
            array (size=1)
              'en_GB' => 
                array (size=1)

2.5

'descriptionTabs' => 
    array (size=2)
      0 => 
        array (size=5)
          'id' => int 1
          'name' => string 'raz' (length=3)
          'position' => int 0
          'content' => string '<p>22222222222222222</p>' (length=24)

In 2.5 I'dont see a field _translation, but forms on the front look the same field names as well.

Entity use

    /**
     * @Form\Attributes({"data-collection-max-count":5})
     * @ORM\OneToMany(targetEntity="CmsShop\Entity\Product\DescriptionTab", mappedBy="product",cascade={"all"})
     * @ORM\OrderBy({"position" = "ASC"})
     */
    protected $descriptionTabs;

Entity

class DescriptionTab implements Sortable {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string",nullable=false)
     * @Gedmo\Translatable()
     */
    protected $name;

    /**
     * @Gedmo\SortablePosition
     * @ORM\Column(type="integer",nullable=true)
     * @Form\Type("hidden")
     */
    protected $position;

    /**
     * @Form\Type("html")
     * @Gedmo\Translatable()
     * @ORM\Column(type="text", nullable=true)
     */
    protected $content;

Anyone have any idea how to solve it?


Originally posted by @GyniO at zendframework/zend-form#73

Zend\Form\Element\Submit and i18n

The "value" attribute of a \Zend\Form\Element\Submit gets translated twice.

Take for example the code below:

$submit = new \Zend\Form\Element\Submit('Submit', array());
$submit->setAttribute('value', 'Sign in');

At this point, if i render the element, the "Sign in" value will get translated, all good. However, after the POST has been sent, in my controller i prepare to perform the validation:

$data = $this->params()->fromPost();
$form->setData($data);

After calling setData(), the already translated "Sign in" will try to get translated again.

This is generally not an issue, however in my implementation if a \Zend\I18n\Translator\Translator::EVENT_MISSING_TRANSLATION is triggered, the unknown string will be added to the PO language file, which kinda messes it up, because you now have strings from different languages into the same language file.


Originally posted by @adrianilie9 at zendframework/zend-form#113

Moving Collection Count Check to isValid Step.

Would it make sense to remove the thrown DomainException when calling $form->setData() (here, here, and here) and add a validator that will check for this? Returning an accurate error message becomes very ugly when using multiple collections on one form.

From:

try{
    $form->setData($data);

    if($form->isValid()){
        ...
    }else{
        ...
    }
}catch(DomainException $e){
    //If I had multiple collections, I would need to check $data to see which one caused the exception.
    $errors = [
        'myCollection' => [
             'count' => 'Some error message'
        ]
    ];
}

To:

$form->setData($data);

if($form->isValid()){
    ...
}else{
    ...
}

Originally posted by @ghost at zendframework/zend-form#97

Inconsistent input filter while using "preferFormInputFilter" form option

InputFilter merging is inconsistent after #78 (was buggy before). I'll explain it basing on example below:

$factory = new \Zend\Form\Factory;
$form = $factory->createForm([
    'fieldsets' => [
        [
            'spec' => [
                'name' => 'baseFieldset',
                'type' => 'Zend\Form\InputFilterProviderFieldset',
                'elements' => [
                    [
                        'spec' => [
                            'name' => 'select',
                            'type' => 'select',
                            'options' => [
                                'value_options' => [
                                    1 => 'foo',
                                    2 => 'bar'
                                ]
                            ]
                        ],
                    ],
                    [
                        'spec' => [
                            'name' => 'collection',
                            'type' => 'collection',
                            'options' => [
                                'target_element' => [
                                    'type' => 'Zend\Form\InputFilterProviderFieldset',
                                    'elements' => [
                                        [
                                            'spec' => [
                                                'name' => 'select',
                                                'type' => 'select',
                                                'options' => [
                                                    'value_options' => [
                                                        1 => 'foo',
                                                        2 => 'bar'
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ],
                                    'options' => [
                                        'input_filter_spec' => [
                                            'select' => [
                                                'required' => false
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ],
                'options' => [
                    'use_as_base_fieldset' => true,
                    'input_filter_spec' => [
                        'select' => [
                            'required' => false
                        ]
                    ]
                ]
            ]
        ]
    ],
    'options' => [
        'prefer_form_input_filter' => false
    ]
]);
$inputFilter = $form->getInputFilter();
$fieldsetElementInputFilter = $inputFilter->get('baseFieldset')->get('select');
$collectionElementInputFilter = $inputFilter->get('baseFieldset')->get('collection')->getInputFilter()->get('select');
$this->assertCount(1, $fieldsetElementInputFilter->getValidatorChain()->getValidators());
$this->assertCount(1, $collectionElementInputFilter->getValidatorChain()->getValidators());
  1. How it worked before #78
    Case 1
    prefer_form_input_filter => true
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 0
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 0
    Case 2
    prefer_form_input_filter => false
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 1
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 0

  2. How it works after #78 (now)
    Case 1
    prefer_form_input_filter => true
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 0
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 1
    Case 2
    prefer_form_input_filter => false
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 1
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 1

  3. How it should work (my guess, but other behavior will mislead developers)
    Case 1
    prefer_form_input_filter => true
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 0
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 0
    Case 2
    prefer_form_input_filter => false
    sizeof($fieldsetElementInputFilter->getValidatorChain()->getValidators()) === 1
    sizeof($collectionElementInputFilter->getValidatorChain()->getValidators()) === 1

As far as I remember, prefer_form_input_filter was introduced to prevent BC break, but right now we did the same for collections input filter (and this is also BC break).


Originally posted by @coder-pm at zendframework/zend-form#160

Form/Fieldset messy and not interchangeable

Since I did not get any response in the slack channel and couldn't find anything related:

Currently Zend Form and Fieldset seem like a huge mess to me.

In most of our projects we extendes the Form class to make our form generation easier and faster. And since Form extends Fieldset I thought they were kinda exchangeable in terms of nested forms/fieldsets - but as it seems they are not.

Now I tried to compose multiple Forms into a bigger one with collections trying to carve the code out of this doc: https://framework.zend.com/manual/2.4/en/modules/zend.form.collections.html

This didn't work (due to several reasons?). The collection has never been hydrated. After lots and lots of frustration I found out that using Forms inside other Forms (instead of Fieldset inside Form) seemed to be the problem. This is kinda weird for me, since Form extends Fieldset I automatically assumed I could nest Forms in Forms too - but instead of giving me an error it just does not work!

One of the main problems seems to be the difference in bindValues in both.

  1. Why does Form NOT return $this->object; ? Fieldset does
  2. Why does Form not foreach over all it's children like Fieldset does?

Originally posted by @scroach at zendframework/zend-form#192

MultiCheckbox: default input filter prevents submitting with no options checked

See zendframework/zendframework#4694, zendframework/zendframework#2395, https://framework.zend.com/issues/browse/ZF2-571.

The issue remains the same now as it was in 2012: MultiCheckbox extends Checkbox. Checkbox's input filter defaults to required, a more or less sensible setup for an element that by default includes a hidden input so something should always be submitted. MultiCheckbox, sensibly, changes the default to not include the hidden input as it doesn't really make sense for a normal multi-checkbox setup. But, it doesn't override the input filter specification.

The result is that by default, a MultiCheckbox will throw a validation error when submitted with nothing checked.


Originally posted by @zerocrates at zendframework/zend-form#123

formCollection View Helper doesn't render name

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7687
User: @gregGit
Created On: 2016-03-14T16:20:39Z
Updated At: 2016-04-13T07:48:07Z
Body
When using form view helper, the formCollection view helper is used to render fieldset.
But form some reason that i don't understand this view helper doesn't set the name attribute in the fieldset (unset($attributes['name']); in the render Method).
I belive name is a valid html attributes for fieldset i don't understand why ZF2 never render this tag in a fieldset, and it can be usefull to have it in the DOM.

For test create an action like this :

  $fs = new \Zend\Form\Fieldset('my-fieldset');
        $fs->setAttribute('name', 'my-fieldset');
        $fs->add(array(
            'type' => 'text',
            'name' => 'text',
            'options' => array(
                'label' => 'The Text'
            )
        ));

        $fs->add(array(
            'type' => 'text',
            'name' => 'title',
            'options' => array(
                'label' => 'Blog Title'
            )
        ));


        $form=new \Zend\Form\Form('my-form');
        $form->add($fs);
        return new ViewModel(array('form' => $form));

and just " echo $this->form($form)" in the view.

No attribute name for the fieldset is rendered.


Comment

User: @froschdesign
Created On: 2016-04-13T07:48:07Z
Updated At: 2016-04-13T07:48:07Z
Body

I belive name is a valid html attributes for fieldset

It's only allowed in HTML5.



Originally posted by @GeeH at zendframework/zend-form#86

Element removed, InputFilter still validates removed Element

If one uses init() Method to add elements within a Fieldset, they are not completely removable. While the element isn't present in the form anymore, the respective InputFilter (which addresses validation of the previously removed element) still is.
This leads to an invalid form, but no error messages are shown (because the elements which cause the error do not exist and are therefore they are not rendered nor the error messages are).

Wouldn't it be more suitable if an element is removed to remove their InputFilter(Specification) too?
I think we need to modify the isValid-Method in "zend-form/src/Form.php" to skip InputFilters of previously removed elements.
I know we are able to set elements which should be validated via setValidationGroup. If a form has many fieldsets / elements this method is somewhat hackish. Is there any other possible solution to this problem?

My code:

$this->form->get('user')->get('address')->remove('street');
$this->form->get('user')->get('address')->remove('number');
$this->form->get('user')->get('address')->remove('postcode');
$this->form->get('user')->get('address')->remove('city');
$this->form->get('user')->get('address')->remove('additionalField');
$this->form->get('user')->get('address')->remove('phone');
$this->form->get('user')->get('address')->remove('country');

VAR_DUMP if form is invalid (normally we have error messages here):

if ($this->form->isValid()) {
    $this->redirect()->toRoute('successRoute');
} else {
    var_dump($this->form->getMessages());
}

VAR_DUMP is executed but getMessages delivers empty array.

Any clues?


Originally posted by @koseduhemak at zendframework/zend-form#126

FormRow helper doesn't invoke the FormLabel helper anymore

The FormRow helper used to call the __invoke() function of the FormLabel helper in earlier versions of zend-form (e.g. 2.7.0), but not anymore. I noticed this because we override the FormLabel helper with a new __invoke function, which is now ignored.

I think this line of code here should be changed back to

$label = $labelHelper($element);

As it used to be in zend-form 2.7.0. Otherwise, the __invoke() function of the FormLabel helper never gets called.

Or am I missing something here? Is there another way now to override the behavior of the FormLabel helper?


Originally posted by @aimfeld at zendframework/zend-form#165

Issue with disabled Checkbox validation

I have a form with some single checkboxes. These checkboxes may be disabled depending on other settings in the application.
So I want to use disabled checkboxes to indicate that there is a option which is currently not available.

The validation for these disabled checkboxes fails because checkboxes are required (hardcoded) but the hidden elements of the checkboxes are disabled too (so nothing is sent at all and the validation fails).

Do I miss anything? There is no setRequired(false) method for checkboxes...

Checkboxes are hardcoded set to be required here:
https://github.com/zendframework/zend-form/blob/master/src/Element/Checkbox.php#L169

The ViewHelper disables the hidden element too here:
https://github.com/zendframework/zend-form/blob/master/src/View/Helper/FormCheckbox.php#L61

I think one of this two behaviors should be changed. I would prefer to be able to setRequried(false) a Checkbox.


Originally posted by @Cyberrebell at zendframework/zend-form#110

Translate MultiCheckbox error message

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7657
User: @dafap
Created On: 2016-01-05T16:17:35Z
Updated At: 2016-02-13T15:37:21Z
Body
Since 2.4.8 release, the error message of a multicheckbox is not translated for IS_EMPTY error.
It worked with Zend\InputFilter\Input::injectNotEmptyValidator() that is now deprecated.


Comment

User: @marciodojr
Created On: 2016-01-20T20:58:54Z
Updated At: 2016-01-20T20:58:54Z
Body
I tried to translate the validations too (with zf2 pre-translated validation messages) and for me the MultiCheckbox and Radios don't translate IS_EMPTY (Value is required and can't be empty). With all the others fields the IS_EMPTY translation works nicely.



Originally posted by @GeeH at zendframework/zend-form#88

Documentation clarifications (quick-start)

Docs for ZF are so good and so essential for the often newbie-mystifying ZF. So I thought I'd seek a few clarifications to the quick start docs.

Happy to work this out and submit a PR once I understand...

From zend-form/quick-start

Item 1:

The chief benefits to using the Factory are allowing you to store definitions in configuration,
and usage of significant whitespace.

"significant whitespace" as in whitespace is significant (a la Python), or there's a significant amount? Either way, "huh"?

Item 2:

The default Form implementation is backed by the Factory. This allows you to extend it,
and define your form internally. This has the benefit of allowing a mixture of programmatic
and factory-backed creation, as well as defining a form for re-use in your application.

What does it mean in OOP or ZF for something to be 'backed by a Factory'? I know what factories are, and how they're used by ZF managers, but as a layman, I see the phrase "This allows you to extend it" and think "But I can extend any non-final class..."

And, many objects implement something like $this->add(), so how does Form being "backed by a Factory" make any difference here?

I think it is important to discuss some of the internals, as knowledge there can help people from being mystified when they 'new' their form in a controller and don't have any access to the usual managers. But some clarification or more explanation is needed for the above.

Thanks for great docs and I hope the above makes sense.


Originally posted by @bitwombat at zendframework/zend-form#147

Remove Zend\I18n\View\Helper\AbstractTranslatorHelper dependency

This is a follow-on from #32.

You cannot use the view helpers without requiring zend-view. This is because Zend\Form\View\Helper\AbstractHelper extends Zend\I18n\View\Helper\AbstractTranslatorHelper, which in turn extends Zend\View\Helper\AbstractHelper.

I would like to break this dependency. After a quick scan it looks like implementing the setView() / getView() / setTranslator() / getTranslator() methods in the abstract helper would do the trick. Would this be the right approach?


Originally posted by @kynx at zendframework/zend-form#41

DateTime min/max validators are not working when using costum format

given this input definition

        $this->add([
            'type' => DateTime::class,
            'name' => 'dutyDate',
            'options' => [
                'label' => 'duty date',
                'format' => 'd.m.Y H:i'
            ],
            'attributes' => [
                'min' => '01.01.2000 00:00',
                'max' => '31.12.2099 00:00',
            ]
        ]);

when you now enter '2.2.2199 12:43' it is accepted without causing the validator to fail

from what i have seen is that to the GreaterThan and LessThan validator the raw string is passed and compared with the raw string from the input definition. i suggest to fill the validator with real DateTime objects for 'value' and also 'min' and 'max'


Originally posted by @BigMichi1 at zendframework/zend-form#190

Default InputerFilter in Form creates Input, instead of ArrayInput for multi select elements

The default InputFilter of Forms creates always an Input for Elements within the Form. Even, if the Select Element has the multiple attribute. The problem is, when you create an InputFilter and set it to the Form, then the default InputFilter won't be replaced, it will merge Validators and Filters with the new ones. So you're given ArrayInput will be an Input in the form and the validators will fail, because they receive an array as value, but expect a string|number.

Code to reproduce the issue

Just create a Form with a multi select.

Expected results

The default Input for Select with multiple attribute should be ArrayInput.

Actual results

The default Input for Select is always Input.


Originally posted by @eweso at zendframework/zend-form#204

Zend Fieldset translation breaks when using formRow helper before

Hi, in a view, when using $this->formRow on a fieldset element then translation is not working for helper $this->formLabel on another element of the same fieldset.

I'm using zend 2.5.1. My simplified view is like this:

$form->prepare();
$busquedas = $form->get('busquedasFS');
echo $this->form()->openTag($form). "\n\n";
echo $this->formRow($busquedas->get('tipoBusqueda')). "\n";
echo $this->formLabel($busquedas->get('palabrasClaveBusqAvanzada')). ' - '.
$this->formText($busquedas->get('palabrasClaveBusqAvanzada')). "\n";
echo $this->form()->closeTag();

$busquedas is a fieldset. With this code translation is not working for element palabrasClaveBusqAvanzada. But if I change $this->formRow($busquedas->get('tipoBusqueda')) for $this->formHidden($busquedas->get('tipoBusqueda') then translation IS working for palabrasClaveBusqAvanzada.

My translation is defined like this:

return array(
    'service_manager' => array(
        'factories' => array (
                   '...',
                   'translator' => 'Zend\Mvc\Service\TranslatorServiceFactory',
        ),
    ),
    'translator' => array(
        'locale' => 'es_ES',
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
                'text_domain' => 'salesianos_td'
            ),
        ),
    ),

Originally posted by @didgewind at zendframework/zend-form#112

Zend\Form\Element\Select default InArray validation broken

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7586
User: @phpManiac77
Created On: 2015-06-15T16:17:13Z
Updated At: 2015-12-09T20:53:03Z
Body
Default in array validation does not work any more.

In method Zend\Form\Element\Select::setValueOptions() on line 80 $this->validator is checked against ! null. This is always false because $this->validator is nowhere set.


Comment

User: @demichl68
Created On: 2015-12-09T20:53:03Z
Updated At: 2015-12-09T20:53:03Z
Body
As soon as getValidator() is called, $validator is not null anymore.
getValidator() is called when getInputSpecification() is called.



Originally posted by @GeeH at zendframework/zend-form#89

Collection has empty bonded nested objects

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7156
User: @epoleacov
Created On: 2015-01-25T22:22:49Z
Updated At: 2015-10-19T21:10:08Z
Body
When nested object bonded to form with related collection elements, this collection elements has just empty objects.
So for example if we run next test:

ZendTest\Form\Element\CollectionTest::testCanBindObjectMultipleNestedFieldsets()

final object used for assertion should have original data ($_product->getObject()->getPrice() == 200), but it has just NULL instead.

Main cause of that is because when values extracted from collection is just takes extracted values, but forget about objects what was used in extraction which should be saved inside of collection under "object" property, which on his side used later for filling collection target elements on populateValues();

Next is line where values extracted, but objects are lost:
https://github.com/zendframework/zf2/blob/b1e9f3bb3ce9cdc925139d98672af40f6b0f33d7/library/Zend/Form/Element/Collection.php#L528


Comment

User: @iprdp
Created On: 2015-04-20T18:15:00Z
Updated At: 2015-04-20T18:15:00Z
Body
I have worked around this bug by creating the targetElementInstance during extract(). Not sure if this is good enough for a fix.


Comment

User: @adamlundrigan
Created On: 2015-10-19T21:10:08Z
Updated At: 2015-10-19T21:10:08Z
Body
@epoleacov could you provide an example showing the behaviour you are seeing? I'm not having any luck reproducing what you're trying to explain



Originally posted by @GeeH at zendframework/zend-form#95

Missing dependency to zend-servicemanager ?

Hi,

I'm using zend-form as a standalone library (in a Symfony2 project), and I realize that since this commit (introduced in v2.8.2) there is a new autoload file which creates an alias FormElementManager for either FormElementManagerV3Polyfill or FormElementManagerV2Polyfill (the latter in my case).

So here's my problem : when I run a composer update the Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap post-update command fails with this error :

PHP Fatal error:  Class 'Zend\ServiceManager\AbstractPluginManager' not found in /sites/sfwebfstore/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerV2Polyfill.php on line 28

Actually the command doesn't matter, the problem appears very soon during the autoload phase.

I suspect this error to be a consequence of the absence of zend-servicemanager as a non-dev dependency in the composer.json of this project.
Indeed, considering I'm using zend-form in standalone and that zend-servicemanager isn't a dependency of any of the others packages, Zend\ServiceManager\AbstractPluginManager doesn't exists and an error appears.

I don't know if it makes sense to set zend-servicemanager as a non-dev requirement in this project, but I think it would resolve this problem (I'm not sure).
If you think it's not a good idea, please help me to find a solution because I'm pretty stucked there :-)


Originally posted by @chapa at zendframework/zend-form#72

Form implements InputFilterProviderInterface - validators fix

When Form implements InputFilterProviderInterface and validators for an element are defined in method getInputFilterSpecification, only these validators should be added to the InputFilter of the Form for the element.
The same behavior should be for Fieldsets and it works fine. Basically, validators defined in getInputFilterSpecification should override default validators of the Element.


Originally posted by @michalbundyra at zendframework/zend-form#82

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.