You have to create a custom hook either way.
Here is some example code
Create a new database table (for example with phpMyAdmin) with an SQL query like this
CREATE TABLE IF NOT EXISTS `modx_tm2000_vote` (
`option` varchar(150) NOT NULL,
`total` int unsigned NOT NULL default 0,
PRIMARY KEY (`option`)
)
and add rows for the options A
, B
and C
.
Create a page with a form like this:
[[!FormIt?
&hooks=`saveVote`
&validate=`vote:required`
&successMessage=`Your vote was submitted!`
&submitVar=`mySubmit`
]]
[[!+fi.successMessage:notempty=`<p class="success">[[!+fi.successMessage]]</p>`]]
<form action="[[~[[*id]]]]" method="post">
<label for="vote">Your vote:</label>
<select id="vote" name="vote">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<button type="submit" name="mySubmit" value="1">Send</button>
</form>
<hr>
[[!getVotes]]
In the hook snippet saveVote update the total
value in the database.
<?php
$vote = $hook->getValue('vote'); //read value of the 'vote' form field
$stmt = $modx->prepare("UPDATE `modx_tm2000_vote` SET `total` = `total` + 1 WHERE `option` = ?");
if ($stmt->execute([$vote]) && $stmt->rowCount() == 1){
return true;
} else {
return false;
}
Show the totals with the getVotes snippet.
<?php
$stmt = $modx->prepare("SELECT * FROM `modx_tm2000_vote` ORDER BY `option` ASC");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$output = [];
foreach ($rows as $row) {
$output[] = $row['option'] . '=' . $row['total'] . " votes";
}
return implode('<br>', $output);
This is of course just one possible solution.
You could also insert a new row for every vote into the database table, and then use COUNT()
and GROUP BY
in the getVotes snippet.
Or create a proper model for the custom database table, so that you can use xPDO.
Or store the totals in a file instead of a database table, etc.