How to disable buttons in a grid

The documentation doesn’t make it clear how to how to enable or disable buttons in a row. My initial attempts resulted in buttons that were disabled all the time. Turns out that the trick is to set the disabled attribute to null if it should not be disabled.

Here’s sample code if you ever need to enable/disable buttons in a row:

import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.data.renderer.TemplateRenderer;
import com.vaadin.flow.router.Route;

@Route("gridwithdisabledbutton")
public class GridWithDisabledButton extends Composite<Div> {

   Grid grid = new Grid();
   String[] items = new String[]
 { "Oranges", "Apples" };

   public GridWithDisabledButton() {
      grid.addColumn(r -> r);
      grid.addColumn(TemplateRenderer
            .of("<button on-click='buyclick' disabled$='[[item.buydisabled]
]'>Buy</button>"
                  + "<button on-click='sellclick' disabled$='[[item.selldisabled]
]'>Sell</button>")
            .withProperty("buydisabled", item -> "Oranges".equals(item) ? null : "true")
            .withProperty("selldisabled", item -> "Oranges".equals(item) ? "true" : null)
            .withEventHandler("buyclick", item -> Notification.show("Buying " + item))
            .withEventHandler("sellclick", item -> Notification.show("Selling " + item)));

      grid.setItems(items);
      getContent().add(grid);
   }

}

17233777.png

Hello Martin,

I think it is just possible to set true or false. You don’t need to use null or “boolean”.

.withProperty("buydisabled", item -> "Oranges".equals(item) ? false : true)
.withProperty("selldisabled", item -> "Oranges".equals(item) ? true : false)

or

.withProperty("buydisabled", item -> "Oranges".equals(item) )
.withProperty("selldisabled", item -> !"Oranges".equals(item) )

Diego Sanz Villafruela:
Hello Martin,

I think it is just possible to set true or false. You don’t need to use null or “boolean”.

.withProperty("buydisabled", item -> "Oranges".equals(item) ? false : true)
.withProperty("selldisabled", item -> "Oranges".equals(item) ? true : false)

or

.withProperty("buydisabled", item -> "Oranges".equals(item) )
.withProperty("selldisabled", item -> !"Oranges".equals(item) )

Good catch Diego. I only tried “false” and null, not realizing that withProperty could take other datatypes.

Thanks for sharing!