I've read through the tutorials/reference of the Form-Component in Zend-Framework 2 and maybe I missed it somehow, so I'm asking here.
I've got an object called Node and bound it to a form. I'm using the Zend\Stdlib\Hydrator\ArraySerializable-Standard-Hydrator. So my Node-object has got the two methods of exchangeArray() and getArrayCopy() like this:
class Node
{
public function exchangeArray($data)
{
// Standard-Felder
$this->node_id = (isset($data['node_id'])) ? $data['node_id'] : null;
$this->node_name = (isset($data['node_name'])) ? $data['node_name'] : null;
$this->node_body = (isset($data['node_body'])) ? $data['node_body'] : null;
$this->node_date = (isset($data['node_date'])) ? $data['node_date'] : null;
$this->node_image = (isset($data['node_image'])) ? $data['node_image'] : null;
$this->node_public = (isset($data['node_public'])) ? $data['node_public'] : null;
$this->node_type = (isset($data['node_type'])) ? $data['node_type']:null;
$this->node_route = (isset($data['node_route'])) ? $data['node_route']:null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
In my Controller I've got an editAction(). There I want to modify the values of this Node-object. So I am using the bind-method of my form. My form has only fields to modify the node_name and the node_body-property. After validating the form and dumping the Node-object after submission of the form the node_name and node_body-properties now contain the values from the submitted form. However all other fields are empty now, even if they contained initial values before.
class AdminController extends AbstractActionController
{
public function editAction()
{
// ... more stuff here (getting Node, etc)
// Get Form
$form = $this->_getForm(); // return a \Zend\Form instance
$form->bind($node); // This is the Node-Object; It contains values for every property
if(true === $this->request->isPost())
{
$data = $this->request->getPost();
$form->setData($data);
// Check if form is valid
if(true === $form->isValid())
{
// Dumping here....
// Here the Node-object only contains values for node_name and node_body all other properties are empty
echo'<pre>';print_r($node);echo'</pre>';exit;
}
}
// View
return array(
'form' => $form,
'node' => $node,
'nodetype' => $nodetype
);
}
}
I want to only overwrite the values which are coming from the form (node_name and node_body) not the other ones. They should remain untouched.
I think a possible solution would be to give the other properties as hidden fields into the form, however I don't wanna do this.
Is there any possibility to not overwrite values which are not present within the form?
I rechecked the code of \Zend\Form and I gotta be honest I just guessed how I can fix my issue.
The only thing I changed is the Hydrator. It seems that the Zend\Stdlib\Hydrator\ArraySerializable is not intended for my case. Since my Node-Object is an object and not an Array I checked the other available hydrators. I've found the Zend\Stdlib\Hydrator\ObjectProperty-hydrator. It works perfectly. Only fields which are available within the form are populated within the bound object. This is exactly what I need. It seems like the ArraySerializable-hydrator resets the object-properties, because it calls the exchangeArray-method of the bound object (Node). And in this method I'm setting the non-given fields to null (see code in my question). Another way would propably be to change the exchangeArray-method, so that it only sets values if they are not available yet.
So the solution in the code is simple:
$form = $this->_getForm();
$form->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty()); // Change default hydrator
There is a bug in the class form.php, the filters are not initialized in the bindvalues method just add the line $filter->setData($this->data);
it should look like this after including the line
public function bindValues(array $values = array())
{
if (!is_object($this->object)) {
return;
}
if (!$this->hasValidated() && !empty($values)) {
$this->setData($values);
if (!$this->isValid()) {
return;
}
} elseif (!$this->isValid) {
return;
}
$filter = $this->getInputFilter();
$filter->setData($this->data); //added to fix binding empty data
switch ($this->bindAs) {
case FormInterface::VALUES_RAW:
$data = $filter->getRawValues();
break;
case FormInterface::VALUES_NORMALIZED:
default:
$data = $filter->getValues();
break;
}
$data = $this->prepareBindData($data, $this->data);
// If there is a base fieldset, only hydrate beginning from the base fieldset
if ($this->baseFieldset !== null) {
$data = $data[$this->baseFieldset->getName()];
$this->object = $this->baseFieldset->bindValues($data);
} else {
$this->object = parent::bindValues($data);
}
}
to be precious it is line no 282 in my zf2.0.6 library
this would fix your problem, this happen only for binded object situation
I ran into the same problem, but the solution of Raj is not the right way. This is not a bug as for today the code remains still similar without the 'fix' of Raj, adding the line:
$filter->setData($this->data);
The main problem here is when you bind an object to the form, the inputfilter is not stored inside the Form object. But called every time from the binded object.
public function getInputFilter()
...
$this->object->getInputFilter();
...
}
My problem was that I created every time a new InputFilter object when the function getInputFilter was called. So I corrected this to be something like below:
protected $filter;
...
public function getInputFilter {
if (!isset($this->filter)) {
$this->filter = new InputFilter();
...
}
return $this->filter;
}
I ran into the same issue today but the fix Raj suggested did not work. I am using the latest version of ZF2 (as of this writing) so I am not totally surprised that it didn't work.
Changing to another Hydrator was not possible as my properties are held in an array. Both the ObjectProperty and ClassMethods hydrators rely on your properties actually being declared (ObjectProperty uses object_get_vars and ClassMethods uses property_exists). I didn't want to create my own Hydrator (lazy!).
Instead I stuck with the ArraySerializable hydrator and altered my exchangeArray() method slightly.
Originally I had:
public function exchangeArray(array $data)
{
$newData = [];
foreach($data as $property=>$value)
{
if($this->has($property))
{
$newData[$property] = $value;
}
}
$this->data = $newData;
}
This works fine most of the time, but as you can see it blows away any existing data in $this->data.
I tweaked it as follows:
public function exchangeArray(array $data)
{
$newData = [];
foreach($data as $property=>$value)
{
if($this->has($property))
{
$newData[$property] = $value;
}
}
//$this->data = $newData; I changed this line...
//to...
$this->data = array_merge($this->data, $newData);
}
This preserves any existing keys in $this->data if they are missing from the new data coming in. The only downside to this approach is I can no longer use exchangeArray() to overwrite everything held in $this->data. In my project this approach is a one-off so it is not a big problem. Besides, a new replaceAllData() or overwrite() method is probably preferred in any case, if for no other reason than being obvious what it does.
Related
Hi all I'm using zend framework (but I think this is irrelevant) and php5 and I just want to modify an object of an object
public function saveSite($post) {
$form = new Diff_Form_Download();
$subform = new Diff_Form_DownloadSubform();
$form = $this->view->form;
$newSite = 0;
$sitesRecord = new Diff_Model_Sites();
$debugString = null;
if (is_array($post)) {
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
echo $debugString;
//new site instertion
if (is_null($subform)) {
$subform = $form->getSubForm('NewSite');
$newSite = 1;
}
$values = reset($subform->getValues());
$sitesRecord = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $values['idSite']);
if ($sitesRecord) {
$sitesRecord->idSite = $values['idSite']; //useless but necessary to make Doctrine understand to use update?
} else { //if the record is not present instantiate a new object (otherwise save() will not work
$sitesRecord = new Diff_Model_Sites();
}
$sitesRecord->content = $subform->getContent(); //$values['content'];
$sitesRecord->newHtml = $subform->getContent();
$sitesRecord->url = $values['url'];
$sitesRecord->shortName = $values['shortName'];
$sitesRecord->lastChanged = date("Y-m-d H:i:s");
$sitesRecord->pollingHours = $values['pollingHours'];
$sitesRecord->minLengthChange = $values['minLenghtChange'];
if (Zend_Auth::getInstance()->hasIdentity()) { //save the owner
$sitesRecord->idOwner = Zend_Auth::getInstance()->getIdentity()->idOwner; //retrieve the owner
$sitesRecord->save();
} else {
throw new Exception("your session have expired: \n please login again");
}
}
}
/**
* return the calling subform
* #param type $post
* #return type
*/
public function getSubformByPost($post) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subformName = "site" . $post['idSite'];
$subform = $form->getSubForm($subformName);
return $subform;
}
public function refreshOneDiff($post) {
$debugString;
if (is_array($post)) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subform = $this->getSubformByPost($post);
if (!$subform)
$subform = $this->view->form->getSubformByPost('NewSite');
$url = $subform->getUrl();
$idSite = $subform->getIdSite();
$crawler = new Crawler();
$newpageContent = $crawler->get_web_page($url);
$siteRecord = new Diff_Model_Sites();
$siteRecord = $subform->getSiteRecord();
if ($siteRecord) //check if the record is not null
$oldpageContent = $siteRecord->get('content');
else
$oldpageContent = null;
$differences = $this->getDiff($oldpageContent, $newpageContent);
if (!is_null($differences)) {
$siteRecord->content = $newpageContent;
$subform->setContent($newpageContent);
$subform->setContentDiff($differences);
$subform->setSiteRecord($siteRecord);
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
}
//echo $debugString;
$sitePresence = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $idSite);
if ($sitePresence) {
//$this->saveSite($post);
$this->debugtry($post);
}
} else {
}
}
Basically what I'm doing here is:
1) grab a the form from the view
2) grab a subform from the form (let's call it SubformX)
3) grab an object "siteRecordX" from SubformX
4) change a value of "siteRecordX"
5) call a function saveRecord()
6) In this function regrab the same SubformX and echoing the value of the object siteRecordX
Surprisingly if i change a variable of SubformX it will stay that way, if I change a variable of an object of SubformX it will remain unchanged (if I retrieve SubformX).
It looks like, even if SubformX is passed by reference it is not the same for it's subobjects, wich are passed by value and so they disappear changing the context of the function.
Can you please help me?
Thanks
EDIT
I still cannot solve this issue nor understand it:
This is the constructor of the subform:
public function __construct($site = null, $options = null) {
if ($site instanceof Diff_Model_Sites) {
$this->_shortName = $site->get('shortName');
$this->_url = $site->get('url');
$this->_content = $site->get('content');
$this->_idSite = $site->get('idSite');
$this->_siteRecord = $site;
$this->_lastChanged = $site->get('lastChanged');
}parent::__construct($options);}
while this is the function of SubformX i use to set the value.
public function setContent($contentText) {
$this->_siteRecord->content = $contentText;
$this->_content = $contentText;
}
and this is the function of the subform that I call to get the value
public function getContent() {
if (isset($this->_siteRecord)) {
//return $this->_content;
return $this->_siteRecord->content;
}
}
with the commented line I'm able to retrieve the updated value, not with the second.
This is a real mystery to me because i set and get them exactly the same way at exactly the same point and i cannot understand the difference.
Your _siteRecord property is an ORM object (Doctrine, it appears). So its data may have some behaviors that are not standard for a reference-type object. It surely has some override of __get and __set. It also employs caching. These things are necessary to keep the database-model interaction working properly, but they can confuse what should be a reference and value types. (See: http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html)
P.S.: in your constructor you use:
$this->_content = $site->get('content');
$this->_siteRecord = $site;
but in your getContent() you use:
$this->_siteRecord->content;
That difference might be part of the problem.
Thank you all guys. It was Doctrine caching.
I have not investigated further the problem, but after getting rid of Doctrine everything works fine.
I have lost one entire day after this issue.
Moreover today I have lost another day for another curious problem related to Doctrine.
It seems that each time you gather data from your db Doctrine decode them for you (just like the php function utf8_decode($data).
Of course if you get the data and then put it back in the db again it will result in a total mayhem of coding and decoding.
This is enough. I still think that ORM are great programming tools but simply Doctrine is not.
I will not rest in peace since I'll have it eliminated from my program.
I will use Zend_Db library instead. Which I have mostly already done without regret and without facing the above-mentioned Doctrine's problems.
Again thanks to Seth Battin and Dave Random for the help and patience to understand my noob-coding.
I'm wondering if there was a way to add a group of elements to a zend form as if they were one element, I guess much like a subform, but it seems the functionality of a subform may be too much...
Here's my use-case. I've created a class that handles multi-page forms. I want to be able to write logic to change the buttons at the bottom of the form based on the page of the form I'm on.
I originally thought that Zend-Form-DisplayGroup would fix my problem, but you have to add the items to the form first and then add them to the display group and can't pass a display group through a function with attached elements. I would like to have a function that would be something like
public function setSubmitButtonGroup($submitButtonGroupElements)
{
/*Code to set button group*/
}
The idea of using an array of elements just hit me right now as opposed to something else and add logic to add that array of elements to the form on render... but does anyone have any "better" ideas or done this before?
BTW, if anyone is wondering... I'm loosely basing my initial design off of this section: Zend Framework Advance Form Usage.
Not sure I understand your problem correctly but this how I do some things.
In a Zend_Form object you can add elements as a group with `addElements($elements) in an array. For the Submit button etc. I have a class where I get the $elements array from and then I simply pop it in. I also add a displayGroup but separately and simply to control where the buttons are. Because a form is an object you can do simple things like the following but I always add a reference to show my intent.
update: shuffled the button manipulation
function addButtons(&$form,$nextName = null) {
$buttons = $this->getButtons(); // this will be an array with your buttons
// make sure you have the element names in your buttons arrays
if ( is_string($nextName) ) {
$buttons['nextButton']->setLabel($nextName);
} elseif ( is_bool($nextName) && false === $nextName ) {
unset($buttons['nextButton'];
}
// repeat for other buttons
$form->addElements($buttons);
$elementNames = array_keys($buttons);
$form->addDisplayGroup($elementNames,'buttonGroup',array('legend'=>'Click some buttons'));
}
$this->addButtons($form,'Finish');
You could make yourself a factory that receive three params, your form element, the current controller and the current action. Then in that factory, you could call a builder based on the controller/action combination and you pass your form.
In your builder you add 1, 2 or 3 buttons based on the corresponding controller/action requirement which are stored in diffrent components. Once it is done, you return your form to the factory and the factory return the form.
My_Form // your Zend_Form object
My_Form_Factory // Your new factory (see below)
My_Form_Factory_Builder_Controller_Action // One of your builder (see below)
My_Form_Factory_Component // Extends the corresponding Zend_Form_Elements
// basic factory that can be called like My_Factory::factory($form, $controller, $action)
class My_Form_Factory {
static public function factory($form, $controller, $action)
$builderClass = "My_Form_Factory_Builder_" . $controller . '_' . $action;
$builder = new $builderClass($form);
return $builder->buildForm();
}
// Basic builder
class My_Form_Factory_Builder_Controller_Action
{
protected $_form;
protected $_previousComponent ;
protected $_nextComponent ;
protected $_cancelComponent ;
public function __construct($form)
{
$this->_form = $form;
$this->_previousComponent = new My_Form_Factory_Component_Previous();
$this->_nextComponent = new My_Form_Factory_Component_Next();
$this->_cancelComponent = new My_Form_Factory_Component_Cancel();
}
public function buildForm()
{
$this->_form->addElement($previousCompnent);
$this->_form->addElement($nextComponent);
$this->_form->addElement($cancelComponent);
return $this->_form;
}
}
If you want to automatize the instanciation you could initialize all the different compoments you might require in an abstract class and in the method buildForm() only add the elements you need for that current interface. (I would rather repeat the code in each builder than rely on this kind of "magic" but it a viable method to do it).
So the complexity of my problem comes with knowing what page of the multipage form. Using an array and the above mentioned addElements() helped.
Simple Answer
The answer to my problem was an array that could be manipulated after the form was "built" so to speak but before it was rendered so that I could add to the form using addElements().
Long Answer
To get the whole picture, imagine each time you hit the next or previous button, you are traversing through an array of subforms. In this case one would need a function to handle the button rendering. I ended up using a case statment, though it's not the best implementation in the world (not reusable in the parent class Form_MultiPage), but it worked:
in my extention of my mulipage form class I have
public function setSubmitControls()
{
$previous = new Zend_Form_Element_Submit('previous',array(
'label'=>'previous',
'required'=>false,
'ignore'=>false,
'order'=>9000
));
$cancel = new Zend_Form_Element_Submit('cancel',array(
'label'=>'Cancel',
'required'=>false,
'ignore'=>false,
'order'=>9003
));
$next = new Zend_Form_Element_Submit('next',array(
'label'=>'Next',
'required'=>false,
'ignore'=>false,
'order'=>9002
));
$finished = new Zend_Form_Element_submit('finish',array(
'label'=>'Finish',
'required'=>false,
'ignore'=>false,
'order'=>9004
));
$submitControls = array();
echo var_dump($this->getCurrentSubForm()->getName());
switch($this->getCurrentSubForm()->getName())
{
case 'billInfo':
$submitControls = array(
$next,
$cancel
);
break;
case 'payerInfo':
$submitControls = array(
$previous,
$next,
$cancel
);
break;
//So on for other subforms
}
$this->setSubmitButtonGroup($submitControls);
}
In my parent class, Form_Multipage, I have
public function setSubmitButtonGroup(array $elements)
{
$this->_submitButton = $elements;
}
And
public function addSubmitButtonGroupToSubForm(Zend_Form_SubForm $subForm)
{
$subForm->addElements($this->_submitButton);
return $subForm;
}
Which is called when I render the "page" of the form with this function
public function prepareSubForm($spec)
{
if (is_string($spec)) {
$subForm = $this->{$spec};
} elseif ($spec instanceof Zend_Form_SubForm) {
$subForm = $spec;
} else {
throw new Exception('Invalid argument passed to ' .
__FUNCTION__ . '()');
}
$subform = $this->setSubFormDecorators($subForm);
$subform = $this->addSubmitButtonGroupToSubForm($subForm);
$subform = $this->addSubFormActions($subForm);
$subform->setMethod($this->getMethod());
return $subForm;
}
I've been looking at this event-listeners page http://www.doctrine-project.org/documentation/manual/1_1/pl/event-listeners and I'm not sure which is the listener I have to use to make a change after the doSave() method in the BaseModelForm.class.php.
// PlaceForm.class.php
protected function doSave ( $con = null )
{
...
parent::doSave($con);
....
// Only for new forms, insert place into the tree
if($this->object->level == null){
$parent = Place::getPlace($this->getValue('parent'), Language::getLang());
...
$node = $this->object->getNode();
$method = ($node->isValidNode() ? 'move' : 'insert') . 'AsFirstChildOf';
$node->$method($parent); //calls $this->object->save internally
}
return;
}
What I want to do is to make a custom slug with the ancestors' name of that new place. So if I inserting "San Francisco", the slug would be "usa-california-san-francisco"
public function postXXXXXX($event)
{
...
$event->getInvoker()->slug = $slug;
}
The problem is that I'm inserting a new object with no reference to its parent. After it's saved, I insert it to the tree. So I can't change the slug until then.
I think a Transaction listener could work, but I'm use there is a better way I'm not seeing right now.
thanks!
You are looking at the wrong piece of code. As stated by benlumley, you should manage your slug directly in the model, not in the form. To achieve what you want (a recursive slug) is quite easy using doctrine's Sluggable behavior. You need to implement a getUniqueSlug() into your model so that it gets called by the behavior (it's automatic) and handle your slug specifities in there:
public function getUniqueSlug()
{
$slug = '';
$parent = $this->getParent();
if ($parent->exists())
{
$slug = $this->getParent()->getUniqueSlug().'-';
}
return $slug.$this->getName();
}
What we do here is basically traverse all the ancestors of the current object and append the slugs on the go (replace the getParent() by whatever method you use to retrieve an object's parent.
Firstly, I'd put this into the model rather than the form - that way if the object is ever edited/updated the behaviour would still happen.
In the form though, I'd use updateObject:
function updateObject($values = array()) {
parent::updateObject($values);
// do your stuff
}
In the model (looks like you are using doctrine ...) I'd put this into the postSave() method. As I say, I think its better there than the form.
I had the same problems, and the Doctrine_Record::postInsert(Doctrine_Event $event) method did not work for me. Indeed the node aren't hydrated yet.
I had to overwrite the sfFormObject::doSave method like this:
protected function doSave($con = null)
{
$is_new = $this->isNew();
parent::doSave($con);
$this->doSaveNestedSet($con);
$service = $this->getObject();
if( $is_new and ! $service->getClientId() and $parent = $service->getParent())
{
$service->setClient($parent->getClient());
$service->save();
}
}
Once you're OK with basic record form built after example from Tutorial, you realize you want more professionally designed Record Form. E.g. I don't want to duplicate record form for the same table in User and Admin areas.
1) Does anyone use some mechanism, possibly inheritance, to reduce duplication of almost similar admin and user forms? Is that burdensome or sometimes you better just do with copy-pasting?
2) Has anyone considered it to be a good idea to build some basic Record class
that can determine that among several record forms on this page, the current post is addressed specifically to this record form
that can distinguish between Edit or Delete buttons clicks in some organized fashion.
3) My current practice includes putting all form config code (decorators, validations, initial values) into constructor and form submit handling is put into a separate ProcessSubmit() method to free controller of needless code.
All the above addresses to some expected Record Form functionality and I wonder if there is any guideline, good sample app for such slightly more advanced record handling or people are still reinveting the wheel. Wondering how far you should go and where you should stop with such impovements...
Couple of suggestions:
First of all - Use the init() function instead of constructors to add your elements when you are subclassing the form. The init() function happens after the parameters you pass to the class are set.
Second - Instead of subclassing your form - you can just set an "option" to enable the admin stuff:
class My_Record_Form extends Zend_Form {
protected $_record = null;
public function setRecord($record) {
$this->_record = $record;
}
public function getRecord() {
if ($this->_record === null || (!$this->_record instanceOf My_Record)) {
throw new Exception("Record not set - or not the right type");
}
return $this->_record;
}
protected $_admin = false;
public function setAdmin($admin) {
$this->_admin = $admin;
}
public function getAdmin() { return $this->_admin; }
public function init() {
$record = $this->getRecord();
$this->addElement(......);
$this->addElement(......);
$this->addElement(......);
if ($this->getAdmin()) {
$this->addElement(.....);
}
$this->setDefaults($record->toArray());
}
public function process(array $data) {
if ($this->isValid($data)) {
$record = $this->getRecord();
if (isset($this->delete) && $this->delete->getValue()) {
// delete button was clicked
$record->delete();
return true;
}
$record->setFromArray($this->getValues());
$record->save();
return true;
}
}
}
Then in your controller you can do something like:
$form = new My_Record_Form(array(
'record'=>$record,
'admin'=>My_Auth::getInstance()->hasPermission($record, 'admin')
));
There is nothing "wrong" with making a My_Record_Admin_Form that handles the admin stuff as well - but I found this method keeps all the "record form" code in one single place, and a bit easier to maintain.
To answer section 2: The edit forms in my code are returned from a function of the model: $record->getEditForm() The controller code ends up looking a little like this:
protected $_domain = null;
protected function _getDomain($allowNew = false)
{
if ($this->_domain)
{
return $this->view->domain = $this->_domain;
} else {
$id = $this->_request->getParam('id');
if (($id == 'new' || $id=='') && $allowNew)
{
MW_Auth::getInstance()->requirePrivilege($this->_table, 'create');
$domain = $this->_table->createRow();
} else {
$domain = $this->_table->find($id)->current();
if (!$domain) throw new MW_Controller_404Exception('Domain not found');
}
return $this->view->domain = $this->_domain = $domain;
}
}
public function editAction()
{
$domain = $this->_getDomain(true);
MW_Auth::getInstance()->requirePrivilege($domain,'edit');
$form = $domain->getEditForm();
if ($this->_request->isPost() && $form->process($this->_request->getPost()))
{
if ($form->delete && $form->delete->getValue())
{
return $this->_redirect($this->view->url(array(
'controller'=>'domain',
'action'=>'index',
), null, true));
} else {
return $this->_redirect($this->view->url(array(
'controller'=>'domain',
'action'=>'view',
'id'=>$form->getDomain()->id,
), null, true));
}
}
$this->view->form = $form;
}
So - the actual id of the record is passed in the URI /domain/edit/id/10 for instance. If you were to put multiple of these forms on a page - you should make sure to set the "action" attribute of the form to point to an action specific to that form.
I created a SimpleTable extends Zend_Db_Table and SimpleForm extends Zend_Db_Form classes. Both of these assume that your table has an auto-incrementing ID column.
SimpleTable has a saveForm(SimpleForm $form) function which uses the dynamic binding to match form element names to the columns of the record. I also included an overridable saveFormCustom($form) for any special handling.
The SimpleForm has an abstract setup() which must be overridden to setup the form. I use the init() to do the initial setup (such as adding the hidden ID field).
However, to be honest, I really don't like using the Zend_Form object, I feel like that should be handled in the View, not the Model or Controller.
I'm overriding my doSave() method to basically do the following: I have a sfWidgetFormPropelChoice field that the user can either choose from, or type a new option. How can I change the widget's value? Or maybe I am approaching this the wrong way. So here is how I overrode the doSave() method:
public function doSave($con = null)
{
// Save the manufacturer as either new or existing.
$manufacturer_obj = ManufacturerPeer::retrieveByName($this['manufacturer_id']->getValue());
if (!empty($manufacturer_obj))
{
$this->getObject()->setManufacturerId($manufacturer_obj->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD?
}
else
{
$new = new Manufacturer();
$new->setName($this['manufacturer_id']->getValue());
$new->save();
$this->getObject()->setManufacturerId($new->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD?
}
parent::doSave($con);
}
You should use setDefault or setDefaults and then it will autopopulate with the bound values.
(sfForm) setDefault ($name, $default)
(sfForm) setDefaults ($defaults)
usage
$form->setDefault('WidgetName', 'Value');
$form->setDefaults(array(
'WidgetName' => 'Value',
));
You could do it in the action :
$this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */
$this->form->save();
But I prefer to do the kind of work you are doing with your manufacturer directly in my Peer so my business logic is always at the same place.
What I put in my forms is mainly validation logic.
Example of what to put in the save method of the Peer :
public function save(PropelPDO $con= null)
{
if ($this->isNew() && !$this->getFooId())
{
$foo= new Foo();
$foo->setBar('bar');
$this->setFoo($foo);
}
}
Two assumption here: a) your form gets the name of the manufacturer and b) your model wants the ID of a manufacturer
public function doSave($con = null)
{
// retrieve the object from the DB or create it
$manufacturerName = $this->values['manufacturer_id'];
$manufacturer = ManufacturerPeer::retrieveByName($manufacturerName);
if(!$manufacturer instanceof Manufacturer)
{
$manufacturer = new Manufacturer();
$manufacturer->setName($manufacturerName);
$manufacturer->save();
}
// overwrite the field value and let the form do the real work
$this->values['manufacturer_id'] = $manufacturer->getId();
parent::doSave($con);
}