Using vue.js with concrete5

Apr 17, 2019

In this tutorial we'll create a new block type that uses vue.js to collect data, and post data back to the server via ajax.

Here we'll use jQuery to perform the ajax call since it's bundled with concrete5, but of course you can use any other library (like axios for example).

Block controller

The controller.php file of the block type:

<?php

namespace Application\Block\MyBlock;

use Concrete\Core\Block\BlockController;
use Concrete\Core\Error\UserMessageException;
use Concrete\Core\Http\ResponseFactoryInterface;
use Concrete\Core\User\User;

defined('C5_EXECUTE') or die('Access denied.');

class Controller extends BlockController
{
    /**
     * Get the name of the block type.
     *
     * @return string
     */
    public function getBlockTypeName()
    {
        return t('My Block');
    }

    /**
     * Get the description of the block type.
     *
     * @return string
     */
    public function getBlockTypeDescription()
    {
        return t('A sample block type to demonstrate how you can use vue.js in concrete5.');
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Block\BlockController::registerViewAssets()
     */
    public function registerViewAssets($outputContent = '')
    {
        $this->requireAsset('javascript', 'jquery');
        $this->requireAsset('javascript', 'vue');
    }

    public function view()
    {
        $user = new User();
        $token = $this->app->make('token');
        $this->set('dataForVue', [
            'userName' => $user->isActive() ? $user->getUserName() : t('guest'),
            'busy' => false,
            'data' => [
                $token::DEFAULT_TOKEN_NAME => $token->generate('my-block-submit'),
                'age' => null,
            ],
        ]);
        $this->set('uniqueBlockIdentifier', $this->getUniqueBlockIdentifier());
    }

    public function action_submit()
    {
        $token = $this->app->make('token');
        if (!$token->validate('my-block-submit')) {
            throw new UserMessageException($token->getErrorMessage());
        }
        $post = $this->request->request;
        $age = (int) $post->get('age');
        if ($age < 1 || $age > 150) {
            throw new UserMessageException(t('The age does not seems correct'));
        }

        return $this->app->make(ResponseFactoryInterface::class)->json([
            'message' => t('Well done!'),
        ]);
    }

    /**
     * @return int
     */
    private function getUniqueBlockIdentifier()
    {
        $bID = null;
        $b = $this->getBlockObject();
        if ($b) {
            $pb = $b->getProxyBlock();
            if ($pb) {
                $bID = $pb->getBlockID();
            }
        }

        return (int) ($bID ?: $this->bID);
    }
}

The getBlockTypeName() and getBlockTypeDescription() methods are the concrete5 way to give a name and a description to a block type.

The registerViewAssets() method instructs concrete5 that we'll need vue and jquery in the block type view.

The view() method prepares the data for the view. In this case we create an array named $dataForView, and define $uniqueBlockIdentifier that contains an integer that uniquely identifies the block instance (returned by the uniqueBlockIdentifier() method).

action_submit() is the method that will receive the data via ajax. In this example it simply protects agains CSRF attacks, checks that the data is valid, and send back a message to the client.

Block view

Here's the view.php file of the block type:

<?php

defined('C5_EXECUTE') or die('Access denied.');

/** @var Application\Block\MyBlock\Controller $controller */
/** @var array $dataForVue */
/** @var int $uniqueBlockIdentifier */

?>

<div id="my-block-<?= $uniqueBlockIdentifier ?>">
    <form v-on:submit.prevent="save">
        <?= t('Hello %s', '{{ userName }}') ?><br />
        <?= t('Your age?') ?><br />
        <input type="number" min="1" max="150" v-model="data.age" required="required" /><br />
        <input type="submit" value="<?= t('Save') ?>" v-bind:disabled="busy" />
    </form>
</div>

<script>
$(document).ready(function() {
    var vue;

    vue = new Vue({
        el: '#my-block-<?= $uniqueBlockIdentifier ?>',
        data: function() {
            return <?= json_encode($dataForVue) ?>;
        },
        methods: {
            save: function() {
                if (this.busy) {
                    return;
                }
                this.busy = true;
                $.ajax({
                    dataType: 'json',
                    method: 'POST',
                    url: <?= json_encode((string) $controller->getActionURL('submit')) ?>,
                    data: this.data
                })
                .done(function (data) {
                    window.alert(data.message);
                })
                .fail(function (xhr, status, error) {
                    if (xhr.responseJSON && xhr.responseJSON.errors && xhr.responseJSON.errors.length > 0) {
                        window.alert(xhr.responseJSON.errors.join('\n'));
                    } else {
                        window.alert(status);
                    }
                })
                .always(function() {
                    vue.busy = false;
                });
            }
        }
    });
});
</script>

The above code defines the <div> node that will contain the vue application. It prints out the current user name (contained in the userName property of the vue app) and it asks for an integer (bound to the data.age property of the app).

When the user hit the submit button, the save method of the vue app performs an ajax call that sends all the values contained in the data property), and correctly handles errors in case of problems.

Recent Tutorials
Updating Concrete Themes from Version 8 to Version 9
Nov 24, 2022

This tutorial covers commonly encountered issues when upgrading a Concrete CMS theme from version 8 to version 9

Transferring ownership of an add-on and a theme
Nov 15, 2022
By katzueno.

If you encounter a Concrete CMS add-on or theme that you love but not being maintained, you may want to ask the author to help or take over the add-on or theme. Here is the quick step-by-step guide of how to transfer the ownership.

How to update Add-Ons if not on the Update Add-Ons Menu item
Jul 4, 2022

How to manually download an add-on and update it when your site's core versions isn't considered compatible with the add-on version.

Generate a report with author information and form summaries in Concrete CMS.
May 9, 2022

In Concrete CMS, you can use a form to initiate contact between logged-in users and then create helpful reports. After form submissions are collected, they can be searched, sorted, and exported as a spreadsheet. This tutorial will detail how to add author information to a report using the advanced search.

How to clone and customize Atomik theme
Feb 14, 2022
By linuxoid.

How to clone and customize Atomik theme

Update jQuery to 3.5 on Concrete CMS version 8.5.x
Dec 1, 2021
By hissy.

If you have to take some time to fix your site to work with version 9 and want to update jQuery immediately, you can override it.

Was this information useful?
Thank you for your feedback.