Populating $form_input with 'select' element options? - perl

I'm trying to understand the data-structure required to populate a
form with 'select' element values (options).
When I dump (Data::Dumper) the FormFu object, I see that the object structure
looks similar to the following:
'name' => 'EmailDL',
'_options' => [
{
'label_attributes' => {},
'value' => 'm',
'container_attributes' => {},
'label' => 'Male',
'attributes' => {}
},
{
'label_attributes' => {},
'value' => 'f',
'container_attributes' => {},
'label' => 'Female',
'attributes' => {}
}
],
Seeing this, I figured that the way to structure $form_input (being that $form_input = \%cgivars) would be something like the following:
'Firstname' => 'Faisal',
'EmailDL' => [
{
'value' => 'myvalue',
'label' => 'mylabel'
}
],
However this doesn't seem to work. I've found that structuring $form_input correctly, and then issuing a $fu->default_values($form_input) to be simple and effective, except in this instance when I'm trying to include the select/options sub-structure.
So the question is: How should I structure 'EmailDL' above to correctly populate 'select' options when doing $fu->default_values($form_input) or $fu->process($form_input)?

To set the options you use the options call,
$fu->get_all_element('EmailDL')->options([ [ 'myvalue', 'mylabel' ],
[ 'val2', 'label2' ] ]);
If you then want to set one of those values you can use the default_values.
$fu->default_values({ EmailDL => 'val2' });
Further help is available here in the Element::Group documentation. Note the code examples are in the text of the help.

Related

TYPO3 TCA label with UserFunc - how to get HTML formatted label?

I want to format the title showing in a list of TCA items which can contain italic text. But whatever I try, I get only unformatted text - even from RTE text fields.
My base information is "partA", "partB", "partC" and I need a title like "partA : partC - part B"
My Code so far:
<?php
return [
'ctrl' => [
'title' => 'LLL:EXT:myext/Resources/Private/Language/myext.xlf:tx_myext_domain_model_myitem',
'label' => 'partC',
'label_alt' => 'partA',
'formattedLabel_userFunc' => T395\myExt\Classes\UserFuncs\MyBEUserFuncs::class.'->getFullMyitemTitle',
'formattedLabel_userFunc_options' => [
'sys_file' => [
'partC','partA','partB'
]
],
'iconfile' => 'fileadmin/Resource/icons/svgs/myext.svg',
],
'columns' => [
'partC' => [
'label' => 'LLL:EXT:myext/Resources/Private/Language/myext.xlf:tx_myext_domain_model_myitem.partC',
'config' => [
'type' => 'text',
'enableRichtext' => true,
],
],
'partA' => [
'label' => 'LLL:EXT:myext/Resources/Private/Language/myext.xlf:tx_myext_domain_model_myitem.partA',
'config' => [
'type' => 'input',
'size' => '5',
'eval' => 'trim',
],
],
'partB' => [
'label' => 'LLL:EXT:myext/Resources/Private/Language/myext.xlf:tx_myext_domain_model_myitem.partC',
'config' => [
'type' => 'input',
'size' => '5',
'eval' => 'trim',
],
],
],
'types' => [
'0' => ['showitem' => 'partA,partB,partC'],
],
];
And the UF:
<?php
T395\myExt\Classes\UserFuncs;
class MyBEUserFuncs
{
public function getFullMyitemTitle(&$params, &$pObj)
{
echo "Hello World!";
$params['title'] = $params['row']['partA'].' : '.$params['row']['partC'].' - '.$params['row']['partB'];
}
}
Even the echo is not showing. Changing the formattedLabel_userFunc to label_userFunc results in getting a string in right order - but right without any text formats like <i> etc but showing them as text. I'm sure, I'm missing something, but I can't figure out what it is - I was also unable to find any code snippets or examples showing the right way - and the docs from TYPO3 saying only that exists formattedLabel_userFunc and it has options - but no proper example there. Hope you can help me. Thank you!
in the documentation for formattedlabel_userfunc you can find:
[...] return formatted HTML for the label and used only for the labels of inline (IRRE) records.
and for label_userfunc there is the warning:
The title is passed later on through htmlspecialchars() so it may not include any HTML formatting.

Different value_options in Form Collection

