Issue #657Opened December 19, 2017by michaellwatson1 reactions

Setting values of hidden fields

Question

I have an issue with hidden fields inside a form element, I want to select the form in the editor and then change the values of the hidden fields by clicking on select boxes. I've added the select boxes to a new panel.

How do I find the hidden fields within the selected form component and then set their values? The hidden fields are not direct children of the form.

<form>
<div>
<input type="hidden" value="1,2,3">
</div>
</form>

I'm interested in discussing best practice solution to this problem. It might be the case that the values need to be set when the form is added.

Thanks

Answers (3)

michaellwatsonDecember 20, 20171 reactions

Great stuff, grapesjs is amazing btw

artfDecember 19, 20170 reactions

Hi Michael, you might want to rely on Component's view for this purpose

const selected = editor.getSelected();

// Here you can use any type of query string
selected.view.$el.find('[type=hidden]').each((el, i, $el) => {
	const model = $el.data('model');
    model && console.log('Hidden component found', model);
});

Probably I'll add find(query) into Component in the next release

michaellwatsonDecember 20, 20170 reactions

Thanks @artf this is what I ended up with

const selected = editor.getSelected();
    selected.view.$el.find('[type=hidden]').each((el, i, $el) => {
    const model = $el.data('model');
    model && console.log('Hidden component found', model);

    for (var i = 0, len = model.collection.models.length; i < len; i++) {
        console.log(model.collection.models[i]);
        //change my_field to the name of the field you want to target
        if(model.collection.models[i].attributes.attributes.name=='my_field'){
	    var attributes = model.collection.models[i].get('attributes');
            attributes.value = 'Value here';
	    model.collection.models[i].set('attributes', attributes);
            return;
	}
    }
    return;
});

This kind of repeats itself a bit, because each hidden field is picked up in the foreach, but the $el variable holds all of the hidden fields, which is why added the returns to break the loops.

Would be interested to know if there was a more elegant way of doing it, but this seems fit for purpose for now anyway.

It would be good to know if there was an "on selected" kind of trigger that fired when an element was selected so I could set the field values on the new edit menu once the form got selected.

I tried an iframe method for that but it didn't seem to work.

Thanks again

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.