How to fix 'The input was not found in the haystack' in ZF2? - zend-framework2

I have an issue in my code which I can't resolve. I'm using Zend framework 2.4 and I wrote a form but as soon as I validate it, I got the error The input was not found in the haystack. This are the 3 input where I got the error:
$this->add(array(
'name' => 'ACTIVITE1',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
),
'disable_inarray_validator' => false,
),
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session1'
)
));
$this->add(array(
'name' => 'ACTIVITE2',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
)
),
'disable_inarray_validator' => false,
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session2'
)
));
$this->add(array(
'name' => 'ACTIVITE3',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
'Choisir l\'activité'
)
),
'disable_inarray_validator' => false,
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session3'
)
));
I saw in other form that I should put 'disable_inarray_validator' => false but this doesn't work too.

Of course it's not working.
That message comes from the \Zend\Validator\InArray and essentially, it means: "your user is doing something hacky with your select, pay attention".
An exemple would be a Select Preferred fruit with two options, like "Banana" and "Ananas", but the user "hacks" the select and sends to the server the value "Audi". The InArray validator is really important and shouldn't be disabled (well, only in a few exceptions..).
Now, why are you getting this error? The answer is... You didn't told what are the select options. You created a Select, but you didn't specified what are its options. You put the label/placeholder at the place of the options. A correct Select would be:
$this->add(array(
'name' => 'ACTIVITE1',
'type' => 'Zend\Form\Element\Select',
'required' => 'required',
'options' => array(
'value_options' => array(
1 => 'Fitness',
2 => 'Parcour',
3 => 'Velo',
4 => 'Tapis roulant',
// ... and so on
)
),
'attributes' => array(
'class' => 'form-control',
'id' => 'select-session1',
'placeholder' => "Choisir l'activité"
)
));
What is "weird" is the fact that you are filling something in an empty select, and my question then is: why?
Selects are (typically) there for a predefined list of values. If you want to allow your users to fill a custom text, then you should consider to create a Text field with the autocomplete option.
Edit: select with values from DB
If you want to create a select with a list of options that come from the database, the route is a bit more complex, but once you've learned how to do it, it will become way easier.
PAY ATTENTION: this will not be a "copy&paste solution". Since I'm not having access to your code, I'm making up names (classes, namespaces, methods, variables) just to create a complete example :)
First off, you must create a custom element. In this case, it will be a custom select:
namespace Yournamespace;
use Zend\Form\Element\Select;
use Yournamespace\ActivityMapper;
class ActivitySelect extends Select {
protected $activityMapper;
public function __construct(ActivityMapper $activityMapper, $name = null, $options = []) {
parent::__construct($name, $options);
$this->activityMapper = $activityMapper;
}
public function init() {
$valueOptions = [];
foreach ($this->activityMapper->fetchAll() as $activity) {
$valueOptions[$activity->getActivityId()] = $activity->getActivityName();
}
$this->setValueOptions($valueOptions);
}
}
What is really important here is that you must instantiate your element (options, classes, and so on..) inside init method.
Since this element has a dependency (ActivityMapper), you'll have to create a factory for this element:
namespace Yournamespace;
use Zend\ServiceManager\Factory\FactoryInterface;
use \Interop\Container\ContainerInterface;
class ActivitySelectFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options = null): object {
$activityMapper = $container->get(\Yournamespace\ActivityMapper::class);
return \Yournamespace\ActivitySelect($activityMapper);
}
}
This factory must be added in the configuration, more precisely, inside module.config.php:
return [
// ...
'form_elements' => [
'factories' => [
\Yournamespace\ActivitySelect::class => \Yournamespace\ActivitySelectFactory::class,
]
]
// ...
];
Now, you must modify your form too. All elements must be added to form inside init method, and not inside the constructor:
namespace Yournamespace;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class ActivityForm extends Form implements InputFilterProviderInterface {
public function init() {
parent::init();
// ...
$this->add([
'name' => 'ACTIVITE1',
'type' => \Yournamespace\ActivitySelect::class,
'attributes' => [
'class' => 'form-control',
'id' => 'select-session1',
'required' => true, // This will work only clientside, don't forget the inputfilter!
'placeholder' => 'Choisir l\'activité',
],
'options' => [
'label' => 'Choisir l\'activité',
]
]);
// ...
}
public function getInputFilterSpecification() {
// ...
$inputFilter[] = [
'name' => 'ACTIVITE1',
'required' => true
];
// ...
return $inputFilter;
}
}
Finally, you'll have to modify your controller too, because you need to retrieve the form from the FormElementManager:
namespace Yournamespace;
use Zend\Form\FormElementManager;
class YourController extends AbstractActionController {
private $formManager;
public function __construct(FormElementManager $formManager) {
$this->formManager = $formManager;
}
public function choisirActiviteAction(){
// ...
$form = $this->formManager->get(\Yournamespace\ActivityForm::class);
// ...
}
}
A next nice step would be to create a controller plugin for the $formManager, instead of making it as a dependency of each controller, but this is a different problem..

