We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to prevent the addition of duplicate records to the Grid Mode Dialog Template


I want to insert only unique code identification record in grid 

if I will enter non-unique record in grid in net core js2.

I should show me an error.

Thank you, waiting for you example reply


11 Replies

PK Prasanna Kumar Viswanathan Syncfusion Team January 27, 2020 12:47 PM UTC

Hi Luis, 
 
Thanks for contacting Syncfusion support. 
 
To achieve your requirement, we have used the Custom Validation of EJ2 Grid. The Custom validation is used to define own custom validation rules for the specific columns by using Form Validator custom rules. In this we have checked if the record entered is already present in the Datasource using customFuntion of validation. 
 
Please refer to the below code snippet and sample link for more information. 
 
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowPaging="true" actionBegin="actionBegin" load=”load” actionFailure="actionFailure" toolbar="@(new List<string>() {"Add", "Edit", "Update", "Delete" })" actionComplete="actionComplete"> 
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column> 
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column> 
        <e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column> 
    </e-grid-columns> 
</ejs-grid> 

<script> 
function load(args) { 
              this.columns[0].validationRules = { required: true, value: [customFn, 'Enter a unique value'] }; 

function customFn(args) { 
              var grid = document.getElementById('Grid').ej2_instances[0]; 
              for (i = 0; i < grid.dataSource.length; i++) { 
                             if (args['value'] === grid.dataSource[i].OrderID.toString())
                                           return false; 
                             } 
                             else { 
                                           return true; 
                             } 
              } 
}; 
</script> 

 
 
 
Please get back to us if you need further assistance. 
 
Regards, 
Prasanna Kumar N.S.V 
 



LU luis January 27, 2020 09:05 PM UTC

It does not allow me to download the example, the permission is not associated with my account.



PK Prasanna Kumar Viswanathan Syncfusion Team January 28, 2020 07:07 AM UTC

Hi Luis, 
 
Sorry for the inconvenience caused. 
 
We have attached the new sample and please download the sample from the following link 
 
 
Regards, 
Prasanna Kumar N.S.V 



LU luis March 31, 2020 02:24 AM UTC

The example does not work.





I implemented it this way because load locks the grid.


function actionComplete(args) {

if (args.requestType === 'beginEdit' || args.requestType === 'add') {
if (args.requestType === 'beginEdit') {
args.dialog.header = 'Modificar Registro';
args.dialog.width = '500px';
args.dialog.height = '400px';
var ajax = new ej.base.Ajax({
url: "@Url.Action("EditPartial", "Cargos")", //render the Edit partial view
type: "POST",
contentType: "application/json",
data: JSON.stringify({ value: args.rowData })
});
ajax.send().then(function (data) {
appendElement(data, args.form); //Render the edit form in newly created template with the selected record
args.form.elements.namedItem('Codigo').focus();
}).catch(function (xhr) {
console.log(xhr);
});
}
if (args.requestType === 'add') {
args.dialog.header = 'Adicionar Registro';
args.dialog.width = '500px';
args.dialog.height = '400px';
var ajax = new ej.base.Ajax({
url: "@Url.Action("AddPartial","Cargos")", //render the Add partial view
type: "POST",
contentType: "application/json",
data: JSON.stringify({ value: args.rowData })
});
ajax.send().then(function (data) {
appendElement(data, args.form); //Render the edit form with selected record
args.form.elements.namedItem('Codigo').focus();
}).catch(function (xhr) {
console.log(xhr);
});
}


if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {

// Add Validation Rules
args.form.ej2_instances[0].addRules('Codigo', { required: [true, 'Este dato es requerido'], maxLength: [10, '10 caracteres máximo'], value: [customFn, 'Enter a unique value'] });

}

}
}

function customFn(args) {
var grid = document.getElementById('Grid').ej2_instances[0];
for (i = 0; i < grid.dataSource.length; i++) {
if (args['value'] === grid.dataSource[i].Codigo.toString()) {
return false;
}
else {
return true;
}
}
};




Please review what happens. in advance Thanks for the support.


MS Manivel Sellamuthu Syncfusion Team March 31, 2020 11:13 AM UTC

Hi luis, 

Thanks for your update. 

Based on your code example we have modified the sample at our end, but the validation rules are working fine and duplicate values are prevented. We have attached the sample and our modified code example for your reference. 

Please note that while adding validation rules for form in Dialog template validation will be performed after focus-out only. 

