XF 2.1 Object to array

abdfahim

Well-known member
I have defined the following entity which shares a relation with XF:User.

Code:
public static function getStructure(Structure $structure)
    {
        $structure->table = 'xf_abdfahim_myaddon';
        $structure->shortName = 'AbdFahim\MyAddon:MyAddon';
        $structure->primaryKey = 'user_id';
        $structure->columns = [
            'user_id' => ['type' => self::UINT, 'required' => true],
            'col1' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col2' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col3' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            ...............
            ...............
            ...............
            ...............
            'col30' => ['type' => self::STR, 'nullable' => true, 'default' => null]
        ];
        $structure->getters = [];
        $structure->relations = [
            'User' => [
                'entity' => 'XF:User',
                'type' => self::TO_ONE,
                'conditions' => 'user_id',
                'primary' => true
            ],
        ];

        return $structure;
    }

While extending AbstractWidget class to define a new widget, I can access these values using
Code:
$myaddon = \XF::visitor()->MyAddon;
var_dump($myaddon->col1);
var_dump($myaddon->col2);
.........

I was wondering if there is a shortcut to get all these values (col1 through col30) in an array so that I can easily loop through them.
 
Well the obvious way is iterating your columns:

PHP:
for ($i = 1; i <= 30; i++)
{
    var_dump($myaddon->getExistingValue('col' . $i));
}

But it is better to use one column of type JSON_ARRAY for such things I guess.

PHP:
$structure->columns = [
    'user_id' => ['type' => self::UINT, 'required' => true],
    'columns' => ['type' => self::JSON_ARRAY, 'default' => []]
];

And then $myaddon->columns will be a normal array.
 
Last edited:
Back
Top Bottom