passing value to form - zend-framework

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!

Related

HTML::FormHandler dynamically set default form value

I'm using HTML::FormHandler and I'd like to be able to dynamically set default values for the form. Here would be a good example of what I would like to be able to do:
#this doesn't work
my $form = myapp::Form::Example->new(field1=>'default1',field2=>$default2);
In the example above, field1's value would hold "default1" and field2's value would hold whatever the scalar $default2 holds. However, the above example does not do this. Does anyone know of a way to do this? Thanks!
There are a lot of ways of setting default values. You can use an init_object:
my $form = MyApp::Form::Example->new;
$form->process( init_object => { field1 => 'default1', field2 => 'default2' }, ... );
You can also use the 'defaults' shortcut for updating fields dynamically:
$form->process( defaults => { field1 => 'default1', field2 => 'default2' }, ... );
The 'init_object' acts instead of a database row (item), so if you're also passing an 'item', you might also have to set the 'use_init_obj_over_item' flag. It uses the object/form 'value' format, which includes nested hashrefs and arrayrefs. The 'defaults' hashref requires a flattened hashref, such as you get from the 'fif' (fill-in-form) method.
See https://metacpan.org/module/HTML::FormHandler::Manual::Defaults
From the docs the code in the Q is good. Please try to debug thhe problem with the following. This will allow you peeek "inside" the object and see whats going on.
My guess: The default value gets overwritten with actual data or variable is empty.
use Data::Dumper;
print Dumper($default2);
my $form = myapp::Form::Example->new(field1=>'default1',field2=>$default2);
print Dumper($form);

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.

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

Drupal select list only submitting first character

I have a select list I've created in a form alter, however, when I select an option and submit the value, only the first digit gets stored in the database. I know this has something to do with how the array is formatted, but I can't seem to get it to submit properly.
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
$form['field_sr_account'] = array( '#weight' => '-50',
'#type' => 'select',
'#title' => 'Select which account',
'#options' => addSR_getMultiple());
//Custom submit handler
$form['#submit'][] = 'addSR_submit_function';
}
function addSR_submit_function{
$form_state['values']['field_sr_account'] = array('0' => array('value' => $form['#field_sr_account']));
Below is the function that returns the associative array. It is returning the proper options, as I can view the correct value/option in the HTML source when the page loads
//The values returned are not the problem, however, the format of the array could be..
function addSR_getMultiple(){
$return = array();
$return['one'] = 'Choice1'
$return['two'] = 'Choice2'
return $return;
}
Update:
Drupal 6: Only inserting first character of value to MySQL
I had a similar issue with the same field. However, in that case, I knew the value I wanted to submit, and I was able to assign the value to the field in the form alter, before the form was submitted. The difference with this issue, is that I don't know the value of the field until it is submitted, so I can't "assign" it in the form alter. How can I assign it the same way in the submit handler.
Edit after question update (and discovery of root problem within the linked separate question):
As you are trying to manipulate CCK fields, and those have pretty special handling mechanisms compared to 'standard' Drupal FAPI form elements, you should probably read up on CCK form handling in general, and hook_form_alter() and CCK fields and CCK hooks in particular. Glancing at those documentations (and the other CCK articles linked in the left sidebar), it looks like there should be a straight forward solution to your problem, but it might require some digging.
As a potential 'quick fix', you could try keeping your current approach, and adjust the submitted value on validation, somewhat like so:
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
$form['field_sr_account'] = array(
'#weight' => '-50',
'#type' => 'select',
'#title' => 'Select which account',
'#options' => addSR_getMultiple()
);
// Add custom validation handler
$form['#validate'][] = 'addSR_validate_function';
}
function addSR_validate_function (&$form, &$form_state) {
// Assemble result array as expected by CCK submit handler
$result = array();
$result[0] = array();
$result[0]['value'] = $form_state['values']['field_sr_account'];
// Set this value in the form results
form_set_value($form['field_sr_account'], $result, $form_state);
}
NOTE: This is untested code, and I have no idea if it will work, given that CCK will do some stuff within the validation phase as well. The clean way would surely be to understand the CCK form processing workflow first, and manipulating it accordingly afterward.