How to render a template with VueJS and Axios? - api

I have a Vue app that generates as many forms as the user likes. Each form represent a 'risk' in this 'risks' data model:
var app = new Vue({
el: '#app',
data: {
risks: [
{
'risk_name': '', 'fields': [{'field': '', 'type': ''}], 'errors':[]
}
],
},
Then I send the 'risks' to a post API request. Then I make a second get request that brings back a template with the processed data as JSON. So far so good. However, how do I render the template (new page) with this data.
This is how I receive the data:
Submit() {
if (this.checkValidity()) {
console.info(this.risks)
axios.post('risks', this.risks)
.then(function(response) {
axios.get('risks')//This gets the data back
})
.catch(function(error) {
alert('This Error occured: ' + error)
})
}
},
This is the GET API call that I called above (Flask):
#app.route('/risks', methods=['GET'])
def getInsurancePolicyForm():
risks = getTables(app.metadata)
return render_template('form.html', risks=risks)
I can see the rendered template in developer tools, but the page the user sees remains the same.

Your page should be focussed on the risks object instead of the response from the API call.
When the user selects options, add them to the risks data object so your risks object looks like:
risks: [
{
'risk_name': '', 'fields': [{'field': 'My Field', 'type': 'text', modelToHoldData: ''}], 'errors':[]
}
]
Then, when the user clicks on Submit, by all means send it to the API but you don't need a template from there, use the risks object like so (remembering to hide the form they've just chosen their fields with):
<div v-for="risk in risks">
<label>{{risk.field}}</label>
<input type="text" v-if="risk.type === 'text'" v-model="risk.modelToHoldData" />
</div>
You can adjust the above example to add as many variations of the example as you allow the user to select.
Once all this is done and you need access to the data the user enters, you can loop through the array again and just access the modelToHoldData prop on each of the risks.

Related

Issue with aws cognito UI form fields in vue js

I'm using AWS cognito and amplify in my vue js application. Everything is working fine with pre-defined fields.
I've added the custom fields in AWS user pool attributes section. Those newly added fields are not reflecting in UI.
Here is my code for amplify config and custom fields.
HTML Code:
<amplify-authenticator>
<amplify-sign-up
slot="sign-up"
header-text="My Project Sign-Up"
submit-button-text="Register"
:formFields="formFields"
></amplify-sign-up>
</amplify-authenticator>
Custom Fields JSON
formFields: [
{ type: 'username' },
{ type: 'password' },
{ type: 'email', inputProps: { required: true, autocomplete: 'username' } },
{ type: 'phone_number' },
{ type: 'custom:name' },
]
Result form
Custom fields are not coming in the form. Can some one please help me to solve this issue?
The issue appears to be related to Stencil. See this discussion.
The solution suggested is to change formFields to formFields.prop.
E.g.
<amplify-authenticator>
<amplify-sign-up
slot="sign-up"
header-text="My Project Sign-Up"
submit-button-text="Register"
:formFields.prop="formFields"
></amplify-sign-up>
</amplify-authenticator>
This worked for me using Vue 2.

How to upload a photo in my Form and into my Vuex store?

I'm practicing building a Hybrid Mobile app with Quasar, Vue and Vuex.
I've successfully added my form input fields to my Vuex store but I don't know how to upload a file, in this case a photo, within my Form.
Here is my q-file input from my form, with the data.
<q-file
v-model="mealToSubmit.photo"
label="Upload File"
outlined
>
Data:
data () {
return {
mealToSubmit: {
name: '',
description: '',
photo: null,
grams: '',
calories: '',
visible: false
}
}
}
After I fill in the Form and click Save, all of the data appears on the page except for the photo I selected. In the console I get a 404 error:
404  http://localhost:8080/img/null 404 (Not Found)
I can see the problem here is that it's displaying null, instead of the name of the photo I upload, which is why I'm getting a 404 error.
Here are two screenshots, one of me filling in the Form and second is the data being displayed properly except for the photo, with the error message in the console.
NOTE:
Just to add to this, I've uploaded files before using Vue js and Bootstrap-Vue. I add an #change event on the File input with a v-model like this:
<b-form-group label="Upload Profile Photo (optional)" label-for="photo_id">
<b-form-file
v-model="profileData.photo_id"
id="photo_id"
placeholder="Choose a file..."
#change="attachImage"
accept=".jpg, .jpeg, .png"
></b-form-file>
</b-form-group>
Than in the Methods{}:
methods: {
attachImage(evt) {
const file = evt.target.files[0];
let reader = new FileReader();
reader.addEventListener('load', function() {
}.bind(this), false);
reader.readAsDataURL(file);
},
}
And then I bind the data using FormData(); and send it to the backend. This approach isn't working with the Quasar file upload input and the code that I have above.
I got it now:
<q-file
#input="getFile"
label="Upload file"
/>
methods: {
getFile(file) {
// file is in the file variable
this.mealToSubmit.photo = file
}
}

React-Admin doesn't show column data in List component

I don't seem to be able to understand why data is missing. Here is my field:
<ReferenceField source="imageId" reference="files">
<TextField source="urlPath" />
</ReferenceField>
Here is what the main model papers is returning:
brandId: "b3dc4246-3adf-4f4e-9f81-294f23d24977"
brandModelId: "2819360d-2e6e-48e4-88a3-823a03177a7c"
colorId: "98031f74-a83f-4389-b9d6-bab959ff8a0e"
gsm: 200
id: "058cc13d-1255-4d9b-9ccf-e087ddb3935d"
imageId: "1bc99717-f60c-485e-989a-5d1726501b8d"
originalSize: "A4"
paperMaterialId: "5afd0d7c-5ace-49e3-a538-894ce288fe71"
paperSurfaceId: null
price: 12
ref: "44202129"
storeId: "2f7567ad-fa62-4bda-851b-89b8c39a189e"
Here is what the related model files is returning:
id: "1bc99717-f60c-485e-989a-5d1726501b8d"
originalFileName: "palette1.2.png"
type: "undefined"
urlPath: "asdf/101d7c68-9bf4-4d55-bbb5-818f62c480a3-palette1.2.png"
but here is my screenshot with missing data:
Note that the Store related field works, which has the exact same code:
<ReferenceField source="storeId" reference="stores">
<TextField source="name" />
</ReferenceField>
Also, here is my getMany dataProvider:
getMany: (resource, params) => {
const query = {
filter: JSON.stringify({ id: params.ids }),
};
const url = `${API_URL_LOCAL}/${resource}?${stringify(query)}`;
return request(url, 'get', {}, {}).then(({ data }) => ({
data,
}));
},
Any help is welcome.
In cases where you have some reference fields working, and others not, and no error is logged in console, this probably means that the non-working reference resource wasn't declared as Admin child with <Resource name="files" .../>.
From react-admin docs:
Note: You must add a <Resource> for the reference resource -
react-admin needs it to fetch the reference data. You can omit the
list prop in this reference if you want to hide it in the sidebar
menu.
https://marmelab.com/react-admin/Fields.html#referencefield
If none reference resource is working, and the resources has been properly declared, the error will probably rely on your data provider. Log the responses for getMany requests and see if it match the expected format and if it contains any data and not an empty array:
getMany { data: {Record[]}, validUntil?: {Date} }
A {Record} is an object literal with at least an id property, e.g. {
id: 123, title: "hello, world" }.
The validUntil field in the response is optional. It enables the
Application cache, a client-side optimization to speed up rendering
and reduce network traffic
https://marmelab.com/react-admin/DataProviders.html#writing-your-own-data-provider

Can anyone help implementing Nuxt.js Google Tag Manager?

Hey i've built a Nuxt app and am having trouble with the package #nuxtjs/google-tag-manager package. Found below. The documentation is pretty light and I haven't found many example implementations out there. In my nuxt.config.js I have the following set.
['#nuxtjs/google-tag-manager', {
id: process.env.GTM_ID,
layer: 'dataLayer',
pageTracking: true
}],
..but unfortunately am not getting any Page Views in Google Tag Manager
Does anyone have any ideas or experience in how to best implement GTM or what has worked for them?
Thanks in advance
I had a look at the package, inside https://github.com/nuxt-community/gtm-module/blob/master/lib/defaults.js there is this piece of code:
function startPageTracking(ctx) {
ctx.app.router.afterEach((to) => {
setTimeout(() => {
ctx.$gtm.push(to.gtm || {
routeName: to.name,
pageType: 'PageView',
pageUrl: '<%= options.routerBase %>' + to.fullPath,
pageTitle: (typeof document !== 'undefined' && document.title) || '',
event: '<%= options.pageViewEventName %>'
})
}, 250)
})
}
From that, it looks like the datalayer looks like this:
{
routeName: to.name,
pageType: 'PageView',
pageUrl: '<%= options.routerBase %>' + to.fullPath,
pageTitle: (typeof document !== 'undefined' && document.title) || '',
event: '<%= options.pageViewEventName %>' //default is 'nuxtRoute'
}
The default name for the event is 'nuxtRoute'. Thus in GTM, you'll get to define a custom event trigger to trigger on the "nuxtRoute' event. Like so:
Then you want to create two DataLayer variables in GTM that will capture pageUrl(Please note the camel case) and possibly routeName, I say routeName is optional depends on if you're changing/updating the of the document or not.
Then create your Google Analytics tag in GTM. Make sure it is the "pageview" type, then check the "enable overriding settings in this tag" checkbox, under "more settings > fields to set" type in "page" for fieldname and for "value" reference that variable we created. If you want to set the page title using the to.name variable just use the "title" field. Make sure you add the nuxt route trigger as well under "triggering".
Save and publish everything or run it in preview mode and you should see the pageviews some through.

emberjs rails submitting in controller without model

I'm am brand new to emberjs (1.0.0-RC1) which I'm using on top of rails. I want to submit a form for a session without using an ember model. I feel this is better because there is not real session model in my rails app. For now what works is the following:
#login_controller.js.coffee
SkillUp.LoginController = Ember.ObjectController.extend
# Just a title to pass to the template, for fun
title: "Login Controller"
submit: (controller) ->
model = #get 'model'
model.get('transaction').commit()
#session.js.coffee
SkillUp.Session = DS.Model.extend
email: DS.attr 'string'
password: DS.attr 'string'
#login_route.js.coffee
SkillUp.LoginRoute = Ember.Route.extend
setupController: (controller) ->
controller.set 'title', "Login"
controller.set 'content', SkillUp.Session.createRecord()
<!-- login.handlebars -->
<h2>template: {{title}}</h2>
<form>
{{#with controller}}
email: {{view Ember.TextField valueBinding="email"}}
password: {{view Ember.TextField valueBinding="password" type="password"}}
<button {{action submit}}>Submit</button>
{{/with}}
</form>
As I said my goal is to remove the session.js.coffee because a rails model does not exist for it.
Help would be appreciated thanks
I don't recommend implementing $.ajax directly. I recommend keeping the DS model. This should make testing easier if you use DS.FixtureAdapter. Ideally you should keep all the ajax behind a layer in the application. You shouldn't be dropping in $.ajax in various parts of the application.
EDIT: just because you don't have a Session model in the backend doesn't mean you can't have one on the frontend. The ember app will have it's own models. Don't worry about a 1:1 mapping.
You can just use $.ajax in your controller method to post the values to rails using jQuery manually.
$.ajax('/sessions', {
type: 'POST',
data: {
email: this.get('email'),
password: this.get('password)
},
...
});
Add appropriate handlers for success and failure.