Cannot read property 'stripeTokenHandler' of undefined vuejs component - javascript

I am building a payment form with vuejs, it included stripe js.
This is my card elements:
<!-- CARD form -->
<label class="mt-5 font-20px"> Tarjeta </label>
<div class="mt-4"> Número </div>
<div class="row mt-2">
<div class="col-md-12">
<div id="card-number-element" class="form-control rounded-pill" placeholder="**** **** **** ****"> </div>
</div>
</div>
<div class="row">
<div class= "col-md-6 mt-3">
<span> Nombre de la Tarjeta </span></br>
<input type="input" id="card-name-element" class="form-control rounded-pill" placeholder ="Juan Pérez"> </input>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> Expiración </span></br>
<div id="card-expiry-element" class="form-control rounded-pill" placeholder ="MM / YY"> </div>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> CCV </span></br>
<div id="card-cvc-element" class="form-control rounded-pill" placeholder ="***"> </div>
</div>
</div>
<div class="row mt-3">
<div id="card-error text-danger"></div>
<div id="card-success">
Your Stripe token is <span class="token text-success"></span>
</div>
</div>
I initialized stripe elements in mounted function:
initStripeElements(){
cardNumberElement = elements.create('cardNumber', { placeholder: '**** **** **** ****', });
cardNumberElement.mount('#card-number-element');
var cardExpiryElement = elements.create('cardExpiry', { placeholder: 'MM / YY', });
cardExpiryElement.mount('#card-expiry-element');
var cardCvcElement = elements.create('cardCvc', { placeholder: '***', });
cardCvcElement.mount('#card-cvc-element');
},
mounted() {
this.initStripeElements();
}
Everything work fine and the stripe card token can be retrieved and returned.
After that I invoke: this.stripeTokenHandler(result.token.id); to send token and data to server
submitForm(e) {
e.preventDefault();
this.submitted = true;
if (this.formInvalid()) {
return;
}
var options = {
name: document.getElementById('card-name-element').value,
};
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
this.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
console.log(this)
});
if (this.cardError) {
return;
}
// this.nextStep();
},
This calling never work as it always show the error:
Finaliza.vue:415 Uncaught (in promise) TypeError: Cannot read property 'stripeTokenHandler' of undefined
Can you please help, what am I wrong here?

By somehow this variable is become undefined inside the stripe scope. So I can solve issue by saving this variable outside the stripe callback.
var context = this;
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
context.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
});

Related

Data variable gets undefined in Vue after submit

I have defined isError as false in data, however once there is an error from laravel i get the 422 error. I would like to then define isError as true but when i do it i get an error from the console saying that iserror is undefined even though it has been defined. What is the problem?
The error is as per below:
app.js:1925 Uncaught (in promise) ReferenceError: isError is not defined
Thanks
<template>
<div class="contact-section">
<div class="container">
<div class="section-content row">
<div class="contact-text col-lg-6">
<div class="text-box">
<h1 class="subtitle text-white">Contact</h1>
<h2 class="text-white"> Have You Any Project? <br> Please Drop a Message </h2>
<p class="text-white"> Get in touch and let me know how i can help. Fill out the form and i’ll be in touch as soon as possible. </p>
</div>
<ul class="contact-info">
<li>
<img src="assets/images/icons/email.png" alt="Email">
<div>
<strong>Email:</strong>
<ul>
<li>info#nafie.com</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="col-lg-6">
<form class="contact-form form-styled" #submit.prevent="send">
<div class="group">
<label>Name</label>
<div class="control has-prefix-icon">
<input type="text" name="name" placeholder="e.g. John Doe" minlength="3" v-model="form.name">
</div>
</div>
<div class="group">
<label>Email</label>
<div class="control has-prefix-icon">
<input class="ltr-dir" type="email" name="email" placeholder="e.g. john.doe#gmail.com" v-model="form.email">
</div>
</div>
<div class="group">
<label>Message</label>
<div class="control has-prefix-icon">
<textarea name="message" placeholder="Write message..." v-model="form.message"></textarea>
</div>
</div>
<div class="group">
<p v-if="isError" class="error large">All fields are required</p>
<div class="control"><button class="submit-btn btn btn-dark" type="submit">Send</button></div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
form: {
email: '',
message: '',
name: ''
},
errors: {},
isError: false
}
},
methods: {
send: function() {
// Reset is error
this.isError = false;
axios.post("/send", this.form)
.then(function (response) {
// Reset form on success
this.form.name = '';
this.form.email = '';
this.form.message = '';
console.log(response);
})
.catch(function (error) {
// Says here undefined?
this.isError = true;
console.log(error);
console.log(error.response.data.errors);
});
}
}
}
</script>
send: function()
{
// Reset is error
this.isError = false;
let self = this;
axios.post("/send", this.form).then(function(response)
{
// Reset form on success
self.form.name = '';
self.form.email = '';
self.form.message = '';
console.log(response);
}).catch(function(error)
{
// Says here undefined?
self.isError = true;
console.log(error);
console.log(error.response.data.errors);
});
}

