开发者

CakePHP more efficient way of setting empty variables from model into view

开发者 https://www.devze.com 2023-02-21 20:30 出处:网络
Consider such code in CakePHP: $query =$this->find(\'first\'...); That produces this array: [UserAddress] => Array

Consider such code in CakePHP:

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

That produces this array:

[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);

Now if I use city name in the view like:

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

I'll get a 'notice' because city_name isn't set. Can anyone suggest more efficient ways to set 'unset' varia开发者_如何学运维bles to '' (empty string) than writing everywhere

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

for null values in arrays got from model queries?

Thanks.


According to this existing question, in PHP 5.3 there is a new operator which might help:

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

Note that this seems to only do you good if the key exists in the array. Some examples:

$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' 


Use the Model callbacks.

In the afterFind function check for the variables you need to set from NULL to a "" value.

<?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' ] = "";
        }
        ...
    }        
?>

You could even abstract it out to a behavior or have it loop over the data array fixing nulls to strings.

Take a look at the callback functions here (Models)

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

OR look at the callback methods here (Controllers)

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


you can try this:

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

if the value is set, then it will print it..
if not, it will print nothing, and will ignore the notice..

hope this helps...

good luck with your development...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号