Only allow one component to be dropped
Question
Sorry for the newbie question, but say I have a text field component and I only want to allow the user to drop a specific number of them into the canvas, say just one. How do I limit it? Perhaps a way that shows an alert to explain they cannot add another text field component to the canvas unless they remove the existing one?
Answers (2)
So I have a very ugly solution right now:
editor.on('load',
function() {
var existingComponents = editor.getComponents();
if (existingComponents.models.filter(function(e) { return e.attributes.tagName === 'form'; }).length > 0) {
$($($("body .gjs-block-category")[1]).find(".gjs-block")[0]).hide();
}
}
);
editor.on('component:add', component => {
if (component.is('form')) {
$($($("body .gjs-block-category")[1]).find(".gjs-block")[0]).hide();
}
});
editor.on('component:remove', component => {
if (component.is('form')) {
$($($("body .gjs-block-category")[1]).find(".gjs-block")[0]).show();
}
});
This basically looks whether the component is in the canvas on load. If it is then it hides the draggable component button - Here I could use a better way to hide the button - how? I can get to the component with const form = editor.BlockManager.get('form'); but how do I hide it once I have it?
Then I have listeners for add and remove to hide and show the component button - same issue as above.
This seems like a horrible way to do it. There must be some setting I am missing for "only allowed one". Any suggestions?
Related Questions and Answers
Continue research with similar issue discussions.
Issue #577
Only allow one component of specific type on editor
is there way to not allow to drop any specific component more than one time on page? I have custom component and user cannot drop it more t...
Issue #1464
Customizing the Component Position
First of all thank you guys for this awesome library, And I have one Clarification that is how do i customize the drop position example if...
Issue #2061
[QUESTION] How to place a component at the end of the canvas.
How can I put my footer at the end of the canvas? I want the editor to not allow placing a block/widget below the footer. example
Issue #2768
[QUESTION] Can I add listener when user drag element on the canvas?
Hello, GrapesJS has bunch of events which could be listened with editor.on. One of them is canvas:drop. But it triggers only when I drop el...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.