Set values to form builds by zend framework - forms

I use Zend framework to build the forms, I want to make the edit action, since the user click on edit, the form appears with users data, how can I set the data to the form which is built dynamically??

$form->populate($data);
where $data is an array of key value pairs containing your data.

$form = new Zend_Form;
if ($this->_request->isPost()) {
//to just populate
$form->populate($this->_getAllParams());
//or auto populate during validation
if ($form->isValid($this->_getAllParams()) {
//do stuff if valid
}
}
I know that ZF maunal is pretty messy and not everything is clear, but I think forms are explained pretty nice (with examples). You should research more by yourself.
http://framework.zend.com/manual/en/zend.form.html

$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());

Related

Trying to copy values into multiple embedded forms

I have a Symfony 1.4 application to allow users to enter data to a electrical appliance testing database. The page in questions consists of multiple embedded "new" forms so the user can submit many tests in one go. The form validates and saves correctly, but feedback is that it will be tedious to use.
As much of the data may be the same in each test (e.g. same date, same result, same person doing the testing), I would like the user to be able to fill in values in the top row, then click a button to fill the same information in the rows below. I'm pretty sure this would require javascript, but I don't have much experience.
I would appreciate any suggestions.
Many Thanks.
Well, I managed to figure it out without using javascript.
I put a button on the page
<input type="submit" name="copy_values" value="duplicate">
In the action for the page I included the code...
elseif (isset($_POST['copy_values'])) {
// get values from first embedded test
$newTests = $testList['new_tests'];
$testDate = $newTests[0]['et_date_tested'];
$testedBy = $newTests[0]['et_tester_id'];
$formOptions = array('test_date'=>$testDate, 'tester'=>$testedBy);
$this->form = new MultiTestForm(null, $formOptions);
}
$this->setTemplate('multiAdd');
... which takes the values from the widgets in the top row of the form and creates an array. This is passed as the options array to create a new form.
In the top level form class..
public function configure()
{
...
$subform = new sfForm();
for($i = 0;$i < sfConfig::get('app_new_test_rows'); $i ++)
{
$formToAdd = new TestsForMultiAddForm(null,$this->getOptions());
$subform->embedForm($i, $formToAdd);
}
$this->embedForm('new_tests', $subform);
}
...and in the embedded form class...
public function configure()
{
...
if ($this->getOption('test_date')) {
$this->setDefault('et_date_tested', $this->getOption('test_date'));
}
if ($this->getOption('tester')) {
$this->setDefault('et_tester_id', $this->getOption('tester'));
}
...
}
Not sure if this is the conventional way to approach the problem, but it works!

How to add two numbers in sugar crm

I made module addition and in this made three fields amount1_c, amount2_c and total_amount_c to add the two numbers and display the result in the third field. I done coding in the logic looks here is my code
<?
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(1,'calculate_field', 'custom/modules/cases/LogicHookMath.php','LogicHookMath', 'calculate_field');
?>
and made one more file logic hook math. here is my code for
<?php
class LogicHookMath {
function calculate_field(&$bean, $event, $arguments) {
$field1 = $bean->amount1_c;
$field2 = $bean->amount2_c;
$field3 = $field1 + $field2;
$bean->amount_total_c = $field3;
}
}
?>
but still i did not get any result. Please help me out for this.
The code looks correct.
Some common "mistakes" when custom logic hooks are not working:
Make sure, the custom logic hook has the correct name (LogicHookMath.php)
Make sure, that the $bean variable is prefixed with &, so the variable is passed as a reference
Make sure the logic_hooks.php and the LogicHookMath.php files are readable by the web server user
The entire custom directory should also be writeable for the web server user
If the above does not help, try logging the progress to the sugarcrm.log using $GLOBALS['log']->info( "Value 3: ". $field3); in the custom logic hook.

Help needed formatting Doctrine Query in Zend Framework

Can anyone tell me how to format the query below correctly in my controller.
Currently it gives me nothing in my FilteringSelect. However if I change it to >= I get back all the kennelIDs which is incorrect also but at least I'm getting something.
I've tested that the session variable is set and can confirm that there are kennels with the matching capacity.
// Create autocomplete selection for the service of this booking
public function servkennelAction()
{
$sessionKennelBooking = new Zend_Session_Namespace('sessionKennelBooking');
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
// get list of grooming services for dogs from the table
$qry= Doctrine_Query::create()
->from('PetManager_Model_Kennels k');
//This should be set by default and narrows down the search criteria
if(isset($sessionKennelBooking->numPets)){
$b=(int)$sessionKennelBooking->numPets;
$qry->addWhere('k.capacity = ?','$b');
}
$result=$qry->fetchArray();
//generate and return JSON string using the primary key of the table
$data = new Zend_Dojo_Data('kennelID',$result);
echo $data->toJson();
}
Many thanks in Advance.
Graham
I think that addWhere condition is wrong. It has to be:
$qry->addWhere('k.capacity = ?', $b);
i.e. $b without quotes.

How to get zend_lucene and zend_paginator to work

I've been using Zend Framework for a few months now. So, my knowledge is pretty good but I'm not quite an expert yet. I am trying to use zend_lucene with zend_paginator and so far not successful. I am able to use zend_lucene and index data successfully by itself and able to do use zend_paginator when querying the database, but I can't seem to combine the two. Here is a sample of what I am doing:
try {
$searchresults = $index->find($lucenequery);
}
catch (Zend_Search_Lucene_Exception $e) {
echo "Unable {$e->getMessage()}";
}
$page = $this->_getParam('page',1);
$paginator = Zend_Paginator::factory($searchresults);
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;
Is there a different step I need to do with lucene and zend_paginator? I am really uncertain. The result I get is that for the first page results display properly. But when I hit the second page or third my results are blank. So uncertain what might be wrong as I can't find docs or tutorials in using the two together. Any help would be greatly appreciated.
I think this may work with the iterator adapter:
public function searchAction() {
$index = Zend_Search_Lucene::open('/path/to/lucene');
$results = $index->find($this->_getParam('q'));
$paginator = Zend_Paginator::factory($results);
$paginator->setCurrentPageNumber($this->_getParam('page', 1));
$paginator->setItemCountPerPage(10);
$this->view->results = $paginator;
}
Perhaps the problem you are having is that $paginator doesn't know how many search results there are..
So you may need to do that manually:
$paginator->setDefaultPageRange($results->count());

Zend Framework email content generation

With Zend_Framework, I wondered what is considered best practice for building up the content to send in a HTML email. In my case the content of the email that is sent is determined by a number of factors, for example the number of returned rows for a specific value in the database. Because of this it makes sense for me that the content is built up within the controller that sends the email which talks to the relevant database models and determines what the content should be. Where i'm not sure this works is that our designers and copyrighters will often want to adjust the copy in emails and this would then require them to make changes to a model or ask me to. Should i be handling this differently? Should i perhaps be storing HTML snippets somewhere containing the different text and then calling these somehow?
EDIT following from the answer by fireeyedboy, would it be acceptable to do something like this. Create a folder inside views called "partials" and use this to store text/html snippets that i can then call in where i need and replace special strings with dynamic values using regexp(or similar).
$nview = new Zend_View();
$nview->setScriptPath(APPLICATION_PATH.'/views/partials/');
$bodytext = $nview->render('response.phtml');
$mail = new Zend_Mail();
$mail->setBodyText($bodytext);
// etc ...
e.g. in this context where two different templates could be used depending on variables returned from a Model:
// within a controller
public function emailAction()
{
$images = new Model_ApplicationImages();
$totimages = count($images->fetchImages($wsid));
$acceptedImages = $images->fetchImages($wsid,'approved');
$accepted = count($acceptedImages);
$rejectedImages = $images->fetchImages($wsid,'rejected');
$rejected = count($rejectedImages);
$response = ($rejected == $totimages)?'rejected':'approved';
$nview = new Zend_View();
$nview->setScriptPath(APPLICATION_PATH.'/views/partials/');
$content = $nview->render($response.'.phtml');
$mail = new Zend_Mail();
$mail->setBodyText($content);
// etc
}
Is there a more elegant way i can/should be doing this?
Not sure if this is best practice, but what I did is extend Zend_Mail with methods like these:
setTemplatePath( $templatePath );
setTemplateHtml( $templateHtml );
setTemplateText( $templateText );
setTemplateArguments( array $templateArguments );
...then at some point in my overwrittensend() I do:
$view = new Zend_View();
$view->setScriptPath( $this->_templatePath );
foreach( $this->_templateArguments as $key => $value )
{
$view->assign( $key, $value );
}
if( null !== $this->_templateText )
{
$bodyText = $view->render( $this->_templateText );
$this->setBodyText( $bodyText );
}
if( null !== $this->_templateHtml )
{
$bodyHtml = $view->render( $this->_templateHtml );
$this->setBodyHtml( $bodyHtml );
}
So to utilize this you would do something like:
$mail = new My_Extended_Zend_Mail();
$mail->setTemplatePath( 'path/to/your/mail/templates' );
$mail->setTemplateHtml( 'mail.html.phtml' );
$mail->setTemplateText( 'mail.text.phtml' );
$mail->setTemplateArguments(
'someModel' => $someFunkyModel,
/* etc, you get the point */
)
$mail->send();
In other words, with this you can let your designers and copywriters simply edit views (templates) like they are used to already. Hope this helps and has inspired you to come up with something funky that suits your needs.
PS:
Since you mention arbitrary data rows, you can, for instance, utilize the partialLoop view helper that comes with ZF for this. But you probably were aware of this already?
PPS:
I actually agree with chelmertz' comment about not extending Zend_Mail but wrapping it in my own component.