Skip to main content

Dynamic Forms

For the case that a form model should have changing properties, there are dynamic form models. This article explains this concept without going into its purpose in detail. You can skip this article without any problems.

DynamicDispatchable​

Implement n2n\dispatch\DynamicDispatchable to define the properties of your form model dynamically.

class ExampleDynForm implements DynamicDispatchable {
private $values = array();

public function setup(DispatchModel $dispatchModel) {
$nameProperty = new ScalarProperty(new DynamicAccessProxy('name'), false);
$dispatchModel->addProperty($nameProperty);

$birthdayProperty = new DateTimeProperty(new DynamicAccessProxy('birthday'), false);
$birthdayProperty->setDateStyle(DateTimeFormat::STYLE_MEDIUM);
$birthdayProperty->setTimeStyle(DateTimeFormat::STYLE_NONE);
$dispatchModel->addProperty($birthdayProperty);
}

public function getPropertyValue($name) {
if (isset($this->values[$name])) return $this->values[$name];
return null;
}

public function setPropertyValue($name, $value) {
$this->values[$name] = $value;
}

private function _validation(BindingDefinition $bd) {
$bd->val(array('name', 'birthday'), new ValNotEmpty());
}

public function save() {
// submit code
}
}

You can now assemble the desired properties dynamically in the setup() method by registering them via n2n\dispatch\model\DispatchModel::addProperty(). n2n provides the following property types by default:

  • n2n\dispatch\property\impl\ScalarProperty
  • n2n\dispatch\property\impl\DateTimeProperty
  • n2n\dispatch\property\impl\FileProperty
  • n2n\dispatch\property\impl\ObjectProperty

All these property types expect an n2n\reflection\property\AccessProxy as first parameter. For this, use instances of n2n\dispatch\property\DynamicAccessProxy in dynamic form models, via which you can also define the property name. The purpose of the further parameters can be found in the PHPDoc of those classes.

Furthermore, in dynamic form models the getter and setter methods getPropertyValue($name) and setPropertyValue($name, $value) are used for the values of all properties.

Working with dynamic form models in views does not differ from static ones.

<?php $formHtml->open($exampleDynForm) ?>
<?php $formHtml->messageList() ?>

<div>
<?php $formHtml->label('name') ?>
<div><?php $formHtml->input('name') ?></div>
</div>
<div>
<?php $formHtml->label('birthday') ?>
<div><?php $formHtml->input('birthday') ?></div>
</div>

<?php $formHtml->buttonSubmit('save', 'Save') ?>
<?php $formHtml->close() ?>

Also in the controller a dynamic form model can be "dispatched" as usual.

class ExampleController extends ControllerAdapter {
public function index() {
$exampleDynForm = new ExampleDynForm();

if ($this->dispatch($exampleDynForm, 'save')) {
// do something
}

$this->forward('view\dynForm.html', array('exampleDynForm' => $exampleDynForm));
}
}