How to correctly register a CMS element with the Shopware 6 Admin SDK - shopware6

With the Shopware 6 Admin SDK it's possible to add CMS Elements to the Shopware Admin from an external app via iFrame. However, by following the documentation there are some issues one might tackle along the way. If everything is done as stated in the docs following issues occur that I'd like to discuss:
First issue: If the newly registered CMS element is used more than once in a shopping experience layout the same config data is shared between all elements. This is the most severe issue that I need to solve. The second issue sounds kind of the reason for it. Therefore I attached my code at the end.
Second issue: Once the newly registered CMS element's config modal is opened the following error is thrown: The dataset id "swag-dailymotion__config-element" you tried to publish is already registered. The error is thrown in this file. I guess this has something to do in which I set up the element.
Third issue: If e.g. some text element is exchanged with the newly registered element the following console error is thrown once the element switch button is clicked and all element previews are visible: An error was captured in current module: TypeError: this.initElementConfig is not a function. Since there is a // #ts-expect-error in the responsible file I think this is not too important for the extension developer, since Shopware is already aware of it.
I have the following setup for implementing the CMS element. It differs in some way, since I am using .vue files instead of plain .ts as explained in the docs. However, except the mentioned issues, everything seems to be working fine:
This file is the entry point for the <base-app-url>
<template>
<view-renderer v-if="showViewRenderer"></view-renderer>
</template>
<script lang="ts">
import Vue from 'vue';
import { location, cms } from '#shopware-ag/admin-extension-sdk';
import viewRenderer from '#/components/cms/view-renderer.vue';
import { CONSTANTS } from '#/components/cms/index';
export default Vue.extend({
components: {
'view-renderer': viewRenderer
},
data() {
return {
showViewRenderer: false
};
},
created(): void {
if (location.isIframe()) {
if (location.is(location.MAIN_HIDDEN)) {
this.mainCommands();
} else {
this.showViewRenderer = true;
}
}
},
methods: {
mainCommands(): void {
this.registerCmsElements();
},
registerCmsElements(): void {
cms.registerCmsElement({
name: CONSTANTS.CMS_ELEMENT_NAME,
label: this.$t('cms.dailymotion.preview.label') as string,
defaultConfig: {
dailyUrl: {
source: 'static',
value: '',
},
},
});
}
}
});
</script>
#/components/cms/view-renderer.vue
<template>
<div>
<swag-dailymotion-config v-if="location.is('swag-dailymotion-config')"></swag-dailymotion-config>
<swag-dailymotion-element v-else-if="location.is('swag-dailymotion-element')"></swag-dailymotion-element>
<swag-dailymotion-preview v-else-if="location.is('swag-dailymotion-preview')"></swag-dailymotion-preview>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import { location } from '#shopware-ag/admin-extension-sdk';
import swagDailymotionConfig from '#/components/cms/swag-dailymotion/swag-dailymotion-config.vue';
import swagDailymotionElement from '#/components/cms/swag-dailymotion/swag-dailymotion-element.vue';
import swagDailymotionPreview from '#/components/cms/swag-dailymotion/swag-dailymotion-preview.vue';
export default Vue.extend({
components: {
'swag-dailymotion-config': swagDailymotionConfig,
'swag-dailymotion-element': swagDailymotionElement,
'swag-dailymotion-preview': swagDailymotionPreview
},
data() {
return {
location
};
},
created(): void {
location.startAutoResizer();
}
});
</script>
The individual components are not doing anything special. They are fetching the element with this.element = await data.get({ id: CONSTANTS.PUBLISHING_KEY }); as stated in the docs and doing some work with it. However, it's always fetching the same element without considering the slot the current element is in, therefore it's always fetching the same data set.
What am I doing wrong?

Related

Same VueX store module registered from components on two pages

