Object of class AppBundle\Entity\Tarifa could not be converted to string - forms

I saw a lot of similar issues, but I can't find the solution to this without adding __toString() method.
This works for me:
$tarifa = new Tarifa();
$form = $this->createForm('AppBundle\Form\TarifaType', $tarifa);
And this does not work...
$tarifa = new Tarifa();
$peso1 = new TarifaPeso();
$tarifa->addPeso($peso1);
$form = $this->createForm('AppBundle\Form\TarifaType', $tarifa);
Any help is welcome...

I believe you need this
$tarifa->addPeso($peso1->getPeso());
or this
$tarifa->addPeso($peso1->getAmount());
Depending on which property in TarifaPeso you have for this, if its also an entity and have getters
or its a ValueObject?

Configure option choice_label to be a property from TarifaPeso in your TarifaType class. This way, symfony does not intend to convert entity to a string when printing the option label. Instead, it will take the property that you point to.

Finally I solved it! The fact is I had added the field in the TarifaType that is related to the Collection. I removed the field below and now it works! Hope it could help anybody... Thanks to all
->add('tarifa', null, array(
'attr' => array('autofocus' => true),
'label' => 'label.code',
))

Related

passing value to form

I'm not quite sure about the way of doing.
The challenge:
I call an addAction which shows a form. The point of calling the addAction gives two routing parameters, say value1 and value 2 separated by an "-".
I need value 1 and value 2 to search a pk in a table which will be saved as a foreignkey value by the addAction. I take both values give it to a method and get the key I need, that is tested and ok so far.
My problem.
In the first call of addAction I get the routing parameters and find the key. But afterwards of course it is forgotten. How can I remember the found value, so that I can use it for my saveModel method?
What would be the best way?
Idea 1:
Can I give it to the form and set it as value to the hidden keyfield?
For example:
class PadForm extends Form
{
public function __construct($name = null, $unitpartid)
{
parent::__construct('pad');
$this->add([
'name' => 'UnitPartPadID',
'type' => 'hidden',
'value' => $unitpartid,
]);
Would this be working? And would this be an accepted, proper way?
Idea 2:
Or would I try to use an instance variable in my controllerclass, like $this->smtg; ?
In both cases I get an understandable error
Trying to get property of non-object
Questions:
what would be the best way?
and
how to do it, perhaps somebody could give a short example.
EDIT:
I really would appreciate to learn about the best way. I now tried to give a variable to my form and then fill in some field, but that doesn't work.
Part of Controlleraction
(the action works if I set a constant value for the related field)
$parameter = $this->params()->fromRoute('id');
// echo $parameter;
$partnumber =substr($parameter,0,strpos($parameter,"-"));
// echo $partnumber;
$unitid=substr($parameter, strpos($parameter,"-")+1, strlen($parameter));
// echo $unitid;
$test=$this->unitparttable->getUnitPartID($unitid, $partnumber);
echo $test->UnitPartID;
$form = new PadForm(NULL, $test->UnitPartID);
Then in the Formclass:
public function __construct($name = null, $unitpartid)
{
// We will ignore the name provided to the constructor
parent::__construct('pad');
// $this->db=$db;
$this->add([
'name' => 'UnitPartPadID',
'type' => 'hidden', //hidden
]);
$this->add([
'name' => 'UnitPartID',
'type' => 'text', //hidden
'value' => $unitpartid,
]);
The question is now, how to fill the formfield UnitPartID with the value of $unitpartid given within the constructor.
I also tried $form->populate but it is unknown, I used it in ZEND1 before, but probably it doesn't exist anymore.
any help appreciated!

ZF2 refresh input filter after dynamicly adding elements to form

I have a form that triggers on event in __construct method to load some items from another modules . So far so good , a field set is loaded from the other module and added to the form and in the request->getPost() I have the data for the elements inside the fieldset , but the $form->getData() doesn't have the data for the fieldset.
I am calling $form->getInputFilter() before adding this fieldsets to the form and it seems that calling the $form->getInputFilter() dosn't creates the filters for the newly added elements . so how can i create inputfilters for the dynamic events without recreating the hole filters again ?
Or should i just delay calling $form->getInputFilter() untill all of the elemnts have been added to the form ?
I also added some elements to the form later what was ignored by the input filter.
My solution is most likely not exactly the best one, but as you haven't received any other answers yet, here's what I did:
I added
use Zend\InputFilter\Factory as InputFactory;
in the class where I'm validating the form data and then used
$factory = new InputFactory();
$form->getInputFilter()->add($factory->createInput(array(
'name' => 'title_str',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
#Afterdark017 that works and also i think it is possible to reset the filters.
protected function resetFilters(){
$this->filter = null;
$this->hasAddedInputFilterDefaults = false;
}
but i have not tested this yet.

Passing variables to a viewScript Decorator

I have tried adding a partial to my form using the Zend Form's viewScript decorator, however i seem unable to pass along variables to the partial. Here's my code:
In the controller i add the form:
$form = new Content_Form_ContentForm(array("categories" => $sortedCategories));
$form->submit_button->setLabel("Add content");
$this->view->form = $form;
Then inside the form i add the viewscript:
public function setCategories($categories) {
$this->setDecorators(array(array('ViewScript', array(
'viewScript' => 'partials/dtreePartial.phtml',
'List'=>"{$categories}",
))));
}
I have tried printing the options for the view script by using print_r($this->getDecorator('ViewScript')->getOptions()); wich results in Array ( [viewScript] => partials/dtreePartial.phtml [List] => Array )
However when i run it all, the script returns an error about the List not existing.
I have the feeling i am missing something but i am unsure as to what it is. Any advice or solutions will be appreciated! :)
The problem is with this line:
'List'=>"{$categories}",
Because you put the variable inside quotes, it gets cast to a string. In PHP, when you cast an array to a string, the result is always the word Array.
Simply change to:
'List'=> $categories,
and it should work as you expect.

Silex / Symfony2 Post-Validation

Im sure this must be a RTM question, but I must be looking in the wrong places. In symfony 1.4 I used post validator callbacks quite a lot. For example checking that start and end dates were in the correct order. I am developing an app in Silex but cant figure out how to add similar functionality as a validator. This is what I am working with (basically):
$app['form.example'] = function ($app) {
$constraints = new Assert\Collection(array(
'date1' => new Assert\Date(),
'date2' => new Assert\Date(),
));
$builder = $app['form.factory']->createNamedBuilder('form', 'example', array(), array('validation_constraint' => $constraints));
return $builder
->add('date1', 'date')
->add('date2', 'date')
->getForm();
};
I can put my own validation test in the 'process form' part, like: if ($form->isValid() && --my datetest--) but it doesnt feel right to me there.
Any help? Thanks!
I guess you can use form events for this kind of thing; certainly for Symfony2, so I assume Silex too? There's a cookbook article about using it to generate dynamic forms:
http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html
Some useful detail in another SO question:
Description of Symfony2 form events?
Could have sworn I had a SO discussion about this with someone before but I cannot find the question. I used BIND_CLIENT_DATA to calculate some form fields in some code a while back; I'll see if I can dig it out.
EDIT
Okay, I found something but I'm modifying this from Symfony code so I'm not 100% on this but it might be a starting point (I hope):
$builder->addEventListener(FormEvents::BIND_NORM_DATA, function($event) {
// your form data
$data = $event->getData();
// get date objects - if you cannot dereference this way try getters
$d1 = $data['date1'];
$d2 = $data['date2'];
// naive comparison :)
$isCorrectDateOrder = $d1->getTimestamp() < $d2->getTimestamp();
// check the comparison
if (!$isCorrectDateOrder) {
// trouble... create and add a FormError object to the form
$event->getForm()->get('date1')->addError(new \Symfony\Component\Form\FormError('uh oh...'));
}
});
Hope this helps :)

Creating a Zend_Validate object from an array

I have this in a Zend_Form's init method:
$username_validators = array(
'Alpha',
array('StringLength', false, array(3, 20)),
);
$some_form->addElement('text', 'username', array(
'filters' => array('StringTrim', 'StringToLower'),
'validators' => $username_validators,
'required' => true,
'label' => 'Username:',
));
Is it possible to create a Zend_Validate object that loads the same validators array that I'm passing addElement? It would be something like:
$v = new Zend_Validate();
//this is the part I'm unsure. Zend_Validate doesn't have an addValidators method.
$v->addValidators($username_validators);
echo $v->isValid('testuser1');
Sure you can add a collection of validators from a member variable, as long as they don't require any dynamic options that need to be specified at instantiation.
Edit
It appears to me that, out of the box, you cannot do something similar. Zend_Form has a plugin loader/registry that enables you to use "short forms" for validators. The plugin loader is configured with paths and class prefixes that allow it to actually create true validator instances from the short forms and any provided validator options.
In contrast, the code of Zend_Validate::addValidator() appears to actually require an actual validator instance.
But it looks like you could kind of piggyback on this form/element registry as follows: create a form element, assign short form validators to the element, call getValidators() on the element (Zend_Form_Element::getValidators() seems to convert each short form validator into a real instance), and then feed these validators one at a time into Zend_Validate. Seems to be a long way around, but it should work.
Yes, you can do what you want as long as $username_validators has been declared and is accessible in the scope of the function / class. If you are using a class, you will declare a private variable:
private $userVariables;
Then in the constructor populate it:
public function __construct()
{
$this->userVariables = array(
//validator options here
);
}
You can now assign this single validator as many times as you like by calling $this->userVariables:
$v = new Zend_Validate();
$v->addValidators($this->userVariables); //this is the part I'm unsure
echo $v->isValid('testuser1');