@{ 
    ViewData["Title"] = "Home Page"; 
} 
 
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowPaging="true" actionBegin="actionBegin" actionFailure="actionFailure" toolbar="@(new List<string>() {"Add", "Edit", "Update", "Delete" })" actionComplete="actionComplete"> 
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column> 
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column> 
        <e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column> 
    </e-grid-columns> 
</ejs-grid> 
 
<script id='dialogtemplate' type="text/x-template"> 
    <div id="dialogTemp"> 
    </div> 
</script> 
 
<script type="text/javascript"> 
 
    function customFn(args) { 
        debugger 
        var grid = document.getElementById('Grid').ej2_instances[0]; 
        for (i = 0; i < grid.dataSource.length; i++) { 
            if (args['value'] === grid.dataSource[i].OrderID.toString()) { 
                return false; 
            } 
            else { 
                return true; 
            } 
        } 
    }; 
 
    function actionBegin(args) { 
        if (args.requestType === 'save') { 
            console.log(args); 
        } 
    } 
 
    function actionFailure(args) { 
        console.log(args); 
    } 
 
    function actionComplete(args) { 
        if (args.requestType === 'beginEdit' || args.requestType === 'add') { 
              args.form.ej2_instances[0].addRules('OrderID', { required: [true, 'Este dato es requerido'], maxLength: [10, '10 caracteres máximo'], value: [customFn, 'Enter a unique value'] }); 
                let spinner = ej.popups.createSpinner({ target: args.dialog.element }); 
                ej.popups.showSpinner(args.dialog.element); 
                if (args.requestType === 'beginEdit') { 
                    var ajax = new ej.base.Ajax({ 
                        url: "@Url.Action("Editpartial", "Home")", //render the partial view 
                        type: "POST", 
                        contentType: "application/json", 
                        data: JSON.stringify({ value: args.rowData }) 
                    }); 
                    ajax.send().then(function (data) { 
                        appendElement(data, args.form); //Render the edit form with selected record 
                        args.form.elements.namedItem('CustomerID').focus(); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }).catch(function (xhr) { 
                        console.log(xhr); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }); 
                } 
                if (args.requestType === 'add') { 
                    var ajax = new ej.base.Ajax({ 
                        url: "@Url.Action("Addpartial","Home")", //render the partial view 
                        type: "POST", 
                        contentType: "application/json", 
                        data: JSON.stringify({ value: args.rowData }) 
                    }); 
                    ajax.send().then(function (data) { 
                        appendElement(data, args.form); //Render the edit form with selected record 
                        args.form.elements.namedItem('OrderID').focus(); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }).catch(function (xhr) { 
                        console.log(xhr); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }); 
                } 
            } 
    } 
 
    function appendElement(elementString, form) { 
        form.querySelector("#dialogTemp").innerHTML = elementString; 
        var script = document.createElement('script'); 
        script.type = "text/javascript"; 
        var serverScript = form.querySelector("#dialogTemp").querySelector('script'); 
        script.textContent = serverScript.innerHTML; 
        document.head.appendChild(script); 
        serverScript.remove(); 
    } 
</script> 


If you still faced the issue, please replicate the issue in the attached sample. 

Regards, 
Manivel 



SU Surendra January 29, 2021 07:41 PM UTC

customFn() code hanging my browser and not validating uniqueness. I am using datamanager so I have json instead of datasource. Please find attached index file.




Attachment: Index_c40175ac.zip


MS Manivel Sellamuthu Syncfusion Team February 2, 2021 02:10 PM UTC

Hi Surendra, 

Greetings from Syncfusion support. 

Custom validation is used for local data and it will be triggered for each interaction on the corresponding input element. While having the large dataSource it may affect performance. Also custom function allows to define our own rules. 


We suggest you to share the below details which will be helpful for us to validate further about issue. 

  1. Share the video demo or screenshot of the issue
  2. Share the total number of records in the Grid

Regards, 
Manivel 



SU Surendra February 9, 2021 06:26 AM UTC

I using .net core 5.0. Your code to prevent duplication not working properly. Please check the attached sample & screenshots.

I found 3 errors as below.

1) At edit time uniqueness of the email not working properly.
2) Command button(Edit) incorrect behavior.
3) Please guide me or give me an example, how to do server-side validation for an email address?



Attachment: SyncFusionGridIssues_a0c9e1da.zip


MS Manivel Sellamuthu Syncfusion Team February 12, 2021 12:05 PM UTC

Hi Surendra, 

Thanks for your update. 

Query: 1) At edit time uniqueness of the email not working properly. 
 
We have modified the code example, please refer the below code example for more information. 

    function customFn(args) { 
        var grid = document.getElementById('Grid').ej2_instances[0]; 
        var action = args.element.closest('.e-row').classList.contains('e-addedrow') ? 'add' : 'edit'; 
        if (action == 'edit') { 
            var key = grid.getRowInfo(args.element.closest('tr')).rowData.Id 
        } 
        var y = grid.dataSource.executeLocal( 
            new ej.data.Query().where("EmailAddress""equal", args.value) 
        ); 
        if (y.length == 0 || key == y[0].Id) { 
            return true; 
        } else { 
            return false; 
        } 
    }; 

Query: 2) Command button(Edit) incorrect behavior. 
 
This is the default behavior of the Grid. From that screenshot we could see that you are trying to edit the second row while the first row is in edited state. So by default the First row will be saved , While clicking the second row ‘s edit command icon. 

Query: 3) Please guide me or give me an example, how to do server-side validation for an email address? 
 
By default In EJ 2 Form validator we do not have support for server side validation. But we can achieve this requirement by sending Ajax request to the server as a workaround . Once you confirm whether this is ok from your end we will provide the workaround solution for it. 

Please let us know, if you need further assistance. 

Regards, 
Manivel 



SU Surendra replied to Manivel Sellamuthu February 12, 2021 12:40 PM UTC

Hi Surendra, 

Thanks for your update. 

Query: 1) At edit time uniqueness of the email not working properly. 
 
We have modified the code example, please refer the below code example for more information. 

    function customFn(args) { 
        var grid = document.getElementById('Grid').ej2_instances[0]; 
        var action = args.element.closest('.e-row').classList.contains('e-addedrow') ? 'add' : 'edit'; 
        if (action == 'edit') { 
            var key = grid.getRowInfo(args.element.closest('tr')).rowData.Id 
        } 
        var y = grid.dataSource.executeLocal( 
            new ej.data.Query().where("EmailAddress""equal", args.value) 
        ); 
        if (y.length == 0 || key == y[0].Id) { 
            return true; 
        } else { 
            return false; 
        } 
    }; 

Query: 2) Command button(Edit) incorrect behavior. 
 
This is the default behavior of the Grid. From that screenshot we could see that you are trying to edit the second row while the first row is in edited state. So by default the First row will be saved , While clicking the second row ‘s edit command icon. 

Query: 3) Please guide me or give me an example, how to do server-side validation for an email address? 
 
By default In EJ 2 Form validator we do not have support for server side validation. But we can achieve this requirement by sending Ajax request to the server as a workaround . Once you confirm whether this is ok from your end we will provide the workaround solution for it. 

Please let us know, if you need further assistance. 

Regards, 
Manivel 


thank you Manivel,


3) <<<Once you confirm whether this is ok from your end we will provide the workaround solution for it. >>>>

Yes please give me an example. 


MS Manivel Sellamuthu Syncfusion Team February 16, 2021 10:57 AM UTC

Hi Surendra, 

Thanks for your update. 

We have validated your query and created a sample based on your requirement. Here, we have performed the validation at server side and return a value. 
Based on the returned value, we have shown an alert(we have checked whether the edited record OrderID is 2) or close the Edit(If the OrderID is not 2). 
Please find the below code example and sample for your reference. 

<ejs-grid id="Grid" dataSource="ViewBag.DataSource" actionBegin="actionBegin" width="800"> 
     . . . 
</ejs-grid> 
 
<script> 
    let selectedRecord = {}; 
    var initial = false; 
 
    function actionBegin(args) { 
        if ((args.requestType === "save") && initial) { 
            initial = false; 
        } 
        else if ((args.requestType === "save")) { 
            args.cancel = true; 
            var sendObj = { value1: args.data.OrderID }; 
            var ajax = new ej.base.Ajax({ 
                url: "/Home/DataFrm", 
                type"POST", 
                contentType: "application/json", 
                data: JSON.stringify(sendObj) 
            }); 
            ajax.send().then(function (data) { 
                if (data == 'true') { 
                    alert("grid payment value is greater..."); 
                } else { 
                    var grid = document.getElementsByClassName('e-grid')[0].ej2_instances[0]; 
                    if (!initial) { 
                        initial = true; 
                        grid.endEdit(); 
                    } 
                } 
            }).catch(function (xhr) { 
                console.log(xhr); 
            }); 
        } 
    } 
</script> 
        public bool DataFrm([FromBody]Values val2) 
        { 
            if(val2.value1 == 2) 
            { 
                return true; 
            } else 
            { 
                return false; 
            } 
        } 


Please let us know, if you need further assistance. 

Regards, 
Manivel 


Loader.
Up arrow icon