subform within a subform - zend-framework

I'm working on a model using Zend Form. I have a subform called $product_item. I would like to add multiple instances of it to another subform called $items. How would I go about doing that? I'm not finding the Zend reference guide particularly helpful.

You can just add sub-forms to sub-forms:-
$form = new Application_Form_Test();
$subForm1 = new Application_Form_TestSubForm();
$subForm2 = new Application_Form_TestSubForm();
$subForm1->addSubForm($subForm2, 'sub2');
$form->addSubForm($subForm1, 'sub1');
$this->view->form = $form;
On submission the subform values will be available in arrays in the $_POST array. $value=$_POST['sub1']['sub2']['name'] for example.
http://framework.zend.com/manual/en/zend.form.forms.html#zend.form.forms.subforms
To print or access elements in sub forms you have several options:-
If $subForm1 has an element declared thus:-
$email = new Zend_Form_Element_Text('email');
Then the email field can be rendered in the view like this:-
<?php echo $this->element->sub1->email; ?>
Remember that the elements are referenced by their names not by the variables you use to declare them.
Also, remember that $this->element is referencing an instance of Zend_Form so you have all of those methods available. That means you can do this:-
<?php
$form = $this->element;
$formElements = $form->getElements();
?>

Related

Zend Form create button link

I have Zend_Form with button type element. i don't how to use onclick type from zend_form.
Index.phtml
Search
Zend_Form
$Search = new Zend_Form_Element_Submit('Search');
$Search->setAttrib('ID', 'searchbutton');
$Search->setDecorators(array('ViewHelper'));
Here using this zend form how to perform the onclick action using search button.could you please any one help on this?
Thanks for advice!
Hey you would have to do something like this
$Search = new Zend_Form_Element_Submit('Search');
$Search->setAttrib('ID', 'searchbutton');
$Search->setDecorators(array('ViewHelper'));
$form = new Zend_Form('FormExample');
$form->setAction('destination.php');
$form->setMethod('POST');
$form->addElement($Search);
$form->setView(new Zend_View());
print($form);
If you have other elements than the $Search you just have to addElements as an array, like this:
$form->addElements([$Search,$Element1, $Element2]);

Wordpress Plugins / Custom Class / get_option() / shortcode

