简体   繁体   English

有没有办法从闪电 Web 组件(LWC)中的 JS 将多个(和不同的)参数传递给 Apex Controller class?

[英]Is there a way to pass multiple (and different) parameters to an Apex Controller class from JS in Lightning Web Components (LWC)?

I'm currently stuck at a problem and was hoping someone here could help me.我目前遇到一个问题,希望这里有人可以帮助我。 I also certainly hope this is the right place to ask it.我当然也希望这是问它的正确地方。

I'm trying to create a custom Invoice record with its corresponding Invoice Line records upon firing an event.我正在尝试在触发事件时创建具有相应发票行记录的自定义发票记录。 I already have some logic in place to gather ID of selected rows in the JS.我已经有一些逻辑来收集 JS 中选定行的 ID。

I've gone so far as to be able to create the Invoice record (using LDS) and the Invoice Line records (using Apex), but can't seem to pass the Invoice ID for the Invoice Line records.我已经能够创建发票记录(使用 LDS)和发票行记录(使用 Apex),但似乎无法传递发票行记录的发票 ID。 I know I'm able to create the records because it works when I tested this with a hardcoded Invoice ID.我知道我能够创建记录,因为当我使用硬编码的发票 ID 测试它时它可以工作。

Would it be possible to pass multiple parameters of List and String to an Apex method in LWC?是否可以将 List 和 String 的多个参数传递给 LWC 中的 Apex 方法?

I would appreciate any help.我将不胜感激任何帮助。 Thanks in advance!提前致谢!

JS JS

    selectedRowsEvent(event) {

    ...some codes here...

    this.selectedRecords = Array.from(conIds);
    }


    handleSave() {

         **invId;**

         ...some codes here...

        createRecord(recordInput)
        .then(invoice => {
            **this.invId = invoice.Id;**  
            **createInvLines({ lstConIds : this.selectedRecords, invoiceId : this.invId})**
        }).catch(error => {

          ...some codes here...

          });
    }

Controller Controller

@AuraEnabled
    public static void createInvLines(list<Id> lstConIds, string invoiceId){
        if(lstConIds.size() > 0){
            List<OpportunityLine__c> oppLst = new List<OpportunityLine__c>([SELECT Id, Description__c FROM OpportunityLine__c WHERE Id = :lstConIds]);
            try {
                List<InvoiceLine__c> lstInvLinesToInsert = new List<InvoiceLine__c>();
                for(OpportunityLine__c idCon : oppLst) {
                    lstInvLinesToInsert.add(new InvoiceLine__c(**InvoiceId__c = invoiceId**, Description__c = idCon.Description__c));
                }
                if(!lstInvLinesToInsert.isEmpty()) {
                    insert lstInvLinesToInsert;
                }
            }
            catch(Exception ex) {
                throw new AuraHandledException(ex.getMessage());
            }
        }
    }  

Yes, you can pass complex parameters to methods marked as @AuraEnabled .是的,您可以将复杂的参数传递给标记为@AuraEnabled的方法。 On client side it'll be a JSON object with right field names, like you already have { lstConIds: this.selectedRecords, invoiceId: this.invId} .在客户端,它将是一个 JSON object 具有正确的字段名称,就像您已经拥有{ lstConIds: this.selectedRecords, invoiceId: this.invId} On Apex side it can be a function with multiple arguments or just 1 argument (some helper wrapper class, again with right field names).在 Apex 方面,它可以是 function 和多个 arguments 或只有 1 个参数(一些辅助包装器 class,同样具有正确的字段名称)。 Salesforce will "unpack" that JSON for you and put into right fields before your code is called. Salesforce 将为您“解包” JSON 并在调用您的代码之前放入正确的字段中。

