Generating a zend form with dynamic data?
-
26-09-2019 - |
Question
I need to access my session and based on the session property I need to grab stuff from the database to use as options in my dropdown.
$_SESSION is:
[sess_name] => Array(
[properties] => Array(
1=> Hotel A,
2=> Hotel B
),
[selected] => 1
)
I need to grab Hotel A from selected, and then access all accounts under Hotel A from the database:
id title hotel_id
------------------------------
1 Hotel A Twitter Account 1
2 Hotel B Facebook Account 2
3 Hotel A Facebook Account 1
I need ids 1 and 3 because my hotel_id is 1 in the context of:
$this->addElement( 'select', 'account', array(
'multioptions' => $NEED_IT_HERE
));
Here's my query / session grabbing code:
$cs = new Zend_Session_Namespace( SESS_NAME );
$model = new Model_DbTable_Social;
$s = "
SELECT social_accounts.*
FROM social_accounts
LEFT JOIN social_media_outlets ON social_media_outlets.id = social_accounts.property
WHERE social_accounts.property=".(int)$cs->selectedclient;
I have this code in my form page, but I need to move it into my model now.
Solution
So where is your problem?
Make a proper query on your database to get those accounts.
Make a proper array from the result. ( id => Title )
You can set options on already existing element:
$element = $form->getElement('account');
$element->setMultiOption( $option_array );
You can create a method in your form class which would accept DB obj, Session obj and perform the actions needed to load and set those options.
model, which is in application/modules/foo/models/DbTable/Social, the model class name is Model_DbTable_Social and the module is foo. Throws Fatal error:
Your db-table class probably should be named:
Foo_Model_DbTable_Social
And application.ini should contain:
resources.modules[] =
; (It is autoloader for modules)
Class 'Model_DbTable_Social' when I try to invoke it in my form. Or is that way which you mention easier?
It is a good practice to ask for those resources in __construct like chelmertz said. Here is a nice talk on related subject: http://www.youtube.com/watch?v=-FRm3VPhseI
You might want to read my question on "where to connect forms to models": zend-framework doctrine, and mvc pattern: what kind of layer should connect data between models and forms? Not too many solutions though