thanks for your answer! I understand what you mean but i did this because i don't want to control the select because i can't control all the possible options.
Because the options are from a database, i get them doing an AJAX request and i add all the option to the select in the view. So the options can vary and are not fixed.
Here is my AJAX request :
$("#input-dtNaissance").change(function() {
$.when($(".activites-options").remove()).then(function() {
if ($("#input-dtNaissance").val() != " ") {
//on supprime les anciennes activités proposées au cas où il y en ai
var year = $("#input-dtNaissance").val().substring(0,4);
if (year == "") {
year = 1;
}
// si date supprimée/réinitialisée
if (year == 1) {
// on supprime les activités proposées du select
$(".activites-options").remove();
} else {
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession1/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "' class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session1").append(option);
});
});
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession2/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "'class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session2").append(option);
});
});
$.getJSON("http://localhost/ecoleMunicipalSport/app/public/activite/listActivitySession3/" + year, function(data) {
data.forEach(element => {
var option = "<option value='" + element.ID_ACTIVITES + "' class='activites-options'>" + element.activite[0] + element.activite.substring(1).toLowerCase() + " avec " + element.INTERVENANT + " - " + element.HORAIREDEB + "/" + element.HORAIREFIN + " (" + element.site[0] + element.site.substring(1).toLowerCase() + ")" + "</option>";
$("#select-session3").append(option);
});
});
}
}
});
})
I know that it's not very safety and if you have a better solution with more security i'm open to the propositions.
Good evening.
PS : Sorree faur my terribl anglish :)

Related

How to add class to fieldset?

