16
import { LightningElement, track, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

const FIELDS_SOLICITUD = [
    'DCABM_obj_solicitudABM__c.DCABM_fld_aplicacionSolicitud__c',
];

export default class DCABM_lwc_form extends LightningElement {

    @api recordId;

    idAplicacion;

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS_SOLICITUD })
    aplicacionSolicitud({ data, error }) {
        if (data) {
            this.idAplicacion= data.fields.DCABM_fld_aplicacionSolicitud__c.value;
        } else if (error) {
            window.console.log("Error");
        }
    }

}

I have a second object that has a relation with the value of "idAplicacion". How can I get all the objects that have that id as a value, without using APEX?

2
  • 7
    To my knowledge lightning data service only works with 1 record at a time. I am up-voting though as I hope there is a better answer.
    – gNerb
    Jun 11, 2019 at 15:38
  • Kris is correct: you can only do specific queries with Apex. The only workaround is fetching all the records and filtering on the client, but if you have too many records that can potentially be really slow. With the Winter '21 release, there is the getListUi option, but I don't believe it's dynamic in the way you're looking for. What is the reason you don't want to use Apex? Oct 16, 2020 at 16:23

4 Answers 4

5

It is possible to get records "without apex" or without using the lwc wrappers that leverage the uiRecordApi. If you go through the User Interface API Developer Guide, you can find sample apps (external) and detailed methods and endpoints that can be used to interact with the DB.

There are several things that need to be considered to make this work:

  1. Security, you still need to authenticate the requests.

  2. Forget about using GET due to CSP.

  3. You will most likely need to use an Apex Class to securely handle getting an access token to securely request data.

  4. A connected app is required for the apex Class.

Once you do manage to set yourself up with the aforementioned (securely getting access tokens to auth. your requests), you can use the Fetch Api to get data with and write your SOQL's from the client (amongst other things).

Also, it is important to understand that not everything is supported if you opt to using this approach.

Sample Applications:

  • Record Viewer
  • Record Viewer Native FYI, both these repo's are archived, however, if you browse through it, you can get a general idea of how they interact with the API.

Bear in mind that this API was mainly created for external web apps to interact with your SF data.

Quick example. this is my utility method that I use to fetch an access token from my apex class:

import getAccessToken from '@salesforce/apex/UiAuth.getAccessToken';

const getToken = async () => {
    const token = await getAccessToken();
    return token;
   
}

I can use the access token to get data using the available resources documented here.

const queryRecords = async (soql) =>{    
    const token = await getToken();    
    const requestURL =`${document.location.origin}/services/data/v51.0/query?q=${soql}`;    
    const getData = await fetch(requestURL,{
       method : 'POST',
       headers : {
           'Authorization': `Bearer ${token}`
       },    
    });    
    const response = await getData.json();    
    return response; 
}
8

Another Update: With Spring '23, there is a pilot for the GraphQL wire adapter. This would allow you to perform a query on any UI API enabled object and get the records without needing apex.

import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';

export default class ExampleGQL extends LightningElement {
    @wire(graphql, {
        query: gql`
            query AccountInfo {
                uiapi {
                    query {
                        Account(where: { Name: { like: "United%" } }) @category(name: "recordQuery") {
                            edges {
                                node {
                                    Name @category(name: "StringValue") {
                                        value
                                        displayValue
                                    }
                                }
                            }
                        }
                    }
                }
            }`
    })
    propertyOrFunction
}

Update: With Spring '22, there is now a uiRelatedList module in beta that would allow you to retrieve related list records from a single record without apex.

This module includes new wire adapters to get records, metadata, and record count for a related list.

  • getRelatedListRecords — Returns record data for a related list.
  • getRelatedListInfo — Returns metadata for a related list.
  • getRelatedListsInfo — Returns metadata for multiple related lists.
  • getRelatedListCount — Returns the record count for a related list.
import { LightningElement, wire } from 'lwc';
import { getRelatedListRecords } from 'lightning/uiRelatedListApi';

export default class LdsGetRelatedListRecords extends LightningElement {
    @wire(getRelatedListRecords, {
          parentRecordId: '001RM000003UNu6YAG',
          relatedListId: 'Contacts',
          fields: ['Contact.Name','Contact.Id']
    })
}

original answer

I don't believe you can.

https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.data_wire_example

You can utilize the lightning data service to get the current RecordId when it's displayed on one, but I'm not aware of a way to query for specific records with specific text without utilizing apex to do that query.

3
  • Thanks for this update. Just a side note : the uiRelatedList link seems broken, getting a toast error message on the page
    – Shamina
    Jan 19, 2022 at 19:16
  • 1
    It's for Spring 22, so the link won't work until API 54 docs are released. Jan 19, 2022 at 19:33
  • Just wanna say... cripes, the graphquery query looks horrible. It's benefits are going to be outweighed by it's awfulness to use, I reckon. Jan 17, 2023 at 19:22
1

As of now, there is nearly no way get related records without using Apex.

With Apex, you could get the child records using an SOQL query.

1

There is a special method for this. https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_wire_adapters_records

import { LightningElement, api, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRecords } from 'lightning/uiRecordApi';

const FIELDS = ['Contact.Name', 'Contact.Phone'];

export default class LoadContact extends LightningElement {
    @api recordId;
    contacts;
    name;
    phone;
    @wire(getRecords, {
        records: [
            {
              recordIds: ['005XXXXXXXXXXXXXXX', '005XXXXXXXXXXXXXXX'],
              fields: FIELDS
            }
        ]
    })
    wiredRecord({ error, data }) {
        if (error) {
            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map(e => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading contacts',
                    message,
                    variant: 'error',
                }),
            );
        } else if (data) {
            this.contacts = data;
            this.name = this.contacts.results[1].result.fields.Name.value;
            this.phone = this.contacts.results[1].result.fields.Phone.value;
        }
    }

 }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .