cakephp3 共通処理
■AppController.phpを使う場合
・AppController.php
namespace App\Controller; use Cake\Controller\Controller; use Cake\Event\Event; use Cake\ORM\TableRegistry; // この行を追加 class AppController extends Controller { public function initialize() { ・・・ $obj = TableRegistry::get('モデル名(+s)'); $変数名 = $obj->find('list',['valueField' => 'フィールド名'])->toArray(); $this->set('文字列', $変数名); ・・・ }
・view
debug($変数名);
■Componentを使う場合
・SearchComponent.php
ドキュメントルート > src > Controller > Component > SearchComponent.php(作成)
namespace App\Controller\Component; use Cake\Controller\Component; class SearchComponent extends Component { } ↓ namespace App\Controller\Component; use Cake\Controller\Component; use Cake\ORM\TableRegistry; class SearchComponent extends Component { public function search() { $cities = TableRegistry::get('Model名'); $cities = $cities->find('list',['valueField' => 'フィールド名'])->toArray(); return $cities; } }
・controller
class Model名Controller extends AppController { // コンポート名 public $components = ['Search']; public function index() { $cities = $this->Search->search(); $this->set('cities', $cities); } }
・view
debug($cities);