Skip to content

Instantly share code, notes, and snippets.

@gbirke
Created December 31, 2010 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbirke/761231 to your computer and use it in GitHub Desktop.
Save gbirke/761231 to your computer and use it in GitHub Desktop.
Example for default values in Zend_Form
<?php
class Example_Customer {
// Some properties
protected $name = "Joe Schmoe";
protected $street = "1st St NW";
protected $city = "Washington";
protected $zipcode = "20008";
protected $spamLikeThereIsNoTomorrow = true;
// Getter methods for the properties
public function getName() { return $this->name; }
public function getStreet() { return $this->street; }
public function getCity() { return $this->city; }
public function getZipcode() { return $this->zipcode; }
public function getSpamLikeThereIsNoTomorrow() {
return $this->spamLikeThereIsNoTomorrow;
}
// Setters are left as an exercise :)
}
<?php
/**
* This form class demonstrates how to get default values for form fields
* from an object with getters.
* @author Gabriel Birke <birke@d-scribe.de>
*/
class Example_Form extends Zend_Form {
// Set up the form fields
function init() {
$this->addElement('text', 'name', array('label' => 'Name'));
$this->addElement('text', 'street', array('label' => 'Street'));
$this->addElement('text', 'city', array('label' => 'City'));
$this->addElement('text', 'zipcode', array('label' => 'ZIP'));
$this->addElement('checkbox', 'spamLikeThereIsNoTomorrow',
array('label' => 'Send me a newsletter'));
$this->addElement('checkbox', 'sucker',
array('label' => 'I have read the terms and conditions'));
$this->addElement('submit', 'submit', array('label' => 'Order now'));
}
public function setDefaultsFromObject($object)
{
$reflector = new ReflectionObject($object);
$fields = array_keys($this->getElements());
foreach($fields as $field) {
$method = 'get'.ucfirst($field);
if($reflector->hasMethod($method)) {
$this->setDefault(
$field,
$reflector->getMethod($method)->invoke($object)
);
}
}
return $this; // fluent interface
}
}
<!DOCTYPE html>
<html>
<head>
<title>Zend_Form with setDefaultsFromObject example</title>
</head>
<body>
<?php
ini_set('include_path', dirname(__FILE__));
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->registerNamespace("Example_");
$form = new Example_Form();
$form->setView(new Zend_View());
$form->setDefaultsFromObject(new Example_Customer());
echo $form;
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment