简体   繁体   中英

cakePHP 3.0 - displaying images differently in the same view - querybuilder

I have a projects table and an images' table. A project has many images and an image belongs to a project. In the images table I have a field called image_dimensions. What I want to achieve is to get foreach loops, but those loops need to be different for each image_dimensions.

I can display all the images by doing this:

<?php foreach ($project->images as $images): ?>

For example, there are 5 images in the database. 3 images that have the dimensions 2x2 and 2 images that have the dimensions 3x3. So in the code below it will give me 3 div's with an image and 2 empty divs. Those empty divs shouldn't be there.

What also needs to be different for the each image dimension is the class of the div. Sometimes I want to use col-lg-6, sometimes col-lg-12,...

<?php foreach ($project->images as $images): ?>
    <div class="col-lg-6">
       <?php
         if($images->image_path && $images->image_dimensions == '2x2')
         echo $this->Html->image($images->image_path, array(
        'class' => 'img-responsive center-block project-images'));
       ?>
    </div>
<?php endforeach; ?>

I also have read about the querybuilder in cakephp. I think I need to use it for my problem. But can't seem to get the query to work.

$project = $this->Projects->find();
$project->matching('Images', function($q){
   return $q->where(['Images.image_dimensions' => '2x2']);
}

What I wanna achieve is to display all images, but images with 2x2 dimensions should be displayed differently then images with 3x3 dimensions. All the images in the same view ofcourse. So the class of the image and the class of the div around the image should be different for 2x2 and 3x3 image dimensions. Is it possible to add conditions inside a foreach loop?

My view action inside my Projectscontroller

public function view($id = null)
{
    $project = $this->Projects->get($id, [
        'contain' => ['Categories', 'Users', 'Tags', 'Images'],
    ]);

    $this->set('project', $project);
    $this->set('_serialize', ['project']);
}

Solution

<?php if($images->image_dimensions == '2x2')
         echo $this->Html->div(array('class' => 'col-lg-6')
      );
      elseif($images->image_dimensions == '3x3')
         echo $this->Html->div(array('class' => 'col-lg-12')
      );
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM