Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions

check for Checkbox values in template


Reply

4 Posts   1569 Views

Avatar
NickJacobs

26 April 2010 at 3:09pm (Last edited: 26 April 2010 3:10pm), Community Member, 144 Posts

Hi, I have a checkbox field going into the database:

new CheckboxSetField("CropUse", "Crop Use",array("silage" => "Silage","grain" => "Grain","dual" => "Dual Purpose")),


so, the value in the field will be "grain" or "grain,dual" or "grain,silage,dual" etc...

How do I test for the inclusion of a value in this field in the template? Ie I want to do something like:

<% if CropUse = grain %>
<h4>Grain CRM: $GrainCRM</h4>
<% end_if %>

<% if CropUse = silage %>
<h4>Silage CRM: $SilageCRM</h4>
<% end_if %>

<% if CropUse = dual %>
<h4>Grain CRM: $GrainCRM / Silage CRM: $SilageCRM</h4>
<% end_if %>

something like that....what I want is to be able to test whether one of the 3 values exist in the db field.
thanks in advance!

Avatar
qbahamutp

21 December 2010 at 4:50am Community Member, 8 Posts

I've got the same problem :( Of course I could divide it into a set of seperate checkboxes, each saved into a Boolean, but this method looks so much better on the backend.

Is there an efficient way that the controller could separate (explode?) them into different names?

Avatar
pakeeza1990

31 January 2011 at 6:53pm Community Member, 1 Post

its difficult to tell here

Avatar
Ryan M.

5 February 2011 at 12:20pm Community Member, 309 Posts

This is some code I wrote for your case. The first part is plain, non-SS php to demonstrate that this logic works.
Second part is an example application of the logic in SS. You will most likely need to tweak it for your particular case.

<?php

$data = "dual,silage";
$d = explode(",", $data);
foreach($d as $key) {
   if($key == 'silage') {
      $silage = true;
   }
   if($key == 'grain') {
      $grain = true;
   }
   if($key == 'dual') {
      $dual = true;
   }
}

if($dual) { echo "dual "; }
if($silage) { echo "silage "; }
if($grain) { echo "grain "; }

// Convert into SilverStripe compatible function

function index() {
   $d = explode(",", $this->CropUse);
   foreach($d as $key) {
      if($key == 'silage') {
         $silage = true;
      }
      if($key == 'grain') {
         $grain = true;
      }
      if($key == 'dual') {
         $dual = true;
      }
   }
   return $this->customise(array(
      'Silage' => $silage,
      'Grain' => $grain,
      'DualPurpose' => $dual
   ));
}

?>

With that, you can do this in the template:

<% if Silage %>
<h4>Put something here</h4>
<% end_if %>

Let me know if that works.