Your preference which would be cleaner.您的偏好会更清洁。 I tend to use wrappers.我倾向于使用包装器。 If you have a reusable service-like function and you want to add some optional parameters later - you'd simply put new field in wrapper class and job done.如果您有类似 function 的可重用服务,并且您想稍后添加一些可选参数 - 您只需将新字段放入包装器 class 并完成工作。 Might be not as easy to add a new parameter to function used in other apex code, bit messier.向其他顶点代码中使用的 function 添加新参数可能并不容易,有点混乱。

(in your scenario I'd definitely try to create invoice and line items as 1 call so if anything fails - the normal transaction rollback will help you. if one of items fails - you don't want to be left with just invoice header, right?) (在您的情况下,我肯定会尝试将发票和行项目创建为 1 个调用,因此如果有任何失败 - 正常的事务回滚将帮助您。如果其中一个项目失败 - 您不想只留下发票 header,正确的?)

Have you seen https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex ?你见过https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex吗? it's a wall of text but it mentions interesting example, search for "apexImperativeMethodWithParams" in there.这是一堵文字墙,但它提到了有趣的例子,在那里搜索“apexImperativeMethodWithParams”。

Look at JS file here: https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/apexImperativeMethodWithComplexParams And see how it calls在这里查看 JS 文件: https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/apexImperativeMethodWithComplexParams看看它是如何调用的

ApexTypesController {
    @AuraEnabled(cacheable=true)
    public static String checkApexTypes(CustomWrapper wrapper) {
...

Where CustomWrapper is CustomWrapper在哪里

public with sharing class CustomWrapper {
    class InnerWrapper {
        @AuraEnabled
        public Integer someInnerInteger { get; set; }
        @AuraEnabled
        public String someInnerString { get; set; }
    }

    @AuraEnabled
    public Integer someInteger { get; set; }
    @AuraEnabled
    public String someString { get; set; }
    @AuraEnabled
    public List<InnerWrapper> someList { get; set; }
}

The issue is that the inserts are asynchronous and you are firing them synchronously.问题是插入是异步的,并且您正在同步触发它们。 So, that means you are trying to insert the lines before the parent record has completed.因此,这意味着您正在尝试在父记录完成之前插入行。

// CREATE THE INVOICE RECORD
    createRecord(recordInput)
        .then(invoice => {
                **this.invId = invoice.Id;**
                // Call the next function here

                   // CREATE THE INVOICE LINE RECORDS
                **createInvLines({ lstConIds : this.selectedRecords, invoiceId : this.invId})**
                 .then(result => {
                   ...some codes here...
                  })
                 .catch(error => {
                   ...some codes here...

                 }); 
              );
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 LWC:如何在 Lightning Web Components(LwC) salesforce 中的图表 js 条中显示数据值 - LWC: How to display data values in chart js bars in Lightning Web Components(LwC) salesforce 在没有顶点的闪电 web 组件上创建任务仅 javascript controller? - Create a task on a lightning web component without apex only javascript controller? <noerrorobjectavailable>闪电 web 组件 (LWC) 中的脚本错误</noerrorobjectavailable> - <NoErrorObjectAvailable> Script error in lightning web component (LWC) Salesforce LWC - 多个 Apex 标注必须失败 - Salesforce LWC - Multiple Apex Callout Imperatively Fails 使用 Charts Js 在 Lightning Web 组件中将数据从父级传递给子级 - Pass data from parent to child in lightning web component using Charts Js 如何在angular4中将多个参数传递给Web API控制器方法 - How to pass multiple parameters to the Web API controller methods in angular4 如何将Javascript映射作为参数从闪电组件发送到Apex服务器控制器? - How to send Javascript map as a parameter from lightning component to Apex server controller? 如何将多个变量从typescript(angular.js)传递给Web API(MVC)中的Controller - How to pass multiple variable from typescript (angular.js) to Controller in Web API(MVC) 如何将多个参数传递给控制器 - How to pass multiple parameters to controller JS:EcmaScript6如何将不同数量的参数传递给扩展类 - JS: EcmaScript6 how to pass different number of parameters to extended class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM