How to create instance to zend controller - zend-framework

I have a controller named class TestController which extends some Zend_Controller_Action. Now I would like to use create an instance of TestController in TestForms (a Zend_Form). I want to populate a Zend_Form_Element_Select dynamically.
Please suggest how I can do this. Thanx in advance.

Where are you instantiating the form - is it in the controller? Instead of having the form call an action on the controller to dynamically get the values, you should look at setting the values on the form after it has been instantiated.
A quick and dirty way of doing that would be to grab the values in the controller and assign it to the element via:
$values = $db->query('query');
$element = $form->getElement('dynamicSelect');
$element->setValue($values);
Of course having DB queries to a table in your controller isn't exactly best practice... Per philistyne's suggestion, I use a a form builder class to build forms dynamically from my models. I have mappers for each model, and I pass in the mapper to the form builder class so it can dynamically populate my select elements.

A couple of things to try (passing a controller into a form or instantiating from within one is not recommended):
Use a model to access the dynamic values you want to put into your Zend_Form_Element_Select.
If the form is complex, create a form builder class to take care of, and separate out, the heavy lifting of the form construction.
Create customised form elements by extending from Zend_Form_Element_(Radio, Select, etc etc) if you feel you need very fine control over the form element's construction/behaviour/appearance, but wish to be able to reuse that element elsewhere.

Related

Initiating objects in Zend Framework?

How can I eliminate to write $object = new Application_Model_Database() in every controller?
For example for an article controller, I have to type $articles = new Application_Model_Articles() for every controller. Should I put it under viewer controller, action helpers, or any other way?
Your question almost sounds like an OOP best practices question as opposed to a Zend Framework specific question. Regardless of whether or not I'm using a framework, and regardless of what framework I choose, I base when and where I create new objects on testability how many times I have to write $object = new My_Random_Object();.
Speaking specifically to the Zend Framework: Objects I'm going to use everywhere, or almost everywhere, get created in Bootstrap.php. These objects generally include a database adapter, logger, view object, and any plugins I might use. To access these across the application, I'll create private properties in the appropriate controllers and assign the objects to those properties in the controller's init() method.
class ExampleController extends Zend_Controller_Action
{
public function init()
{
$bootstrap = $this->getInvokeArg('bootstrap');
$this->_db = $bootstrap->getResource('db');
$this->_log = $bootstrap->getResource('log');
// and so on, and so forth
}
}
Ideally, models, services, daos, etc, will all be relatively tightly grouped by controller and by action. In my experience, and this is speaking generally, if I have the same model or service class showing up across all of the controllers in my application, I have an organization problem. That being said, any model that shows up in only one action gets created in that action. If it's across actions in a controller, it gets created in the init() method and assigned to a property. If it shows up across multiple controllers, it gets created in my Bootstrap.php.
(Ideally, everything gets created in the Bootstrap.php, so you can swap out that bootstrap for testing purposes. Sadly, I don't always do that, and I most often use the principles I outlined above.)
Well do you really need it in every controllers? Because that's pretty much by design. You implement models when you need them. Its not that much code really.
Now if its to be used across actions from a controller you could always:
class MyController extends Zend_Controllers{
$protected $_articleModel;
...
and in your constructor or __init() function initialize it so you can use it in every action thru $this->_articleModel
If you REALLY want it everywhere in your application just initialize it in your bootstrap and store it in the registry.
public function __initModels(){
$articles = new Application_Model_Articles()
Zend_Registry::set('articles', $articles );
}
And access it in your controllers like so:
Zend_Registry::get('articles')->fetchAll();
But then your still writing a couple of characters.
Hope this help!
IF you want to use models in the controllers you must call it..anyway some shortcuts are here
1.You can initialize it in the init section of your controller like
public function init(){
$this->object = new Application_Model_Database();
}
So that the this->object is available in all the actions of that particular controller
2.Use Zend_registry as suggested in the above answer
Another possibility is to use a Dependency Injection container, such as the Symfony DI component. It takes care of instantiating your objects, and you get some additional benefits:
Separation of concerns. You have a component devoted to create your object tree.
Easier testability of the objects.
Last, but not least, the performance benefits given by lazy instantiation (objects are created only when you ask for them). Thus, if some object is not used by the particular controller serving your request, it's not instantiated).
It's a bit more laborious than the above solutions, but much more flexible if you need to maintain and extend your application in the future.
Hope that helps,
If you are using this object to just display data in your view and are using your controller to grab the data and assign it to your view, like so:
//someControllerAction
$object = new Application_Model_Articles();
$object->fetchAll();
//assign to view
$this->view->articles = $object;
You might be better off making a view helper similar to:
//Articles.php put in /application/views/helpers
class Zend_View_Helper_Articles extends Zend_View_Helper_Abstract {
public function Articles() {
$articles = new Application_Model_Articles();
$articles->fetchAll();
//return rowset object
return $articles;
Then in your view (phtml) you could do something like:
//someView.phmtl
<?php $articles = $this->Articles(); ?>
<h1><?php echo $this->escape($articles->title); ?></h1>
<p><?php echo $this->escape($articles->body); ?></p>
building a view helper allows you to bypass the controller completely if you just need to display data from the model. This is a very simple example and can be used with partials and partialLoops.
REF:ZF reference Custom View Helper
ZF partial view helper reference

Spring List Binding in Form

I'm trying to bind a list/arraylist/hashmap/etc of custom objects to my form in JSP using Spring. Right now, the controller creates a Map of the two lists (Boolean list and custom object list) in referenceData(), and provides it to the form which uses those values to populate the fields. The values are initialized from a MySQL database using Hibernate, and all that works fine. The list is a known length before the form is initialized, so that part is easier. Now what I'd like to do is correctly bind those objects in the form, so that when there are changes made, I can detect that in onSubmit() (or wherever is appropriate), and update the database accordingly. I can't seem to bind them correctly in the form so that I can see changes made. I tried just using a list of the form fields as the model, but even that wasn't working correctly. Do I just need to inject the list in a particular way? Any ideas or examples here? Any help would be greatly appreciated.
UPDATE: At Ralph's request here is the solution I used:
In my data object class, I lazy loaded a map using MapUtils.lazyMap(), with a String key and other custom object value. The other custom object is just a class that contains List<String> and getters/setters. In the corresponding .jsp file, I just nest several loops to loop through the keys first using loop.current.key and then loop2.current.value.paramsList to loop through the values for that key. This was not really what I asked for in my original post, as I was looking for a more general solution, and the lazy loading pointed me in the right direction.
In Spring 2 you need a special List in your Command object, that is able to grow if one add the x-th element event if the list has not this size yet.
One way to do that is to use LayzList decorator from commons-collections.
#Override
protected Object formBackingObject(final HttpServletRequest request)
throws Exception {
List<PosterSelectionRow> posterSelectionRowList = LazyList.decorate(
new ArrayList<PosterSelectionRow>(),
new PosterSelectionRowListFactory());
return new PosterSelectionCommand(posterSelectionRowList);
//PosterSelectionCommand contains a list of selected poster rows
}
private static class PosterSelectionRowListFactory
implements org.apache.commons.collections.Factory {
/** Invoked if the list need a new element */
public Object create() {
return = new PosterSelectionRow();
}
}
When I remember right, there is a way without that Factory stuff, but I am not sure.

Symfony : Add widgets to already defined form

I would like to add widgets (checkboxes) in an already defined form (with configure method).
I can't add them in the definition of the form because the number of widgets varies (according to the object).
I see two ways of doing it :
Either pass a variable into the configure method of the form or maybe use embedded forms.
But which one is the right way ? Is there another solution ?
Thank you
The right way is to pass the object right into the options. In the form you can use the $this->getOption method to retrieve the passed options.
I Agree with Don Pinkster on passing option and use it to configure form in configure() method.
But if need it or can't get the value when instanciating the class, you can use from anywhere :
$form->getWidgetSchema()->offsetSet($name, $widget);
$form->getValidatorSchema()->offsetSet($name, $validator)
The fact you use embedded forms or widget will not change that much, as you can do this after the form is initially configured :
$form->embedForm($name, $form2);
For just one checkbox I don't see advantages in using embedded form.
In both cases, I suggest you do this in a public method from your form's class, to avoid exploding the form configuration in the action class or elsewhere.
Regards,

Zend Framework - Using custom functions in Forms

I have MyForm extending Zend_Form, with init() doing regular job.
In this init() I also need to use a function to apply some transformation on some element values. Basically, get values from db -> custom transformation function -> apply them to form element.
I can put this custom function inside the form itself, but it's a general one and it will be reused by other forms.
Question: what is the best way to do this? I'm reading that helpers are associated more with views, and plugins with controllers. Is there a nice and easy way to get in the form the functionality of a custom function?
(something as helpers in symfony - just a bunch of functions)
Thanks.
p.s. this custom function is not a validator or so.

ASP.NET MVC 2 - Set ViewData on every request in specific area (without inheritance)

In the "Admin" area of my application, an object must be available in ViewData on every page (for display in the Master template). I have already inherited from Controller, so I cannot make a simple base class that handles it. What is a good solution of doing this when not using inheritance? An ActionFilter seems interesting but I don't want to put it on every controller in the Admin area. I'm considering the following:
Custom ControllerFactory that detects Area as well
Application_BeginRequest(), though I have no knowledge on executing controller then.
Maybe you have a better solution?
In this case I would create a separate action that executes a partial view that shows the data you need. In my opinion this is the most clean solution for this kind of problem and it's easily testable and reusable.
i have a dropdown on my masterpage. you dont need viewdata for it. i did it like this
code on masterpage:
<%= Html.DropDownList("schselectr", MVC2_NASTEST.MvcApplication.masterSchooljaarList())%>
in Global.asax.cs
public static SelectList masterSchooljaarList() {
NASDataContext _db = new NASDataContext();
List<Schooljaar> newlist = _db.Schooljaars.ToList();
return new SelectList(_db.Schooljaars.ToList(), "Sch_Schooljaar", "Sch_Schooljaar");
}
so simply, it calls the method, which returns the data i need, every time you load the page. easy, clean, effective.