• Fnu Sumit
  • NEWBIE
  • 5 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 9
    Replies
i have used akansha code and mousin suggestion to remove space but still challange is not complete:
Callout Class
global class AnimalLocator
{
    public class Animal {
    public Integer id;
    public String name;
    public String eats;
    public String says;

    }
    
    public class AnimalResult {
    public Animal animal;
    }

    public Static String getAnimalNameById(integer id)
    {
        List<Object> animal;
        String returnValue ;
        AnimalResult result;
        Http http=new Http();
        HttpRequest request =new HttpRequest();
        request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        //request.setBody('{"id":"'+id+'"}');
        HttpResponse response= http.send(request);
        if(response.getStatusCode()==200)
        {
       result = (AnimalResult) JSON.deserialize(response.getBody(), AnimalResult.class);
       }
        return result.animal.name;

    }
    
}

MOCKResponse Class
@isTest
global class AnimalLocatorMock implements HttpCallOutMock
{
    public static HTTPResponse respond(HttpRequest req) 
    {
            HTTPResponse response =new HTTPResponse();
            response.setHeader('Content-Type', 'application/json');
            response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
            response.setStatusCode(200);

             return response;

    }

}

Test Class

@isTest
public class AnimalLocatorTest 
{
    public static testMethod void mytestMethod()
    {
        Test.SetMock(HttpCallOutMock.class,new AnimalLocatorMock());
        
         String res= AnimalLocator.getAnimalNameById(1);
       
        
        String expectedValue = 'chicken';
        System.assertEquals(res, expectedValue);
        


    }

error: 
Something has gone wrong. Error during init [TypeError: Cannot read property 'apply' of undefined] . Please try again
expenses component:
<aura:component controller="ExpensesController">

    <aura:attribute name="expenses" type="Expense__c[]"/>

 
    <aura:handler name="createExpense" event="c:expensesItemUpdate"
        action="{!c.handleCreateExpense}"/>
    <aura:handler name="updateExpense" event="c:expensesItemUpdate"
        action="{!c.handleUpdateExpense}"/>
   <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <!-- PAGE HEADER -->
    <div class="slds-page-header" role="banner">
      <div class="slds-grid">
        <div class="slds-col">
          <p class="slds-text-heading--label">Expenses</p>
          <h1 class="slds-text-heading--medium">My Expenses</h1>
        </div>
      </div>
    </div>
    <!-- / PAGE HEADER -->

    <!-- NEW EXPENSE FORM -->
    <div class="slds-col slds-col--padded slds-p-top--large">

        <c:expenseForm/>

    </div>
    <!-- / NEW EXPENSE FORM -->

    <!-- EXISTING EXPENSES -->
    <div class="slds-grid slds-m-top--large">

        <!-- EXPENSES LIST -->
        <div class="slds-col slds-col-rule--right slds-p-around--small
            slds-size--8-of-12">
            <c:expensesList expenses="{!v.expenses}"/>
        </div>
        <!-- / EXPENSES LIST -->

        <!-- SOMETHING COOL -->
        <div class="slds-col slds-p-left--large slds-size--4-of-12">
            <!-- Bonus lesson, coming in July.
                 Watch this space for details. -->
        </div>
        <!-- / SOMETHING COOL -->

    </div>
    <!-- / EXISTING EXPENSES -->

</aura:component>
expenses controller:
({
    
handleCreateExpense: function(component, event, helper) {
    var newExpense = event.getParam("expense");
    helper.createExpense(component, newExpense);
},
    handleUpdateExpense: function(component, event, helper) {
    var updatedExp = event.getParam("expense");
    helper.updateExpense(component, updatedExp);
},




   // Load expenses from Salesforce
doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getExpenses");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            component.set("v.expenses", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
}
    
        }
    }
})
expenses halper:
({
   
  createExpense: function(component, expense) {
    this.saveExpense(component, expense, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var expenses = component.get("v.expenses");
            expenses.push(response.getReturnValue());
            component.set("v.expenses", expenses);
        }
    }
},

updateExpense: function(component, expense) {
    this.saveExpense(component, expense);
}


   
})


expenseList component:
<aura:component >

    <aura:attribute name="expenses" type="Expense__c[]"/>

    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Expenses</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.expenses}" var="expense">
                    <c:expenseItem expense="{!expense}"/>
                </aura:iteration>
            </div>
        </section>
    </div>

</aura:component>

expensesItem component:
<aura:component>
    <aura:attribute name="expense" type="Expense__c"/>
