My requirement is to build lightning datatable dynamically.
I can able to dynamically create and view lightning data table. But as soon as I am adding "onrowselection":component.getReference("c.getSelectedRecord") line, datatable is not rendering. So adding this line is causing the issue, but I need to hookup onrowselection event.
What is the proper way to add onrowselection event dynamically to my dynamically created datatable?
Error Reproduce: I have prepared demo code below.
Component: demoDynamicDataTable.cmp
<aura:component controller="demoDynamicDataTableController">
<aura:attribute name="returnList" type="Contact[]" access="public"/>
<aura:attribute name="returnColumns" type="List" access="public"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<lightning:button label="Create Data Table" onclick="{!c.createDT}" variant="brand"/>
<div aura:id="newDtPlaceholder">
{!v.body}
</div>
</aura:component>
JS Controller: demoDynamicDataTableController.js
({
doInit : function(component,event,helper) {
console.log("doinit");
//Column data for the table
var columns = [
{
label:'Customer Name',
fieldName:'Name',
type:'text'
},
{
label:'Phone#',
fieldName:'Phone',
type:'text'
}
];
//pass the column information
component.set("v.returnColumns",columns);
//recriving data from server
helper.fetchData(component);
},
createDT : function(component, event, helper) {
//Creating dynamic Lightning datatable
var targetCmp=component.find("newDtPlaceholder");
targetCmp.set("v.body",[]); //destroying existing one
$A.createComponent(
"lightning:datatable",
{
"data":component.get("v.returnList"),
"columns":component.get("v.returnColumns"),
"keyField":"Id",
"maxRowSelection":"1",
"onrowselection":component.getReference("c.getSelectedRecord") //adding this line is causing the issue. But I need to hookup onrowselection event
},
function(tbl,state,message)
{
console.log(state +" - " +message);
var body=targetCmp.get("v.body");
body.push(tbl);
targetCmp.set("v.body",body);
}
);
},
getSelectedRecord: function(component, event, helper){
var selectedRows = event.getParam('selectedRows');
console.log(JSON.stringify(selectedRows[0]));
}
})
Helper: demoDynamicDataTableHelper.js
({
fetchData : function(cmp) {
var action = cmp.get("c.getContact");
action.setCallback(this,function(resp){
var state = resp.getState();
if(state === 'SUCCESS'){
var records = resp.getReturnValue();
//console.log(JSON.stringify(records));
//pass the records to be displayed
cmp.set("v.returnList",records);
}
});
$A.enqueueAction(action);
}
})
Apex Controller: demoDynamicDataTableController.apxc
public class demoDynamicDataTableController {
#AuraEnabled
public static List<Contact> getContact(){
return [Select Id,Name,Phone from Contact];
}
}
App: demoDynamicDataTableApp.app
<aura:application extends="force:slds">
<c:demoDynamicDataTable/>
</aura:application>
Related
Apex class code-
public class DesignAttClass {
#AuraEnabled public static sObject[] getRecords(String query) {
return Database.query(query);
}
}
helper code-
({
getRecrdHelper : function(component, event, helper) {
var action = component.get('c.getRecords');
action.setParams({'query' : component.get('v.Query')});
action.setCallback(this, function (res){
if(res.getState() === 'SUCCESS'){
console.log('Received = '+JSON.stringify(res.getReturnValue()));
component.set('v.recordsData',res.getReturnValue());
}else{
console.log('Something went wrong...!!!!');
}
});
$A.enqueueAction(action);
}
})
Now i wanted to try the upcoming data show in lightning datatable dynamically.
I am attempting to build a simple lightning component that will display field values from the object that it is referencing on the page. I have applied the tutorial but cannot get the field values to display on the page.
It is not clear to me how to reference the id of the object on the page and/or whether it is necessary for the apex query or if the field value can be rendered without it.
Position__c is the reference object API with some fields:
This is my component:
<aura:component implements="flexipage:availableForAllPageTypes" controller="positionController" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="recordId" type="Id" />
<aura:attribute name="position" type="Position__c"/>
{!v.position.Job_Posting_One_liner__c} //I really just need to print this field value
</aura:component>
Controller:
({
doInit : function(component, event, helper) {
var recordId = component.get("v.recordId");
var action = component.get("c.getPositionDetails");
action.setParams({
"PosId": recordId
});
action.setCallback(this, function(response){
var state = response.getState();
if (component.isValid() && state === "SUCCESS") {
var position = response.getReturnValue();
component.set("v.position", position);
}
});
$A.enqueueAction(action);
}
Apex:
public class positionController {
#AuraEnabled
public static Position__c getPositionDetails(Id PosId) {
Position__c positions =
[SELECT Id, Job_Posting_One_liner__c FROM Position__c Where Id= :PosId limit 1 ];
return positions;
}
}
In js controller try remove quotes from this line:
action.setParams({
"PosId": recordId
});
so that it reads like this:
action.setParams({ PosId: recordId });
I am creating dynamic child components for a table.
Parent Component
class SimpleView extends Component {
constructor(props) {
super(props);
this.onAutoChange = this.onAutoChange.bind(this);
this.state = {
columns: this.createcolumns(clone(this.props.tableInfo.columns)),
dataList: this.props.data,
result: []
};
}
createcolumns(columns) {
const editColumnRender = (text, record, index) =>
<AssingCell
index={index}
columnsKey={columns[3].key}
onAutoChange={this.onAutoChange}
/>;
columns[3].render = editColumnRender;
return columns;
}
onAutoChange(value){
this.props.fetchDrivers('',value);
}
componentWillReceiveProps(nextProps){
if(nextProps.driversData && nextProps.driversData.message === 'SUCCESS' && i<1)
{
this.setState({driversResult: nextProps.driversData.data});
i=i+1;
}
}
render() {
const { columns, dataList, loading } = this.state;
return (
<TableWrapper
columns={columns}
dataSource={dataList}
/>
);
}
}
Here is a child component named AssingCell. There is a modal button inside the button. There is also one autocomplete in Modal. This.props.onAutoChange is called during every call. In this section, data is fetched from the server. How can I send this data to the child component?
Or how else can I do this?
I have a table that is populated by OData but I want it to not populate when first loading the page.
How can I have it be empty until the user selects a choice in the combo box first? Is there suppose to be a change in the view, controller, or manifest?
View
<ComboBox id="officeComboBox"
width="100%"
placeholder="Office"
selectionChange=".officeComboChange"
>
<items>
<core:Item key="{OFFICE_CODE}" text="{OFFICE_CODE}" textDirection="RTL"/>
</items>
</ComboBox>
<!-- ... -->
<Table id="statTable"
noDataText="Initializing Data"
growing="true"
includeItemInSelection="true"
headerText="EST"
items="{/ESTSet}"
>
Controller
Handler officeCodeChange works fine for displaying the right items on the table after combo box selection
onInit: function() {
var oViewModel, iOriginalBusyDelay, oTable = this.byId("officeCombo");
this._oTableSearchState = [];
},
officeCodeChange: function(event) {
var aFilters = [];
var officeCode = event.getParameter("selectedItem").getText();
var filter = new Filter("EST_ID", sap.ui.model.FilterOperator.Contains, officeCode);
var list = this.getView().byId("statTable");
var binding = list.getBinding("items");
binding.filter(aFilters.concat(filter), "Application");
},
Remove the initial aggregation binding items="{/ESTSet}" and the corresponding template control from the view.
Use bindItems in combination with the created filter(s):
officeCodeChange: function(event) {
const filter = /*...*/;
const table = this.byId("statTable");
const listBinding = table.getBinding("items");
if (listBinding) {
listBinding.filter(filter, FilterType.Application); // FilterType required from "sap/ui/model/FilterType"
} else {
this.bindStats(table, filter);
}
},
bindStats: function(table, filter) {
table.bindItems({
path: "/ESTSet",
filters: [filter],
template: new ColumnListItem({ // required from "sap/m/ColumnListItem"
//...
}),
});
},
Ive got a dropdown on one of my views. This dropdown only has for entries. Basically i need to know how to call an action when the dropdown value is changed?
My situation is: Im making a simple inbox page. The dropdown has the filter options: View All, View Invites, View Replies etc..
When the user selects a filter option from the dropdown I want to call to an action to return the new view with the filtered data.
Any ideas? Im guessing it is somehow going to be a script attached to the OnChange of the dropdown, but i wouldnt have a clue what the syntax is or how call MVC action from the script.
Thanks in advance
You need to use javascript for this. Here's an example. Suppose you have the following view model:
public class MyViewModel
{
public IEnumerable<SelectListItem> Values { get; set; }
}
which you would populate in your controller:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Values = new[]
{
new Item { Value = "1", Text = "Item 1" },
new Item { Value = "2", Text = "Item 2" },
new Item { Value = "3", Text = "Item 3" }
}
};
return View(model);
}
}
And then the view which is strongly typed to this model:
<%: Html.DropDownListFor(x => x.SelectedValue,
new SelectList(Model.Values, "Value", "Text"),
new { id = "items" }
)%>
The last part is to register for the change event (using jquery in this example):
$(function () {
// Register for the change event of the drop down
$('#items').change(function () {
// When the value changes, get send an AJAX request to the
// Filter action passing the selected value and update the
// contents of some result div with the partial html returned
// by the controller action
$('#result').load('<%: Url.Action("filter") %>',
{ selectedValue: $(this).val() }
);
});
});