Despite numerous tutorials I cannot get a simple LMS example to work that is virtually cut and paste from samples. I have created an extremely simple pair of LWCs, one that publishes a hard coded value at the click of a button and a second that simply logs/displays the message that was sent. It compiles and deploys without error and console log reports that the value is published and that the subscriber is subscribed, but the message handler in the subscriber is never called. What the heck am I missing?
Here is my code:
PUBLISHER LWC:
testPub.html
<template>
<lightning-button onclick={handlePubClick} variant="brand" label="Test Publish" title="Primary action" class="slds-var-m-left_x-small"></lightning-button>
</template>
testPub.js
import { LightningElement, wire} from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import XingoFiltersMC from '#salesforce/messageChannel/XingoFilters__c';
export default class TestPub extends LightningElement {
#wire(MessageContext)
messageContext;
handlePubClick(){
const message = {fu: 'bar'};
console.log('publishing ' + JSON.stringify(message));
publish(this.MessageContext,XingoFiltersMC, message)
}
}
testPub.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
SUBSCRIBER LWC:
testSub.html
<template>
Received: {msg}
</template>
testSub.js
import { LightningElement, wire } from 'lwc';
import {subscribe, MessageContext} from 'lightning/messageService';
import XingoFiltersMC from '#salesforce/messageChannel/XingoFilters__c';
export default class TestSub extends LightningElement {
#wire(MessageContext)
messageContext;
msg = "";
subscription = null;
subscribeToMessageChannel() {
console.log("subscribing");
this.subscription = subscribe(
this.messageContext,
XingoFiltersMC,
(message) => this.handleMessage(message)
);
}
handleMessage(message) { //<-- this here never is reached
this.msg = message ? JSON.stringify(message, null, "\t") : "no message payload";
console.log("received " + this.msg);
}
connectedCallback() {
this.subscribeToMessageChannel();
}
}
testSub.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
MESSAGE CHANNEL:
force-app\main\default\messageChannels\XingoFilters.messageChannel-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>XingoFilters</masterLabel>
<isExposed>true</isExposed>
<description>Xingo message channel for filter change.</description>
</LightningMessageChannel>
I'm using sfdx force:source:push --json --loglevel debug -f in VisualCode to push to my org where I have a Lightning App with these two components on it.
Any help greatly appreciated, I feel like I have exhausted the tutorials and docs out there which all looks consistent with this test that isn't working for me.
The root cause was:
publish(this.MessageContext,XingoFiltersMC, message)
should have been
publish(this.messageContext,XingoFiltersMC, message)
Over a day lost to this capitalization typo... any idea on how to configure VS Code catch these sorts of typos better?
Related
I tried to build a LWC component to view data, but the data was not showing on UI. i can't get what was wrong with my code.
Html:
<template>
<lightning-card title="LDS Lab" icon-name="custom:custom54">
<div class="slds-m-around_small">
<lightning-record-form
record-id={recordId}
object-api-name={objectApiName}
layout-type="full"
mode="view"
columns="2"
>
</lightning-record-form>
</div>
</lightning-card>
</template>
JavaScript:
import { LightningElement,api } from 'lwc';
export default class LdsRecord extends LightningElement {
#api recordId;
#api objectApiName;
}
Meta File:
<?xml version="1.0" encoding="UTF-8"?><LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
First thing you need to check here is if you are getting recordId before the LDS form get loads, if it is not having blank value while loading then try below.
Using getter setters to set the recordId attribute
Add a console log in getter if the _recordId is having value
If not then use a boolean to avoid lightning-record-form load,
if:true=attribute
And load it when you have recordId in getter.
load = false;
#api set recordId(value) {
console.log(value);
this._recordId = value;
load = true
}
get recordId() {
console.log(this._recordId);
return this._recordId;
}
Please check this post also: https://salesforce.stackexchange.com/questions/344045/recordid-is-undefined-in-lwc-quick-action-component
I have a requirement where LWC component is fired everytime when a case is opened,I want to change LWC component to work only for NEW cases,what changes needs to be done in the LWC to make it work only for specific case types which are in NEW status
Here is JS code
import { LightningElement } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class CaseTypeInformation extends LightningElement {
connectedCallback() {
var toast = new ShowToastEvent({
'title': 'Case Type Level 1, level 2 and level 3 fields ',
'message': 'must be selected before saving'
});
this.dispatchEvent(toast);
}
}
here is HTML
<template>
</template>
here is metaxml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel> CaseType Levels Info Component</masterLabel>
<description> CaseType Levels Info Component.</description>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Few ways to do it.
Ignore LWC completely. Does it have to be a "toast" at all? You could drop to the page a Rich Text Area field, put some text in red and use conditional display rules. Job done, zero code.
Similar - still use your component as is, but use the component visibility rules to make it display (run) only on New Cases.
Edit your component to be something like this
import { LightningElement, api, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRecord } from 'lightning/uiRecordApi';
import CASE_STATUS_FIELD from '#salesforce/schema/Case.Status';
export default class CaseTypeInformation extends LightningElement {
#api recordId;
#wire(getRecord, { recordId: '$recordId', fields: [CASE_STATUS_FIELD] }) wiredCase({ error, data }){
if(data && data.fields.Status.value === 'New'){
this.dispatchEvent(new ShowToastEvent({
'title': 'Case Type Level 1, level 2 and level 3 fields ',
'message': 'must be selected before saving'
}));
}
}
}
I have the following lightning web component.
MyPage.html
<template>
<lightning-record-form
object-api-name={contactObject}
fields={myFields}
onsuccess={handleContactCreated}>
</lightning-record-form>
</template>
MyPage.js
import { LightningElement } from 'lwc';
import CONTACT_OBJECT from '#salesforce/schema/Contact';
import NAME_FIELD from '#salesforce/schema/Contact.Name';
export default class ContactCreator extends LightningElement {
contactObject = CONTACT_OBJECT;
myFields = [NAME_FIELD];
handleContactCreated(){
// Run code when account is created.
}
}
This works if I drop this lightning component in Account record detail page.
But it does not work in Contact record detail page.
No matter how many times I save it, it disappears. when I come and check it again in the contact record detail page, it's not there.
Can someone help ?
You must have a reference to the Contact page in your web components meta.xml file. I'm assuming yours looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"
fqn="nameOfComponent">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
when you need to add Contact as an object inside the objects tags.
I am trying to add data to mysql database. There is a single textInput for entering name and a Button.(addBtn) on click of which the textInput.text should be inserted in to the database. The php file is autogenerated from the database. In Button handler i wrote the following code
protected function addBtn_clickHandler(event:MouseEvent):void
{
namBol= new Naming();
namBol.name=nameTxt.text;
createNamingResult.token = namingService.createNaming(namBol);
}
The database has only two feilds, sr_no and name. While running this code, on clicking the addBtn the name does not get inserted into the database. What might be the problem?
Here is the whole code, let me know if I miss something.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:valueObjects="valueObjects.*"
xmlns:namingservice="services.namingservice.*"
minWidth="955" minHeight="600"
>
<fx:Declarations>
<valueObjects:Naming id="namBol"/>
<s:CallResponder id="createNamingResult" result="createNamingResult_resultHandler(event)"/>
<namingservice:NamingService id="namingService"
fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
showBusyCursor="true"/>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.rpc.events.ResultEvent;
protected function addBtn_clickHandler(event:MouseEvent):void
{
namBol= new Naming();
namBol.name=nameTxt.text;
createNamingResult.token = namingService.createNaming(namBol);
}
]]>
</fx:Script>
<s:TextInput id="nameTxt" x="216" y="144" />
<s:Button id="addBtn" x="217" y="204" label="Button" click="addBtn_clickHandler(event)"/>
</s:Application>
in your function addBtn_clickHandler add :
namingService.commit();
I've created a database connection and some entities, now I'm trying to test the functionality of my database. I have a User entity class, which has a unique username along with some other information. Right now I'm trying to simply create a new User and Profile and map them together, then persist them. When I test the code, it successfully runs through, but the DB is not updated. Here's what I have:
package servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import entities.Profile;
import entities.User;
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
#Resource
UserTransaction utx;
#PersistenceUnit
EntityManagerFactory emf;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String email = request.getParameter("email");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String phone = request.getParameter("phone");
String address1 = request.getParameter("address1");
String address2 = request.getParameter("address2");
try {
utx.begin();
EntityManager em = emf.createEntityManager();
//create User & Profile
User u = new User();
u.setUsername(username);
Profile p = new Profile();
p.setUser(username);
//add email to profile's list
List<String> emails = new ArrayList<String>();
emails.add(email);
p.setEmails(emails);
//assign the profile to the user
u.setProfile(p);
//persist user to the database
em.persist(u);
utx.commit();
em.close();
emf.close();
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("index.jsp");
}
}
Am I doing something wrong or is the problem somewhere else in the application?
EDIT: I found the following error: Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
I'm not sure what to make of the error, however...I've checked my db connection and everything seems to be in order. :/
My persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myPersistenceUnit" >
<jta-data-source>jdbc/mydatasource</jta-data-source>
<class>entities.User</class>
<class>entities.Profile</class>
<class>entities.Message</class>
<class>entities.Image</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/>
</properties>
</persistence-unit>
</persistence>
I have never use container managed transactions but your persistence.xml at least have.
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">