Dropdown in grid popup editor needs to be filtered by parent id

1 Answer 252 Views
DropDownList Grid
PaulH
Top achievements
Rank 1
PaulH asked on 17 May 2022, 11:12 AM

We have a grid of data items that we are editing with a custom popup editor. In the popup is a dropdown list to a foreign key field. When we're editing we need the dropdown list to contain all items so that the existing values show correctly but when we're adding a new record the dropdown list must only show the items in the dropdown where the parent entity does not already have a record associated with that related entity.

So, an example scenario is we have a list of companies and a list of products and some companies have discounts for certain products - a separate company discount table. We navigate to a view with a grid of discounts for a chosen company. In the list of company discounts there is a foreign key to the product. When an edit of one of these discount records is performed the popup opens and the dropdown is populated with all products and the dropdown is made readonly. When a new "discount" record is added, the popup opens and it needs to filter the dropdown items to just those products where the company doesn't already have a discount. We have all the controller code deriving the correct data but we have an issue. When the popup opens for an edit the dropdown data source "read" action executes but at that point in time the id of the parent object hasn't been initialised so it always looks like we are adding a new record - the id is showing as 0. We've added an additional call to the datasource.read on document.ready effectively forcing it to derive the data twice and that then populates the dropdown successfully but it no longer seems to be bound to the field as the current value is not selected. Additionally, when we open the popup for a new record we need to pass in the company id which we know from the grid view but can't seem to get to populate the model object that the popup is bound to. I've searched the web and forums and so far not managed to find a matching scenario. Do you have some advice on how to resolve these issues?

Thanks in advance

1 Answer, 1 is accepted

Sort by
0
Alexander
Telerik team
answered on 20 May 2022, 09:37 AM

Hi Paul,

In general, the Edit and Create operations' s nature is to use the same template for both the create and edit popup of the Grid. Having this in mind, one possible approach to the scenario would be to pass on additional data based on the action method of the DropDownList and based on it execute any arbitrary logic on the server-side to retrieve the desired data. For example:

Action Method:

public ActionResult Status_Read(string firstName, string lastName)
{
    // The implementation is omitted.
}

DropDownList:

@(Html.Kendo()
          .DropDownListFor(m => m.Status)
          .DataTextField("StatusName")
          .DataValueField("StatusID")
          .DataSource(source => source
                .Read(read=>read.Action("Status_Read","Home").Data("statusReadData"))
          )
)		

<script>
    function statusReadData() {
        return {
            firstName: "John",
            lastName: "Doe"
        };
    }
</script>

More information regarding the mentioned above can be found here:

Pass Additional Data to Action Methods

Alternatively, you can utilize different Popup Editors for Create and Update operations and configure the DropDownList to show only the relevant items. You can review the following knowledge base article that goes more in-depth:

Use Different Popup Editors for Create and Update Operations

In regards to populating a value to the model, you can set desired fields programmatically to the model bound to the Popup Editor using the following approach:

  • Subscribe to the Edit event of the Grid.
  • Check if the model is a newly created one using the model.isNew() method.
  • Set programmatically the value using the model.set() method.
.Events(e=>e.Edit("onEdit"))

<script>
function onEdit(e){
    if(e.model.isNew()){
        e.sender.editable.options.model.set('ProductName', "Kendo");
        e.sender.editable.options.model.set('UnitsInStock', 77777);
    }    
}
</script>

Here is a Telerik REPL that illustrates this approach. Notice, that values are set for both the "ProductName" and "UnitsInStock" fields.

If this does not help. Please consider sharing additional details regarding the configuration you currently have. For example, a code snippet illustrating the current Grid and DropDownList editor would be beneficial for the case, as it will give a better understanding of the desired result that needs to be achieved, and provide further guidance based on the obtained evidence.

Looking forward to hearing back from you.

Regards,
Alexander
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

PaulH
Top achievements
Rank 1
commented on 20 May 2022, 02:43 PM

 

Hi Alexander

That is pretty much the approach we are applying here. So the dropdown list data source read action is as follows:


                .DataSource(source =>
                {
                     source.Read(read =>
                     {
                          read.Action("GetDropdownData", "Maintenance").Data("getUserIDData");
                      }).ServerFiltering(true);
                 })
The function to get the user ID is as follows:

 

    function getuserIDData() {
        return {
            userId: $('#UserId').val()
        };
    }

The user ID is in a hidden input field. The point here is that when a new record is being added the user ID should be 0 whereas for editing an existing record we should have the actual user ID. The problem is that when we open the popup from the grid for an edit when the javascript function is called the user ID input field hasn't been initialised so returns 0 making our controller action think this a new record instead. Is this normal? We've added a call to perform the datasource read again as below in the document.ready function by which point the user ID field has been initialised:

$('#DropdownColumnId').data('kendoDropDownList').dataSource.read();

But once that has happened the relevant item in the dropdown is not automatically populated - the ID is present in the model but the dropdownlist doesn't automatically select the item.

The key issue around this is that the view is bound to a model which contains a number of fields, one of which is the ID of the item obviously. The issue is that we need the dropdown's list of items to be different for new items than it is for editing - in an edit it should contain all possible values and in a new it should only list the items that haven't already got existing records for that chosen value.

on document.ready() but then the dropdown is populated correctly but the selected item is not displayed

Alexander
Telerik team
commented on 25 May 2022, 08:41 AM

Hi Paul,

Based on my current understanding of the case. The desired result is to show a portion of the DropDownList data upon a record's creation whilst displaying all the available data when editing is that correct? In addition, could you please confirm if the UserId field is part of the Grid model? Its value is set to the hidden input element when the editor template is bound?

Regardless, a similar topic has been discussed in the following forum thread that tackles a similar scenario. Notice that the approach targets the Telerik UI for the ASP.NET MVC suite, but a similar approach is also applicable for an ASP.NET Core application as well:

https://www.telerik.com/forums/foreign-key-dropdown-depending-on-content

In addition, if the issue still persists could you please consider opening a support ticket and attaching a minimal runnable sample demonstrating the scenario. This will help me test and debug the behavior locally.

PaulH
Top achievements
Rank 1
commented on 25 May 2022, 11:30 AM

Hi Alexander

I've been giving this some thought and at this point I think the simplest solution is just to remove the ability to add the items in. While there is a logic to the need to do it, it's actually not in the scope of this particular project so rather than jump through hoops to meet a requirement that is in my head rather than the client's I'll remove the feature and we'll address it later if it's deemed necessary to support it at a later time.

Thanks for the feedback and I'll keep a not of this for future reference.

Kind regards

Paul.

Tags
DropDownList Grid
Asked by
PaulH
Top achievements
Rank 1
Answers by
Alexander
Telerik team
Share this question
or