<aura:registerEvent name="updateExpense" type="c:expensesItemUpdate"/>

    <div class="slds-card">

        <!-- Color the item green if the expense is reimbursed -->
        <div class="{!v.expense.Reimbursed__c == true ?
            'slds-theme--success' : 'slds-theme--warning'}">

            <header class="slds-card__header slds-grid grid--flex-spread">
                <a aura:id="expense" href="{!'/' + v.expense.Id}">
                    <h3>{!v.expense.Name}</h3>
                </a>
            </header>

            <section class="slds-card__body">
                <div class="slds-tile slds-hint-parent">
                    <p class="slds-tile__title slds-truncate">Amount:
                        <ui:outputCurrency value="{!v.expense.Amount__c}"/>
                    </p>
                    <p class="slds-truncate">Client:
                        <ui:outputText value="{!v.expense.Client__c}"/>
                    </p>
                    <p class="slds-truncate">Date:
                        <ui:outputDate value="{!v.expense.Date__c}"/>
                    </p>
                    <p class="slds-truncate">Reimbursed?
                        <ui:inputCheckbox value="{!v.expense.Reimbursed__c}"
                            click="{!c.clickReimbursed}"/>
                    </p>
                </div>
            </section>
        </div>
    </div>

</aura:component>
expensesItem controller:
({
    clickReimbursed: function(component, event, helper) {
        var expense = component.get("v.expense");
        var upsertEvent = component.getEvent("updateExpense");
        upsertEvent.setParams({ "expense": expense });
        upsertEvent.fire();
    }
})

expenses form:
<aura:component >
    <aura:attribute name="newExpense" type="Expense__c"
     default="{ 'sobjectType': 'Expense__c',
                    'Name': '',
                    'Amount__c': 0,
                    'Client__c': '',
                    'Date__c': '',
                    'Reimbursed__c': false }"/>
    <aura:registerEvent name="createExpense" type="c:expensesItemUpdate"/>

    
	 <!-- CREATE NEW EXPENSE FORM -->
    <form class="slds-form--stacked">

      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="expname" label="Expense Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newExpense.Name}"
                  required="true"/>
          </div>
     </div>

     <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputNumber aura:id="amount" label="Amount"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newExpense.Amount__c}"
                  required="true"/>

          </div>
      </div>

      <div class="slds-form-element">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="client" label="Client"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newExpense.Client__c}"
                  placeholder="ABC Co."/>
          </div>
      </div>

      <div class="slds-form-element">
          <div class="slds-form-element__control">
              <ui:inputDate aura:id="expdate" label="Expense Date"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newExpense.Date__c}"
                  displayDatePicker="true"/>
          </div>
      </div>

      <div class="slds-form-element">
          <ui:inputCheckbox aura:id="reimbursed" label="Reimbursed?"
              class="slds-checkbox"
              labelClass="slds-form-element__label"
              value="{!v.newExpense.Reimbursed__c}"/>
      </div>

      <div class="slds-form-element">
          <ui:button label="Create Expense"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateExpense}"/>
      </div>

    </form>
    <!-- / CREATE NEW EXPENSE FORM -->

</aura:component>

expenseForm controller:
({
    clickCreateExpense: function(component, event, helper) {
    if(helper.validateExpenseForm(component)){
        // Create the new expense
        var newExpense = component.get("v.newExpense");
        helper.createExpense(component, newExpense);
    }

    
        }
    
})


expenseFrom Helper:
({
     validateExpenseForm: function(component) {

    // Simplistic error checking
    var validExpense = true;

    // Name must not be blank
    var nameField = component.find("expname");
    var expname = nameField.get("v.value");
    if ($A.util.isEmpty(expname)){
        validExpense = false;
        nameField.set("v.errors", [{message:"Expense name can't be blank."}]);
    }
    else {
        nameField.set("v.errors", null);
    }

    // Amount must be set, must be a positive number
    var amtField = component.find("amount");
    var amt = amtField.get("v.value");
    if ($A.util.isEmpty(amt) || isNaN(amt) || (amt <= 0.0)){
        validExpense = false;
        amtField.set("v.errors", [{message:"Enter an expense amount."}]);
    }
    else {
        // If the amount looks good, unset any errors...
        amtField.set("v.errors", null);
    }
    
    return(validExpense);
},
    createExpense: function(component, newExpense) {
    var createEvent = component.getEvent("createExpense");
    createEvent.setParams({ "expense": newExpense });
    createEvent.fire();
}


   
})

 

Although i finish the trailhead challange but record is not saved and getting following error: (please send answer with full code)

Something has gone wrong. Action failed: c$campingList$controller$clickCreateitems [TypeError: Cannot read property 'get' of undefined] Failing descriptor: {c$campingList$controller$clickCreateitems}. Please try again.
here is code


