I understand that “views” should only display information to the user and not do any real “thinking”.
If I have a field in a form that i wasnt to restrict some user levels accessing what I do is put a condition into my view:
<td style="v-align: middle;">
<?php
if ($auth['level_id'] == 6) {
echo $form->input('product_date',
array('class' => 'input-box',
'div' => false,
'label' => false,
'readonly' => 'readonly',
'style' => 'width:100px; margin-top: 8px; float:left;',
'value' => $productiondate,
'tabindex' => 3013
)
);
echo '<div style="padding-left: 10px; float:left;"><a href="#" id="supplier_submit" name="supplier_submit"><img src="/img/submit.png" border="0"/></a></div>';
}
else {
echo $form->input('product_date_ro',
array('class' => 'input-box',
'div' => false,
'label' => false,
'readonly' => 'readonly',
'style' => 'width:100px',
'value' => $productiondate,
'tabindex' => 3013
)
);
}
?>
</td>
What is best practice for not doing this?
Regards
Paul
You have to make that decision at some point. Wherever you put it, you need the
if ($level = 6)switch somewhere. If you absolutely want to keep it out of the view, the only other possible place is the controller. The only thing you could do in the Controller is to render a different View. This is perfect in the sense that it keeps all logic out of the view, but you’ll end up with a lot of duplicate code with only small differences.What you could do:
This places the logic in the controller while avoiding the worst duplication. The more complex your views get the less workable this solution is though.
You could also simply abstract the decision a bit to the controller and only set flags for the view:
This would provide better separation of internal logic. The actual decision on what to render would still be done in the View though.
The best solution for you is probably somewhere in between. The most important thing to remember is that there’s nothing wrong with having logic in the view. It’s virtually impossible to not have
ifstatements in views. Views can be intelligent and full of code, that’s absolutely no problem. They should just not contain any code that is concerned with anything other than outputting the data handed to it by the controller. And, naturally, the code should be as concise and readable as possible. You need to find the right balance between abstracting things to helpers, elements or entirely different view files based on the situation.