1

I have a plugin that wants to set a value for an entries existing matrix field, from a form on the font-end. Think of it like:

Movies (matrix field)
  Movie (matrix block)
    Name (plain text)
    votes (plain text)
  Movie (matrix block)
    Name (plain text)
    votes (plain text)

I want to increment the number of votes when a user clicks a button for a particular movie.

I've tried all sorts of methods, but being pretty novice at php I just can't seem to grasp how Craft is storing everything. I just keep getting back an array of ALL fields on the site, rather than the specific ones I'm searching for.

All existing SE questions seem to relate to adding new rows, I just want to edit an existing one.

Normal fields are (from existing code) along the lines of

$currentVotes = $movie->getFieldValue('votes');
$movie->setFieldValue('votes', $currentVotes + 1);

Which seems rather simple. What is the Matrix version of that?

2

Since Matrix blocks are elements as well it's the same

Your form could be

{% set movies = entry.movies.all() %}
{% for movie in movies %}
    <form>
        <input type="hidden" value="plugin/controller/function" name="action">
        {{ csrfInput() }}
        <input type="hidden" value="{{ movie.id }}" name="id">
        <input type="submit" value="Vote this movie">
    </form>
{% endfor %}

And your controller

public function actionSave(){
    $id = Craft::$app->getRequest()->getRequiredBodyParam('id');
    $matrixBlock = Craft::$app->getMatrix()->getBlockById($id);
    if($matrixBlock === null){
        throw new ElementNotFoundException('Could not find Block with ID ' . $id);
    }

    $matrixBlock->setFieldValue('votes', $matrixBlock->getFieldValue('votes')+1);
    if(!Craft::$app->getElements()->saveElement($matrixBlock)){
        // handle an error
    }

    return $this->redirectToPostedUrl();
}
  • I don't totally understand, but it works great, thank you! :) I think my main problem was not understanding the docs. – evu Aug 8 '18 at 8:49
  • Glad to hear that.. I didn't even test it at all. If you want to understand more about Craft you may want to join slack – Robin Schambach Aug 8 '18 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.