Symfony is_active field get 1,0 instead of true,false

时间:2016-07-11 23:22:37

标签: php symfony boolean

In my symfony app I have a Page Entity and in this Entity I have a boolean variable. This is my code:

/**
 * @var Boolean $active whether page is active.
 *
 * @ORM\Column(name="is_active", type="boolean", options={"default"=false})
 *
 * @JS\Groups({"pageDetail", "pageOwner"})
 */
protected $active;

I want to this variable in addition to true,false accept 0,1 and on,off.
Can I do it by event listeners? How I do it?

1 个答案:

答案 0 :(得分:1)

我并不完全理解这些要求,但如果您需要在实体级别接受这些值,我建议您在setter方法中吸收类型的差异。

/**
 *
 * @param mixed $active
 */
public function setActive( $active ) {
    if ( $active )
       if ( is_string( $active ) ){
           if ( $active == '1' || $active == 'on' ){
               $this->active = true;
           }else if ($active == '0' || $active == 'off' ){
               $this->active = false;
           }   
       }else if ( is_bool( $active ) ){
           $this->active = $active;
       }
}

我还注意到,如果列名为is_active,也许您可​​以考虑将此成员变量的名称更改为$ isActive而不是$ active。