[TYPO3-mvc] How to set default values for a new Model object?

Franz Koch typo3.RemoveForMessage at elements-net.de
Wed Mar 16 12:51:49 CET 2011


Hey François,

> I'm wondering what is the proper way of setting default values when
> creating a new model object. In the controller, I have the newAction()
> method which is supposed to receive an empty model object (according to
> the comments generated by the Extbase kickstarter).
>
> But it seems like I'm not receiving an object actually. When I tried to
> call a setter, I had an error about calling a method on a non-object.

Your function should look like this:

public function newAction( Tx_Extkey_Domain_Model_ObjectName $object = 
NULL) {

please notice the "$object = NULL" - this indicates that you don't 
necessarily get a object there. Those method params are only filled if 
there are accordingly named parameters (piVars) in the request 
(GET/POST). So you won't get a object on the first call to that action 
because there hasn't been any object related data submitted, but a 
object will be passed in cases where the validation of the object failed 
while trying to call the createAction (send the form) and you get 
redirected to the newAction again in order to correct your form inputs.

So if you like to prefill the model you have to do this:

// if no object has been submitted by the form, create and prefill one
if ($object === NULL) {
	$object = $this->createEmptyObject();
}

...
private function createEmptyObject() {
	$object = 
$this->objectManager->create('Tx_Extkey_Domain_Model_ObjectName');
	$object->setSomeDefaultValue($this->settings['defaults']['someDefaultValue']);
	return $object;
}


Hope that was somehow understandable.
-- 
kind regards,
Franz Koch


More information about the TYPO3-project-typo3v4mvc mailing list