2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Phlacon でモデルの値が空のときに DB のデフォルト値を使う

Posted at

ビヘイビアでバリデーション前にデフォルト値を設定するようにしてみた.
MySQL で一応動作確認してる.

<?php

use Phalcon\Db\RawValue;
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;

/**
 * オプションで指定した値が '' や null で合った場合に DB のデフォルト値を入れるようにするビヘイビア
 */
class DefaultValue extends Behavior implements BefaviorInterface
{
  public function notify($type, $model)
  {
    if ($type === 'beforeValidation')
    {
      foreach ((array)$this->getOptions() as $property) {
        if ($model->$property === '' || $model->$property === null) {
          $model->$property = new RawValue('default');
        }
      }
    }
  }
}

使用例

<?php

use Phalcon\Mvc\Model;

class SomeModel extends Model
{
  public $name;
  public $hobby;

  public function initialize()
  {
    $this->addBehavior(new DefaultValue(array('name', 'hobby')));
  }
}

実行例はあとで書くかも.

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?