I hava a Collection, in which a field User (a multiselect) depends on a previous Select, the Department. Therefore each User select contain a different "value_options".
How can I set different "value_options" when retrieving the form for each row of the Collection?
You have different options:
You create an API endpoint to retrieve form options
You make this into two different pages, the first one you choose the department and the second one you choose the user (ew)
You populate the form in server-side and you filter the selects on client side
I personally discourage the second option. Is there just to say that it is a possible solution, but NO.
The first option, the API, is interesting, but requires actually more work, especially if it is the only endpoint in your application.
The third option is the one I always use, since it requires the less code and it quite simple to implement.
In your form, you have your two elements:
$this->add([
'name' => 'department_id',
'type' => 'Select',
'attributes' => [
'id' => 'department_id'
],
'options' => [
'value_options' => [
1 => 'Marketing',
2 => 'IT',
3 => 'Logistic'
]
]
]);
$this->add([
'name' => 'user_id',
'type' => 'Select',
'attributes' => [
'id' => 'user_id',
'multiple' => true
],
'options' => [
'value_options' => [
[
'value' => 1,
'label' => 'John Doe - Marketing',
'attributes' => ['data-department-id' => 1]
],
[
'value' => 2,
'label' => 'Jane Doe - Marketing',
'attributes' => ['data-department-id' => 1]
],
[
'value' => 3,
'label' => 'Jack Doe - IT',
'attributes' => ['data-department-id' => 2]
],
[
'value' => 4,
'label' => 'Dana Doe - IT',
'attributes' => ['data-department-id' => 2]
],
[
'value' => 5,
'label' => 'Frank Doe - Logistic',
'attributes' => ['data-department-id' => 3]
],
[
'value' => 6,
'label' => 'Lara Doe - Logistic',
'attributes' => ['data-department-id' => 3]
]
]
]
]);
As you can see, all the users are put in the value_options. Keep in mind that this is just an example, you should use custom elements to populate this kind of selects ;)
Then, in your view, you render the elements:
<?= $this->formElement($this->form->get('department_id')); ?>
<?= $this->formElement($this->form->get('user_id')); ?>
And you finally add the JS code to handle the filter. Here I use jQuery, but it's not necessary to use it:
$(function () {
// Filter users when you load the page
filterUsers(false);
// Filter users when you change value on multiselect
$('#department_id').on('change', function () {
filterUsers(true);
});
});
function filterUsers(resetValue) {
var departmentId = $('#department_id').val();
// Remove previous value only when filter is changed
if (resetValue) {
$('#user_id').val(null);
}
// Disable all options
$('#user_id option').attr('disabled', 'disabled').attr('hidden', true);
// Enable only those that respect the criteria
$('#user_id option[data-department-id=' + departmentId + ']').attr('disabled', false).attr('hidden', false);
}
Final tip: don't forget to create and add to the form a Validator to check the couple department_id - user_id is correct, just to avoid (on my example) to accept Lara Doe (logistic) with IT department ;)

TYPO3 selectSingle, add an option which creates a new element (addRecord)

I have a selectSingle element which gets a list of some addresses from another table. Since the following doesn't work on TYPO3 v9 with selectSingle
'fieldControl' => [
'editPopup' => [
'disabled' => false,
],
'addRecord' => [
'disabled' => false,
],
'listModule' => [
'disabled' => false,
],
],
i would like to create an option inside the select list which duplicates the behaviour of the addRecord. So far my elements is located in
myExt/Configuration/TCA/Overrides/tx_domain_model_modelName
and my element looks like this:
$GLOBALS['TCA'][$tableName]['columns']['db_field'] = [
'exclude' => false,
'label' => 'LLL:EXT:myExt/Resources/Private/Language/locallang_db.xlf:.db_field',
'config' => [
'type' => 'select',
'renderType' => 'selectSingle',
'items' => [
["LLL:EXT:myExt/Resources/Private/Language/locallang_db.xlf:.selectItem", 0],
],
'foreign_table' => 'tx_ext_domain_model_address',
],
];
If there is a way around it (addRecord) i would definetely use it. If not, i would really appreciate it of you point me to the right direction on how to create this item inside the select list.
Additional information
i tried to use the following code Code but i got this error:
Too few arguments to function
TYPO3\CMS\Backend\Form\Element\AbstractFormElement::__construct(), 0
passed in
/my/home/path/htdocs/typo3/sysext/core/Classes/Utility/GeneralUtility.php
on line 3667 and exactly 2 expected
and the function which causes this error inside the AbstractFormElement::__construct looks like this:
public function __construct(NodeFactory $nodeFactory, array $data)
{
parent::__construct($nodeFactory, $data);
$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
}
Thanks in advance,

Radio button: input was not found in the haystack?