I have a form in ZF2 with the following element being added:
$this->add(array(
'name' => 'animals',
'type' => 'radio',
'attributes' => array(
'id' => 'animals',
'class' => 'form-control',
),
'options' => array(
'label' => 'Favourite animal',
'options' => array(
'cat' => 'Cat',
'dog' => 'Dog',
'fish' => 'Fish',
),
),
));
And in my view script I have the folloing line:
<?php echo $this->formrow($form->get('animals')); ?>
Which is generating the following html:
<fieldset>
<legend>Favourite Animal</legend>
<label><input type="radio" name="animals" id="animals" class="form-control input-error" value="cat">Cat</label>
<label><input type="radio" name="animals" class="form-control input-error" value="dog">Dog</label>
<label><input type="radio" name="animals" class="form-control input-error" value="fish">Fish</label>
</fieldset>
How do I add a class to the fieldset?
I have tried adding the following to the options array, the attributes array, and as an option to the main array but it is not adding the class to the fieldset:
'fieldset_attributes' => array(
'class' => 'form-group',
),
[edit]
Looking into the code (\Zend\Form\View\Helper\FormRow::render) I've found this:
...
// Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
// labels. The semantic way is to group them inside a fieldset
if ($type === 'multi_checkbox' || $type === 'radio' || $element instanceof MonthSelect ) {
$markup = sprintf('<fieldset><legend>%s</legend>%s</fieldset>', $label, $elementString);
}
...
Which means the only way to add a class to the fieldset (or legend if you wanted) is to extend the view helper.
I followed the answer as posted here (https://stackoverflow.com/a/27273068/351785).
From the answer (modified to suit my requirements):
Create the Application\Form\View\Helper\FormRow.php helper class like
below:
<?php
/**
* Extend zend form view helper formrow to allow class to be added to fieldset / legend
*/
namespace Application\Form\View\Helper;
use Zend\Form\View\Helper\FormRow as ZendFormRow;
class FormRow extends ZendFormRow
{
/**
* Utility form helper that renders a label (if it exists), an element and errors
*
* #param ElementInterface $element
* #throws \Zend\Form\Exception\DomainException
* #return string
*/
public function render(\Zend\Form\ElementInterface $element)
{
//... other code here
// Multicheckbox elements have to be handled differently as the HTML standard does not allow nested
// labels. The semantic way is to group them inside a fieldset
if ($type === 'multi_checkbox'
|| $type === 'radio'
|| $element instanceof MonthSelect
) {
$fieldset_class = $legend_class = '';
if($class = $element->getOption('fieldset_class')) {
$fieldset_class = sprintf(' class="%s"', $class);
}
if($class = $element->getOption('legend_class')) {
$legend_class = sprintf(' class="%s"', $class);
}
$markup = sprintf(
'<fieldset%s><legend%s>%s</legend>%s</fieldset>',
$fieldset_class,
$legend_class,
$label,
$elementString);
}
//... other code here
return $markup;
}
}
And override the factory in the onBootstrap() method of the Module.php
file like below:
namespace Application;
use Zend\Mvc\MvcEvent;
use Zend\View\HelperPluginManager;
class Module
{
/**
* On bootstrap for application module.
*
* #param MvcEvent $event
* #return void
*/
public function onBootstrap(MvcEvent $event)
{
$services = $event->getApplication()->getServiceManager();
// The magic happens here
$services->get('ViewHelperManager')->setFactory('formrow', function (HelperPluginManager $manager) {
return new \Application\Form\View\Helper\FormRow();
});
}
}
And add the classes as such:
$this->add(array(
'name' => 'animals',
'type' => 'radio',
'attributes' => array(
'id' => 'animals',
'class' => 'form-control',
),
'options' => array(
'label' => 'Favourite animal',
'fieldset_class' => 'form-group', //<== this
'legend_class' => 'form-legend', //<== and this
'options' => array(
'cat' => 'Cat',
'dog' => 'Dog',
'fish' => 'Fish',
),
),
));

ZF2 Adding filters with element definition

I am trying to add filters and validators with element definition. But so far it is not working. Here is my controller class code.
public function validateAction() {
$testVals = Array ('question1' => 'value1' );
$formMaker = $this->getServiceLocator ()->get ( 'ttForm\Maker' );
$form = $formMaker->generateForm();
$form->setData($testVals);
if ($form->isValid()){
echo "Valid form";
}
else{
print_r($form->getMessages());
echo "Invalid form";
}
die;
}
This is form class code
public function generateForm (){
$element = array (
'options' => array(
'label' => "First Name :",
),
'attributes' => array(
'required' => 'required',
'type' => 'text'
),
'name' => 'firstName',
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
),
'validators' => array(
array(
'name' => 'not_empty',
)),
);
$form = new Form();
$form->add($element);
return $form;
}
As you can see in form class, I have attached filters and validators with element definition, it does not work. Looking at docs, it seems like we can do so. Can anybody point out missing link? Thanks.

zendfamework 2 form validation set attributes to an input