I'm having an issue displaying information returned from a custom class defined within a plugin's files, when using a shortcode. I'll write up some mock files that showcase my issue.
/wp-content/plugins/my-plugin/classes/my_class.php
<?php
class People {
public $api_url = "https://www.external-service.com/api";
private $api_key;
function __construct($key = null) {
if $(key) {
$this->api_key = $key;
}
function get_response() {
$path = $this->api_url . "?my_api_token=" . $this->api_key;
}
}
?>
/wp-content/plugins/my-plugin/my-plugin.php
<?php
/**
* all of the wordpress plugin comments
* ...
*/
require "myplg_options.php";
require "myplg_shortcodes.php";
The options page and menu is generated from myplg_options; it is functioning correctly (including using get_option to retrieve the saved option (in this case, the api key).
/wp-content/plugins/my-plugin/myplg_shortcodes.php
<?php
require "classes/my_class.php";
$options = get_option('myplg_settings');
$myplg = new People($options['myplg_api_key']);
$response = $myplg->get_response();
function myplg_list_result(){
echo "the shortcode is working!";
var_dump($options, $myplg, $respnose);
}
add_shortcode('myplg_list', 'myplg_list_result');
?>
Testing externally from wordpress, the class works and everything is fine and dandy. The plugin's option page sets and retains the single option perfectly; the shortcode actually registers and is usable from within a WordPress page/portfolio/etc.
The issue I'm having is that using var_dump, all three of those variables are dumped as NULL.
After doing some homework, I was able to determine that moving the three variable declarations inside the shortcode makes it work. It would seem to me, however, that doing that is not the best workflow, as I'd need to re-grab the option, instantiate a new class, and call the class' function for every shortcode.
Is there a way around this?
As mentioned in the comment it's because variables are function scoped. You may be better off using a Closure.
<?php
require "classes/my_class.php";
$options = get_option('myplg_settings');
$myplg = new People($options['myplg_api_key']);
$response = $myplg->get_response();
add_shortcode('myplg_list', function() use ($options, $response, $myplg) {
echo "the shortcode is working!";
var_dump($options, $myplg, $respnose);
});

Zend Framework View Helper - how to get it to work

I'm trying to get started with Zend Framework , followed the quickstart project and am trying to start a new module of my own.
Am trying to implement view helpers and I keep getting the following message:
Message: Method formDate does not exist
Last entry at the stack trace:
0 D:\work\quickstart_zend\application\views\scripts\users\register.phtml(38): Zend_Form_Element->__call('formDate', Array)
I have the following file structure:
quickstart_zend
+ application
+ configs
+ controllers
[...]
+ views
+ helpers
+ scripts
[...]
+ library
+ Application
+ Form
+ Element
Date.php
+ View
+ Helper
FormDate.php
+ public
I have added in my public/Bootstrap.php this method:
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH.'/../library/Application/View/Helper', 'Application_View_Helper');
Zend_Controller_Action_HelperBroker::addPrefix('Application_View_Helper');
}
I have also added in my application.ini:
autoloaderNamespaces[] = "Application"
resources.view.helperPath.Application_View_Helper = APPLICATION_PATH "/../library/Application/View/Helper/"
And i have seen a version and also have tried with resources.view.helperPath.Application_View_Helper_, nothing seems to get it to work.
Of course, i have a Users.php form where i create a 'date' element:
// Add a dateOfBirth element
$element = new Application_Form_Element_Date('dateOfBirth');
$this->addElement($element);
Of course, i have a Users.php form where i create a 'date' element:
// Add a dateOfBirth element
$element = new Application_Form_Element_Date('dateOfBirth');
$this->addElement($element);
And in my view script, where the errors shows up:
<? echo $form->dateOfBirth->formDate() ?>
What am i missing to get it to work? :-( i've spent a day so far looking for solutions
You are receiving this error because there is no such method in Zend_Form_Element. I think you are trying to use your view helper to display in some way this form element, but if this is the case it is better to use form decorators. You can use the standard decorators or you can create a custom one. Check the documentation for more info - http://framework.zend.com/manual/en/zend.form.decorators.html
to properly use your view helper on that data you would use it like:
In your view (.phtml)
//a view helper should act on a piece of data and return something
//so I assume your formDate() helper takes a date value and reformats it.
<?php echo $this->formDate($this->form->dateOfBirth) ?>
assuming you assigned your form to the view in your controller using the standard:
$this->view->form = $form;

Populate values to checkbox while editing in zend framework

I am trying to populate the values into check box. I want check box to be checked when there is value stored in database.
This is my code in form:
$form ['test_1'] = new Zend_Form_Element_Checkbox('test_1');
$form['test_1']->setLabel('test1')->setCheckedValue('1');
$form ['test_2'] = new Zend_Form_Element_Checkbox('test_2');
$form['test_2']->setLabel('test2')->setCheckedValue('2');
If there is value 1 in database i want first check box to be checked and if its 2 then 2nd checkbox needs to be checked.
What do i need to do in the controller.
Could anyone please help me on this issue.
The easiest way would be to fetch the values from the database as an array that maps to the form input elements, e.g. return a row like
array('test_1' => 'value of checkbox', 'test_2' => 'value of checkbox');
You could then simply call $form->populate($values) and let do Zend_Form do the setting, e.g. in your controller do
public function showFormAction()
{
$form = $this->getHelper('forms')->get('MyForm');
$data = $this->getHelper('dbGateway')->get('SomeTable');
$form->populate($data->getFormData());
$this->view->form = $form;
}
Note: the helpers above do not exist. They are just to illustrate how you could approach this. Keep in mind that you want thin controllers and fat models, so you should not create the form inside the controller, nor put any queries in there.

Zend Avoid submit button value in GET parameters in url

I have a form, created with Zend_Form, with method = GET used for searching records with elements as below:
[form]
user name [input type="text" name="uname"]
[input type="submit" value="Search" name="search"]
[/form]
After form is submitted all the GET parameters along with submit button value are appearing in the url.
http://mysite.com/users/search?uname=abc&search=Search
How to avoid submit button value appearing in the url? is custom routing the solution ?
When you create your element, you can simply remove the name attribute that was automatically set at creation
$submit = new Zend_Form_Element_Submit('search')->setAttrib('name', '');
Or inside a Zend_Form
// Input element
$submit = $this->createElement('submit', 'search')->setAttrib('name', '');
// Or Button element
$submit = $this->createElement('button', 'search')->setAttribs(array
(
'name' => '', 'type' => 'submit',
);
When a form gets submitted, all of its elements with their names and values become a part of a GET / POST - query.
So, if you don't want an element to appear in your GET - query, all you need to do is to create this element without a name. That's probably not the best approach, but since we're talking about the 'submit' element, I guess it doesn't matter that much.
Looking at Zend_View_Helper_FormSubmit helper, you can see that it's creating the 'submit' element and setting its name. So, the possible solution would be to create your own view helper and use it for rendering the 'submit' element instead of the default helper.
You can set a custom helper with
$element->setAttribs( array('helper' => 'My_Helper_FormSubmit') );
Then build your own form element class and remove the name attribute from the element with preg_replace. The beauty of it is, it will not interfere with the other decorators.
So the something like this:
class My_Button extends Zend_Form_Element_Submit
{
public function render()
{
return preg_replace('/(<input.*?)( name="[^"]*")([^>]*>)/', "$1$3", parent::render(), 1);
}
}
You can remove name attribute for submit button in javascript.
jQuery example:
$('input[name="submit"]').removeAttr('name');
In the controller that represents the form's action, redirect to another (or the same controller) only including the relevant params.
Pseudocode:
$params = $this->getRequest()->getParams();
if isset($params['search'])
unset($params['search']);
return $this->_helper->Redirector->setGotoSimple('thisAction', null, null, $params);
handle form here
This is basically the same idea as Post/Redirect/Get except that you want to modify the request (by unsetting a parameter) in between the different stages, instead of doing something persistent (the images on that Wiki-page shows inserting data into a database).
If I were you, I would leave it in. IMO it's not worth an extra request to the webserver.