camping app:
<aura:application  >
 
    <!-- Include the SLDS static resource (adjust to match package version) -->
    <ltng:require styles="{!$Resource.SLDS100 +
         '/assets/styles/salesforce-lightning-design-system-ltng.css'}"/>
 
    <!-- Add the "scoping" element to activate SLDS on components
         that we add inside it. -->
    <div class="slds">
       
        <!-- This component is the real "app" -->
        <c:campingList />
       
    </div>
    <!-- / SLDS SCOPING DIV -->
 
</aura:application>

CampingList component:
<aura:component controller="CampingListController">
    
    <aura:attribute name="newitems" type="Camping_item__c"
     default="{ 'sobjectType': 'Camping_items__c',
                    'Name': '',
                    'Quantity__c': 0,
                    'Price__c': 0,
                    'Packed__c': false }"/>
    
    <aura:attribute name="itemss" type="Camping_item__c[]"/>
    
    <ol>
    <li>Bug Spray</li>
    <li>Bear Repellant</li>
    <li>Goat Food</li>
    </ol>
    
    <!-- CREATE NEW items FORM -->
    <form class="slds-form--stacked">

      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="itemsname" label="Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newitems.Name}"
                  required="true"/>
          </div>
     </div>

     <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputNumber aura:id="quantity" label="Quantity"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newitems.Quantity__c}"
                  required="true"/>

          </div>
      </div>

      <div class="slds-form-element">
          <div class="slds-form-element__control">
              <ui:inputCurrency aura:id="price" label="Price"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newitems.Price__c}"
                  />
          </div>
      </div>

      <div class="slds-form-element">
          <ui:inputCheckbox aura:id="packed" label="Packed?"
              class="slds-checkbox"
              labelClass="slds-form-element__label"
              value="{!v.newitems.Packed__c}"/>
      </div>

      <div class="slds-form-element">
          <ui:button label="Create Camping items"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateitems}"/>
      </div>

    </form>
    <!-- / CREATE NEW items FORM -->
    
   

    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">itemss</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.itemss}" var="items">
                    <c:campingListitem items="{!items}"/>
                </aura:iteration>
            </div>
        </section>
    </div>

</aura:component>

CampingListController

