View Logic

Hi,

I find myself coding ‘conditional view logic’ into my views. See code snippet below. Note that I am calling the Bid model directly from the view.




<div id="bidSummary">

    <ul>

         <li>Bid(s): <?php echo $model->bidCount; ?></li>

	 <?php if($model->bidCount>=1): ?>

         <li>Last Bid: 

         <?php 

             echo Yii::app()->getDateFormatter()->formatDateTime(

	         Bid::model()->find(array(

		     'order'=>'created_on DESC',

		     'limit'=>'1',

	             )

	    	 )

	         ->created_on, 'long', 'short'); ?>

         </li>

       	<?php endif; ?>

    </ul>

</div>



[list=1]

[*]Is this acceptable?

[*]Are there best practices that I should be following for these cases?

[*]Where do you put your logic for displaying operational links/buttons? Ex. Display ‘delete’ button if logged-in user is Post creator? In the view, controller, somewhere else?

[/list]

Cheers.

What you’re doing here generally goes against good MVC design principles, because you’re calling the model directly out of the view. There’s no problem with your view containing very simple if else statements, foreach loops and so on, but you really shouldn’t be calling the model directly out of the view as it goes against the principles of separating the presentation and the logic.

In your case what you should do is firstly, assign the bidCount into the template as template variable in the controller. Then, check the bidCount in the controller and if it is more than 1 retrieve the last bid also in the controller and assign it into the template. Also, I wouldn’t use UL for what you’re doing, it’s better to use a table or divs as it will result in better presentation and UL isn’t really appropriate here. Furthermore you should probably be using labels as supported by Yii rather than just hardcoding, but that’s a separate thing. So basically your template should look like this:




<div id="bidSummary">

         <div>Bid(s): <?php echo $bidCount; ?></div>

	 <?php if($showLastBid): ?>

         <div>Last Bid: <?php echo $lastBid; ?></div>

       	<?php endif; ?>

</div>



I would highly recommend you read the difinitive guide to Yii and some stuff on MVC in general.

Regarding your last question… You should that in the Controller and only add the basic output into the template to keep the template simple.