[SalesForce] How to create a custom lightning web component for Knowledge Articles to show article title and article body only

I have been trying to create a lwc that will only show the article title and body within our community. so far I am running into some trouble with the lightning record view form commnd and assigning a proper record id as our community has dynamic pages. i . am hoping that someone can help me figure out how to either hide the other fields or to just display the article body and title fields. I am using visual studio to create the lwc.

html:

<template>
   <lightning-record-view-form record-id="ka0170000009rYcAAI" object-api-name="Knowledge__kav">
      <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
                 <lightning-output-field field-name= "Title">
            </div>
            <div class="slds-col slds-size_1-of-2">
                 <lightning-output-field field-name="Article_body__c"
            </div>
   </lightning-record-view-form>
</template>

js:

// myComponent.js
import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement {
    @api recordId;
}

js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>47.0</apiVersion>
<isExposed><targets>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
</targets></isExposed>
</LightningComponentBundle>

Best Answer

The lightning data service does not support the Knowledge__kav object as per the User Interface API guide. It is supported in Lightning communities container but your object is not supported. Hence, You need to explicitly make an apex call to get the record.

A sample example would be:-

        <template if:true={article}>
            <p>{article.Title}</p>
            <p>{article.Article_body__c}</p>
        </template>

Javascript file:-

import { LightningElement, api, track} from 'lwc';
import findArticles from '@salesforce/apex/KnowledgeController.findArticles';

export default class ApexImperativeMethodWithParams extends LightningElement {
     @api recordId;
     @track article;
     @track error;

     connectedCallback() {
        findArticles({ knowledgerecordid: this.recordId})
            .then(result => {
                this.article= result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.article= undefined;
            });
    }
}

Check out this:- trailheadapps/lwc-recipes

Related Topic