Zend_Form how to put <a> behind input text? - zend-framework

I try to put some HTML link behind input text and I try to do it's somthing like this:
$aElements[$iKey] = $oName = new Zend_Form_Element_Text($aValue['newsletter_question_answer_id']);
$oName->addDecorator('HtmlTag', array(
'tag' => 'a',
'href'=>'http://some_url.html',
'placement' => Zend_Form_Decorator_Abstract::APPEND
));
and my question is how can I put somthing between <a> and </a> ?
Best Regards

If You don't want to write Your own decorator You have to use callback:
$element->addDecorator('Callback', array(
'callback' => function($content, $element, $options) {
Zend_Debug::dump($content, 'content'); //elements decorated so far
Zend_Debug::dump($element, 'element'); //current element
Zend_Debug::dump($options, 'options'); //other options
return "{$options['label']}";
},
'option' => 'value', //everything but 'callback' and 'placement' gets
//passed to callback as option
'href' => 'http://example.com',
'label' => 'Link!',
'placement' => Zend_Form_Decorator_Abstract::APPEND
));
Ofcourse it's php5.3 style callback, but You can use oldstyle too.

Related

How to set a class attribute to a Symfony form input with an attribut from entity linked

I have in my form a "beds" attribute, an entity linked to another "bedroom".
I would like for each input to add a class with the id of the linked entity "bedroom".
$form->add('beds', EntityType::class, array(
'class' => 'DamiasResaBundle:Bed',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('b')
->orderBy('b.id', 'ASC');
},
'choice_label' => 'id',
'label' => 'lits ',
'multiple' => true,
'expanded' =>true,
'attr' => array(
'class' => function ($bed) {
return $bed->getBedroom()->getId();
}
),
))
I have two problems:
'attr' => array('class'=>'test) return a class attribut in the div containing the input, not a class attribut in the input.
This previous code does not work and returns:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.
Thank you for your help
I see you are using checkboxes.
Your code seems ok, and since you use query_builder, the values should be a Bed Entity. Note that attr is not mentioned in the EntityType documentation, and I think you need to use choice_attr instead.
Can you try this. I'm not sure if it will work or not:
$form->add('beds', EntityType::class, array(
'class' => 'DamiasResaBundle:Bed',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('b')
->orderBy('b.id', 'ASC');
},
'choice_label' => 'id',
'label' => 'lits ',
'multiple' => true,
'expanded' =>true,
'choice_attr' => function ($val) {
return ['class' => $val->getId()];
},
))
Let us know the results.
You need to customize form rendering
Previous code doesn't work because you're trying to pass Closure object instead of string value. attr array is used as field attributes, so it must contain only string values (or objects with __toString() method).
For EntityType it would rather look like this:
$form->add('beds', EntityType::class, array(
'class' => 'DamiasResaBundle:Bed',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('b')
->orderBy('b.id', 'ASC');
},
'choice_label' => 'id',
'label' => 'lits ',
'multiple' => true,
'expanded' =>true,
'choice_attr' => function (Bed $bed, $key, $index) {
return ['class' => $bed->getBedroom()->getId();];
},
))
Since choice_attr seems not to be working anymore, I am writing another solution. I wasn't able to set attribute (exactly "min") directly from formBuilder. I managed to add it with help of js. I simply searched element by ID given by formBuilder and added atribute.
Inspect your form in browser element inspector and find id.
<div id="form_deadLine">
<input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>
</div>
Id you wanna look for in my case is form_deadLine_date.
Then you wanna connect .js file to you twig template and write there simple script.
const form = document.getElementById('form_deadLine_date');
if(form){
form.setAttribute("min", "2020-01-02")
}
then my code looks like:
<div id="form_deadLine">
<input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>
</div>

ZF2 Form: NumberFormat-filter with localization

