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
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.

Add-On Developers: Get Your Add-Ons Ready for Concrete CMS 9.0
Aug 6, 2021
By andrew.

Concrete CMS 9.0 is coming! But there are some changes in version 9 that might affected your add-ons and themes. This document aims to answer questions about the most common ways that your add-ons might need to be changed, and common problems you'll run into.

Permissions for editors in a multilingual site
Jun 2, 2021
By myq.

How to set up a multilingual Concrete CMS site for groups of language-specific editors

Was this information useful?
Thank you for your feedback.