Whenever I submit the form I get this message:
The input was not found in the haystack.
This is for the shipping-method element (radio button). Can't figure out what it means, the POST data for that element is not null.
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
// Some other basic filters
$inputFilter->add(array(
'name' => 'shipping-method',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'max' => 20,
),
),
array(
'name' => 'Db\RecordExists',
'options' => array(
'table' => 'shipping',
'field' => 'shipping_method',
'adapter' => $this->dbAdapter
)
),
),
));
$inputFilter->get('shipping-address-2')->setRequired(false);
$inputFilter->get('shipping-address-3')->setRequired(false);
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
I only keep finding solutions for <select>.
Here's the sample POST data:
object(Zend\Stdlib\Parameters)#143 (1) {
["storage":"ArrayObject":private] => array(9) {
["shipping-name"] => string(4) "TEST"
["shipping-address-1"] => string(4) "test"
["shipping-address-2"] => string(0) ""
["shipping-address-3"] => string(0) ""
["shipping-city"] => string(4) "TEST"
["shipping-state"] => string(4) "TEST"
["shipping-country"] => string(4) "TEST"
["shipping-method"] => string(6) "Ground"
["submit-cart-shipping"] => string(0) ""
}
}
UPDATE:
form.phtml
<div class="form-group">
<?= $this->formRow($form->get('shipping-method')); ?>
<?= $this->formRadio($form->get('shipping-method')
->setValueOptions(array(
'Ground' => 'Ground',
'Expedited' => 'Expedited'))
->setDisableInArrayValidator(true)); ?>
</div>
ShippingForm.php
$this->add(array(
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Shipping Method',
'label_attributes' => array(
'class' => 'lbl-shipping-method'
),
)
));
The problem lies with when you use the setValueOptions() and the setDisableInArrayValidator(). You should do this earlier within your code as it is never set before validating your form and so the inputfilter still contain the defaults as the InArray validator. As after validation, which checks the inputfilter, you set different options for the shipping_methods.
You should move the setValueOptions() and the setDisableInArrayValidator() before the $form->isValid(). Either by setting the right options within the form itsself or doing this in the controller. Best way is to keep all of the options in one place and doing it inside the form class.
$this->add([
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => [
'value_options' => [
'Ground' => 'Ground',
'Expedited' => 'Expedited'
],
'disable_inarray_validator' => true,
'label' => 'Shipping Method',
'label_attributes' => [
'class' => 'lbl-shipping-method',
],
],
]);
Another small detail you might want to change is setting the value options. They are now hardcoded but your inputfilter is checking against database records whether they exist or not. Populate the value options with the database records. If the code still contains old methods but the database has a few new ones, they are not in sync.
class ShippingForm extends Form
{
private $dbAdapter;
public function __construct(AdapterInterface $dbAdapter, $name = 'shipping-form', $options = [])
{
parent::__construct($name, $options)
// inject the databaseAdapter into your form
$this->dbAdapter = $dbAdapter;
}
public function init()
{
// adding form elements to the form
// we use the init method to add form elements as from this point
// we also have access to custom form elements which the constructor doesn't
$this->add([
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => [
'value_options' => $this->getDbValueOptions(),
'disable_inarray_validator' => true,
'label' => 'Shipping Method',
'label_attributes' => [
'class' => 'lbl-shipping-method',
],
],
]);
}
private function getDbValueOptions()
{
$statement = $this->dbAdapter->query('SELECT shipping_method FROM shipping');
$rows = $statement->execute();
$valueOptions = [];
foreach ($rows as $row) {
$valueOptions[$row['shipping_method']] = $row['shipping_method'];
}
return $valueOptions;
}
}
Just had this happen yesterday.
The select and multi select ZF2+ elements have a built in in_array validator.
Remember filters occur before validators.
You may be doing too much here -- it is very rare to need to filter or add validators ot select and multi select form elements in ZF2 forms. The built in element validator is robust, ZF does a lot of work for us.
Try removing both filter and validator for the element, such as:
$inputFilter->add(array(
'name' => 'shipping-method',
'required' => true,
));
There is another edge case that I have seen: changing the select element's valueOptions somewhere in the controller (or view) resulting in different valueOptions used in view vs form validation (in our case it was replacing the element with a new one before validation).
I think your problem lies in the fact you are adding your value options after the InArray validator has been set, hence the validator has no haystack.
Try this
$this->add(array(
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Shipping Method',
'label_attributes' => array(
'class' => 'lbl-shipping-method'
),
'value_options' => array(
'Ground' => 'Ground',
'Expedited' => 'Expedited'
),
'disable_inarray_validator' => TRUE,
)
));
and remove setValueOptions and setDisableInArrayValidator from your view.
Hope this works.