Is it possible to do while validate a form with an input filter to not just send an error message but also set the border colour change to red?
something like this:
$this->add(array(
'name' => 'test',
'required' => true,
'attributes' => array(
'style' => 'border-color:red'
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Please fill me out'
)
)
)
)
));
One way of doing this would be to create your own view helper to render a form element and in that add error classes if the field has errors.
To start you need to create your view helper and if the form element has errors, then you add a class.
The view helper:
namespace Application\View\Helper;
use Zend\Form\View\Helper\FormInput as ZendFormInput;
use Zend\Form\ElementInterface;
use Zend\Form\Exception;
class FormInput extends ZendFormInput
{
/**
* Render a form <input> element from the provided $element
*
* #param ElementInterface $element
* #throws Exception\DomainException
* #return string
*/
public function render(ElementInterface $element)
{
$name = $element->getName();
if ($name === null || $name === '') {
throw new Exception\DomainException(sprintf(
'%s requires that the element has an assigned name; none discovered',
__METHOD__
));
}
$attributes = $element->getAttributes();
$attributes['name'] = $name;
$attributes['type'] = $this->getType($element);
$attributes['value'] = $element->getValue();
return sprintf(
'<input %s class="form-control '.(count($element->getMessages()) > 0 ? 'error-class' : '').'" %s',
$this->createAttributesString($attributes),
$this->getInlineClosingBracket()
);
}
}
And to your module.config.php you will need to add
'view_helpers' => array(
'invokables'=> array(
'formInput' => 'Application\View\Helper\FormInput',
),
),

How to get data from different model for select?

I have form with some attributes:
class ToraForm extends Form
{
public function __construct($name = null)
{
parent::__construct('tora');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'name',
'attributes' => array(
'type' => 'text',
'required' => true,
),
'options' => array(
'label' => 'name',
),
));
}
but I want add drop-down list with data taken from another model. How to do it?
There are several different approaches you can take. Ultimately your Form has a dependency, which needs to be injected. I have written an in-depth blog-post about the three most common use-cases for Form-Dependencies for a Select-List.
Zend\Form\Element\Select and Database-Values
My BlogPost covers the following scenarios:
Zend\Form\Element\Select via DbAdapter
Zend\Form\Element\Select via TableGateway
DoctrineModule\Form\Element\DoctrineObject via Doctrine2
Here i will demonstrate only the DbAdapter approach without much explanation. Please refer to my blogpost for the in-depth explanations.
public function formDbAdapterAction()
{
$vm = new ViewModel();
$vm->setTemplate('form-dependencies/form/form-db-adapter.phtml');
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new DbAdapterForm($dbAdapter);
return $vm->setVariables(array(
'form' => $form
));
}
Then the respective Form Class:
class DbAdapterForm extends Form
{
protected $dbAdapter;
public function __construct(AdapterInterface $dbAdapter)
{
$this->setDbAdapter($dbAdapter);
parent::__construct('db-adapter-form');
$this->add(array(
'name' => 'db-select',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Dynamic DbAdapter Select',
'value_options' => $this->getOptionsForSelect(),
'empty_option' => '--- please choose ---'
)
));
}
// more later...
// Also: create SETTER and GETTER for $dbAdapter!
}
And last but not least the DataProvider function:
public function getOptionsForSelect()
{
$dbAdapter = $this->getDbAdapter();
$sql = 'SELECT t0.id, t0.title FROM selectoptions t0 ORDER BY t0.title ASC';
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['id']] = $res['title'];
}
return $selectData;
}
My use is like that:
Class Useful{
/**
* All languages
* #return array
*/
public static function getLanguages(){
return array(
'fr_DZ'=>'Algeria - Français',
'es_AR'=>'Argentina - Español',
'en_AU'=>'Australia - English',
'nl_BE'=>'België - Nederlands',
'fr_BE'=>'Belgique - Français',
'es_BO'=>'Bolivia - Español',
'bs_BA'=>'Bosna i Hercegovina - Hrvatski',
...
);
}
}
After I use like that:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'languages',
'attributes'=>array(
'multiple'=>"multiple",
),
'options' => array(
'label' => 'My languages I speak',
'description' => '',
'value_options' => Useful::getLanguages()
),
));

dynamic dropdown get in zf2?

I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);

Resources