2

When using the Lithium framework for developing a PHP application, I am noticing that the value zero is not being displayed in a text field in a form. Currently, I am grabbing data from a MySQL database, displaying it, and updating it. I am able to save the value zero to the database and the information returned from the database is correct, as I am able to view it when echoing the values directly to the page, and any value other than zero displays correctly. Does anyone know how to enable rendering of zero value in a lithium form, or possibly disable value checking before rendering in Lithium?

I am using the default <?=$this->form->field... provided by lithium inside a form binded to an object using <?=$this->form->create($object); ?>

Mehdi Lahmam B.
  • 2,240
  • 16
  • 22
iralls
  • 376
  • 4
  • 16

1 Answers1

2

Ha. I never noticed that before. Seems like it should be fixed.

In the meantime, you can either edit lithium\template\helper\Form or create app\extensions\helper\Form in your app (replacing app with your app's namespace if you changed it from the default app).

The method that needs to change is _defaults(). Here are contents that will get a zero value to display:

protected function _defaults($method, $name, $options) {
    $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : array();
    $options += $methodConfig + $this->_config['base'];
    $options = $this->_generators($method, $name, $options);

    $hasValue = (
        (!isset($options['value']) || $options['value'] === null) &&
        $name && $value = $this->binding($name)->data
    );
    $isZero = (isset($value) && ($value === 0 || $value === "0"));
    if ($hasValue || $isZero) {
        $options['value'] = $value;
    }
    if (isset($options['value']) && !$isZero) {
        $isZero = ($options['value'] === 0 || $options['value'] === "0");
    }
    if (isset($options['default']) && empty($options['value']) && !$isZero) {
        $options['value'] = $options['default'];
    }
    unset($options['default']);

    $generator = $this->_config['attributes']['name'];
    $name = $generator($method, $name, $options);

    $tplKey = isset($options['template']) ? $options['template'] : $method;
    $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey;
    return array($name, $options, $template);
}

The current version has some conditionals that fail with either an actual zero integer or the string "0".

rmarscher
  • 5,596
  • 2
  • 28
  • 30
  • I'm looking into submitting a pull request. This change breaks some unit tests with binding multiple objects to the form. Not really sure why (I didn't even know multiple bindings was possible). I will update this answer with the final solution once it's worked out. – rmarscher May 30 '12 at 22:25
  • This was merged to the Lithium dev branch. Should be available in master soon. – rmarscher May 31 '12 at 21:23