Search code examples
phpnette

Add Custom Class on Controls during rendering for Nette Forms


I am using this example Bootstrap3 example to render a form and was wondering if it was possible to add custom classnames to form input wrappers based on the control type. I tried the following but it applies to the form inputs and not the surrounding wrapper divs (form-group in this case):

foreach ($form->getControls() as $control) {
    $type = $control->getOption('type');
    $control->getControlPrototype()->addClass('form-' . $control->getControlPrototype()->type);
}

Solution

  • The input wrapper is not a concern of the Control (input) but of the Renderer. DefaultFormRenderer wraps the control in the renderPair method – other renderers do not even have to do any wrapping. For that reason you can not get the wrapper’s prototype.

    You can use $control->setOption('class', …), though, and DefaultFormRenderer will use it as a class for the wrapper (as you can see in the source of DefaultFormRenderer::renderPair).

    Rather than manipulate the the form directly, it is much cleaner to implement a custom IFormRenderer as @hrach mentions above. His Bs3FormRenderer is a nice example.