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   1604 Views

Avatar
NickJacobs

Community Member, 144 Posts

26 April 2010 at 3:09pm

Edited: 26/04/2010 3:10pm

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

Community Member, 8 Posts

21 December 2010 at 4:50am

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

Community Member, 1 Post

31 January 2011 at 6:53pm

its difficult to tell here

Avatar
Ryan M.

Community Member, 309 Posts

5 February 2011 at 12:20pm

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.