Difference between #7 and #8 of
Custom Number Formatting or Decimal Separators and i18n

Revision #8 has been created by c@cba on Aug 2, 2012, 2:30:25 PM with the memo:

Removed function 'setAttribute()' from class ActiveRecord. Caused problems in my tests. Has problem to do with magic setter methods?
« previous (#7)

Changes

Title unchanged

Custom Number Formatting or Decimal Separators and i18n

Category unchanged

Tutorials

Yii version unchanged

Tags unchanged

decimal separator, number format, i18n, customize, floating point numbers, localization

Content changed

[...]
We usually assign the received user input (=POST variables) to the model before performing other operations (calculations, validaton, saving, etc.).<br>
Therefore we sugges to do the 'unformatting' during the assignment process. This way, after one of the following lines is executed:

```php
$product->attributes = $_POST['Product']; // or ...
$product->setAttribute('price', $_POST['Product']['price']); // or ...
 
$product->setAttributes(array('price'=>$_POST['Product']['price']));
```
`$product->price` will be a valid numerical value and available for further use.
[...]
###2. The 'unformatting' of a number
Extend the CActiveRecord class and override its function
s `setAttribute()` and `setAttributes()` to add the 'unformatting' functionality. <br>
For this, create the new file `components/ActiveRecord.php` with the following content:
[...]
}
}

 
  public function setAttribute($name,$value) {
 
    $column = $this->getTableSchema()->getColumn($name); // new
 
    if (stripos($column->dbType, 'decimal') !== false) // new
 
      $value = Yii::app()->format->unformatNumber($value); // new
 
    if(property_exists($this,$name))
 
      $this->$name=$value;
 
    else if(isset($this->getMetaData()->columns[$name]))
 
      $this->_attributes[$name]=$value;
 
    else
 
      return false;
 
    return true;
 
  }
 
}
```

Derive all models from this new ActiveRecord class. For example in the Product model `models/Product.php` edit the following line:

```php
[...]
4 0
16 followers
Viewed: 86 478 times
Version: 1.1
Category: Tutorials
Written by: c@cba
Last updated by: c@cba
Created on: Aug 1, 2012
Last updated: 11 years ago
Update Article

Revisions

View all history