How to validate a checkbox in ZF2

I've read numerous workarounds for Zend Framework's lack of default checkbox validation.
I have recently started using ZF2 and the documentation is a bit lacking out there.
Can someone please demonstrate how I can validate a checkbox to ensure it was ticked, using the Zend Form and Validation mechanism? I'm using the array configuration for my Forms (using the default set-up found in the example app on the ZF website).
Try this
Form element :
$this->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'agreeterms',
'options' => array(
'label' => 'I agree to all terms and conditions',
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 'no'
),
));
In filters, add digit validation
use Zend\Validator\Digits; // at top
$inputFilter->add($factory->createInput(array(
'name' => 'agreeterms',
'validators' => array(
array(
'name' => 'Digits',
'break_chain_on_failure' => true,
'options' => array(
'messages' => array(
Digits::NOT_DIGITS => 'You must agree to the terms of use.',
),
),
),
),
)));
You could also just drop the hidden form field (which I find a bit weird from a purist HTML point of view) from the options instead of setting its value to 'no' like this:
$this->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'agreeterms',
'options' => array(
'label' => 'I agree to all terms and conditions',
'use_hidden_element' => false
),
));
I had the same problem and did something similar to Optimus Crew's suggestion but used the Identical Validator.
If you don't set the checked_value option of the checkbox and leave it as the default it should pass in a '1' when the data is POSTed. You can set it if you require, but make sure you're checking for the same value in the token option of the validator.
$this->filter->add(array(
'name' => 'agreeterms',
'validators' => array(
array(
'name' => 'Identical',
'options' => array(
'token' => '1',
'messages' => array(
Identical::NOT_SAME => 'You must agree to the terms of use.',
),
),
),
),
));
This won't work if you use the option 'use_hidden_element' => false for the checkbox for the form. If you do this, you'll end up displaying the default NotEmpty message Value is required and can't be empty
This isn't directly related to the question, but here's some zf2 checkbox tips if you're looking to store a user's response in the database...
DO use '1' and '0' strings, don't bother trying to get anything else to work. Plus, you can use those values directly as SQL values for a bit/boolean column.
DO use hidden elements. If you don't, no value will get posted with the form and no one wants that.
DO NOT try to filter the value to a boolean. For some reason, when the boolean value comes out to be false, the form doesn't validate despite having 'required' => false;
Example element creation in form:
$this->add([
'name' => 'cellPhoneHasWhatsApp',
'type' => 'Checkbox',
'options' => [
'label' => 'Cell phone has WhatsApp?',
'checked_value' => '1',
'unchecked_value' => '0',
'use_hidden_element' => true,
],
]);
Example input filter spec:
[
'cellPhoneHasWhatsApp' => [
'required' => false,
],
]
And here's an example if you want to hide some other form fields using bootstrap:
$this->add([
'name' => 'automaticTitle',
'type' => 'Checkbox',
'options' => [
'label' => 'Automatically generate title',
'checked_value' => '1',
'unchecked_value' => '0',
'use_hidden_element' => true,
],
'attributes' => [
'data-toggle' => 'collapse',
'data-target' => '#titleGroup',
'aria-expanded' => 'false',
'aria-controls' => 'titleGroup'
],
]);
I'm a ZF2 fan, but at the end of the day, you just have to find out what works with it and what doesn't (especially with Forms). Hope this helps somebody!
Very old question, but figured it might still be used/referenced by people, like me, still using Zend Framework 2. (Using ZF 2.5.3 in my case)
Jeff's answer above helped me out getting the right config here for what I'm using. In my use case I require the Checkbox, though leaving it empty will count as a 'false' value, which is allowed. His answer helped me allow the false values, especially his:
DO NOT try to filter the value to a boolean. For some reason, when the boolean value comes out to be false
The use case is to enable/disable certain entities, such as Countries or Languages so they won't show up in a getEnabled[...]() Repository function.
Form element
$this->add([
'name' => 'enabled',
'required' => true,
'type' => Checkbox::class,
'options' => [
'label' => _('Enabled'),
'label_attributes' => [
'class' => '',
],
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 0,
],
'attributes' => [
'id' => '',
'class' => '',
],
]);
Input filter
$this->add([
'name' => 'enabled',
'required' => true,
'validators' => [
[
'name' => InArray::class,
'options' => [
'haystack' => [true, false],
],
],
],
])