On click function is not defined and i dont know why

I have to validate an email and a phone. It is not necessary that both are mandatory, just one is enough.
When i click my button, the code error is that handleValidation is not defined, but i do not why. Even the console don't print the console.log.
Here the HTML:
<form class="form-group p-4">
<div class="row">
<div class="col-12 col-md-6 d-flex flex-column">
<input type="text" class="form-control rounded-0 p-3 m-1" id="name" required
placeholder="NOMBRE Y APELLIDO">
<input type="email" class="form-control rounded-0 p-3 m-1" id="email" placeholder="E-MAIL">
<input type="tel" class="form-control rounded-0 p-3 m-1" id="phone" placeholder="TELÉFONO">
</div>
<div class="col-12 col-md-6 d-flex flex-column">
<textarea id="message" class="form-control rounded-0 h-100 p-3 m-1" required
placeholder="DEJANOS TU MENSAJE"></textarea>
</div>
</div>
<div class="row">
<div class="col-12 col-md-3 d-flex flex-column float-right align-items-end">
<button onclick="handleValidation()" id="send-btn"
class="main-btn btn btn-primary col-12 rounded-0 p-2 mt-3">ENVIAR</button>
</div>
</div>
</form>
and here the JS:
let email = document.querySelector("#email");
let tel = document.querySelector("#phone");
const emailVal = () => {
if (!(/\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)/.test(email))) {
console.log("bad")
return false;
}
console.log("good")
return true;
}
const telVal = () => {
if (!(/^\d{9}$/.test(tel))) {
console.log("bad")
return false;
}
console.log("good");
return true;
}
const handleValidation = () => {
if (emailVal() === true || telVal() === true) {
alert("tu consulta fue enviada satisfactoriamente");
} else {
alert("el email y/o el teléfono son necesarios para contactarte");
}
}
Set an event listener in the script instead of onclick attribute
You do not get the values of the inputs but the inputs
Input values should be grabbed into the validations functions, not outside
Your email regex doesn't seems to work (I didn't check the phone number one)
If you correct all this problems, your script should look like that :
const emailVal = () => {
let email = document.querySelector("#email").value;
if (!(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email))) {
console.log("bad email")
return false;
}
console.log("good")
return true;
}
const telVal = () => {
let tel = document.querySelector("#phone").value;
if (!(/^\d{9}$/.test(tel))) {
console.log("bad tel")
return false;
}
console.log("good");
return true;
}
const handleValidation = () => {
if (emailVal() || telVal()) {
alert("tu consulta fue enviada satisfactoriamente");
} else {
alert("el email y/o el teléfono son necesarios para contactarte");
}
}
document.getElementById('send-btn').addEventListener('click', handleValidation);
You will also have to remove your button onclick attribute of course.
Source for email validation regex : https://www.w3resource.com/javascript/form/email-validation.php
I checked your code in jsfiddle. I receive very time "el email y/o el teléfono son necesarios para contactarte". So code is correct to some extends. I suggest add the JSSript after the html and vice versa. I'm mixing this all time up.

How to get Stripe token in the controller of MVC framework?

I am using CodeIgniter and I can't get the Stripe Token in the controller function.
I got the PHP Error :
Severity: Notice
Message: Undefined index: stripeToken
Filename: controllers/App.php
Line Number: 339
Here is my code:
HTML:
<script src="https://js.stripe.com/v3/"></script>
<form action="<?php echo site_url('app/save/'.$event['code']);?>" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Please pay:
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Pay</button>
</form>
I checked the action URL in front-end. It shows the link:
https://www.example.com/enrollment/index.php/app/save/EVENT_A
This is the correct link to my controller.
The JS: (I have changed the key here)
<script>
// Create a Stripe client.
var stripe = Stripe('my_correct_key');
// Create an instance of Elements.
var elements = stripe.elements({
locale: 'en',
});
// Create an instance of the card Element.
var card = elements.create('card', {hidePostalCode: true});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
console.log(errorElement.textContent);
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
console.log(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
In my Controller:
public function save($event_code){
$token=$_POST['stripeToken'];
echo $token;
}
I can't get the token here. I am not familiar with CodeIgniter. What's going wrong?
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Stripe Payment Integration Example - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.panel-title {
display: inline;
font-weight: bold;
}
.display-table {
display: table;
}
.display-tr {
display: table-row;
}
.display-td {
display: table-cell;
vertical-align: middle;
width: 61%;
}
</style>
</head>
<body>
<div class="container">
<h1>Codeigniter Stripe Payment Integration Example <br/> ItSolutionStuff.com</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default credit-card-box">
<div class="panel-heading display-table" >
<div class="row display-tr" >
<h3 class="panel-title display-td" >Payment Details</h3>
<div class="display-td" >
<img class="img-responsive pull-right" src="http://i76.imgup.net/accepted_c22e0.png">
</div>
</div>
</div>
<div class="panel-body">
<?php if($this->session->flashdata('success')){ ?>
<div class="alert alert-success text-center">
×
<p><?php echo $this->session->flashdata('success'); ?></p>
</div>
<?php } ?>
<form role="form" action="/stripePost" method="post" class="require-validation"
data-cc-on-file="false"
data-stripe-publishable-key="<?php echo $this->config->item('stripe_key') ?>"
id="payment-form">
<div class='form-row row'>
<div class='col-xs-12 form-group required'>
<label class='control-label'>Name on Card</label> <input
class='form-control' size='4' type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 form-group card required'>
<label class='control-label'>Card Number</label> <input
autocomplete='off' class='form-control card-number' size='20'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 col-md-4 form-group cvc required'>
<label class='control-label'>CVC</label> <input autocomplete='off'
class='form-control card-cvc' placeholder='ex. 311' size='4'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Month</label> <input
class='form-control card-expiry-month' placeholder='MM' size='2'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Year</label> <input
class='form-control card-expiry-year' placeholder='YYYY' size='4'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-md-12 error form-group hide'>
<div class='alert-danger alert'>Please correct the errors and try
again.</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now ($100)</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
$(function() {
var $form = $(".require-validation");
$('form.require-validation').bind('submit', function(e) {
var $form = $(".require-validation"),
inputSelector = ['input[type=email]', 'input[type=password]',
'input[type=text]', 'input[type=file]',
'textarea'].join(', '),
$inputs = $form.find('.required').find(inputSelector),
$errorMessage = $form.find('div.error'),
valid = true;
$errorMessage.addClass('hide');
$('.has-error').removeClass('has-error');
$inputs.each(function(i, el) {
var $input = $(el);
if ($input.val() === '') {
$input.parent().addClass('has-error');
$errorMessage.removeClass('hide');
e.preventDefault();
}
});
if (!$form.data('cc-on-file')) {
e.preventDefault();
Stripe.setPublishableKey($form.data('stripe-publishable-key'));
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
}
});
function stripeResponseHandler(status, response) {
if (response.error) {
$('.error')
.removeClass('hide')
.find('.alert')
.text(response.error.message);
} else {
var token = response['id'];
$form.find('input[type=text]').empty();
$form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
$form.get(0).submit();
}
}
});
</script>
</html>
/**
* Get All Data from this method.
*
* #return Response
*/
public function index()
{
$this->load->view('my_stripe');
}
/**
* Get All Data from this method.
*
* #return Response
*/
public function stripePost()
{
require_once('application/libraries/stripe-php/init.php');
\Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));
\Stripe\Charge::create ([
"amount" => 100 * 100,
"currency" => "usd",
"source" => $this->input->post('stripeToken'),
"description" => "Test payment from itsolutionstuff.com."
]);
$this->session->set_flashdata('success', 'Payment made successfully.');
redirect('/my-stripe', 'refresh');
}

Can't get error handing in vue.js 1.0 and Laravel 5.1 to work

I'm building an app which uses vue.js and Laravel 5 to persist data into a database. So far, it can successfully save data.
My problem
I'm having trouble with displaying errors when the user validation fails using the 'out of the box' authorisation that Laravel has. I keep getting the error:
[Vue warn]: Error when evaluating expression "form.errors.length > 0"
(referring to errors.js in my code below)
Piecing it together
So how this should work...a user enters their details into the registration page and Vue (using vue-resource) makes an AJAX request to the 'out of the box' Laravel AuthController#postRegister method. On error, Laravel nicely spits out the JSON error messages we all expect. Now in theory, the sendRegistration method within my subscription.js file should detect the errors that Laravel spits out (I've tested this with console.log's and it works) and pass them into the errors.js component to display the errors within the <spark-errors> tags. In order to do this, it uses a setErrorsOnForm: function within my <head> tag. However it's not working as expected and I cannot workout why.
My code
My code consists of a registration page:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Laravel Spark Globals -->
<script>
window.Spark = {
// Laravel CSRF Token
csrfToken: '{{ csrf_token() }}',
// Flatten errors and set them on the given form
setErrorsOnForm: function (form, errors) {
if (typeof errors === 'object') {
form.errors = _.flatten(_.toArray(errors));
} else {
form.errors.push('Something went wrong. Please try again.');
}
}
}
</script>
</head>
<body>
<div id="spark-app">
<spark-subscription-register-screen inline-template>
<div class="panel panel-default">
<div class="panel-heading">Your Information</div>
<div class="panel-body">
<spark-errors form="#'{'{ registerForm '}'}"></spark-errors>
<form class="form-horizontal" role="form" id="subscription-basics-form">
<div class="form-group">
<label class="col-md-4 control-label">Your Name</label>
<div class="col-md-6">
<input type="text" class="form-control spark-first-field" name="name" v-model="registerForm.name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" v-model="registerForm.email">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password" v-model="registerForm.password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation" v-model="registerForm.password_confirmation">
</div>
</div>
<div v-if="freePlanIsSelected">
<div class="form-group">
<div class="col-sm-6 col-sm-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" v-model="registerForm.terms"> I Accept The Terms Of Service
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-4">
<button type="submit" class="btn btn-primary" v-on:click="register" :disabled="registerForm.registering">
<span v-if="registerForm.registering">
<i class="fa fa-btn fa-spinner fa-spin"></i> Registering
</span>
<span v-if=" ! registerForm.registering">
<i class="fa fa-btn fa-check-circle"></i> Register
</span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</spark-subscription-register-screen inline-template>
</div>
</body>
</html>
From a vue.js perspective there is a subscription.js file:
Vue.component('spark-subscription-register-screen', {
/*
* Initial state of the component's data.
*/
data: function () {
return {
registerForm: {
nhs_org: '', team_name: '', name: '', email: '', password: '', password_confirmation: '',
plan: '', terms: false, coupon: null, invitation: null,
stripe_token: null, errors: [], registering: false
},
};
},
methods: {
/*
* Initialize the registration process.
*/
register: function(e) {
var self = this;
e.preventDefault();
this.registerForm.errors = [];
this.registerForm.registering = true;
return this.sendRegistration();
},
/*
* After obtaining the Stripe token, send the registration to Spark.
*/
sendRegistration: function() {
this.$http.post('/register', this.registerForm)
.success(function(response) {
window.location = '/';
})
.error(function(errors) {
this.registerForm.registering = false;
Spark.setErrorsOnForm(this.registerForm, errors);
});
},
}
});
and there is an errors.js Vue component:
/*
* Common Error Display Component.
*/
Vue.component('spark-errors', {
props: ['form'],
template: "<div><div class='alert alert-danger' v-if='form.errors.length > 0'>\
<strong>Whoops!</strong> There were some problems with your input.<br><br>\
<ul>\
<li v-for='error in form.errors'>\
{{ error }}\
</li>\
</ul>\
</div></div>"
});
Now the Vue files which piece all of this together (in the correct order):
app.js:
require('./core/dependencies');
if ($('#spark-app').length > 0) {
new Vue(require('./core/spark.js'));
}
core/dependencies.js:
/*
* Load Vue & Vue-Resource.
*
*/
if (window.Vue === undefined) window.Vue = require('vue');
require('vue-resource');
Vue.http.headers.common['X-CSRF-TOKEN'] = Spark.csrfToken;
/*
* Load Underscore.js, used for map / reduce on arrays.
*/
if (window._ === undefined) window._ = require('underscore');
/*
* Load jQuery and Bootstrap jQuery, used for front-end interaction.
*/
if (window.$ === undefined || window.jQuery === undefined) window.$ = window.jQuery = require('jquery');
require('bootstrap-sass/assets/javascripts/bootstrap');
core/spark.js:
/*
* Load the Spark components.
*/
require('./components');
/**
* Export the Spark application.
*/
module.exports = {
el: '#spark-app',
/*
* Bootstrap the application. Load the initial data.
*/
ready: function () {
$(function() {
$('.spark-first-field').filter(':visible:first').focus();
});
}
}
and core/components.js:
require('./../auth/registration/subscription');
require('./../common/errors');
I had the same issue, and instead of using the out of the box errors from spark, I defined my own component:
<template>
<div v-if="errors">
<div class="alert alert-danger" v-if="formattedErrors.length > 0">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
<li v-for="error in formattedErrors">
{{ error }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props: ['errors'],
computed: {
formattedErrors() {
return this.format(this.errors);
}
},
methods: {
format(errors) {
if (typeof errors === 'undefined') {
return [];
}
if (typeof errors === 'object') {
return _.flatten(_.toArray(errors));
}
}
}
}
</script>
Then you bind in your html:
<form-errors :errors="registerForm.errors"></form-errors>
It makes sense because your component just need the to now about errors, and nothing else about the registerForm.
Hope this helps.