({
               // Load expenses from Salesforce
doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getitems");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            component.set("v.items", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
},
   
    clickCreateitems: function(component, event, helper) {

        // Simplistic error checking
        var validItem = true;

        // Name must not be blank
        var nameField = component.find("itemname");
        var itemname = nameField.get("v.value");
        if ($A.util.isEmpty(itemname)){
            validItem = false;
            nameField.set("v.errors", [{message:"Items name can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }
        
        // Quantity must not be blank
        var quantityField = component.find("quantity");
        var quantity = nameField.get("v.value");
        if ($A.util.isEmpty(quantity)){
            validItem = false;
            quantityField.set("v.errors", [{message:"Quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }

        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price)){
            validItem = false;
            priceField.set("v.errors", [{message:"Price can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }


        if(validItem){
            var newItem = component.get("v.newItems");
            console.log("Create item: " + JSON.stringify(newItems));
            //helper.createItem(component, newItems);
            //        var theItems = component.get("v.items");
 
        // Copy the expense to a new object
        // THIS IS A DISGUSTING, TEMPORARY HACK
        var newItem = JSON.parse(JSON.stringify(item));
 
        console.log("Items before 'create': " + JSON.stringify(theItems));
        theExpenses.push(newItems);
        component.set("v.expenses", theItems);
        console.log("Items after 'create': " + JSON.stringify(theItems));
        theItems.push(newItems);
        component.set("v.items", theItems);
             component.set("v.newItems", 
                          {'sobjectType' : 'Camping_Item__c',
                           'Name' : '',
                           'Quantity__c' : 0,
                           'Price__c' : 0,
                           'Packed__c' : false});
        
        }
  
    }
})

>campingListHelper
({
     
   createitems: function(component, items) {
    var action = component.get("c.saveitem");
    action.setParams({
        "items": items
    });
    action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var items = component.get("v.items");
            items.push(response.getReturnValue());
            component.set("v.items", items);
        }
    });
    $A.enqueueAction(action);
},
    validateExpenseForm: function(component) {

    // Simplistic error checking
    var validExpense = true;

    // Name must not be blank
    var nameField = component.find("itemname");
    var expname = nameField.get("v.value");
    if ($A.util.isEmpty(itemname)){
        validExpense = false;
        nameField.set("v.errors", [{message:"item name can't be blank."}]);
    }
    else {
        nameField.set("v.errors", null);
    }

    // Amount must be set, must be a positive number
    var priField = component.find("Price");
    var pri = priField.get("v.value");
    if ($A.util.isEmpty(pri) || isNaN(pri ) || (pri  <= 0.0)){
        validitems = false;
        priField.set("v.errors", [{message:"Enter an item price."}]);
    }
    else {
        // If the price looks good, unset any errors...
        priField.set("v.errors", null);
    }
    
    return(validitems);
},
   
})

campingList ApexController

public class CampingListController {
    
     @AuraEnabled
    public static List<Camping_Item__c> getItems () {
        // Perform isAccessible() checking first, then
        return [SELECT Id, Name, Packed__c, Price__c, Quantity__c
      
                FROM Camping_Item__c];
    }
    
    @AuraEnabled
public static Camping_Item__c    saveItem (Camping_Item__c items) {
        // Perform isUpdatable() checking first, then
        upsert items;
        return items;
    }

}

campingListItem:

<aura:component >
    <aura:attribute name="items" type="Camping_Item__c"/>
    
    <p>Name:
        <ui:outputText value="{!v.items.Name}"/>
    </p>
    <p>Quantity:
        <ui:outputNumber value="{!v.items.Quantity__c}"/>
    </p>
    <p>Price:
        <ui:outputCurrency value="{!v.items.Price__c}"/>
    </p>
    <p>Packed?:
        <ui:outputCheckbox value="{!v.items.Packed__c}"/>
    </p>
</aura:component>
 
i have used akansha code and mousin suggestion to remove space but still challange is not complete:
Callout Class
global class AnimalLocator
{
    public class Animal {
    public Integer id;
    public String name;
    public String eats;
    public String says;

    }
    
    public class AnimalResult {
    public Animal animal;
    }

    public Static String getAnimalNameById(integer id)
    {
        List<Object> animal;
        String returnValue ;
        AnimalResult result;
        Http http=new Http();
        HttpRequest request =new HttpRequest();
        request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        //request.setBody('{"id":"'+id+'"}');
        HttpResponse response= http.send(request);
        if(response.getStatusCode()==200)
        {
       result = (AnimalResult) JSON.deserialize(response.getBody(), AnimalResult.class);
       }
        return result.animal.name;

    }
    
}

MOCKResponse Class
@isTest
global class AnimalLocatorMock implements HttpCallOutMock
{
    public static HTTPResponse respond(HttpRequest req) 
    {
            HTTPResponse response =new HTTPResponse();
            response.setHeader('Content-Type', 'application/json');
            response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
            response.setStatusCode(200);

             return response;

    }

}

Test Class

@isTest
public class AnimalLocatorTest 
{
    public static testMethod void mytestMethod()
    {
        Test.SetMock(HttpCallOutMock.class,new AnimalLocatorMock());
        
         String res= AnimalLocator.getAnimalNameById(1);
       
        
        String expectedValue = 'chicken';
        System.assertEquals(res, expectedValue);
        


    }

Hi Guys
I have created a class for searching record .after searching record i need to export that record in excel format.i mean i need one export button ,on click of that button its automatically download that record in excel format
<apex:page docType="html-5.0" standardController="MasterCopy__c"  extensions="dateInPBTbaleControllernewOk"  showHeader="false" sidebar="false">

<apex:pageMessages ></apex:pageMessages>
<style type="text/css" media="print">
@media print
{
#non-printable { display: none; }
#printable {
display: block;
width: 100%;
height: 100%;
}
}
</style>

<style type = "text/css">
        .colHeadr {text-align:center;}
        .colHeadrRight{
            text-align:right;
        }
        }
    </style>


        <apex:define name="body">
            
            <div style="width:1000px;margin: 0px auto 10px auto;border: 1px solid black;">
    <apex:form id="tableId">
        <apex:pageBlock >
            
                    <b><apex:outputLabel value="Trial Balance Report On: "  style="font-weight: bold;color:red;"/></b>
                     <apex:inputField value="{!account.DateUpdate__c}" style="font-weight: bold;color:red;" required="false"/>
                     
                     
                   <!--- Trial Balance Report On: <apex:input type="date" value="{!dat}"/>-->
                 
                 <apex:commandButton value="Display" action="{!displaingTable}" reRender="tableId" style="font-weight: bold;color:red;" oncomplete="window.opener.location.refresh();" />
        <b><apex:commandLink id="printable"  onclick="JavaScript:window.print();" value="Print"/></b> <br/><br/><br/>
                
                 
                 <apex:outputPanel rendered="{!If(totalRevenue != totalRevenue1,true,false)}">
                 <apex:outputLabel style="font-weight: bold;color:red;font-size:15px;padding-left:49%"> Debit and Credit Balances do not match. </apex:outputLabel>
                 </apex:outputPanel>
                 
                 <apex:outputPanel rendered="{!If(account.DateUpdate__c== null,true,false)}">
                 <apex:outputLabel style="font-weight: bold;color:blue;font-size:15px;padding-left:1%" > Please enter date to fetch accurate results. </apex:outputLabel>
                 </apex:outputPanel>
                 
                 
                 
                 <apex:pageblockTable value="{!listAccount }" var="record">
               
                  <apex:column headerValue="Master Code" Value="{!record.Master_Name__c}" headerClass="colHeadr" style="font-weight: bold;font-size:12px;height=18px;text-align:center;">
                     <!----  <apex:column headerValue="Master Code">
                       <apex:outputPanel >
                            <apex:commandLink action="{!Go}">
                               {!record.Master_Name__c}<apex:param name="Id" value="{!record.id}"/>
                            </apex:commandLink>
                       </apex:outputPanel>
                    </apex:column>--->
                   
                   </apex:column>
                    <apex:column value="{!record.Master_Code__c}" headerValue="Master Name" headerClass="colHeadr" style="text-align:center;"/>
                    
                    
                    <apex:column value="{!record.Debit_Balance__c}" headerValue="Debit(+)" style="color:black;" headerClass="colHeadrRight" dir="RTL">
                     <apex:facet name="footer" >
        
                   <!---- <apex:outputText value=" Rs.{!totalRevenue}<br/> Rs.{!totalRevenuee}<br/>-----------------<br/> Rs.{!totalRevenuee1}" style="font-weight: bold;color:green;font-size:12px;height=18px;" escape="false">
                      
                       
                    </apex:outputText>-->
                    <apex:outputText value="Rs.{0, number, ###,###,###,##0.00}"  style="font-weight: bold;color:black;font-size:12px;height=18px;float:right;"  >
                        <apex:param value="{!totalRevenue}"  />
                    </apex:outputText> 
                </apex:facet>
            </apex:column>
                    <apex:column value="{!record.Credit_Balance__c}" headerValue="Credit(-)" style="color:black;"  headerClass="colHeadrRight" dir="RTL">
                    <apex:facet name="footer" >
                   
                        
                   <apex:outputText value="Rs.{0, number, ###,###,###,##0.00}"  style="font-weight: bold;color:black;font-size:12px;height=18px;float:right;"  >
                        <apex:param value="{!totalRevenue1}"  />
                    </apex:outputText> 
                </apex:facet>
                 
            </apex:column>
            
           
          
                    </apex:pageblockTable>
                            
                    
        </apex:pageBlock>
    </apex:form>
    
      
      </div>
        </apex:define>
</apex:page>
public with sharing class dateInPBTbaleControllernewOk {
    public MasterCopy__c account{get;set;}
    public List<MasterCopy__c> listAccount {get;set;}
    public Double totalRevenue {get;set;}
    public Double totalRevenue1 {get;set;}
    public Double totalRevenuee {get;set;}
    public Double totalRevenuee1 {get;set;}
   
    public Date dat {get;set;}
    
    public Map<Date,List<MasterCopy__c>> mapOfDateWithEntry;

    public dateInPBTbaleControllernewOk(ApexPages.StandardController controller){
    
        account = new MasterCopy__c();
        totalRevenue = 0;
        totalRevenue1 = 0;
        totalRevenuee = 0;
        totalRevenuee1 = 0;
        
    }
     
   public void setValues(){
        listAccount  = new List<MasterCopy__c>([SELECT id,Name,  Closing_Balance__c,Credit__c,Date__c,DateUpdate__c,Debit__c,Debit_Balance__c,Credit_Balance__c,
        Group__c,Master_Code__c,Master_Name__c,New_Debit__c,New_Credit__c
                        FROM MasterCopy__c
                        order by Master_Name__c ASC ]);
        mapOfDateWithEntry = new Map<Date,List<MasterCopy__c>>();
        List<MasterCopy__c> listOfEntryData;
        for(MasterCopy__c entry : listAccount){
            if(entry.DateUpdate__c != null){
                if(mapOfDateWithEntry.containsKey(entry.DateUpdate__c)){
                    mapOfDateWithEntry.get(entry.DateUpdate__c).add(entry);
                }
                else{
                    listOfEntryData = new List<MasterCopy__c>();
                    listOfEntryData.add(entry);
                    mapOfDateWithEntry.put(entry.DateUpdate__c,listOfEntryData);
                }
            }
        }
        calculateTotalRevenue();
        calculateTotalRevenue1();
        calculateTotalRevenue2();
   }
   public void displaingTable(){
   
   
   try{
   
        setValues();
        
        
        
 
        if(account.DateUpdate__c!= null){
            totalRevenue = 0;
            totalRevenue1 = 0;
            totalRevenuee = 0;
            totalRevenuee1 = 0;
            system.debug('Map '+mapOfDateWithEntry);
            Set<Date> allDateSet = mapOfDateWithEntry.keySet();
            if(allDateSet.contains(account.DateUpdate__c)){
                listAccount = mapOfDateWithEntry.get(account.DateUpdate__c);
            }
            else {
                List<Date> sortedDateList = new List<Date>();
                sortedDateList.addAll(allDateSet);
                sortedDateList.sort();
                
                Boolean isAnyPastDate = false;
                Date requiredDate;
                for(Date recordDate : sortedDateList){
                    if(account.DateUpdate__c > recordDate){
                        requiredDate = recordDate;
                        isAnyPastDate = true;
                    }
                    else{
                        break;
                    }
                }
                if(isAnyPastDate){
                    listAccount = mapOfDateWithEntry.get(requiredDate);
                }
                else{
                    listAccount = new List<MasterCopy__c>();
                }
                /*Date compareDate ;
                Integer count = 0;
                for(Date firstKeydate : allDateSet){
                    compareDate = firstKeydate;
                    break;
                }
                system.debug('Before Compare Date'+compareDate);
                for(Date keyDate : allDateSet){
                    if(keydate < account.DateUpdate__c && keydate > compareDate){
                        compareDate = keyDate;
                    }
                    if(account.DateUpdate__c < keyDate){
                        count ++ ;
                    }
                }
                system.debug('After Compare Date'+compareDate);
                Date requiredDate ;
                
                if(allDateSet.size() == count){
                    requiredDate = [Select DateUpdate__c from MasterCopy__c Order by DateUpdate__c Desc LIMIT 1][0].DateUpdate__c;
                }
                else {
                    requiredDate = compareDate;
                }
                listAccount = mapOfDateWithEntry.get(requiredDate);*/
            }
        }
       calculateTotalRevenue();
        calculateTotalRevenue1();
        calculateTotalRevenue2(); 
    
    }
    
    catch(Exception e)
        {  
        //ApexPages.Message myMsg = new  ApexPages.Message(ApexPages.Severity.ERROR,'Sorry...... You have entered DUPLICATE MASTER CODE' );
           // ApexPages.addMessage(myMsg); 
         
           Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,' NO RECORD FOUND'));
       }
       } 
     public void calculateTotalRevenue() {
     //for(MasterCopy__c acct2 : listAccount) {
           // if(acct2.Closing_Balance__c!= null)
               // totalRevenuee= acct2.Closing_Balance__c;
                //}
        for(MasterCopy__c acct : listAccount) {
            if(acct.Debit_Balance__c!= null)
                totalRevenue+= acct.Debit_Balance__c;
                
                }
totalRevenuee1=totalRevenuee+totalRevenue;
             
       
        
    }
    
    
    
    public void calculateTotalRevenue2() {
        for(MasterCopy__c acct2 : listAccount) {
            if(acct2.Closing_Balance__c!= null)
                totalRevenuee= acct2.Closing_Balance__c;
            
              
        }
        
    }
    public void calculateTotalRevenue1() {
        for(MasterCopy__c acct1 : listAccount) {
            if(acct1.Credit_Balance__c!= null)
                totalRevenue1+= acct1.Credit_Balance__c;
                 
               
        }
        
    }
    
    
}


 
Hi everyone!
I have a problem with the challenge, my App work fine but I don´t pass the challenge. This is my code:

campingList.cmp:
 
<aura:component controller="CampingListController">
    
    <ltng:require styles="/resource/SLDS105/assets/styles/salesforce-lightning-design-system-ltng.css"/>

	<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
     <aura:attribute name="newItem" type="Camping_Item__c"
     default="{ 'sobjectType': 'Camping_Item__c',
                    'Price__c': 0,
                    'Quantity__c': 0}"/>
    
    <div class="slds-card slds-p-top--medium">
    <ui:inputText aura:id="campname" label="Camping Name"
        value="{!v.newItem.Name}" required="true"/>
    <ui:inputCheckbox aura:id="packed" label="Packed?"
        value="{!v.newItem.Packed__c}"/>
     <ui:inputCurrency aura:id="price" label="Price"
        value="{!v.newItem.Price__c}" required="true"/>
     <ui:inputNumber aura:id="quantity" label="Quantity"
        value="{!v.newItem.Quantity__c}" required="true"/>
    
    <ui:button label="Create Camping" press="{!c.clickCreateCamping}"/>
    </div>
    
    <aura:attribute name="items" type="Camping_Item__c[]"/>	 
    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Campings</h3>
        </header>
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="item">
                    <c:campingListItem item="{!item}"/>
                </aura:iteration>
            </div>
        </section>
    </div>
</aura:component>

campingListController.js:
 
({
    
    // Load expenses from Salesforce
	doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getItems");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            component.set("v.items", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
	},
    
    clickCreateCamping: function(component, event, helper) {
        
        if(helper.validateCampingForm(component)){
	        // Create the new expense
	        var newCamping = component.get("v.newItem");
	        helper.createItem(component, newCamping);
	    }
    }
})
campingListHelper.js
 
({
    
    createItem: function(component, camping) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": camping
        });
    	action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var campings = component.get("v.items");
            campings.push(response.getReturnValue());
            component.set("v.items", campings);
        }
    	});
    	$A.enqueueAction(action);
    },
    
    validateCampingForm: function(component) {
      
     	var validQuantity = true;
        var validPrice = true;

        var nameField = component.find("campname");
        var campname = nameField.get("v.value");
        
        var quantityField = component.find("quantity");
        var quantity = quantityField.get("v.value");
        
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        
        if ($A.util.isEmpty(campname) || $A.util.isEmpty(quantity) || $A.util.isEmpty(price)){
            validQuantity = false;
            validPrice = false;
            nameField.set("v.errors", [{message:"Camping name, quantity or price can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }
		
		return(validQuantity && validPrice);        
	}
})
CampingListController.apxc:
 
public with sharing class CampingListController {

    @AuraEnabled
    public static List<Camping_Item__c> getItems() {
    
        // Check to make sure all fields are accessible to this user
        String[] fieldsToCheck = new String[] {
            'Id', 'Name', 'Packed__c', 'Price__c', 'Quantity__c'
        };
        
        Map<String,Schema.SObjectField> fieldDescribeTokens = 
            Schema.SObjectType.Camping_Item__c.fields.getMap();
        
        for(String field : fieldsToCheck) {
            if( ! fieldDescribeTokens.get(field).getDescribe().isAccessible()) {
                throw new System.NoAccessException();
                return null;
            }
        }        
        
        // Perform isAccessible() checking first, then
        return [SELECT Id, Name, Packed__c, Price__c, Quantity__c 
                FROM Camping_Item__c];
    }
    
    @AuraEnabled
    public static Camping_Item__c saveItem(Camping_Item__c item) {
        // Perform isUpdatable() checking first, then
        upsert item;
        return item;
    }
}
I am still getting this error:

Challenge Not yet complete... here's what's wrong:
The campingList JavaScript helper isn't saving the new record to the database or adding it to the 'items' value provider.


My App save the new record into the database and add it to the "items" list.
Thanks for your answers!




 
Hi all, 

I have a problem with this challenge :

Create a Queueable Apex class that inserts the same Contact for each Account for a specific state. Write unit tests that achieve 100% code coverage for the class.
Create an Apex class called 'AddPrimaryContact' that implements the Queueable interface.
Create a constructor for the class that accepts as its first argument a Contact sObject and a second argument as a string for the State abbreviation.
The execute method must query for a maximum of 200 Accounts with the BillingState specified by the State abbreviation passed into the constructor and insert the Contact sObject record associated to each Account. Look at the sObject clone() method.
Create an Apex test class called 'AddPrimaryContactTest'.
In the test class, insert 50 Account records for BillingState "NY" and 50 Account records for BillingState "CA". Create an instance of the AddPrimaryContact class, enqueue the job and assert that a Contact record was inserted for each of the 50 Accounts with the BillingState of "CA".
The unit tests must cover all lines of code included in the AddPrimaryContact class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.


I haven't 100% for my test class. 
 
@isTest
 public class AddPrimaryContactTest {
   
   
     @isTest static void TestList(){
         List<Account> Teste = new List <Account>();
         for(Integer i=0;i<50;i++){
             
             Teste.add(new Account(BillingState = 'CA', name = 'Test'+i));
         }
             for(Integer j=0;j<50;j++){
             
             Teste.add(new Account(BillingState = 'NY', name = 'Test'+j));
         
         }
         insert Teste;
         Contact co = new Contact();
          String state = 'CA';
     AddPrimaryContact apc = new AddPrimaryContact(co, state);
	Test.startTest();
	System.enqueueJob(apc);
     Test.stopTest();
         for (Account t:Teste){
             if( t.BillingState == 'CA'){
               	  
             	System.assertEquals(1, t.Number_of_contacts__c);
            
             
         }
         }      
}
 }
 
public class AddPrimaryContact implements Queueable{
    private Contact c;
    private String state;
    public  AddPrimaryContact(Contact c, String state){
        this.c = c;
        this.state = state;
        
    }
     public void execute(QueueableContext context) {
        List<Account> ListAccount = [SELECT ID, Name FROM ACCOUNT WHERE BillingState = :state LIMIT 200];
         for (Account l:ListAccount){
             for (Contact co:l.Contacts){
                 
                 c = co.clone(false,false,false,false);
                 insert c;
             }
                 
                 
             }
             
         }

}


Anyone can help me please?
Thanks!
Hello everyone I could use some help on the using future Methods trailhead. Please keep in mind I am not an Apex coder at all but I am trying to learn as much as I can.

Here is the Task

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

I have written an Apex class and a Test class but I think I am doing them both Wrong: because when I try to check the challenge i Get this error

Challenge Not yet complete... here's what's wrong: 
The 'AccountProcessorTest' test class doesn't appear to be calling the 'AccountProcessor.countContacts' method between Test.startTest() and Test.stopTest().


When I run the Test class I get this error :

System.QueryException: List has no rows for assignment to SObject

Here is the CLASS:
 
public class AccountProcessor {
     @future

  public static void someFutureMethod(List<id> scope) {

   Account[] updates = new Account[] {};
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            updates.add(new Account(
                    Id = (Id) ar.get('a'),
                    Number_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update updates;
    }

}

Here is the Test Class:
 
@IsTest
public class AccountProcessorTest {
  public static testmethod void TestAccountProcessorTest() {
 
Test.startTest();
     Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
      
      Contact cont = New Contact();
      
      cont.FirstName ='Bob';
      cont.LastName ='Masters';
      cont.AccountId = a.Id;
      Insert cont;

    Test.stopTest() ;
     Contact ACC = [select AccountId from Contact where id = :a.id LIMIT 1];

 
        System.assert(Cont.AccountId != null);
        System.assertequals(cont.id, ACC.AccountId);

  }}

I have used alot or diffrent google searches to get me this far. But I have not Idea if Im even remotly close to the right answer or not.


 
Hi All,

I am doing Apex Rest Callouts in Trailhead Apex Integration Service Module.
https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_services/apex_integration_rest_callouts

This is AnimalLocator class.
public class AnimalLocator{
    public static String getAnimalNameById(Integer x){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + x);
        
        req.setMethod('GET');
        
        HttpResponse res = h.send(req);
        Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        Map<String, Object> animal = (Map<String, Object>) results.get('animal');
        return (String)animal.get('name');
    }
}
However, I was encountered this error when checking challenge.
Challenge Not yet complete... here's what's wrong: 
The Apex class does not appear to be calling the REST endpoint using HttpRequest.
I have no idea what it means, but I have call the REST endpoint.
  • December 24, 2015
  • Like
  • 0
Hi All,

Can anyone please help me with bellow challenge.


Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.
For this challenge, you need to create a trigger that, before insert or update, checks for a checkbox, and if the checkbox field is true, sets the Shipping Postal Code (whose API name is ShippingPostalCode) to be the same as the Billing Postal Code (BillingPostalCode).The Apex trigger must be called 'AccountAddressTrigger'.
The Account object will need a new custom checkbox that should have the Field Label 'Match Billing Address' and Field Name of 'Match_Billing_Address'. The resulting API Name should be 'Match_Billing_Address__c'.
With 'AccountAddressTrigger' active, if an Account has a Billing Postal Code and 'Match_Billing_Address__c' is true, the record should have the Shipping Postal Code set to match on insert or update.

For above challenge i tried with following code but looks like it doesnt mach the requirement.

trigger AccountAddressTrigger on Account (before insert, before update) {
    for(Account a : Trigger.new){
        If (a.Match_Billing_Address__c = true) {
            /*ShippingPostalCode = BillingPostalCode;*/
        }   
    } 

}

Please help me

Hey community,

I'm struggling with the logic of the task...

To complete this challenge, add a validation rule which will block the insertion of a contact if the contact is related to an account and has a mailing postal code (which has the API Name MailingPostalCode) different from the account's shipping postal code (which has the API Name ShippingPostalCode).Name the validation rule 'Contact must be in Account ZIP Code'.

A contact with a MailingPostalCode that has an account and does not match the associated Account ShippingPostalCode should return with a validation error and not be inserted.

The validation rule should ONLY apply to contact records with an associated account. Contact records with no associated parent account can be added with any MailingPostalCode value. (Hint: you can use the ISBLANK function for this check)

Here is what I got so far:

AND(
 NOT(ISBLANK(MailingPostalCode)),
 MailingPostalCode  <>  Account.ShippingPostalCode )

I THINK I know how to see if the contact mailing zip is not the same as the account shipping zip, and only if the is not blank.

The part I am stuck on is if the "Contact records with no associated parent account can be added with any MaiilingPostalCode value"...

I don't know what to do with that.

Also, I am now getting the error message when I recheck challenge:

Challenge not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Contact_must_be_in_Account_ZIP_Code: [] 


Double help, please.