Fixing Dojo id conflict

Recently I got an error related to Dojo widget about conflicting id on the HTML element. While it is possible to work with Dojo without ids, those are necessary for field labels to work properly.

Here is the error I got:

Dojo widget conflicting id error.

And the widget code which caused the conflict:

<label for="maxParticipants">Max participants</label>
<div class="dijit dijitReset"
      id="maxParticipants"
      data-dojo-attach-point="maxParticipants"
      data-dojo-type="dijit.form.NumberSpinner"
      data-dojo-props="constraints: { min: 1 }"></div>

It is clear that there could be only one HTML element with the same id on the page and multiple Dojo widgets might be added dynamically on the page. So it might cause the error. In my case, I had only one widget on the page, but I still got an error after publishing page content. Seems that EPiServer creates another instance of the widget at some point.

Stack Overflow to the rescue and I got the solution:

<label for="${id}maxParticipants">Max participants</label>
          <div class="dijit dijitReset" id="${id}maxParticipants" data-dojo-attach-point="maxParticipants" data-dojo-type="dijit.form.NumberSpinner" data-dojo-props="constraints: { min: 1 }"></div>

Each Dojo widget has an id property. And Dojo templates works so that replaces ${property} kind of values with appropriate widget class property's values. So ${id} gets replaced by widget class' property id's value.