Skip to content

Instantly share code, notes, and snippets.

@onefriendaday
Created January 26, 2019 12:07
Show Gist options
  • Save onefriendaday/27a4a5c3973623747fbd33566102094b to your computer and use it in GitHub Desktop.
Save onefriendaday/27a4a5c3973623747fbd33566102094b to your computer and use it in GitHub Desktop.
Fieldtype example of 2 level cascanding select
const Fieldtype = {
mixins: [window.Storyblok.plugin],
template: `<div>
<div class="uk-form-row">
Category
<select v-model="model.category" class="uk-width-1-1">
<option></option>
<option :key="cat.item.id" :value="cat.item" v-for="cat in tree">{{ cat.item.name }}</option>
</select>
</div>
<div class="uk-form-row" v-if="subCategories.length > 0">
Sub-Category
<select v-model="model.subCategory" class="uk-width-1-1">
<option></option>
<option :key="cat.id" :value="cat" v-for="cat in subCategories">{{ cat.name }}</option>
</select>
</div>
<div class="uk-form-row" v-if="subSubCategories.length > 0">
Sub-Sub-Category
<select v-model="model.subSubCategory" class="uk-width-1-1">
<option></option>
<option :key="cat.id" :value="cat" v-for="cat in subSubCategories">{{ cat.name }}</option>
</select>
</div>
</div>`,
data() {
return {
categories: [],
tree: {},
treeMap: {}
}
},
computed: {
subCategories() {
if (!this.model.category) {
return []
}
return this.treeMap[this.model.category.id] || []
},
subSubCategories() {
if (!this.model.subCategory) {
return []
}
return this.treeMap[this.model.subCategory.id] || []
}
},
methods: {
initWith() {
return {
plugin: 'sb-cascanding-selector',
category: {},
subCategory: {},
subSubCategory: {}
}
},
pluginCreated() {
this.api
.get('cdn/links', {starts_with: 'shared/category/', version: 'draft'})
.then((res) => {
this.tree = this.prepareTree(res.data.links)
})
},
prepareTree(cats) {
var tree = {}
for (var uid in cats) {
var parent = cats[uid].parent_id
if (!tree[parent]) {
tree[parent] = []
}
tree[parent].push(cats[uid])
}
this.treeMap = tree
return this.generateTree(497308, tree)
},
generateTree(parent, items) {
var tree = {}
if (items[parent]) {
var result = items[parent]
result.forEach((cat) => {
if (!tree[cat.id]) {
tree[cat.id] = {item: {}, children: []}
}
tree[cat.id].item = cat
tree[cat.id].children = this.generateTree(cat.id, items)
})
}
return tree
}
},
watch: {
'model': {
handler: function (value) {
this.$emit('changed-model', value);
},
deep: true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment