The data grid is one of the most used elements in Flex, for displaying collections of data. There are many reasons for this, among which I'd like to mention its flexibility in handling different data and ease of use (basically, all you need to do, is specify a data provider).
In addition to this, the DataGrid object, can handle more advanced operations. For instance, using customized item rendering components, or data editing (and this will be our main focus for this post).
So, how can we edit the data inside a data grid? First, by specifying that the user is allowed to do this, by setting the editable property of the data grid to true. Then, when running the application, all the user has to do is click on the cell that needs to be edited.
Let's consider the following scenario. We use a data grid for editing the data in an array collection, but we want to check if a cell value was actually modified before we save the new data (since it wouldn't make sense to update the current data if no actual values were changed - i.e. the user edited a field, but then reverted it to the previous value). How do we do this?
First by understanding the events that a DataGrid object dispatches, particularly the ITEM_EDIT_END event, since it is dispatched before the old value is replaced. That being said, we know when to determine if an actual change has been made. The only problem remaining is how, specifically how do we compare the old value, with the new one?
We can determine the initial value by using the data grid's itemRenderer property, which is an instance of the component used to display the data and is passed to the event also. To access the data, we still need to determine the field that was edited, and we can do so by using the event's dataField property. Now to access the data, we can use:
event.itemRenderer.data[ event.dataField ];
So now that we have the old value, we need to get the new value. This step is a little easier, since we don't actually need to know the field that was edited, because the data grid contains a TextInput element instance, for editing a cell. We can retrieve its value by using the data grid's itemEditor property which, as mentioned above, is a TextInput instance, so we can use its text property to get the new value:
event.currentTarget.itemEditorInstance.text;
If we assign these values to, let's say, the oldValue and newValue, we can make a simple comparison to determine if indeed the new value is different from the old one.
Niciun comentariu:
Trimiteți un comentariu