CakePHP更有效地将空变量从模型设置到视图中

时间:2011-04-04 21:34:23

标签: cakephp view

在CakePHP中考虑这样的代码:

$query =  $this->find('first'...);

产生这个数组:

[UserAddress] => Array
    (
        [address_name] => Abc 55 Avenue
        [address_id] => 6
        [country_id] => 9
        [city_id] => 35
        [Country] => Array
            (
                [country_name] => 'China'
            )
    [City] => Array
        (
            [city_name] => Null
        )
)

$this->set('data', $query);

现在,如果我在视图中使用城市名称,那么:

echo $this->data['UserAddress']['City']['city_name']; 

我会收到“通知”,因为未设置city_name。任何人都可以建议更有效的方法将'unset'变量设置为''(空字符串)而不是写到处都是

echo isset($this->data['UserAddress']['address_name']) ? $this->data['UserAddress']['address_name'] : '';

从模型查询得到的数组中的空值?
感谢。

3 个答案:

答案 0 :(得分:4)

根据这个existing question,在PHP 5.3中有一个可能有帮助的新运算符:

echo $this->data['UserAddress']['City']['city_name'] ?: '';

请注意,如果密钥存在于数组中,这似乎对您有好处。一些例子:

$test = null;
echo $test ?: 'default';  // will print 'default'

$test = array();
echo $test['x'] ?: 'default';  // displays notice 'undefined index', prints 'default'

$test = array('x' => null);
echo $test['x'] ?: 'default';  // will print 'default' 

答案 1 :(得分:1)

使用模型回调。

在afterFind函数中检查需要从NULL设置为“”值的变量。

<?php
    // IN THE MODEL FOR UserAddress
    public function afterFind( array $results, bool $primary ){
        if( !isset( $results[ $this->alias ][ 'City' ][ 'city_name' ] )){
            $results[ $this->alias ][ 'City' ][ 'city_name' ] = "";
        }
        ...
    }        
?>

你甚至可以将它抽象为一个行为,或者让它循环遍历数据数组,将空值固定为字符串。

在这里看一下回调函数(模型)

http://book.cakephp.org/#!/view/1048/Callback-Methods

或者看看这里的回调方法(控制器)

http://book.cakephp.org/#!/view/984/Callbacks

答案 2 :(得分:-1)

你可以试试这个:

echo @$this->data['UserAddress']['City']['city_name'];

如果设置了值,那么它将打印出来。
如果没有,它将不打印任何内容,并将忽略该通知..

希望这会有所帮助...

祝你的发展好运......