<p>Although submitting the form causes the same page to be loaded again, it turns out that Craft isn't actually re-parsing the loaded page. You have to tell it to do so.</p>

<p>So, if the plugin was successful you need to set it to redirect back to the URL that POSTed in the first place. Like so:</p>

<pre><code>// save the user
$success = craft()-&gt;users-&gt;saveUser($user);

// redirect back to the original page if successful (as a new page request)
if($success) {
    $this-&gt;redirectToPostedUrl();
} else {
    craft()-&gt;userSession-&gt;setError(Craft::t('Could not purchase document.'));
}
</code></pre>

<p>Many thanks to Hubert Prein on Slack for that :)</p>

CC BY-SA 3.0
2016-10-31T12:36:14.483Z
2016-10-31T16:54:54.257Z
2016-10-31T16:54:54.257Z
Matt Wilcox
<p>I have a plugin which allows Users to "buy" documents associated with an Entry. All it consists of is two fields on the User; a "Credits Available" text field, and an "Owned Documents" Entries field.</p>

<p>On the front end for each Entry I have a block of code which checks to see if the Entry being viewed is in the "Owned Documents" field or not. If it is, a message of "you own this" is shown, if not a form to "purchase" the document is shown. The code is this:</p>

<pre><code>{% if currentUser %}
    {% set displayPurchaseButton = 'yes' %}

    {# Work out if we need to show the purchase button #}
    {% if currentUser.purchasedDocuments | length %}{# there are already purchased documents #}
        {% for document in currentUser.purchasedDocuments %}{# loop through all the currently purchased documents #}
            {% if document.id == entry.id %}{# The entry being viewed is currently purchased #}
                {% set displayPurchaseButton = 'no' %}
            {% endif %}
        {% endfor %}
    {% endif %}

    {% if displayPurchaseButton == 'yes' %}
        {% if currentUser.creditsAvailable &lt; entry.creditCost %}{# They don't have enough to buy the document #}
            &lt;p&gt;Buy more credits&lt;/p&gt;
        {% else %}{# Show the buy button #}
            &lt;form action="" method="post" accept-charset="UTF-8" enctype="multipart/form-data" id="favourite"&gt;
                {{ getCsrfInput() }}
                &lt;input type="hidden" name="action" value="usingCredits/credits/creditPurchase"&gt;
                &lt;input type="hidden" name="documentId" value="{{ entry.id }}"&gt;
                &lt;input type="hidden" name="redirect" value="{{ entry.url }}"&gt;

                &lt;input type="submit" value="Buy Document ({{ entry.creditCost }} Cr)" class="favourite"&gt;
            &lt;/form&gt;
        {% endif %}
    {% else %}
        &lt;p&gt;You own this document&lt;/p&gt;
    {% endif %}
{% endif %}
</code></pre>

<p>This works... except immediately after 'buying' the document. In which case the reloaded page shows an updated Credit field (the cost of the purchase has been deducted from the Available Credits) but does not show the "you own this" message, instead showing the Purchase button. However, if I manually re-load the page, it behaves properly.</p>

<p>What's wrong?</p>

<p>Plugin code:</p>

<pre><code>public function actionCreditPurchase()
{
    // basic security precautions
        $this-&gt;requirePostRequest();

    // Get info about the logged in user
        $user             = craft()-&gt;userSession-&gt;getUser();
        $ownedDocuments   = $user-&gt;getContent()-&gt;purchasedDocuments;
        $creditsAvailable = $user-&gt;getContent()-&gt;creditsAvailable;

    // what's the Entry ID for what they want to buy?
        $purchaseDocumentId = craft()-&gt;request-&gt;getPost('documentId');

    // does such a document exist?
        $document         = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
        $document-&gt;id     = $purchaseDocumentId;
        $purchaseDocument = $document-&gt;first();

        if(!$purchaseDocument) {
            craft()-&gt;userSession-&gt;setError(Craft::t('An error occured: the document could not be found.'));
        }

    // check the user has the credits required
        $documentCost = $purchaseDocument-&gt;getContent()-&gt;creditCost;

        if($documentCost &gt; $creditsAvailable) {
            craft()-&gt;userSession-&gt;setError(Craft::t('You do not have enough credits to purchase this document.'));
        }

    // also check that they don't already own the document
        $purchasedDocumentIds = $user-&gt;purchasedDocuments-&gt;ids();
        if( in_array($purchaseDocumentId, $purchasedDocumentIds) )
        {
            craft()-&gt;userSession-&gt;setError(Craft::t('You already own this document.'));
            $this-&gt;documentOwned = "yes";
        }

    // ok, buy the item
        if($purchaseDocument &amp;&amp;
           $documentCost &lt; $creditsAvailable &amp;&amp;
           $this-&gt;documentOwned !== "yes")
        {
            // append the document ID to the existing array of owned documents
            array_push($purchasedDocumentIds, $purchaseDocumentId);

            // calculate the new creditsAvailable value
            $newCreditsAvailable = $creditsAvailable - $documentCost;

            // update the user fields
            $user-&gt;getContent()-&gt;setAttributes(array(
                'creditsAvailable' =&gt; $newCreditsAvailable,
                'purchasedDocuments' =&gt; $purchasedDocumentIds
            ));

            // save the user
            craft()-&gt;users-&gt;saveUser($user);
        }
}
</code></pre>

<plugin-development>
Form action updates multiple User fields, but front-end template "caches" one field?
# Form action updates multiple User fields, but front-end template "caches" one field?

(Asked by: username_0 on 2016-10-31)

I have a plugin which allows Users to "buy" documents associated with an Entry. All it consists of is two fields on the User; a "Credits Available" text field, and an "Owned Documents" Entries field.
On the front end for each Entry I have a block of code which checks to see if the Entry being viewed is in the "Owned Documents" field or not. If it is, a message of "you own this" is shown, if not a form to "purchase" the document is shown. The code is this:
{% if currentUser %}
    {% set displayPurchaseButton = 'yes' %}

    {# Work out if we need to show the purchase button #}
    {% if currentUser.purchasedDocuments | length %}{# there are already purchased documents #}
        {% for document in currentUser.purchasedDocuments %}{# loop through all the currently purchased documents #}
            {% if document.id == entry.id %}{# The entry being viewed is currently purchased #}
                {% set displayPurchaseButton = 'no' %}
            {% endif %}
        {% endfor %}
    {% endif %}

    {% if displayPurchaseButton == 'yes' %}
        {% if currentUser.creditsAvailable < entry.creditCost %}{# They don't have enough to buy the document #}
            Buy more credits
        {% else %}{# Show the buy button #}
            
                {{ getCsrfInput() }}
                
                
                

                
            
        {% endif %}
    {% else %}
        You own this document
    {% endif %}
{% endif %}

This works... except immediately after 'buying' the document. In which case the reloaded page shows an updated Credit field (the cost of the purchase has been deducted from the Available Credits) but does not show the "you own this" message, instead showing the Purchase button. However, if I manually re-load the page, it behaves properly.
What's wrong?
Plugin code:
public function actionCreditPurchase()
{
    // basic security precautions
        $this->requirePostRequest();

    // Get info about the logged in user
        $user             = craft()->userSession->getUser();
        $ownedDocuments   = $user->getContent()->purchasedDocuments;
        $creditsAvailable = $user->getContent()->creditsAvailable;

    // what's the Entry ID for what they want to buy?
        $purchaseDocumentId = craft()->request->getPost('documentId');

    // does such a document exist?
        $document         = craft()->elements->getCriteria(ElementType::Entry);
        $document->id     = $purchaseDocumentId;
        $purchaseDocument = $document->first();

        if(!$purchaseDocument) {
            craft()->userSession->setError(Craft::t('An error occured: the document could not be found.'));
        }

    // check the user has the credits required
        $documentCost = $purchaseDocument->getContent()->creditCost;

        if($documentCost > $creditsAvailable) {
            craft()->userSession->setError(Craft::t('You do not have enough credits to purchase this document.'));
        }

    // also check that they don't already own the document
        $purchasedDocumentIds = $user->purchasedDocuments->ids();
        if( in_array($purchaseDocumentId, $purchasedDocumentIds) )
        {
            craft()->userSession->setError(Craft::t('You already own this document.'));
            $this->documentOwned = "yes";
        }

    // ok, buy the item
        if($purchaseDocument &&
           $documentCost < $creditsAvailable &&
           $this->documentOwned !== "yes")
        {
            // append the document ID to the existing array of owned documents
            array_push($purchasedDocumentIds, $purchaseDocumentId);

            // calculate the new creditsAvailable value
            $newCreditsAvailable = $creditsAvailable - $documentCost;

            // update the user fields
            $user->getContent()->setAttributes(array(
                'creditsAvailable' => $newCreditsAvailable,
                'purchasedDocuments' => $purchasedDocumentIds
            ));

            // save the user
            craft()->users->saveUser($user);
        }
}

**Tags:** plugin-development


---

## 1 answers

### Answer by username_0 on 2016-10-31. Score: 1 | Accepted answer

Although submitting the form causes the same page to be loaded again, it turns out that Craft isn't actually re-parsing the loaded page. You have to tell it to do so.
So, if the plugin was successful you need to set it to redirect back to the URL that POSTed in the first place. Like so:
// save the user
$success = craft()->users->saveUser($user);

// redirect back to the original page if successful (as a new page request)
if($success) {
    $this->redirectToPostedUrl();
} else {
    craft()->userSession->setError(Craft::t('Could not purchase document.'));
}

Many thanks to Hubert Prein on Slack for that :)


---

