When rendering an InputWidget in Yii2 an id
options HTML tag is automatically generated based on an internal static widget instance counter. By default the id
s will look like w0
, w1
, w2
, ... depending on how many widgets were instantiated. This works great when rendering the whole page at once.
But it quickly becomes problematic when introducing partial rendering (such as AJAX), because every sequential page render will begin with the widget counter at 0
, so if we inject such widgets into an already-rendered page, we will end up with id conflicts (eg. we might have two widgets with the same id w0
). This breaks HTML standards, causes JavaScript issues and other headaches.
So what are the possibilities around this?
- The most obvious way around this is of course manually setting the
id
to a hardcoded string. But now we need to know how many times the widget will be rendered, and we need to add a lot ofif
statements to determine which ID to render. It works but it's very hacky. - Automatically prepending or appending the widget
id
with theid
of its parent container. This sounds nice in theory, but I haven't been able to realize it so far. - Modifying Yii2
InputWidget
to use a UUID (Universally Unique IDentifier) instead of a counter. This sounds promising, but it requires a core framework patch (otherwise it won't work for 3rd party widgets) and makes it impossible to predict the ids (e.g. when testing).
What is the most universal solution for this?