hy,
how can I define the NumberFormat-filter for an input in a fieldset which is aware of the current locale? What I want is that numbers like 1000.33 are displayed in the view like this: 1.000,33 (or whatever locale is specified) I have tried it with the InputFilterProviderInterface, but it doesn't has any effect in the view:
<?php
namespace Customer\Form;
use Customer\Entity\OfferDay;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class OfferDayFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($em)
{
parent::__construct('offerDayFieldset');
$this->setHydrator(new DoctrineHydrator($em))
->setObject(new OfferDay());
$this->add(array(
'name' => 'price',
'type' => 'Text',
'options' => array(
'label' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
),
),
),
),
);
}
}
In the view I output the input via the formRow()-function.
I also know that you can use the NumberFormat-Filter programmatically like this (l18n Filters - Zend Framework 2):
$filter = new \Zend\I18n\Filter\NumberFormat("de_DE");
echo $filter->filter(1234567.8912346);
// Returns "1.234.567,891"
but I wanna use the array-notation.
Has anybody done something like this or something similar?
ok this seems not as trivial as I thought :) but I got a solution.
first define the filter like this:
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
'style' => NumberFormatter::DECIMAL,
'type' => NumberFormatter::TYPE_DOUBLE,
),
),
),
),
);
}
whereas locale is the currently used locale. This formats the numbers into the currect format before saving it to the database.
In the view, you can use the filter view helper to convert the numbers to the right format:
<?php
$this->plugin("numberformat")
->setFormatStyle(NumberFormatter::DECIMAL)
->setFormatType(NumberFormatter::TYPE_DOUBLE)
->setLocale("de_DE");
?>
<p>
<?php
$currentElement = $form->get('price');
$currentElement->setValue($this->numberFormat($currentElement->getValue()));
echo $this->formRow($currentElement);
?>
</p>
Result:
Database: 12.345 ->
View: 12,345 -> Database: 12.345

How do I allow html tags in label for Zend form element using addElement()?

I am brand new to Zend and I've been given a project to make adjustments on. I'd like to add html to the labels for my form elements but I can't seem to get it right.
Here's what I have:
$this->addElement('text', 'school_name', array(
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(0, 150)),
),
'required' => true,
'label' => 'Name* :<img src="picture.png">,
'size' => '90',
));
As is, of course, the <img src="picture.png"> text gets escaped and the whole string is displayed.
I've read that I need to use 'escape' => false in some capacity but I can't figure out where/how to use it in my specific case.
Any help would be great. Thanks!
After calling addElement fetch the label's decorator and change the escape setting:
$form->getElement('school_name')->getDecorator('label')->setOption('escape', false);
If you use this type of label a lot, you should consider writing a custom decorator.
You can also use the disable_html_escape in 'label_options' when adding an element to the form:
$this->add(array(
....
'options' => array(
'label' => '<span class="required">Name</span>,
'label_options' => array(
'disable_html_escape' => true,
)
),
...
));
Credit to Théo Bouveret's post 'Button content in ZF2 forms' for the answer.

How to remove Zend Form error messages?

I have changed decorator:
private function _addErrorDecorator($form)
{
$form->setDecorators(array(
'FormElements',
new Zend_Form_Decorator_FormErrors(array
(
'ignoreSubForms' => true,
'markupElementLabelEnd' => '</b>',
'markupElementLabelStart' => '<b>',
'markupListEnd' => '</div>',
'markupListItemEnd' => '</span>',
'markupListItemStart' => '<span>',
'markupListStart' => '<div id="Form_Errors">'
)
),
'Form'
));
return $form;
}
But now i need to remove error messages under form fields. How do i make it?
Each element, subform and display group in your form has a decorator stack as well, so you will need to modify the stack for the elements you want to not display the error messages.
There's a lot of ways to do this:
$form->setElementDecorators(array(
'ViewHelper',
'HtmlTag',
'Label'
));
Is the way to go if you want to keep the default element decorator stack, but with the error decorator removed. You can also do it on an individual element basis:
$element->setDecorators(array(
'ViewHelper',
'HtmlTag',
'Label'
));
Or when you are adding the element:
$form->addElement($type, $name, array(
'decorators' => $decorators
))

How do i remove the label decorator from a submit button

In my form i have this code;
// Add the submit button
$element = $this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Add new material'
));
$element->removeDecorator('label');
However the form still renders with the label element between the tags.
What am i doing wrong?
This worked for me:
$this->addElements(array(
new Zend_Form_Element_Submit('submit', array(
'label' => 'Save'
))
));
$element = $this->getElement('submit');
$element->removeDecorator('DtDdWrapper');
I did print_r($element); to find out what decorators exist for $element.
The function addElement returns a reference to the current form not to the last added element.
You could try this:
$form = new Zend_Form();
$form->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Add new material'
));
$element = $form->getElement('submit');
$element->removeDecorator('label');
I think the argument to removeDecorator is case-sensitive. I.e., it should be "Label" # note the uppercase 'L'.
To overcome this nuisance I'm defining manually the decorators for my element...
$details->addElement('text', 'in_year', array(
'decorators'=>array(
'ViewHelper',
array('HtmlTag', array('tag' => 'span')),
)
));
You can of course define your own tags. In this example I only initialise the "ViewHelper" decorator. If I want to initialise the "Label" decorator I would do:
$details->addElement('text', 'in_year', array(
'decorators'=>array(
'ViewHelper',
'Label',
array('HtmlTag', array('tag' => 'span')),
),
'attribs' => array('class' => 'required validate-digits')
));
I hope this makes sense... :o)