phpcakephpcakephp-3.x

CakePHP 3: exclude vendor tables when getting a list of all table objects


in my database, I have tables created by some plugins. I need to show only my models in a dropdown list.

in bootstrap.php:

Configure::write('ReportManager.modelIgnoreList',array(
'acl_phinxlog',
'acos',
'aros',
'aros_acos',
'audits',
'burzum_file_storage_phinxlog',
'burzum_user_tools_phinxlog',
'cake_d_c_users_phinxlog',
'file_storage',
'phinxlog',
));

In my controller index function:

if (empty($this->data)) {
        $modelIgnoreList = Configure::read('ReportManager.modelIgnoreList'); 
        $models = ConnectionManager::get('default')->schemaCollection()->listTables();
        foreach($models as $key => $model) {
            if ( isset($modelIgnoreList) && is_array($modelIgnoreList)) {
                foreach ($modelIgnoreList as $ignore) {
                    if (isset($models[$ignore])) {
                        unset($models[$ignore]);
                        $modelData = TableRegistry::get($model);
                        debug($modelData);
                    }
                }
            }
        }
    debug($modelIgnoreList);
}

In index.ctp:

echo $this->Form->create('ReportManager');
    echo '<fieldset>';
    echo '<legend>' . __d('report_manager','New report',true) . '</legend>';        
    echo $this->Form->input('model',array(
        'type'=>'select',            
        'label'=>__d('report_manager','Model',true),
        'options'=>$models,
        'empty'=>__d('report_manager','--Select--',true)
        ));

My result keeps showing all the tables. Where is my mistake ?


Solution

  • You are calling unset using the model name, not the key. Also, you don't need two foreach loops here.

    $models = ConnectionManager::get('default')->schemaCollection()->listTables();
    if (isset($modelIgnoreList) && is_array($modelIgnoreList)) {
        foreach($models as $key => $model) {
            if (in_array($model, $modelIgnoreList)) {
                unset($models[$key]);
            }
        }
    }
    

    Or, even simpler, use the built-in functionality to handle this for you:

    $models = ConnectionManager::get('default')->schemaCollection()->listTables();
    if (isset($modelIgnoreList) && is_array($modelIgnoreList)) {
        $models = array_diff($models, $modelIgnoreList);
    }