Listgrid DataSource

I have a listgrid i want to change the datasource dynamically based on condition .. How to did it…

isc.ListGrid.create({
        ID: "lgrptcard",
       // top:"23%",
        width:"100%",
        height:"68%", 
        border:"0",
        headerHeight:40, 
        border:"0",
        bodyBackgroundColor:"#808080",
        showSortArrow:"none", 
        showFilterEditor:false, 
        sortDirection:false,
        autoDraw:true,
        showAllRecords:true,
        align:"center",
       // canFreezeFields:true,
        dataSource:getDygriddata,
        fields:MainArray,
        showHeader:true,
        enterKeyEditAction:"nextRow",
        editEvent: "click",
        baseStyle: "myBoxedAlternateGridCell", 
        alternateRecordStyles:true,
        canDragSelect: true,
        editByCell: true,
        canReorderFields:false,
      //  canEdit:true, //
        autoSaveEdits:false,
        recordClick:function(rowNum, colNum)
        { 
     
        },

       canEditCell : function (rowNum, colNum) 
        {
            
          

            }
            // otherwise return the returnValue of the superclass implementation
            //                               } 
            return canEdit; 
     },
    
editorExit:function(editCompletionEvent, record, newValue, rowNum, colNum) 
{
           return true;
    }
}                       
}) 

if(Condition 1)
{
getDygriddata ;= RptService.getFetchDS("GetRosterGrades2_final_last", null, { recordXPath:"//Table" });
lgrptcard.fetchData({});
  lgrptcard.setFeilds(MainArray);             
               }


}
else
{
getDygriddata = RptService.getFetchDS("GetStudentSkillSetsNew", null, { recordXPath:"//dtemp" });
lgrptcard.fetchData({});
lgrptcard.setFeilds(MainArray);
}

It Should call separate webservice based on condition and should corresponding feilds retuened by it..
I want to set and reset the datasource dynamically.
I am able to set the feilds but not datasource .
It should switch between the datasource dynamically…

Use the setDataSource() API of course :slight_smile:

I try to change dynamically the datasource with setDatasource (depending on a dropdown list) but I have a message (with SmartGWT) :

Uncaught JavaScript exception [java.lang.IllegalStateException: Cannot change configuration property 'dataSource' to [DataSource ID:personneDS] after the component has been created.

The Pattern reuse sample in the show case has no problem but mine yes. Why? What is the difference ?

That’s my code :

package org.gwtbook.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.types.TopOperatorAppearance;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FilterBuilder;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangeEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.VLayout;

public class PersonnesProto extends ProtoSoclePanel {

	private DynamicForm form;
	private ListGrid table;
	private IButton bouton;
	private PersonneServiceAsync service;
	private FilterBuilder filterBuilder;

	public static class Factory implements PanelFactory {
		private String id;

		public Canvas create() {
			PersonnesProto panel = new PersonnesProto();
			id = panel.getID();
			return panel;
		}

		public String getID() {
			return id;
		}

	}

	public Canvas getViewPanel() {
		
		// Appel au service
		if (service == null) {
			service = (PersonneServiceAsync) GWT.create(PersonneService.class);
			ServiceDefTarget target = (ServiceDefTarget) service;
			target.setServiceEntryPoint(GWT.getModuleBaseURL()
					+ "PersonneService");
		}

		final VLayout layout = new VLayout(15);

		final DataSource dataSource = PersonnePhysiqueDS.getInstance();

		final DataSource dataSourcePhysique = PersonnePhysiqueDS.getInstance();
		final DataSource dataSourceMorale = PersonneMoraleDS.getInstance();

		final DynamicForm formFiltre = new DynamicForm();

		// Personne physique
		final TextItem nom = new TextItem();
		final TextItem prenom = new TextItem();
		nom.setTitle("Nom");
		nom.setName("nom");
		prenom.setTitle("Prénom");
		prenom.setName("prenom");

		// Personne Morale
		final TextItem raisonSociale = new TextItem();
		raisonSociale.setTitle("Raison Sociale");
		raisonSociale.setVisible(false);
		raisonSociale.setName("raisonSociale");

		// Sélection du type de personne
		final SelectItem typePersonne = new SelectItem();
		typePersonne.setValueMap("Physique", "Morale");
		typePersonne.setTitle("Type");
		typePersonne.setName("typePersonne");
		typePersonne.setDefaultValue("Physique");
		typePersonne.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				String selectedItem = (String) event.getValue();
				if (selectedItem.equals("Physique")) {
					raisonSociale.hide();
					nom.show();
					prenom.show();
					form.setDataSource(dataSourcePhysique);
					table.setDataSource(dataSourcePhysique);
					table.fetchData();
					filterBuilder.setDataSource(dataSourcePhysique);
				} else {
					raisonSociale.show();
					nom.hide();
					prenom.hide();
					form.setDataSource(dataSourceMorale);
					table.setDataSource(dataSourceMorale);
					table.fetchData();
					filterBuilder.setDataSource(dataSourceMorale);
				}
			}
		});

		// Activer le filtre
		ButtonItem filterTypeButton = new ButtonItem("Filtrer");
		filterTypeButton
				.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {
					public void onClick(
							com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {

						// Filtrer les résultats

						if (formFiltre.getValueAsString("typePersonne").equals(
								"Physique")) {

							service.rechercherPersonnePhysique(formFiltre
									.getValueAsString("nom"), formFiltre
									.getValueAsString("prenom"),
									new AsyncCallback<List<Personne>>() {

										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub
											System.out
													.println("[ERREUR] Probleme de recuperation des données");
											caught.printStackTrace();
										}

										public void onSuccess(
												List<Personne> result) {
											// TODO Auto-generated method stub
											Personne[] persData = new Personne[result
													.size()];
											int i = 0;
											System.out
													.println("Récupération des données");
											for (Personne p : result) {
												System.out
														.println("Récupération donnée numéro "
																+ String
																		.valueOf(i));
												persData[i] = p;
												i++;
											}

											dataSource.setTestData(persData);

										}

									});

						} else {

							service.rechercherPersonneMorale(formFiltre
									.getValueAsString("raisonSociale"),
									new AsyncCallback<List<Personne>>() {

										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub
											System.out
													.println("[ERREUR] Probleme de recuperation des données");
											caught.printStackTrace();
										}

										public void onSuccess(
												List<Personne> result) {
											// TODO Auto-generated method stub
											Personne[] persData = new Personne[result
													.size()];
											int i = 0;
											System.out
													.println("Récupération des données");
											for (Personne p : result) {
												System.out
														.println("Récupération donnée numéro "
																+ String
																		.valueOf(i));
												persData[i] = p;
												i++;
											}

											dataSource.setTestData(persData);

										}

									});

						}

					}
				});

		formFiltre.setFields(typePersonne, nom, prenom, raisonSociale,
				filterTypeButton);

		layout.addMember(formFiltre);

		// Charger les données depuis le serveur
		IButton dataButton = new IButton("Charger");
		dataButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				// Chargement des données

				service.getListePersonnes(new AsyncCallback<List<Personne>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						System.out
								.println("[ERREUR] Probleme de recuperation des données");
						caught.printStackTrace();
					}

					public void onSuccess(List<Personne> result) {
						// TODO Auto-generated method stub
						Personne[] persData = new Personne[result.size()];
						int i = 0;
						System.out.println("Récupération des données");
						for (Personne p : result) {
							System.out.println("Récupération donnée numéro "
									+ String.valueOf(i));
							persData[i] = p;
							i++;
						}

						dataSource.setTestData(persData);

					}

				});
			}
		});

		layout.addMember(dataButton);

		// Formulaire

		form = new DynamicForm();
		form.setIsGroup(true);
		form.setGroupTitle("Modification");
		form.setNumCols(4);

		form.setDataSource(dataSource);

		// Filtre
		filterBuilder = new FilterBuilder();
		filterBuilder.setDataSource(dataSource);
		filterBuilder.setTopOperatorAppearance(TopOperatorAppearance.RADIO);

		layout.addMember(filterBuilder);

		IButton filterButton = new IButton("Filtrer");
		filterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				table.filterData(filterBuilder.getCriteria());
			}
		});

		layout.addMember(filterButton);

		// Grille

		table = new ListGrid();
		table.setWidth(600);
		table.setHeight(200);
		table.setAutoFetchData(true);
		table.addRecordClickHandler(new RecordClickHandler() {
			public void onRecordClick(RecordClickEvent event) {
				form.reset();
				form.editSelectedData(table);
			}
		});

		table.setDataSource(dataSource);

		layout.addMember(table);
		layout.addMember(form);

		// Bouton de sauvegarde

		bouton = new IButton();
		bouton.setTitle("Sauver");
		bouton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				form.saveData(new DSCallback() {
					public void execute(DSResponse response, Object rawData,
							DSRequest request) {
						// Actions à effectuer à la sauvegarde
					}
				});
			}
		});

		layout.addMember(bouton);

		return layout;

	}

}

Thank you by advance.

I had the same problem with setTestData but with the last build there was no problem.

EDIT : The problem seems to be with the filterBuilder widget. But I have to change his datasource like other components.

We’ll be removing this limitation, but for now, the simplest thing is to recreate the FilterBuilder when the DataSource is changed.

Thank you for the response. I thought about that.

Changing fetchDataURL

Initially I do

filterDS = new RestDataSource();
filterDS.setTableName("user");
DataSourceTextField firstName = new DataSourceTextField("firstName", "First Name");
filterDS.setFields(firstName);
filterDS.setFetchDataURL("/MyApp/smartgwt/user?max=25");
filterBuilder.setDataSource(filterDS);
filterGrid.setDataSource(filterDS);

Which works. I later want to change the datasource and try

// recreate RestDataSource & FilterBuilder
filterDS = new RestDataSource();
filterDS.setTableName(tableName);
filterDS.setFields(fields);
filterBuilder = new FilterBuilder();
filterBuilder.setDataSource(filterDS);
filterGrid.setDataSource(filterDS);
filterDS.setFetchDataURL("/MyApp/smartgwt/" + tableName + "?max=25");

//where 
// String tableName = 'report'
// DataSourceTextField[] fields = populated array

I get the message 'Cannot change configuration property ‘fetchDataURL’ to /MyApp/smartgwt/report?max=25 after the component has been created. I did not get this error on initial creation. Any thoughts?

Thanks, Tom.

Just reorder your calls - setFetchDataURL() first.