Voting site with Kirby possible?

Sure, you could for example store the results for each option in a structure field. Here is a simple implementation (should be refined to have more flexibility depending on your need, probably store everything in a single structure field to allow dynamic options, prevent errors within the controller, etc).

First, in the blueprints/poll.yml, add the structure fields we will populate :

title: Poll

fields:
  title:
    label: Title
    type:  text

  firstoption:
    label: First option
    type: structure
    style: table
    fields:
      name: 
        label: Name
        type: text

  secondoption:
    label: Second option
    type: structure
    style: table
    fields:
      name: 
        label: Name
        type: text

Then, on the templates/poll.php, add the form that will deal with the voting :

<form>
  <input name="name" type="text">
  <div class="radios">
    <div class="radio">
      <input type="radio" name="option" id="firstoption" value="firstoption">
      <label for="firstoption">12:00</label>
      <ul class="attendees">
        <?php foreach($page->firstoption()->toStructure() as $attendee): ?>
        <li class="attendee"><?php echo $attendee->name() ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
    <div class="radio">
      <input type="radio" name="option" id="secondoption" value="secondoption">
      <label for="secondoption">13:00</label>
      <ul class="attendees">
        <?php foreach($page->secondoption()->toStructure() as $attendee): ?>
        <li class="attendee"><?php echo $attendee->name() ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  </div>
  <input type="submit" name="submit" value="Submit">
</form>

Now we need to add add a function (from this post) that will allow us to append the submitted name to the structure (place it within a .php file at the root of the plugins folder) :

<?php

function addToStructure($page, $field, $data = array()) {
  $fieldData = page($page)->$field()->yaml();
  $fieldData[] = $data;
  $fieldData = yaml::encode($fieldData);
  try {
    page($page)->update(array($field => $fieldData));
    return true;
  } catch(Exception $e) {
    return $e->getMessage();
  }
}

And lastly deal with the form submission within the controllers/poll.php :

<?php

return function($site, $pages, $page) {
    if(get('submit')) {
    	$option = get('option');
    	$name = get('name');

    	addToStructure($page, $option, array('name' => $name));
    }
};

Need refining, but the logic should get you started. :slight_smile:

1 Like