Using vue.js with concrete5
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.