Use CKeditor instance in Vue.js

I am trying to implement CKeditor in my Laravel-backoffice which build its views with Vue.js
In this form I want to replace the "textarea" with name="ckeditor1" with a texteditor
<form method="POST" v-on="submit: onSubmitForm">
<div class="col-md-4">
<h1>Pagina: #{{ page.name }}</h1>
<h2>Pagina algemeen</h2>
<div class="form-group">
<label for="name">
Name
<span class="error" v-if="! page.name">*</span>
</label>
<input type="text" name="name" id="name" class="form-control" v-model="page.name">
</div>
<ul class="nav nav-tabs">
<li class="" v-repeat="page.translations" v-class="active: language == defaultLanguage"><a
data-toggle="tab" href="##{{ language }}">#{{ language }}</a></li>
</ul>
<div class="tab-content">
<div v-repeat="page.translations" id="#{{ language }}" class="tab-pane fade in "
v-class="active: language == defaultLanguage">
<h2>Pagina inhoud</h2>
<div class="form-group">
<label for="name">
Titel
</label>
<input type="text" name="title_#{{ language }}" id="title_#{{ language }}"
class="form-control" v-model="title">
</div>
<div class="form-group">
<label for="content">
Inhoud
</label>
<textarea name="ckeditor1" id="content_#{{ language }}"
class="form-control editor" v-model="content"></textarea>
</div>
<h2>Seo</h2>
<div class="form-group">
<label for="meta_keywords">
Meta keywords
</label>
<input type="text" name="meta_keywords_#{{ language }}"
id="meta_keywords_#{{ language }}" class="form-control"
v-model="meta_keywords">
</div>
<div class="form-group">
<label for="meta_decription">
Meta description
</label>
<textarea name="meta_description_#{{ language }}"
id="meta_description_#{{ language }}" class="form-control"
v-model="meta_description"></textarea>
</div>
<input type="hidden" name="page_id_#{{ language }}" id="page_id_#{{ language }}"
class="form-control" v-model="page_id" value="#{{ pageId }}">
</div>
</div>
<div class="form-group" v-if="! submitted">
<button type="submit" class="btn btn-default">
Opslaan
</button>
</div>
</div>
</form>
The #{{ }} fields are loaded and filled with json call and vue.js but there is no problem cause all fields are filled perfectly as needed. The problem is just the initializing of my editor.
This is where I get my data:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var pages = new Vue({
el: '#page',
data: {
pageId: document.querySelector('#page-id').getAttribute('value'),
pageTitle: 'Pagina',
page: [],
submitted: false,
defaultLanguage: 'nl',
errors: false
},
ready: function() {
this.fetch();
},
methods: {
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
});
},
onSubmitForm: function(e) {
e.preventDefault();
this.submitted = true;
this.errors = false;
if(this.pageId == 0) {
this.$http.post('/api/pages/', this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
else
{
this.$http.put('/api/pages/' + this.pageId, this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
}
}
});
UPDATE -> SOLVED
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
},
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
}
I am also using CKeditor with laravel-vue. You just need to set and get data with CKeditor for basic thing.
This is my main.html file in which i need CKeditor.
<div class="row">
<div class="col-md-2">
<label for="body" >Mail Body :</label>
</div>
<div class="col-md-10" >
<textarea class="ckeditor" id="body" rows="5" cols="70" name="body" v-model="template.body" ></textarea>
</div>
</div>
After that i initialize my CKeditor value in app.js file
var vm = this;
axios.post('/fetchEmailTemplate', {
'template_id' : template_id
}).then(function (response) {
vm.template = response.data.emailTemplate;
CKEDITOR.instances['body'].setData(vm.template.body);
}).catch(function (error) {
console.log(error);
setNotification(error, "danger");
});
If I'm not mistaken ckeditor replaces the original textarea by a custom template. So what you see within ckeditor will not be put into your messageArea textarea automatically. That's why you don't see any changes to your model. So, for making changes you need to replace updated text before submit in app.js file like below.
this.template.body = CKEDITOR.instances['body'].getData();

Categories

Resources