Creating a Zend_Validate object from an array - zend-framework

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');

Related

Symfony 4, Object and SubObjects, missing foreign keys

I am not able to find the trick to get the following.
Say I have two Entity: Main and Minor, Main one-to-many Minor, mainId being the foreign key field.
I wish to have both a (Minor) form to create a Minor object, such that users may select its Main object from a list of already available Main objects, and a (Main) form to create a Main object and possibly many different Minor (sub)objects at once.
The issue is that in the latter case, I am not able to save the foreign key.
For the Minor form, I define:
$builder ->add('minorTitle')
->add('Main', EntityType::class, array(
'class' => Main::class,
'choice_label' => 'mainTtile',
'label' => 'main'))
have 'data_class' => Minor::class, and it works fine.
For the Main form, I tried:
$builder
->add('mainTitle')
->add('Minors', CollectionType::class, array(
'entry_type' => MinorType::class,
'allow_add' => true,
'label' => 'Minor'
))
'data_class' => Main::class`
So the Minor form is indeed embedded as a subform within the Main one. To add more subforms, I have some JS as suggested in CollectionType. To avoid to display the Main field in the Minor subforms, I have hacked a little the prototype, by something like:
newWidget = newWidget.replace(newWidget.match(/\B<div class="form-group"><label class="required" for="main_Minors___name_Main">Main<\/label><select id="main_Minors___name_Main" name="main\[Minors\]\[__name__\]\[Main\]" class="form-control">.*<\/select>\B/g),"");
A user is able to create a Main object, and many Minor ones too, but the id of the former is not saved as the foreign keys of the latter ones. I have tried to fix things within the Main Controller by something like (or variants):
public function new(Request $request): Response {
$em = $this->getDoctrine()->getManager();
$main = new Main();
$form = $this->createForm(MainType::class, $main);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$postData = $request->request->get('main');
$minors = array();
foreach($postData['Minors'] as $key => $obj){
$minors[$key]= new Minor();
$minors[$key]->setMain($main);
$minors[$key]->setMinorTitle($obj['minorTitle']);
$em->persist($minors[$key]);
}
$em->persist($main);
$em->flush();
}
but either it does not work, or it saves twice the same subobject (only once with the correct foreign key).
(Maybe, I could fix by two different MinorType classes, but I would like to avoid that)
Thanks
Just a number of hints.
your form types should have the data_class option set to the appropriate class.
your form field names should match the property name on the entity. (and by default, all property names are in camelCase, lowercase first char ... in symfony)
after 1. and 2. you get proper entities by just calling $form->getData() (or, as you might have noticed, when you give the createForm call an entity, it will be modified by the form component - this might not always be intended. consider Data Transfer Objects (DTO) for when it's not intended.)
your CollectionType field should have option byReference set to false, such that the setters get used on the collection field (Main::setMinors, in this case).
usually the one-to-many side (i.e. Main class) can get away with:
public function setMinors(array $minors) {
foreach($minors as $minor) {
$minor->setMain($this); // set the main, just to be safe
}
$this->minors = $minors; // set the property Main.minors
}
but you should not do this in setMain in reverse too (it's also not so trivial. alternative to setMinors are addMinor and removeMinor, there are benefits and costs for either solution, but when it comes to forms, they are quite equivalent, I would say)
on Main if you set the cascade={"PERSIST"} option on the OneToMany (i.e. #ORM\OneToMany(targetEntity="App\Entity\Minor", cascade={"PERSIST"})), you don't have to explicitly call persist on all minors, they will get persisted as soon as you persist (and flush) the Main object/instance.
Finally, either add an option to your minor type, to omit the main form field, or add a new form type MainMinorType (or whatever) that doesn't have the main form field (extend MinorType and remove the main field). This removes the necessity for dirty hacks ;o)
However, overall, if you don't set the minors on the main in a bi-directional relationship, the results are not clearly defined. (just assume for a moment, A has a link to B, but B doesn't have a link to A, but should have, because it's a bi-directional relationship. It could mean, that the link has to be established. It could also mean, that the link should be removed. So, to be safe and clearly communicate what is intended, set both sides!) And ultimately, this might be the reason it doesn't work as intended.
update
To elaborate on point 7. Your MinorType could be amended like this:
class MinorType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
// ... other fields before
if(empty($options['remove_main_field'])) {
// field is the same, but isn't added always, due to 'if'
$builder->add('main', EntityType::class, [
'class' => Main::class,
'choice_label' => 'mainTtile',
'label' => 'main'
]);
}
// ... rest of form
}
public function configureOptions(OptionsResolver $resolver) {
// maybe parent call ...
$resolver->setDefaults([
// your other defaults
'remove_main_field' => false, // add new option, self-explanatory
]);
}
}
in your MainType you had, the following, to which I added the new option
->add('Minor', EntityType::class, array(
'class' => Minor::class,
'remove_main_field' => true, // <-- this is new
))
now, this will remove the main field from your minors forms, when it's embedded in your main form. the default is however, to not remove the main field, so when you edit a minor by itself, the main field will be rendered, as it was before ... unless I made a mistake in my code ;o)

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.

ZendFramework: Changing a form element after failed validation

So I have a form set up in the following manner:
In my forms directory:
Address.php
class Address extends Zend_Form{
// Creates an address input box including address/country/state/zip
// The states is created as a drop down menu
public function init() {
// relevant code to question
$this->addElements(array(
array('select', $names['state'], array(
'label' => "State",
'class' => 'state',
'multiOptions' => array('' => '') + AddressHelper::stateList(),
'required' => $this->_required,
)),
));
}
}
MyForm.php:
class MyForm extends Zend_Form {
public function init() {
//set-up some general form info
// this is the relevant part for my question
// $opt is a predefined variable
$this->addSubForms(array(
'info' => new SubForm($opts),
'mailing' => new Address($opts + array(
'legend' => 'Address',
'isArray' => false,
'required' => true,
)),
));
}
}
Survey.php
class Survey extends MyForm{
// initialize parent (MyForm) and add additional info for the Survey form
}
Okay, so when survey is submitted, if it fails validation, I need to change the Address state element from a select to an input type=text.
So in my controller, under the action that checks for validation I have the following:
public function createAction(){
if ($this->_form->isValid($post)) {
$this->_saveDraft($post, $this->_submissionType);
$this->addSessionMessage('Submission created!');
return $this->redirector->gotoRouteAndExit(array(), 'home', true);
}else{
/* IMPORTANT */
// I need to change the Address select field to a text field here!
$errors[] = 'There was a problem';
$this->view->assign(compact('form', 'errors', 'submission'));
$this->_viewRenderer->renderScript('update.phtml');
}
}
So, would I just create a method in the Address class and somehow call it to swap out. I'm just not sure how to go about this.
You would be looking at using removeElement() to remove the select element, and then addElement() to replace it with the text only version.
The problem you are going to have is that when the validation fails, the select element is changed to a text element and the form is re-displayed. Now, upon resubmission, you need to make the change again prior to calling isValid() because the form uses text input for state instead of select. So you need to make the change twice. Once after failed validation prior to re-displaying the form, and once prior to calling isValid(), but only if there was a previously failed submission.
Now why is it that if the form fails validation, you want the select element for state to be text? Can't it work just the same with a select element and you just pre-select the correct state for them?
EDIT:
You use the form object to call add/removeElement.
$removed = $form->getSubForm('mailing')->removeElement('state_select');
$form->getSubForm('mailing')->addElement($text_state_element);
That call should work to remove an element from a subform.
Without subforms, it is just:
$form->removeElement('username');
$form->addElement($someNewElement);
You can use getElement() in a similar way if you need to get an element from a form to make changes (e.g. remove/add validators, change description, set values)
$el = $form->getElement('username');
$el->addValidator($something)
->setLabel('Username:');
Hope that helps.