Reputation: 1444
I'm trying to use paper-radio-group
on Polymer 2.0. I discovered on this question (How to enforce required paper-radio-group in Polymer?) that normal validation doesn't work because paper-radio-group doesn't implement Polymer.IronFormElementBehavior
. So, one way to workaround is to create a new element that implements this behavior.
I did like the example of the other question:
<dom-module id="app-radio-group">
<template>
<style include="shared-styles">
[invalid] ::slotted(paper-radio-button) {
--paper-radio-button-label-color: red;
--paper-radio-button-unchecked-color: red;
}
</style>
<paper-radio-group
id="group"
attr-for-selected="{{attrForSelected}}"
selected="{{selected}}">
<div invalid$="[[!valid]]">
<slot></slot>
</div>
</paper-radio-group>
</template>
<script>
class AppRadioGroup extends Polymer.Element {
static get is() { return 'app-radio-group'; }
static get behaviors() {
return [
'Polymer.IronFormElementBehavior'
];
}
get selectedItem() {
return this.$.group.selectedItem;
}
validate() {
this.valid = this.selectedItem != null;
return this.valid;
}
}
window.customElements.define(AppRadioGroup.is, AppRadioGroup);
</script>
</dom-module>
But, as the slot element creates a light dom (https://www.polymer-project.org/2.0/docs/devguide/shadow-dom#shadow-dom-and-composition) the actual paper-radio-button
aren't really inside paper-radio-group
. So, the effect of selecting just one radio button doesn't work and I can't get the result of the selected radio-button.
Any ideas how to make this paper-radio-group works with the iron-form validation?
Upvotes: 0
Views: 378
Reputation: 1444
As @HakanC show me that I don't need to implement ironformelementbehavior I ended up doing a manual validation.
Basically I use CSS to show the highlight the unanswered questions. I put a attribute invalid
in the html element to check when is invalid or not and when I will validate the form I also call the functions the validate paper-radio-group
s
CSS:
paper-radio-group[invalid] paper-radio-button {
--paper-radio-button-label-color: red;
--paper-radio-button-unchecked-color: red;
}
HTML:
<div class="question-title">Question?</div>
<paper-radio-group invalid$="[[_isRadioGroupInvalid(answer)]]" attr-for-selected="value" selected="{{answer}}">
<paper-radio-button value="true">Yes</paper-radio-button>
<paper-radio-button value="false">No</paper-radio-button>
</paper-radio-group>
JS:
_isRadioGroupInvalid(input) {
if (input === undefined) {
return true;
} else {
return false;
}
}
_validateRadioGroups() {
for (let radioGroup of this.$.form.querySelectorAll('paper-radio-group')) {
if (radioGroup.getAttribute('invalid') === '') {
return false;
}
}
return true;
}
_validateForm() {
if (this.$.form.validate() === false && this._validateRadioGroups() === false) {
//do case invalid form
} else {
//do case valid form
}
}
Upvotes: 0