How to get Parent id on Related list in salesforce - salesforce

How to get parent id on custom button click of the related list.
Question Exploration:- when we open the Account detail record page and go in the related tab we have a contact list there and a new button on the contact list tile...when we click that new button new record modal is open with a pre-populated account in it.
so, I have to create a custom button that does this same thing.

When you click your custom button, the context is passed in the URL as a variable named inContextOfRef and the value is a base64-encoded string. You can get this value from the URL and decode it in your component. For LWC, you could do something like this:
import { LightningElement } from 'lwc';
export default class MyCoolLWC extends LightningElement {
// this variable will contain the parent record Id
recordId;
// this executes when your LWC is loaded
connectedCallback() {
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop)
});
let inContextOfRef = params.inContextOfRef;
if (inContextOfRef.startsWith("1\.")) { inContextOfRef = inContextOfRef.substring(2); }
var addressableContext = JSON.parse(window.atob(inContextOfRef));
this.recordId = addressableContext.attributes.recordId;
}
}

Related

React : how to call a function as a state object value?

I have a page which contains widgets, each widget contains data and settings used to display the data. When a widget's button is clicked, a sidebar opens (the sidebar component is a child of the page, sibling of the widgets). Within this sidebar, inputs allow to edit the clicked widget data and settings.
What I did to achieve this : I created a state in the parent to both the sidebar and the widgets, when a widget is clicked, this state is setted to contain both the data needed by the sidebar and a callback function to edit them.
What is wrong : The sidebar displays the data from the widget as it should but it does not call the callback function when data is modified.
Here's the code inside the widget component :
(...)
const updatingInformations = (data, settings, config) => {
console.log("updating informations : ", data, settings, config);
data && setWidgetData(data);
settings && setWidgetSettings(settings);
config && setWidgetConfig(config);
};
(...)
<button
onClick={(e)=>{
e.preventDefault();
setSidebarContent({
type: "widget",
widget: widget,
informations: {
data: widgetData,
config: widgetConfig,
settings: widgetSettings,
},
callback: updatingInformations,
});
}}
/>
(...)
Inside the sidebar component :
(...)
const updatingWidget = (path, newValue) => {
let stockInfo = { ...sidebarContent.informations };
stockInfo[path[0]][path[1]][path[2]][path[3]] = newValue;
console.log(
"updating widget : ",
sidebarContent,
stockInfo[path[0]][path[1]][path[2]][path[3]],
);
sidebarContent.callback(null, stockInfo.settings, null);
};
When the action is triggered (after editing an input), updatingWidget() is called as shown by its console.log() but updatingInformations() isn't called.
What is wrong with my code ?

Call lightning Web Component from URL and capture parameter from URL

I want to redirect user from one LWC to another by clicking on URL in experience cloud. Basically, on my first LWC I am showing the list of records retrieved from Apex and then when any row is clicked, I want to pass recordId of that row and redirect to second LWC which will show the record details page. How can I achieve this?
Do you have a Community... sorry, Experience Builder page with that target LWC dropped?
You could use NavigationMixin although documentation says communities don't support the state property.
On source side try something like
/* Assumes the link/button clicked looks like
<button data-id={acc.Id} onclick={handleClick}>Get details</button>
*/
handleClick(event){
if(event.currentTarget.dataset.id){
this[NavigationMixin.Navigate]({
type: 'comm__namedPage',
attributes: {
name: 'MyTargetCommunityPage__c'
},
state: {
id: event.currentTarget.dataset.id
}
});
}
}
And then on target page's LWC it should be accessible as
connectedCallback() {
if(window.location.href){
try{
let url = new URL(window.location.href);
var id = url.searchParams.get('id');
if(id){
this.myId = id;
}
} catch(e){
if(console){
console.log(JSON.stringify(e));
}
}
}
}
If Navigation gives you hard time you can ditch it and go straight for window.open('/pagename?id=123', _self); or something. It's bit annoying that you have 1 set of rules for core Salesforce, 1 for community.
(if you have a namespace - you might need to use myns__id in the state instead of id)

how can I set edit box values (in react application) by clicking on a link in an email?

I am new to react programming, and I have no idea how to set "incoming data" from a hyperlink on a web page when a user clicks a link an email.
In other words, I get an email with a link in it... I click on the link, that link takes me to a web page and populates two edit boxes with data (from the link).
I know how to code up the back end api that would accept data in api formate, for example in the 'discounts.js' api file, I could do this:
router.post('/discounts/:userCode/discount/:discountCode'
BUT what I want to do is send this link via email, have the user click the link and have the resulting page populated with data.
Here is an example link
example.com/discountPage/:snvpsnan8zosfluawpcn50ycdipa6rrqlym/code/:sdfiedgmmkfzuky2f6grds
So after the user clicks the link, the REACT web page edit boxes should look like this:
given the following react (partial) component:
class discountPage extends Component {
constructor() {
super();
this.state = {
userCode: '',
discountCode: ''
errors: {}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
I am thinking I might be able to set the data in the componentDidMount - but really unsure of where the data from link comes from and how it gets set?
Does it come from the props ?
componentDidMount() {
console.log('Register : componentDidMount ');
this.setState({'userCode': this.props.userCode });
this.setState({'discountCode': this.props.discountCode });
}
UPDATE
Based on Pinaka30's response... I did some searching and found this:
https://www.webdeveloperpal.com/2018/02/21/react-router-get-url-params/
import queryString from 'query-string';
class UserComponent extends React.Component{
render(){
// url is 'https://www.example.com/user?id=123&type=4';
let url = this.props.location.search;
let params = queryString.parse(url);
console.log(params);
// The result will be like below
// { id: 123, type: 4 }
// other code
}
}
There can be many methods, and the one I am listing might not be the best, but it will definitely give you desired results.
Since you are clicking a link and then being redirected to a new page with your form, the request will be a GET request. As we know, the parameters are visible in the url in case of a GET request. So what you can do is retrieve userCode and DiscountCode from the url itself.
componentDidMount(){
var url = window.location.href; //Gives you the complete url
temp = url.split(""); //Split the url to retrieve both parameters according to your format
this.setState({
userCode: temp[0],
discountCode: temp[1]
});
}
In your render method, use state as the value
<input id="userCode" value={this.state.userCode} />
<input id="discountCode" value={this.state.discountCode} />
So as soon as your page loads and the component renders, componentDidMount will get called and update the states which will be reflected in your input boxes. Just split the url carefully. I didn't write that line completely because i didn't know the format.

React App: how to pass a variable to other file and read its value there

I am building on sample 16 from Github/Webchat to build a webpage with a webchat interface.
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/16.customization-selectable-activity
The react app consists off different .js files to build the website( Webchat.js, Instuctor.js, App.js, Index.js) and I can't provide file Inspector.js with the data I gathered in file Webchat.js.
I can't find the right code to read the value of a variable from file Webchat.js in file Inspector.js.
I want to build a Webpage where I have on the left side a Chatbot (BotFrameWork) running, and next to it a table running which shows data that has been collected by the chatbot.
I tried answers from
how to get a variable from a file to another file in node.js
but doesn't work.
I tried to get the state of Webchat but gives only undefined.
Example:
(webchat.js) I fetched data from the bot (like [link]How to create a side window or iframe that shows data that was gathered by a Web-Chat in one web page?) and saved it in a state variable 'test'.
(instructor.js) I want to show that data e.g. in a label that is getting updated when new data comes in. How do I get access now to the value of 'test' that is created in another file?
What doesnt work:
in instuctor.js:
var test2 = require ('./webchat');
Console.log(test2.state.test) //this is how I imagine it to work --> undefined
with require I only get an object that has a 'name' variable 'Webchat' and which i can get out with: console.log(test2.default.name);
React only supports one-way data binding, so if you want to share a variable between multiple components, you need to elevate the state to the parent and pass the variable and change handlers to the children as props.
In the example below, Parent has two children: ChildA and ChildB. We could keep myValue in ChildA's state, but then ChildB wouldn't be able to access it, so we elevate myValue to the parent and pass it to both children as props. We also, pass a change handler to ChildB so it can update the value when the user clicks it.
import React from 'react';
const ChildA = ({ myValue }) => (
<div>
{
myValue
? <h1>Hello World</h1>
: <h1>Goodbye!</h1>
}
</div>
);
const ChildB = ({ myValue, handleMyValueChange}) => (
<button onClick={ () => handleMyValueChange(false) } disabled={ myValue }>
Click Me!
</button>
);
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { myValue: true }
}
render() {
return (
<div>
<ChildA myValue={this.props.myValue}/>
<ChildB myValue={this.props.myValue} handleMyValueChange={ handleMyValueChange }/>
</div>
)
}
handleMyValueChange = myValue => {
this.setState({ myValue });
}
}
In terms of the sample you referenced, the parent class is App and the two children are ReactWebChat and Inspector. I would recommend elevating the state of your variable to the parent - App - and pass it as a prop to the Inspector class. Then you can add a custom store middleware to ReactWebChat that updates your variable when the bot sends an update event. For more information on how to configure your bot to send update events and how to make Web Chat listen for them, take a look at this StackOverflow Question.
Hope this helps!

Go to the specific tab when backed from a screen

How can I go to a specific tab when backed from a screen? Lets say I am in newForm screen and when I touch the back button, I'll go to Home screen. There are 4 tabs in homeScreen and I want to go to 3rd tab as soon as I've backed to home.
Home class
Tabs tabs = new Tabs(Component.BOTTOM);
tabs.addTab("Home", icon, homeContainer);
tabs.addTab("Home1", icon1, home1Container);
tabs.addTab("Home2", icon2, home2Container);
tabs.addTab("Home3", icon3, home3Container);
add(BorderLayout.CENTER, tabs);
Button newForm = new Button("New Form");
newForm.addActionListener(e=>{
new NewForm(res).show();
});
NewForm class:
Command back = new Command("") {
#Override
public void actionPerformed(ActionEvent ev) {
new Home(res).show();
}
};
.setBackCommand(back);
I would suggest keeping an instance of the Home form and just using Home.getInstance().showBack(). This will mean that the last selected tab would remain "as is".
If you want to select a specific index use: tabs.setSelectedIndex(idx, false).
Notice that the index starts at 0.

Resources