Insert Many to Many Data into Shopware 6 Database using the Administration - vue.js

I have created a plugin in the adminstration and I want to insert the manyToMany products with vehicles into Shopware 6 database. From the code below I am trying to insert '92961afbc50e4380b3af86b257630ade' into the 'product_id' column of the 'vehicles_product' table :
import template from './sw-vehicles-import.html.twig';
const { Component, Mixin } = Shopware;
Component.register('sw-vehicles-import', {
template,
inject: ['importExport', 'repositoryFactory', 'feature'],
mixins: [
Mixin.getByName('notification'),
],
metaInfo() {
return {
title: this.$createTitle()
};
},
data() {
return {
importFile: null,
repository: null,
entity: undefined,
};
},
computed: {
},
created() {
this.repository = this.repositoryFactory.create('vehicles');
},
methods: {
onStartProcess() {
this.entity = this.repository.create(Shopware.Context.api);
this.entity.categoryFilter = 'CategoryName';
this.entity.featureFilter = 'FeatureName';
this.entity.products.productId = '92961afbc50e4380b3af86b257630ade';
this.repository.save(this.entity, Shopware.Context.api);
}
}
});
The build process doesn't work, what am I doing wrong? Could you help me please ?

You need to create a new entity collection for the association if it doesn't exist yet.
const { EntityCollection } = Shopware.Data;
if (!this.entity.products) {
this.entity.products = new EntityCollection(
'/product',
'product',
Shopware.Context.api
);
}
const product = await this.repositoryFactory.create('product').get('92961afbc50e4380b3af86b257630ade', Shopware.Context.api);
this.entity.products.add(product);
this.repository.save(this.entity, Shopware.Context.api);

Related

Vue Apollo "__typename" is undefined in updateQuery

