Check if object exists or is empty in view template

一世执手 提交于 2019-12-05 20:12:06

You can use the iterator_count() function to know if there are results in the set:

if (iterator_count($articles)) {
 ....
}

You can also use the collection methods to get the first element:

if (collection($articles)->first()) {
}

Edit:

Since CakePHP 3.0.5 the best way to check for emptiness on a query or a result set is this:

if (!$articles->isEmpty()) {
    ...
}

I believe you can call $articles->count() from your template. (Check for 0)

Something I have been struggling for a while..

if(!$articles->isEmpty()) {
gives error on empty value
Call to a member function isEmpty() on null
<?php if(iterator_count($articles)) { ?>
Argument 1 passed to iterator_count() must implement interface Traversable, null given
<?php if (collection($articles)->first()) {?>
Only an array or \Traversable is allowed for Collection

I got to work, the problem if you render a different view in the controller $this->render('index'); for a function you should do that after the values has been set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!