@Override
  protected void onRender(Element parent, int index) {

    super.onRender(parent, index);

    setLayout(new CenterLayout());

    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

    configs.add(sm.getColumn());

    ColumnConfig column = new ColumnConfig();
    column.setId("ragioneSociale");
    column.setHeader("Ragione Sociale");
    column.setWidth(120);

    TextField<String> text = new TextField<String>();
    // text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    column = new ColumnConfig();
    column.setId("cognome");
    column.setHeader("Cognome");
    column.setWidth(120);

    text = new TextField<String>();
    // text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    column = new ColumnConfig();
    column.setId("nome");
    column.setHeader("Nome");
    column.setWidth(120);

    text = new TextField<String>();
    // text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    column = new ColumnConfig();
    column.setId("cf");
    column.setHeader("Codice Fiscale");
    column.setWidth(120);

    text = new TextField<String>();
    // text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    column = new ColumnConfig();
    column.setId("piva");
    column.setHeader("Partita IVA");
    column.setWidth(120);

    text = new TextField<String>();
    text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    column = new ColumnConfig();
    column.setId("denominazione");
    column.setHeader("Denominazione");
    column.setWidth(120);

    text = new TextField<String>();
    text.setAllowBlank(false);
    column.setEditor(new CellEditor(text));
    configs.add(column);

    caricaDati();

    ColumnModel cm = new ColumnModel(configs);

    ContentPanel cp = new ContentPanel();
    cp.setHeading("Anagrafica aziende");
    cp.setFrame(true);
    // cp.setIcon(Resources.ICONS.table());
    cp.setSize(Consts.LarghezzaFinestra, Consts.AltezzaFinestra);
    cp.setLayout(new FitLayout());

    final EditorGrid<BeanModel> grid = new EditorGrid<BeanModel>(store, cm);
    grid.setSelectionModel(sm);
    grid.setAutoExpandColumn("nome");
    grid.setBorders(true);
    grid.setClicksToEdit(EditorGrid.ClicksToEdit.TWO);
    cp.add(grid);

    ToolBar toolBar = new ToolBar();
    Button addButton = new Button("Aggiungi azienda");
    addButton.setIcon(
        IconHelper.create(
            "/resources/grafica/x16/add2.png", Consts.ICON_WIDTH_SMALL, Consts.ICON_HEIGHT_SMALL));
    addButton.addSelectionListener(
        new SelectionListener<ButtonEvent>() {

          @Override
          public void componentSelected(ButtonEvent ce) {
            BeanModelFactory factory = BeanModelLookup.get().getFactory(Azienda.class);
            Azienda azienda =
                new Azienda(
                    "NuovoNome",
                    "NuovoCognome",
                    "nuovaRS",
                    "nuovoCF",
                    "nuovaPIVA",
                    "NuovaDenominazione");
            BeanModel model = factory.createModel(azienda);

            grid.stopEditing();
            aziende.add(azienda);
            store.insert(model, 0);
            grid.startEditing(store.indexOf(model), 0);
          }
        });
    toolBar.add(addButton);
    toolBar.add(new SeparatorToolItem());

    Button remove = new Button("Rimuovi selezionati");
    remove.setIcon(
        IconHelper.create(
            "/resources/grafica/x16/delete2.png",
            Consts.ICON_WIDTH_SMALL,
            Consts.ICON_HEIGHT_SMALL));
    remove.addSelectionListener(
        new SelectionListener<ButtonEvent>() {

          @Override
          public void componentSelected(ButtonEvent ce) {
            if (!(sm.getSelectedItems()).isEmpty()) {
              MessageBox.confirm(
                  "Confirm",
                  "Sei sicuro di voler eliminare gli elemtni selezionati?",
                  cancellazione);
            } else {
              MessageBox.alert("Errore", "Selezionare uno o più elementi", cancellazione);
            }
          }
          // conferma per l'eliminazione
          final Listener<MessageBoxEvent> cancellazione =
              new Listener<MessageBoxEvent>() {

                @Override
                public void handleEvent(MessageBoxEvent ce) {
                  Button btn = ce.getButtonClicked();
                  if (btn.getText().equals("Yes")) {
                    List<BeanModel> modelsDaRimuovere = sm.getSelectedItems();
                    ArrayList<Azienda> aziendeDaRimuovere = new ArrayList();
                    if (modelsDaRimuovere != null) {
                      Iterator it = modelsDaRimuovere.iterator();
                      while (it.hasNext()) {
                        Object model = it.next();
                        store.remove((BeanModel) model);
                        Azienda azienda = ((BeanModel) model).getBean();
                        aziendeDaRimuovere.add(azienda);
                        aziende.remove(azienda);
                      }
                      cancellaDati(aziendeDaRimuovere);
                    }
                  }
                }
              };
        });
    toolBar.add(remove);
    cp.setTopComponent(toolBar);

    ToolBar statusBar = new ToolBar();
    status.setWidth(350);
    statusBar.add(status);
    cp.setBottomComponent(statusBar);
    cp.setButtonAlign(HorizontalAlignment.CENTER);

    Button resetButton =
        new Button(
            "Reset",
            new SelectionListener<ButtonEvent>() {

              @Override
              public void componentSelected(ButtonEvent ce) {
                store.rejectChanges();
              }
            });
    resetButton.setIcon(
        IconHelper.create(
            "/resources/grafica/x16/undo.png", Consts.ICON_WIDTH_SMALL, Consts.ICON_HEIGHT_SMALL));
    cp.addButton(resetButton);

    Button saveButton =
        new Button(
            "Save",
            new SelectionListener<ButtonEvent>() {

              @Override
              public void componentSelected(ButtonEvent ce) {
                store.commitChanges();
                salvaDati(aziende);
              }
            });
    saveButton.setIcon(
        IconHelper.create(
            "/resources/grafica/x16/save.png", Consts.ICON_WIDTH_SMALL, Consts.ICON_HEIGHT_SMALL));
    cp.addButton(saveButton);

    add(cp);
  }
  protected void onRender(Element target, int index) {
    super.onRender(target, index);

    final FitLayout fl = new FitLayout();

    LayoutContainer layoutContainer = new LayoutContainer();
    layoutContainer.setBorders(false);
    layoutContainer.setLayout(fl);

    VerticalPanel vp = new VerticalPanel();
    vp.setSpacing(3);

    ContentPanel cpGrid = new ContentPanel();
    cpGrid.setHeaderVisible(true);
    cpGrid.setHeading("Lista Dipendenti.");
    cpGrid.setBorders(false);
    cpGrid.setFrame(true);
    cpGrid.setHeight((h - 65));
    cpGrid.setWidth(w - 250);
    cpGrid.setScrollMode(Scroll.AUTO);
    cpGrid.setLayout(new FitLayout());
    cpGrid.setButtonAlign(HorizontalAlignment.CENTER);
    Resizable r = new Resizable(cpGrid);

    btnPrint = new Button();
    btnPrint.setEnabled(true);
    btnPrint.setIcon(AbstractImagePrototype.create(MyImages.INSTANCE.print24()));
    btnPrint.setIconAlign(IconAlign.TOP);
    btnPrint.setToolTip("Stampa");
    btnPrint.setSize(26, 26);
    btnPrint.addSelectionListener(
        new SelectionListener<ButtonEvent>() {

          @Override
          public void componentSelected(ButtonEvent ce) {
            SessionManagementService.Util.getInstance()
                .setDatiReportCostiDip(
                    "RIEP.COSTI",
                    store.getModels(),
                    new AsyncCallback<Boolean>() {

                      @Override
                      public void onFailure(Throwable caught) {
                        Window.alert("Error on setNomeReport()");
                      }

                      @Override
                      public void onSuccess(Boolean result) {
                        if (result) fp.submit();
                        else
                          Window.alert(
                              "Problemi durante il settaggio dei parametri in Sessione (http)");
                      }
                    });
          }
        });

    btnAdd = new Button();
    btnAdd.setStyleAttribute("padding-left", "2px");
    btnAdd.setIcon(AbstractImagePrototype.create(MyImages.INSTANCE.add()));
    btnAdd.setIconAlign(IconAlign.TOP);
    btnAdd.setSize(26, 26);
    btnAdd.setToolTip("Nuova Offerta");
    btnAdd.addSelectionListener(
        new SelectionListener<ButtonEvent>() {
          @Override
          public void componentSelected(ButtonEvent ce) {
            RiepilogoCostiDipendentiModel am =
                new RiepilogoCostiDipendentiModel(
                    0, 0, "", "0.00", "", "0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00", "",
                    "", "");

            gridRiepilogo.stopEditing();
            store.insert(am, 0);
            gridRiepilogo.startEditing(store.indexOf(am), 0);
          }
        });

    btnConfirm = new Button();
    btnConfirm.setEnabled(true);
    btnConfirm.setIcon(AbstractImagePrototype.create(MyImages.INSTANCE.confirm()));
    btnConfirm.setIconAlign(IconAlign.TOP);
    btnConfirm.setToolTip("Conferma modifiche");
    btnConfirm.setSize(26, 26);
    btnConfirm.addSelectionListener(
        new SelectionListener<ButtonEvent>() {

          @Override
          public void componentSelected(ButtonEvent ce) {

            RiepilogoCostiDipendentiModel c = new RiepilogoCostiDipendentiModel();

            for (Record record : store.getModifiedRecords()) {

              c = (RiepilogoCostiDipendentiModel) record.getModel();

              AdministrationService.Util.getInstance()
                  .editDatiCostiAzienda(
                      c,
                      new AsyncCallback<Boolean>() {

                        @Override
                        public void onFailure(Throwable caught) {
                          Window.alert("Errore di connessione on insertNewOffertaWithRda();");
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                          if (result) {
                            caricaTabellaDati();
                          } else {
                            Window.alert(
                                "error: Impossibile effettuare l'inserimento/modifica dei dati!");
                          }
                        }
                      });
            }
          }
        });

    if ((ruolo.compareTo("PM") == 0)) {
      btnConfirm.disable();
      btnAdd.disable();
    }

    smplcmbxSede = new SimpleComboBox<String>();
    smplcmbxSede.setFieldLabel("Sede");
    smplcmbxSede.setWidth(65);
    smplcmbxSede.setEmptyText("Sede..");
    smplcmbxSede.setAllowBlank(false);
    smplcmbxSede.add("T");
    smplcmbxSede.add("B");
    smplcmbxSede.setStyleAttribute("padding-left", "2px");
    smplcmbxSede.addListener(
        Events.Select,
        new Listener<BaseEvent>() {
          @Override
          public void handleEvent(BaseEvent be) {
            caricaTabellaDati();
          }
        });

    // caricaTabellaDati();

    cm = new ColumnModel(createColumns());
    gridRiepilogo = new EditorGrid<RiepilogoCostiDipendentiModel>(store, cm);
    gridRiepilogo.setBorders(false);
    gridRiepilogo.setColumnLines(true);
    gridRiepilogo.setStripeRows(true);
    gridRiepilogo.setItemId("grid");
    gridRiepilogo.setSelectionModel(csm);

    fp.setMethod(FormPanel.METHOD_POST);
    fp.setAction(url);
    fp.addSubmitCompleteHandler(new FormSubmitCompleteHandler());
    fp.add(btnPrint);
    ContentPanel cp = new ContentPanel();
    cp.setHeaderVisible(false);
    cp.add(fp);

    ToolBar tlBar = new ToolBar();
    tlBar.add(smplcmbxSede);
    tlBar.add(btnAdd);
    tlBar.add(btnConfirm);
    tlBar.add(new SeparatorToolItem());
    tlBar.add(cp);

    cpGrid.setTopComponent(tlBar);
    cpGrid.add(gridRiepilogo);

    layoutContainer.add(cpGrid, new FitData(3, 3, 3, 3));

    add(layoutContainer);
  }
  public ImportItemSetupPanel() {

    super();

    categoryStore = new ListStore<ItemModel>();

    setLayout(new FitLayout());

    // Grid: setup / configuration
    ArrayList<ColumnConfig> itemColumns = new ArrayList<ColumnConfig>();

    TextField<String> textField = new TextField<String>();
    textField.addInputStyleName(resources.css().gbTextFieldInput());
    CellEditor textCellEditor = new CellEditor(textField);

    setHeading(i18n.navigationPanelImportHeader());

    columnConfigName = new ColumnConfig(ItemKey.S_NM.name(), i18n.importSetupGridItemHeader(), 200);
    columnConfigName.setEditor(textCellEditor);
    itemColumns.add(columnConfigName);

    columnConfigPercentCategory =
        new ColumnConfig(
            ItemKey.D_PCT_CTGRY.name(), i18n.importSetupGridCategoryPercentHeader(), 100);
    columnConfigPercentCategory.setEditor(new CellEditor(new NumberField()));
    itemColumns.add(columnConfigPercentCategory);

    columnConfigPoints =
        new ColumnConfig(ItemKey.D_PNTS.name(), i18n.importSetupGridPointsHeader(), 100);
    columnConfigPoints.setEditor(new CellEditor(new NumberField()));
    itemColumns.add(columnConfigPoints);

    categoryComboBox = new ComboBox<ItemModel>();
    categoryComboBox.setDisplayField(ItemKey.S_NM.name());
    categoryComboBox.setEditable(true);
    categoryComboBox.setTriggerAction(TriggerAction.ALL);
    categoryComboBox.setForceSelection(true);
    categoryComboBox.setStore(categoryStore);
    categoryComboBox.addInputStyleName(resources.css().gbTextFieldInput());

    columnConfigCategory =
        new ColumnConfig(ItemKey.S_ID.name(), i18n.importSetupGridCategoryHeader(), 140);

    categoryCellEditor =
        new CellEditor(categoryComboBox) {

          // Called before the editor sets the value on the wrapped field
          @Override
          public Object preProcessValue(Object value) {

            // Method argument is the selected grid item model id
            String assignmentId = (String) value;

            // Get the assignment and the associated category name
            ItemModel assignment = itemStore.findModel(ItemKey.S_ID.name(), assignmentId);
            String categoryName = assignment.get(ItemKey.S_PARENT.name());

            // Find the category from the category name
            ItemModel category = categoryStore.findModel(ItemKey.S_NM.name(), categoryName);

            // Mark the assignment as the one the user is performing an action on.
            // We will use the marker in the postProcessValue() method to find the assignment,
            // since the assignment is not readily available in that method.
            assignment.set(ItemKey.S_CTGRY_ID.name(), ITEM_MARKER);

            // FIXME:
            // Returning the category. Interestingly, I am not quite sure what the returned
            // object is used for. Testing this with returning null didn't change anything.
            // Following GXT sample code ??
            return category;
          }

          // Called after the editor completes an edit.
          @Override
          public Object postProcessValue(Object value) {

            // Method argument is the selected category model
            ItemModel category = (ItemModel) value;

            // Get the categoryId
            String categoryId = category.get(ItemKey.S_ID.name());

            // We search through all the assignments to find the one that has been marked
            // by the preProcessValue() method
            List<ItemModel> assignments = itemStore.getModels();

            for (ItemModel assignment : assignments) {

              if (ITEM_MARKER.equals(assignment.get(ItemKey.S_CTGRY_ID.name()))) {

                // We have found the marked assignment and are setting the string based categoryId
                // Also, this string based category is used on the server side to reassociate the
                // assignment with the correct category before things are persisted and updated
                assignment.set(ItemKey.S_CTGRY_ID.name(), categoryId);

                // Returning the assignmentId but prefix it so that the renderer thinks
                // that something changes. If we were to just return the assignmentId,
                // the renderer is not called. This also sets the assignmentId to this new
                // prefixed ID. This is fixed in the renderer code.
                return ITEM_PREFIX + assignment.get(ItemKey.S_ID.name());
              }
            }

            // In case we didn't find a marked assignment, we return null
            return null;
          }
        };

    columnConfigCategory.setEditor(categoryCellEditor);

    columnConfigCategory.setRenderer(
        new GridCellRenderer<ItemModel>() {

          public String render(
              ItemModel model,
              String property,
              ColumnData config,
              int rowIndex,
              int colIndex,
              ListStore<ItemModel> store,
              Grid<ItemModel> grid) {

            // Method argument "model" is the selected grid item model
            String categoryId = model.get(ItemKey.S_CTGRY_ID.name());

            // Case when we render the grid for the first time
            if (null == categoryId || "".equals(categoryId)) {

              // Making sure that assignments have the categoryId
              // set if possible
              if (model.getCategoryId().equals(Long.valueOf(-1l))) {

                String categoryName = model.get(ItemKey.S_PARENT.name());
                if (null != categoryName && !"".equals(categoryName)) {

                  Item category = categoryStore.findModel(ItemKey.S_NM.name(), categoryName);
                  // GRBK-681 - Since we don't care if the category id is non numeric, I assume we
                  // don't care if there's no category at all.

                  if (category != null) {
                    try {

                      Long catId = Long.valueOf((String) category.get(ItemKey.S_ID.name()));
                      model.setCategoryId(catId);
                    } catch (NumberFormatException nfe) {
                      // We don't do anything
                    }
                  }
                }
              }

              return model.get(ItemKey.S_PARENT.name());
            } else { // Case where a user selects a different category from the ComboBox

              // First we "restore" the itemId since we prefixed it in the postProcessValue() method
              String assignmentId = model.get(ItemKey.S_ID.name());

              if (assignmentId.startsWith(ITEM_PREFIX)) {

                String fixedAssignmentId = assignmentId.substring(ITEM_PREFIX.length());
                model.set(ItemKey.S_ID.name(), fixedAssignmentId);
              }

              ItemModel category = categoryStore.findModel(ItemKey.S_ID.name(), categoryId);
              // GRBK-681
              if (category != null) {
                String categoryName = category.get(ItemKey.S_NM.name());
                model.set(ItemKey.S_PARENT.name(), categoryName);

                return categoryName;
              } else {
                return "";
              }
            }
          }
        });

    itemColumns.add(columnConfigCategory);

    ColumnModel itemColumnModel = new ColumnModel(itemColumns);
    itemStore = new ListStore<ItemModel>();

    itemGrid = new EditorGrid<ItemModel>(itemStore, itemColumnModel);
    itemGrid.setBorders(true);

    // TODO: In the old upload code, we used the BaseCustomGridView() instead of the GridView()
    // I am not sure yet if this is still needed. Maybe for some CSS adjustments?
    itemGrid.setView(new GridView());

    add(itemGrid);
  }