I'm attempting to create a "Show More" button for my posts index. The index query loads fine with the first 5 posts, when I click the Show More button I can see new posts being returned, however I receive a bunch of errors like:
Missing field id in {
"__typename": "Post",
"posts": [
{
"id": "5f2b26600c3ec47b279d8988",
"title":
I receive one of each of these errors pretty much for each post attribute (id, title, content, slug, etc). This prevents the actual new posts from being added to the index. What causes this issue?
<script>
import postsQuery from '~/apollo/queries/blog/posts';
const pageSize = 5;
export default {
name: 'BlogIndex',
data: () => ({
loadingMorePosts: false,
page: 0,
pageSize,
}),
apollo: {
postsCount: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
posts: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
},
computed: {
morePosts() {
return this.posts.length < this.postsCount.aggregate.totalCount;
}
},
methods: {
async fetchMorePosts() {
this.page += this.pageSize;
this.$apollo.queries.posts.fetchMore({
variables: {
page: this.page,
pageSize,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newPosts = fetchMoreResult.posts;
console.log('typename: ', previousResult.posts.__typename); <--- returns undefined
if (!newPosts.length) return previousResult;
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
}
})
},
},
}
</script>
UPDATE: added imported posts query
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}
I think the problem is here:
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
I'm pretty sure __typename is supposed to belong to each post object, not part of the collection of posts. Let me know how if something like this fixes it:
return {
posts: {
posts: [...previousResult.posts, ...newPosts]
}
}
and changing the query to:
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
__typename // add this here
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}

I'm getting the error in vue.js - Unexpected side effect in "filteredTeamsData" computed property

Unexpected side effect in "filteredTeamsData" computed property
I have imported the two JSON file
import seasonList from '../assets/data/season_list.json'
import team data from '../assets/data/match_team.json'
Code -
export default {
name: 'SeasonSplit',
components: {
TableElement,
},
data () {
return {
selected: '1',
teamData: teamData,
teamList: [],
seasonList: seasonList,
filteredData: [],
tableColumns: ['toss_wins', 'matches', 'wins', 'losses', 'pts']
}
},
computed: {
filteredTeamsData: function () {
this.dataArr = []
this.filteredData = []
this.teamList = []
teamData.forEach(element => {
if(element.season == seasonList[this.selected-1]){
this.filteredData.push(element)
this.teamList.push(element.team)
this.dataArr.push(element.wins)
}
})
// console.log(this.filteredData)
return this.dataArr
}
}
}
I'd do it as follows:
export default {
name: 'SeasonSplit',
components: {
TableElement,
},
data () {
let filteredData = [];
let teamList = [];
let dataArr = [];
teamData.forEach(element => {
if(element.season == seasonList[this.selected-1]){
filteredData.push(element)
teamList.push(element.team)
dataArr.push(element.wins)
}
});
return {
selected: '1',
teamData: teamData,
teamList: teamList ,
seasonList: seasonList,
filteredData: filteredData ,
tableColumns: ['toss_wins', 'matches', 'wins', 'losses', 'pts'],
filteredTeamsData: dataArr
}
}

How can I write this code to be more efficient

I am learning Vue.js and I am setting up a website where I am using LocalStorage to store data.
I wrote some code, which is a little clunky and very repetitive:
<script>
const app = new Vue({
el:'#app',
data:{
explosive_pullups_1: '',
explosive_pullups_2: '',
explosive_pullups_3: '',
tuck_front_raises_1: '',
tuck_front_raises_2: '',
tuck_front_raises_3: '',
},
mounted() {
if (localStorage.explosive_pullups_1) {
this.explosive_pullups_1 = localStorage.explosive_pullups_1;
}
if (localStorage.explosive_pullups_2) {
this.explosive_pullups_2 = localStorage.explosive_pullups_2;
}
if (localStorage.explosive_pullups_3) {
this.explosive_pullups_3 = localStorage.explosive_pullups_3;
}
if (localStorage.tuck_front_raises_1) {
this.tuck_front_raises_1 = localStorage.tuck_front_raises_1;
}
if (localStorage.tuck_front_raises_2) {
this.tuck_front_raises_2 = localStorage.tuck_front_raises_2;
}
if (localStorage.tuck_front_raises_3) {
this.tuck_front_raises_3 = localStorage.tuck_front_raises_3;
}
},
watch: {
explosive_pullups_1(pullups1) {
localStorage.explosive_pullups_1 = pullups1;
},
explosive_pullups_2(pullups2) {
localStorage.explosive_pullups_2 = pullups2;
},
explosive_pullups_3(pullups3) {
localStorage.explosive_pullups_3 = pullups3;
},
tuck_front_raises_1(tuck_front_raises1) {
localStorage.tuck_front_raises_1 = tuck_front_raises1;
},
tuck_front_raises_2(tuck_front_raises2) {
localStorage.tuck_front_raises_2 = tuck_front_raises2;
},
tuck_front_raises_3(tuck_front_raises3) {
localStorage.tuck_front_raises_3 = tuck_front_raises3;
},
}
})
</script>
I would like to know a way to write this code to be less repetitive.
You can put the exercise data into its own object, and save that to localStorage instead. E.g.:
<script>
const app = new Vue({
el:'#app',
data: {
exercises: {},
},
mounted() {
this.exercises = JSON.parse(localStorage.getItem("exercises"));
},
watch: {
exercises(newExerciseValues) {
localStorage.setItem("exercises", JSON.stringify(newExerciseValues));
},
}
})
</script>
If you really need to store and retrieve the individual exercises explicitly, I would recommend keeping the data in one exercises object, and simply use a for loop to check/set everything. Something like this:
[...]
watch: {
exercises(newExercises) {
const exercisesToCheck = [
'explosive_pullups_1',
'explosive_pullups_2',
'explosive_pullups_3',
'tuck_front_raises_1',
'tuck_front_raises_2',
'tuck_front_raises_3',
];
for (const exercise of exercisesToCheck) {
localStorage.setItem(exercise, this.exercises[exercise]);
}
},
},
[...]
On a side note, be very careful when working with objects in Vue. If you need to add a new exercise to the exercises object, avoid using this.exercises['new_exercise'] = newExercise. Instead, use Vue.set(this.exercises, 'new_exercise', newExercise). Check out the Vue docs for an explanation.

graphql mongoose returning null

I am using graphql with express and mongoose. for some reasons, I am getting null value for embedded documents. tried both async/await and promise.
Schema.JS
const typeDefs = `
type Patient{
name:String
}
type Order {
_id: ID!
orderName: String!
orderDate: Int,
patient:Patient
}
type Query {
allOrders: [Order]
}
`;
module.exports.schema = makeExecutableSchema({
typeDefs,
resolvers
});
resolver.JS
module.exports.resolvers = {
Query: {
async allOrders() {
return await db.cpoeDataModel.CpoeOrder.find();
}
},
Order: {
patient: async (order) => {
console.log("patient Id##", order.patientId);
return await db.domainModel.Patient.findById(order.patientId);
}
}
};
the query:
{
allOrders {
orderName,
patient {
name
}
}
}
result:
{
"allOrders": [
{
"orderName": "order1",
"patient": null
},
{
"orderName": "order2",
"patient": null
}]
}
expected result
{
"allOrders": [
{
"orderName": "order1",
"patient": {
"name":"xyz"
}
},
{
"orderName": "order2",
"patient": {
"name":"xyz"
}
}]
}
the problem was with my order collection not with code. there was some reference of patient Ids that does not exist anymore. that's why getting null values that are acceptable. I was confused just bcoz it's on the top of results.

feeding row data to ag-grid vue component

In all the ag-grid-vue examples, data of rows are generated in the component's method of createRowData(), which is simple but not realistic.
I want to see an example in which row-data are provided to ag-grid vue component from the parent Vue instance.
If there's such information, please let me know.
I found a way by using Veux. Here's an example.
Appication.
let gridRows = {
state: {
rowData: []
},
mutations: {
push(state, rows) {
while( 0 < rows.length ){
state.rowData.unshift(rows.pop());
}
},
getters: {
rowData: state => {
let rows = state.rowData;
return state.rowData;
}
}
};
let store = new Vuex.Store(gridRows);
let app01 = new Vue({
el: '#app',
store,
render: h => h(DynamicComponentExample)
});
let rowData = [];
for (var i=0; i < 15; i++) {
rowData.unshift({
row: "Row " + i,
value: i,
currency: i + Number(Math.random().toFixed(2))
});
}
store.commit('push', rowData);
Component (modification to DynamicComponentExample.vue)
data () {
return {
gridOptions: null,
columnDefs: null
//rowData: null
}
},
computed: {
rowData(){
return this.$store.getters['rowData'];
}
},
beforeMount() {
...
//this.createRowData();
this.initColumnDefs();
},