I have encountered a weird case when using VueX and Vue-Router and I am not too sure how to cleanly solve it.
I have a component (let's call it "ComponentWithStore") that registers a named store module a bit like this : (the actual content of the store don't matter. obviously in this toy example using VueX is overkill, but this is a very simplified version of a much more complexe app where using VueX makes sense)
// ComponentWithStore.vue
<script>
import module from './componentStore.js';
export default {
name: 'ComponentWithStore',
beforeCreate() {
this.$store.registerModule(module.name, module);
},
beforeDestroy() {
this.$store.unregisterModule(module.name);
}
}
</script>
Then I place this component in a view (or page) which is then associated to a route (let's call this page "Home").
// Home.vue
<template>
<div class="home">
Home
<ComponentWithStore/>
</div>
</template>
<script>
import ComponentWithStore from '#/components/ComponentWithStore.vue';
export default {
name: "Home",
components: { ComponentWithStore }
};
</script>
So far so good, when I visit the Home route, the store module is registered, and when I leave the Home route the store module is cleaned up.
Let's say I then create a new view (page), let's call it "About", and this new About page is basically identical to Home.vue, in that it also uses ComponentWithStore.
// About.vue
<template>
<div class="about">
About
<ComponentWithStore/>
</div>
</template>
<script>
import ComponentWithStore from '#/components/ComponentWithStore.vue';
export default {
name: "About",
components: { ComponentWithStore }
};
</script>
Now I encounter the following error when navigating from Home to About :
vuex.esm.js?2f62:709 [vuex] duplicate namespace myComponentStore/ for the namespaced module myComponentStore
What happens is that the store module for "About" is registered before the store module for "Home" is unregistered, hence the duplicate namespace error.
So I understand well what the issue is, however I am unsure what would be the cleanest solution to solve this situation. All ideas are welcome
A full sample may be found here : https://github.com/mmgagnon/vue-module-router-clash
To use, simply run it and switch between the Home and About pages.
As you have mentioned, the issue is due to the ordering of the hooks. You just need to use the correct hooks to ensure that the old component unregisters the module first before the new component registers it again.
At a high level, here is the order of hooks in your situation when navigating from Home to About:
About beforeCreate
About created
Home beforeDestroy
Home destroyed
About mounted
So you can register the module in the mounted hook and unregister it in either beforeDestroy or destroyed.
I haven't tested this though. It might not work if your component requires access to the store after it is created and before it is mounted.
A better approach is to create an abstraction to register and unregister modules that allows for overlaps.
Untested, but something like this might work:
function RegistrationPlugin(store) {
const modules = new Map()
store.registerModuleSafely = function (name, module) {
const count = modules.get(name) || 0
if (count === 0) {
store.registerModule(name, module)
}
modules.set(name, count + 1)
}
store.unregisterModuleSafely = function (name) {
const count = modules.get(name) || 0
if (count === 1) {
store.unregisterModule(name)
modules.delete(name)
} else if (count > 1) {
modules.set(name, count - 1)
}
}
}
Specify the plugin when you create your store:
const store = new Vuex.Store({
plugins: [RegistrationPlugin]
})
Now register and unregister your modules like this:
beforeCreate() {
this.$store.registerModuleSafely(module.name, module)
},
destroyed() {
this.$store.unregisterModuleSafely(module.name)
}

Vue.js: is it possible to have a SFC factory?

I'm using single-file-components in a larger project and I'm new to Vue.JS. I'm looking for a way to dynamically create components, especially their templates on-the-fly at run-time.
My idea is to create a "component factory" also as a SFC and to parameterize it with props, e.g. one for the template, one for the data and so forth. I get how this works for already specified SFC and that I can simply exchange them with <component v-bind:is= ..., however the task here is different. I need to compose a template string, which potentially is composed of other component instance declarations, on-the-fly and inject it in another SFC. The code below doesn't work unfortunately.
<template>
<div>
<produced-component/>
</div>
</template>
<style></style>
<script>
import Vue from 'vue'
export default {
props: {
template: { type: String, default: '<div>no template prop provided</div>' }
},
components: {
'produced-component': Vue.extend(
{
template: '<div>my runtime template, this I want to be able to compose on-the-fly</div>'
}
)
}
}
</script>
It says:
The following answer: https://stackoverflow.com/a/44648296/4432432 answers the question partially but I can't figure out how to use this concept in the context of single-file-components.
Any help is greatly appreciated.
Edit 2020.03.16:
For future reference the final result of the SFC factory achieved as per the accepted answer looks like this:
<template>
<component:is="loader"/>
</template>
<script>
const compiler = require('vue-template-compiler')
import Vue from 'vue'
export default {
props: {
templateSpec: { type: String, default: '<div>no template provided</div>' }
},
computed: {
loader () {
let compSpec = {
...compiler.compileToFunctions(this.templateSpec)
}
return Vue.extend(compSpec)
}
}
}
</script>
You can surely have a Factory component with SFC; though what you are trying to do is a very rare case scenario and seems more like an anti/awkward pattern.
Whatever, you are doing currently is right. All you need to do is - use Full build of Vue which include the Vue Template Compiler, which will enable you to compile template at run-time (on the browser when app is running). But remember that for the components written in SFC, they must be compiled at build time by vue-loader or rollup equivalent plugin.
Instead of using vue.runtime.min.js or vue.runtime.js, use vue.min.js or vue.js.
Read Vue installation docs for more details.
Assuming you are using Webpack, by default main field of Vue's package.json file points to the runtime build. Thus you are getting this error. You must tell webpack to use full bundle. In the configuration resolve the Vue imports to the following file:
webpack.config.js
module.exports = {
// ... other config
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
};

Page reload causes Vuex getter to return undefined

Using Vue.js (Vuetify for FE).
A page reload causes the getter in Vuex to fail with pulling required data from the store. The getter returns undefined. The code can be found on GitHub at: https://github.com/tineich/timmyskittys/tree/master/src
Please see the full details on this issue at timmyskittys.netlify.com/stage1. This page has complete info on the issue and instructions on how to view the issue.
Note, there is mention of www.timmyskittys.com in the issue description. This is the main site. timmyskittys.netlify.com is my test site. So, they are the same for all intents and purposes. But, my demo of this issue is at the Netlify site.
I read the complete issue in the website you mentioned. It's a generic case.
Say, for cat details page url: www.timmyskittys.com/stage2/:id.
Now in Per-Route Guard beforeEnter() you can set the cat-id in store. Then from your component call the api using the cat-id (read from getters)
I found the solution to my issue:
I had to move the call of the action which calls the mutation that loads the .json file (dbdata.json) into a computed() within App.vue. This was originally done in Stage1.vue.
Thanks all for responding.
I had the same issue and my "fix" if it can be called that was to make a timer, so to give the store time to get things right, like so:
<v-treeview
:items="items"
:load-children="setChildren"
/>
</template>
<script>
import { mapGetters } from 'vuex'
const pause = ms => new Promise(resolve => setTimeout(resolve, ms))
export default {
data () {
return {
children: []
}
},
computed: {
...mapGetters('app', ['services']),
items () {
return [{
id: 0,
name: 'Services',
children: this.children
}]
}
},
methods: {
async setChildren () {
await pause(1000)
this.children.push(...this.services)
}
}
}
</script>
Even though this is far from ideal, it works.

Issues including Moment.js library for use with Tabulator in Vue.js

I am trying to use the Date Time functionality with Tabulator which requires the moment.js library. In my application before adding Tabulator, moment.js was already being used in certain components that level. I have a new test component that uses Tabulator and attempts to use datetime. Typically I would just import moment and use it here but it seems that moment is required within Tabulator itself.
My first thought is that Moment.js needs to be setup globally in my application so I did that.
Main.js:
```
import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import moment from 'moment'
Vue.prototype.moment = moment
...............
new Vue({
el: '#app',
data () {
return {
info: null,
loading: true,
errored: false // this.$root.$data.errored
}
},
router,
components: { App },
template: '<App/>',
store
})
```
In my component (Testpage.vue)
```
<template>
<div>
<div ref="example_table"></div>
</div>
</template>
<script>
// import moment from 'moment'
var Tabulator = require('tabulator-tables')
export default {
name: 'Test',
data: function () {
return {
tabulator: null, // variable to hold your table
tableData: [{id: 1, date: '2019-01-10'}] // data for table to display
}
},
watch: {
// update table if data changes
tableData: {
handler: function (newData) {
this.tabulator.replaceData(newData)
},
deep: true
}
},
mounted () {
// instantiate Tabulator when element is mounted
this.tabulator = new Tabulator(this.$refs.example_table, {
data: this.tableData, // link data to table
columns: [
{title: 'Date', field: 'date', formatter: 'datetime', formatterParams: {inputFormat: 'YYYY-MM-DD', outputFormat: 'DD/MM/YY', invalidPlaceholder: '(invalid date)'}}
],
}
</script>
```
I receive the error: "Uncaught (in promise) Reference Error: moment is not defined at Format.datetime (tabulator.js?ab1f:14619)"
I am able to use moment in other components by using this.$moment() but I need for it to be available in node_modules\tabulator-tables\dist\js\tabulator.js
since thats where the error is happening. Any idea how to include the library?
Go back to the first option you were trying, because annotating the Vue prototype with moment is definitely not the right approach. Even if it was recommended (which it isn't), Tabulator would have to know to find it by looking for Vue.moment. It isn't coded to do that.
One of the things I love about Open Source is that you can see exactly what a library is doing to help fix the issue. A quick search of the Tabulator code base finds this:
https://github.com/olifolkerd/tabulator/blob/3aa6f17b04cccdd36a334768635a60770aa10e38/src/js/modules/format.js
var newDatetime = moment(value, inputFormat);
The formatter is just calling moment directly, without importing it. It's clearly designed around the old-school mechanism of expecting libraries to be available globally. In browser-land that means it's on the "window" object. Two quick options could resolve this:
Use a CDN-hosted version of Moment such as https://cdnjs.com/libraries/moment.js/ by putting something like this in the header of your page template:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Adjust your code above to set moment on window:
window.moment = moment;
ohgodwhy's comment above isn't necessarily wrong from the perspective of date-fns being better in many ways. But it won't work for you because Tabulator is hard-coded to look for moment, so you'll need moment itself to work.

did you register the component correctly? For recursive components, make sure to provide the "name" option

I configured 'i-tab-pane': Tabpane but report error,the code is bellow:
<template>
<div class="page-common">
<i-tabs>
<i-tab-pane label="wx">
content
</i-tab-pane>
</i-tabs>
</div>
</template>
<script>
import {
Tabs,
Tabpane
} from 'iview'
export default{
name:"data-center",
data(){
return {msg: 'hello vue'}
},
components: {
'i-tabs' : Tabs,
'i-tab-pane': Tabpane
}
}
</script>
Error traceback:
[Vue warn]: Unknown custom element: <i-tab-pane> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> <DataCenter> at src/views/dc/data-center.vue
<Index> at src/views/index.vue
<App> at src/app.vue
I have tried in the main.js to global configuration:
Vue.component("Tabpane", Tabpane);
but still do not work.
How to resolve this issue?
If you're using a component within a component (e.g. something like this in the Vue DOM):
App
MyComponent
ADifferentComponent
MyComponent
Here the issue is that MyComponent is both the parent and child of itself. This throws Vue into a loop, with each component depending on the other.
There's a few solutions to this:
 1. Globally register MyComponent
vue.component("MyComponent", MyComponent)
2. Using beforeCreate
beforeCreate: function () {
this.$options.components.MyComponent = require('./MyComponent.vue').default
}
3. Move the import into a lambda function within the components object
components: {
MyComponent: () => import('./MyComponent.vue')
}
My preference is the third option, it's the simplest tweak and fixes the issue in my case.
More info: Vue.js Official Docs — Handling Edge Cases: Circular References Between Components
Note: if you choose method's 2 or 3, in my instance I had to use this method in both the parent and child components to stop this issue arising.
Since you have applied different name for the components:
components: {
'i-tabs' : Tabs,
'i-tab-pane': Tabpane
}
You also need to have same name while you export: (Check to name in your Tabpane component)
name: 'Tabpane'
From the error, what I can say is you have not defined the name in your component Tabpane. Make sure to verify the name and it should work fine with no error.
Wasted almost one hour, didn't find a solution, so I wanted to contribute =)
In my case, I was importing WRONGLY the component.. like below:
import { MyComponent } from './components/MyComponent'
But the CORRECT is (without curly braces):
import MyComponent from './components/MyComponent'
One of the mistakes is setting components as array instead of object!
This is wrong:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: [
ChildComponent
],
props: {
...
}
};
</script>
This is correct:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
props: {
...
}
};
</script>
Note: for components that use other ("child") components, you must also specify a components field!
For recursive components that are not registered globally, it is essential to use not 'any name', but the EXACTLY same name as your component.
Let me give an example:
<template>
<li>{{tag.name}}
<ul v-if="tag.sub_tags && tag.sub_tags.length">
<app-tag v-for="subTag in tag.sub_tags" v-bind:tag="subTag" v-bind:key="subTag.name"></app-tag>
</ul>
</li>
</template>
<script>
export default {
name: "app-tag", // using EXACTLY this name is essential
components: {
},
props: ['tag'],
}
I had this error as well. I triple checked that names were correct.
However I got this error simply because I was not terminating the script tag.
<template>
<div>
<p>My Form</p>
<PageA></PageA>
</div>
</template>
<script>
import PageA from "./PageA.vue"
export default {
name: "MyForm",
components: {
PageA
}
}
Notice there is no </script> at the end.
So be sure to double check this.
If you have path to the component (which causes a cycle) to index.js, cycle will be begin. If you set path directly to component, cycle will be not. For example:
// WRONG:
import { BaseTable } from #/components/Base'; // link to index.js
// SUCCESS:
import BaseTable from #/components/Base/Table.vue';
I had this error and discovered the issue was because the name of the component was identical to the name of a prop.
import Control from '#/Control.vue';
export default {
name: 'Question',
components: {
Control
},
props: ['Control', 'source'],
I was using file components. I changed the Control.vue to InputControl.vue and this warning disappeared.
The high votes answer is right. You can checkout that you have applied different name for the components. But if the question is still not resolved, you can make sure that you have register the component only once.
components: {
IMContainer,
RightPanel
},
methods: {},
components: {
IMContainer,
RightPanel
}
we always forget that we have register the component before
This is very common error that we face while starting any Project Vue. I spent lot of time to search this error and finally found a Solution.
Suppose i have component that is "table.vue",
i.e components/table.vue
In app.js
Vue.component('mytablecomp', require('./components/table.vue').default);
So in in your index.blade file call component as
<mytablecomp></mytablecomp>
Just you need to keep in mind that your component name is in small not in large or camel case.
Then my above code will surely work for you.
Thanks
We've struggled with this error twice now in our project with different components. Adding name: "MyComponent" (as instructed by the error message) to our imported component did not help. We were pretty sure our casing was correct, as we used what is in the documentation, which worked fine for the other 99% of our components.
This is what finally worked for us, just for those two problematic components:
Instead of this (which, again, works for most of our components):
import MyComponent from '#/components/MyComponent';
export default {
components: {
MyComponent
}
We changed it to ONLY this:
export default {
components: {
MyComponent: () => import('#/components/MyComponent')
}
I can't find the documentation we originally found for this solution, so if anyone has any references, feel free to comment.
If you are using Vue Class Component, to register a component "ComponentToRegister" you can do
import Vue from 'vue'
import Component from 'vue-class-component'
import ComponentToRegister from '#/components/ComponentToRegister.vue'
#Component({
components: {
ComponentToRegister
}
})
export default class HelloWorld extends Vue {}
Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.
I was using vue splitpanes.
Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).
Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.
[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
In my case it was the order of importing in index.js
/* /components/index.js */
import List from './list.vue';
import ListItem from './list-item.vue';
export {List, ListItem}
and if you use ListItem component inside of List component it will show this error as it is not correctly imported. Make sure that all dependency components are imported first in order.
This is WRONG:
import {
Tabs,
Tabpane
} from 'iview'
This is CORRECT:
import Iview from "iview";
const { Tabs, Tabpane} = Iview;
In my case (quasar and command quasar dev for testing), I just forgot to restart dev Quasar command.
It seemed to me that components was automatically loaded when any change was done. But in this case, I reused component in another page and I got this message.
Make sure that the following are taken care of:
Your import statement & its path
The tag name of your component you specified in the components {....} block
i ran into this problem and below is a different solution. I were export my components as
export default {
MyComponent1,
MyComponent2
}
and I imported like this:
import { MyComponent1, MyComponent2} from '#/index'
export default {
name: 'App',
components: {
MyComponent1,
MyComponent2
},
};
And it gave this error.
The solution is:
Just use export { ... } don't use export default
In my case, i was calling twice the import...
#click="$router.push({ path: 'searcherresult' })"
import SearcherResult from "../views/SearcherResult"; --- ERROR
Cause i call in other component...
The error usually arises when we have used the Component (lets say VText) but it has not been registered in the components declaration of the Parent Component(lets say Component B).
The error is more likely to occur when using components in a recursive manner. For example using tag=VText in an tag, as importing the component in a such case will result in error from Eslint as the component is not directly being used in the template. While not importing the component will cause an error in the console saying the component has not been registered.
In this case, it is a better approach to suppress the ESLinter on registration line of the Component(VText in this case). This suppression is done through writing // eslint-disable-next-line vue/no-unused-components
Example code is below
<template>
<i18n path="AssetDict.Companies" tag="VText">
<template>
<span class="bold-500">Hi This is a text</span>
</template>
</i18n>
</template>
<script>
import { VButton, VIcon, VTooltip, VText } from 'ui/atoms'
export default {
name: 'ComponentB',
components: {
VButton,
VIcon,
CompaniesModifyColumn,
VTooltip,
// eslint-disable-next-line vue/no-unused-components
VText,
},
}
</script>
I just encountered this. Easy solution when you know what to look for.
The child component was the default export in it's file, and I was importing using:
import { child } from './filename.vue'
instead of
import child from './filename.vue'.
What happened to me was I had correctly registered the component in components but I had another components key defined at the bottom of my component, so I had two components definitions and it looked like the latter one overrode the previous one. Removing it made it work.
I encounter same error msg while using webpack to async load vue component.
function loadVMap() {
return import(/* webpackChunkName: "v-map" */ './components/map.vue')
.then(({ default: C }) => {
Vue.component('ol-map',C);
return C;
})
.catch((error) => 'An error occurred while loading the map.vue: '+error);
}
I found that the then function never executed.
so I reg this component out of webpack import
import Map from './components/map.vue'
Vue.component('ol-map',Map);
Then I could gain the detailed error msg which said I used a var which is not imported yet.
I ran into this problem when:
I had components defined twice.
Used component instead of components.
I hope this helps others.
The question has been answered very well by #fredrivett here, but I wanted to add some context for other encountering the Circular Reference error when dealing with variables in general.
This error happens with any exported object not just components.
Exporting a variable from parent and importing it in a nested child:
🌐 EXAMPLE
<script>
// parent
export const FOO = 'foo';
...
</script>
❌ WRONG
<script>
// child
import { FOO } from 'path/to/parent'
export default {
data() {
return {
FOO
}
}
}
</script>
✅ CORRECT
<script>
// child
export default {
data() {
return {
FOO: require('path/to/parent').FOO
}
}
}
</script>
Note: in case you are dealing with objects you might want to create a global state which might serve you better.
I'm curious to know if this approach makes sense or it's an anti pattern.
In my case the child component name was "ABCChildComponent" and I was referring in the HTML as assuming it to work correctly. But, the correct name should be or . Hence, changed the name to "AbcChildComponent" and referring in the HTML works fine.
WRONG WAY :
import completeProfile from "#/components/modals/CompleteProfile";
export default {
components: completeProfile
};
RIGHT WAY :
import completeProfile from "#/components/modals/CompleteProfile";
export default {
components: {completeProfile} // You need to put the component in brackets
};