• Chelsea Lukowski
  • NEWBIE
  • 100 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 27
    Questions
  • 26
    Replies
I am trying to create a lightning componet for my Warranty Claim Case layout. On the case layout, I want to show a card of each record from a related object(Warranty_Claim_Line_Item__c) with a preview of the files attached to each of those records. I have the component setup to show the cards but the images are repeating for each record. I just need some advise on how to get only the images associated to each Warranty_Claim_Line_Item__c on the corresponding card. Below is my code. 
 
<aura:component implements="flexipage:availableForRecordHome,force:appHostable,lightning:actionOverride,force:hasRecordId" controller="warrantyLineItemRecordsCtrl">
   <aura:attribute name="lineItems" type="Warranty_Claim_Line_Item__c[]"/>
    <aura:attribute name="recordId" type="Id"/>  
    <aura:attribute name="filesIds" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.loadLineItems}"/>
    <aura:iteration items="{!v.lineItems}" var="l" indexVar="key">
        <lightning:card title="{!l.Name}">
            <aura:set attribute="actions">
                <lightning:button label="Edit" onclick="{!c.edit}" name="{!l.Id}"/>
            </aura:set>
            
            <div class="slds-grid slds-p-left_medium">
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Tire Description</h4>
                        <p><strong>Product Description</strong>:</p><p> {!l.Product__r.Name}</p>
                        <p><strong>Product Weight</strong>:<br/> {!l.Product_Weight__c} LBS</p>
                        <p><strong>Application Use</strong>: {!l.Application__c}</p>
                        <p><strong>Serial Number</strong>: {!l.Serial__c}</p>
                        <p><strong>Manufacturer Date</strong>: {!l.Manufacturer_Date__c}</p>
                        <p><strong>Removed Serial</strong>:</p>
                        <div class="row">
                        </div>
                    </div>
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Purchasing Information</h4>
                        <p><strong>How You Got Your Tire</strong>: {!l.Original_Purchase__c}</p>
                        <p><strong>Purchase Date</strong>: {!l.Purchase_Date__c}</p>
                        <p><strong>Purchased New/Used</strong>:{!l.Purchased_New_or_Used__c}</p>
                        <p><strong>Selling Dealer</strong>: {!l.Selling_Partner_Account_Name__c}</p>
                        
                        <h4 class="slds-text-heading_small">Original Equipment Information</h4>
                        <p><strong>Make</strong>: {!l.Machine_Make__c}</p>
                        <p><strong>Model</strong>: {!l.Machine_Model__c}</p>
                        <p><strong>Year</strong>: {!l.Machine_Year__c}</p>
                        <p><strong>Equipment Hours</strong>: {!l.Machine_Hours__c}</p>
                        <p><strong>Equipment Serial Number</strong>: {!l.Machine_Serial_Number__c}</p> 
                        
                        <h4 class="slds-text-heading_small">Proof of Purchase</h4>
                        <div class="row"></div>
                        <h4 class="slds-text-heading_small">Service and Labor Costs</h4>
                        <p>{!l.Service_and_Labor_Cost__c}</p>                
                    </div>
                    <div  class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Issue with Tire</h4>
                        <p><strong>Defect Location</strong>: {!l.Defect_Location__c}</p>
                        <p><strong>Defect Type</strong>: {!l.Defect_Type__c}</p>
                        <p><strong>Tire Position</strong>: {!l.Tire_Position__c}</p>
                        <h4 class="slds-text-heading_small">Inspection Condition</h4>
                        <p><strong>Tire Hours</strong>: {!l.Tire_Hours__c}</p>
                        <p><strong>Tread Depth</strong>: {!l.Tread_Depth__c}</p>
                        <p><strong>Inflation</strong>: {!l.Tire_Inflation__c}</p>
                        <p><strong>Additional Comments</strong>: {!l.Issue_Additional_Comments__c}</p>
                        <h4 class="slds-text-heading_small">Evidence of Condition</h4>
                        <div>                            
                            <aura:iteration items="{!v.fileIds}" var="t">
                                <lightning:fileCard fileId="{!t.ContentDocumentId}" description="{!t.ContentDocument.title}"/>
                            </aura:iteration>
                        </div>
                        <h4 class="slds-text-heading_small">Proof of Stubble Stomper Purchase</h4>
                        <div class="row"></div>
                    </div>
                </div>
        </lightning:card>
    </aura:iteration>
    
</aura:component>
 
({
    loadLineItems : function(component, event, helper) {
        var action = component.get("c.getLineItems");
        action.setParams({
            MasterRecordId: component.get("v.recordId")
        });
        action.setCallback(this, function(response){
            if(response.getState()==="SUCCESS" && component.isValid()){
                component.set("v.lineItems",response.getReturnValue());
                console.log(JSON.parse(JSON.stringify(response.getReturnValue())));
            }
        });getWarrantyWithContent
        
        $A.enqueueAction(action);
        
        
        var action = component.get("c.fetchFiles");
        action.setParams({
            MasterRecordId : component.get("v.recordId")            
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state == "SUCCESS"){
                var result = response.getReturnValue()
                component.set("v.filesIds",result);
                console.log(result);
            }
        });	
        $A.enqueueAction(action); 
    }, 
    
     edit : function(component, event, helper) {
       var editRecordEvent = $A.get("e.force:editRecord");
         var recordId = event.getSource().get("v.name");
         
         console.log("record id: " + recordId);
        editRecordEvent.setParams({
            "recordId": recordId
        });
        editRecordEvent.fire();
    
    }
    
})
 
@AuraEnabled
    public static List<ContentDocumentLink> fetchFiles(String MasterRecordId){
        System.debug('MasterRecordId - - - - - - ' + MasterRecordId);
        return  [SELECT ContentDocumentId,ContentDocument.title,ContentDocument.LatestPublishedVersion.Warranty_Type__c 
                 FROM ContentDocumentLink 
                 WHERE ContentDocument.LatestPublishedVersion.Warranty_Type__c = 'Evidence' 
                 AND  LinkedEntityId IN (Select Id FROM Warranty_Claim_Line_Item__c WHERE Warranty_Case__c =: MasterRecordId)];        
    }

 
I have a batch job that takes a Salesforce Report and emails an Excel file to a group of addresses. The users are not Salesforce users. The batch job is working perfectly but when the email goes out it shows ALL the email addresses in the To field. Is there a way to hide the email addresses so that it shows on the receipents address but still sends to everyone in the list?
I have a visualforce page used to search for products and calculate a price, when the list populates I want it to display fields from a related list called Inventory. Sometimes there are more than one inventory record to the product and sometimes there are no inventory records to products. If there are no records, I want it to just display the Product infromation. If there are more than one child record, I would like it to diplay both child records on seperate rows. 

Parent Object: Product2
Child Object: Inventory__c

Here is my visualforce page:
<apex:page Controller="ProductPricingInventoryMobileController" standardStylesheets="false"  readOnly="true" docType="html-5.0" >
    <apex:form >
        <apex:tabPanel switchType="client" selectedTab="sch" id="dataTabPanel"  tabClass="myActiveTab" inactiveTabClass="myInactiveTab">
            <apex:tab label="Inventory" name="Inventory Search" id="sch" >
                <br/>
                <apex:outputPanel id="idToRerenderInv">
                    <apex:outputLabel for="input" value="Search:" styleClass="fieldLabel"></apex:outputLabel>&nbsp;&nbsp;
                    <apex:input id="input" value="{!searchstring}" label="Input"/> 
                    <br/>
                    <br/>
                    <apex:commandButton value="Go" action="{!search}" rerender="idToRerenderInv" styleClass="buttonStyle"/> 
                    <apex:commandButton value="Clear" action="{!clear}" rerender="idToRerenderInv" styleClass="buttonStyle"/> 
                    <br/>
                    <br/>
                    <h1>
                        Search Results
                    </h1> 
                    <apex:outputPanel id="invtext" style="width:100%" rendered="{!AND(invList.size=0,searchstring != '')}" styleclass="noDisplay"> 
                        No records to display
                    </apex:outputPanel>
                    <br/>
                    <br/>
                    <c:ProductPricingInventoryMobileComponent />
                    <table>
                        <tr>
                            <th>Product Code</th>
                            <th>Available</th>
                            <th>List Price</th>
                            <th>Warehouse</th>
                            <th>Weight Per U/M</th>
                        </tr>
                        <apex:repeat value="{!invList}" var="i">
                            <tr>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Product__r.ProductCode}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Available__c}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">${!i.Product__r.Standard_Price__c}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Warehouse__c}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Weight_Per_U_M__c}</td>
                            </tr>                    
                        </apex:repeat>
                    </table>
                </apex:outputPanel>
            </apex:tab> 
            <apex:tab label="Pricing" name="Pricing Calculator" id="sch2">
                <br/>
                <apex:outputPanel id="idToRerender">
                    <apex:outputLabel for="criteria" value="Product Code:" styleClass="fieldLabel"></apex:outputLabel>&nbsp;&nbsp;
                    <apex:input id="criteria" value="{!productsearchstring}" label="Input" styleClass="inputfields" /> 
                    <br/>
                    <br/>
                    <apex:outputLabel for="discountlist" value="On-Factor:" styleClass="fieldLabel"></apex:outputLabel>&nbsp;&nbsp;
                    <apex:selectList id="discountlist" value="{!discountsearchstring}" size="1" label="On-Factor:">
                        <apex:SelectOption itemValue="0.0" itemLabel=""/>
                        <apex:SelectOption itemValue=".35" itemLabel=".35"/>
                        <apex:SelectOption itemValue=".419" itemLabel=".419"/>
                        <apex:SelectOption itemValue=".432" itemLabel=".432"/>
                        <apex:SelectOption itemValue=".437" itemLabel=".437"/>
                        <apex:SelectOption itemValue=".45" itemLabel=".45"/>
                        <apex:SelectOption itemValue=".478" itemLabel=".478"/>
                        <apex:SelectOption itemValue=".50" itemLabel=".50"/>
                        <apex:SelectOption itemValue=".51" itemLabel=".51"/>
                        <apex:SelectOption itemValue=".52" itemLabel=".52"/>
                        <apex:actionSupport event="onchange" action="{!query}" rerender="idToRerender"/>
                    </apex:selectList> 
                    <br/>
                    <br/>
                    <apex:commandButton value="Go" action="{!query}" rerender="idToRerender" styleClass="buttonStyle"/> 
                    <apex:commandButton value="Clear" action="{!clearProducts}" rerender="idToRerender" styleClass="buttonStyle"/>
                    
                    <br/>
                    <br/>
                    <h1>
                        Search Results
                    </h1>
                    <apex:outputPanel id="opformofauth" style="width:100%" rendered="{!AND(ProdList.size=0,productsearchstring!='')}" styleclass="noDisplay"> 
                        No records to display
                    </apex:outputPanel>
                    <br/>
                    <br/>
                    <table>
                        <tr>
                            <th>Product Code</th>
                            <th>Name</th>
                            <th>Price</th>
                            <th>Available</th>
                            <th>Warehouse</th>
                        </tr> 
                        <apex:repeat value="{!prodList}" var="p">
                            <tr>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.ProductCode}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.Name}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">
                                    ${!ROUND(IF(discountsearchstring != 0  , discountsearchstring * p.Standard_Price__c, p.Standard_Price__c ),2)}
                                </td>
                                <apex:repeat value="{!p.Inventory__r}" var="inv">
                                    <td  style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!inv.Available__c}</td>
                                    <td  style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!inv.Warehouse__c}</td>
                                </apex:repeat> 
                            </tr> 
                        </apex:repeat>                         
                    </table>
                </apex:outputPanel>
            </apex:tab>
        </apex:tabPanel> 
    </apex:form> 
</apex:page>

Here is my controller:
public class ProductPricingInventoryMobileController {
    
    public string searchstring {
        get {return searchstring;}
        set {searchstring = value;}
    }
    public list<Inventory__c> invList {get;set;}
    
    public string productsearchstring {
        get {return productsearchstring;}
        set {productsearchstring = value;}
    }
    public double discountsearchstring {get;set;}
    public list<Product2> prodList {get;set;}
        
    public PageReference search(){
        String searchResults = '%' + searchstring + '%';
        system.debug('search Results - ' + searchstring);
        if(searchstring != Null){
            invList = [select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id 
                       from Inventory__c 
                       where Lookup_Key__c LIKE: searchResults ORDER BY Product__r.ProductCode ASC]; 
        }else{
            invList = [select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id 
                       from Inventory__c ORDER BY Product__r.ProductCode ASC];
        }
        system.debug('invList = ' + invList.size());
        system.debug('invList = ' + invList);
        
        return null;
    }
    
    public PageReference query() {
        String productsearchResults = '%' + productsearchstring + '%';
        system.debug('Search String - ' + productsearchstring );
        if(productsearchstring == Null || productsearchstring == ''){
            
            prodList = [select Name,ProductCode,Search_String__c,(Select Id,Product__c,Warehouse__c,Available__c FROM Inventory__r ),Include_in_Price_Book__c,Inventory_Count__c, Standard_Price__c 
                        from Product2 
                        where (Material_Type__c !='Yes' OR Obsolete__c != 'Yes') AND Standard_Price__c < 99999.99 AND Include_in_Price_Book__c = true ORDER BY ProductCode ASC];
        }else{
             
            prodList = [select Name, ProductCode,Search_String__c,Include_in_Price_Book__c,(Select Id,Warehouse__c,Available__c FROM Inventory__r),Inventory_Count__c, Standard_Price__c 
                        from Product2 
                        where (Material_Type__c !='Yes' OR Obsolete__c != 'Yes') AND Standard_Price__c < 99999.99 AND ProductCode LIKE: productsearchResults ORDER BY ProductCode ASC];
        }
        system.debug('prodList = ' + prodList.size());
        system.debug('prodList = ' + prodList);
        
        return null;
    }    
    
    public void clearProducts(){
        system.debug('prodList - ' + prodList.size());
        if(prodList.size() > 0){
            productsearchstring = '';
            discountsearchstring = 0.0;
            prodList.clear();  
        }else {
            productsearchstring = '';
            discountsearchstring = 0.0;
        }
    }
    
    public void clear(){
        searchstring = '';
        invList.clear();
    } 
}

This is what it looks like now:
User-added image

​I would like the highlighted line to display 2 lines. One with 72 and 62 in the last two columns and the second line with 50 and 47 in the las two columns. 
 
I am working on a Visualforce page for Salesforce1 and I need some ideas on how to get a picklist on the page since <apex:SelectList> is not supported. The value that is choosen in the picklist will recalculate pricing on the screen. Any ideas on how to create the picklist so it works on both the desktop and SF1?
I need some advise. I am creating a visualforce page where a user can search for a product and see a price, then they can select a percentage to take off that price and the page would recalculate the price times that percentage. I can get the searh to work and a price to show up but it displays the same price for all products.

This is the Class i currently have:
public class ProductInventoryMobileController {
    
    public string searchstring {get;set;}
    public list<Inventory__c> invList {get;set;}
    
    public double discountsearchstring {get;set;}
    public list<Product2> prodList {get;set;}
    public Double dealerPrice {get; set;}
    
    public void search(){
        if(searchstring != Null){
            system.debug('Search String -' + searchstring);
            string searchquery = 'select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id from Inventory__c where Lookup_Key__c LIKE \'%'+searchstring+'%\' ORDER BY Product__r.ProductCode ASC';
            invList = Database.query(searchquery); 
        }else{
            invList = Database.query('select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id from Inventory__c ORDER BY Product__r.ProductCode ASC');
        }
    }
    
    public List<Product2> searchProduct(){        
        string searchquery = 'select Name, ProductCode,Search_String__c,Inventory_Count__c, Standard_Price__c from Product2 where Standard_Price__c < 99999.99 AND ProductCode LIKE \'%'+searchstring+'%\' ORDER BY ProductCode ASC';
        system.debug('Discount String - ' + discountsearchstring);
        dealerPrice = 0;
        for(Product2 p: database.query(searchquery) ){
            if(discountsearchstring != 0.0){
        		dealerPrice = discountsearchstring * p.Standard_Price__c;
                system.debug('dealer price - '+ dealerPrice); 
            }else {
                dealerPrice = p.Standard_Price__c;
                system.debug('dealer price - '+ dealerPrice);
            }
        }
        prodList = database.query(searchquery);
        return ProdList;
    }
    
    public pageReference returnProducts(){
        searchProduct();
        return null;
    }
    
    public void clearProducts(){
        searchstring = '';
        prodList.clear();
    }
    
    public void clear(){
        searchstring = '';
        invList.clear();
    }
}
This is the visualforce page:
<apex:page Controller="ProductInventoryMobileController" standardStylesheets="false" readOnly="true" docType="html-5.0">
    
    <apex:form >
        <apex:tabPanel switchType="client" selectedTab="sch" id="dataTabPanel">
            <apex:tab label="Inventory" name="Inventory Search" id="sch">
                <br/>
                <apex:inputText value="{!searchstring}" label="Input"/> 
                <apex:commandButton value="Search" action="{!search}"/> 
                <apex:commandButton value="Clear" action="{!clear}"/> 
                <p>
                    Search Results
                </p> 
                <c:ProductInventoryMobile />
                <table>
                    <tr>
                        <th>Product Code</th>
                        <th>Available</th>
                        <th>List Price</th>
                        <th>Warehouse</th>
                        <th>Weight Per U/M</th>
                        
                    </tr>
                    <apex:repeat value="{!invList}" var="i">
                        <tr>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Product__r.ProductCode}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Available__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">${!i.Product__r.Standard_Price__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Warehouse__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Weight_Per_U_M__c}</td>
                        </tr>                    
                    </apex:repeat>
                </table>
            </apex:tab>
            <apex:tab label="Pricing" name="Pricing Calculator" id="sch2">
                <br/>
                <apex:inputText value="{!searchstring}" label="Input"/> 
                <apex:commandButton value="Search" action="{!returnProducts}"/> 
                <apex:commandButton value="Clear" action="{!clearProducts}"/> 
                <br/>
                <apex:outputLabel for="discount" value="On-Factor:"></apex:outputLabel>&nbsp;&nbsp;&nbsp;
                    <apex:selectList id="discount" value="{!discountsearchstring}" size="1" label="On-Factor:">
                        	<apex:SelectOption itemValue="0.0" itemLabel=""/>
                            <apex:SelectOption itemValue=".45" itemLabel="45"/>
                            <apex:SelectOption itemValue=".44" itemLabel="44"/>
                            <apex:SelectOption itemValue="54" itemLabel="54"/>
                            <apex:SelectOption itemValue="60" itemLabel="60"/>
                     <apex:actionSupport event="onchange" action="{!returnProducts}"/>
                    </apex:selectList>
                
                <p>
                    Search Results
                </p>
                    <table>
                        <tr>
                            <th>Product Code</th>
                            <th>Inventory</th>
                            <th>Price</th> 
                        </tr>
                        <apex:repeat value="{!prodList}" var="p" id="list">
                            <tr>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.ProductCode}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.Inventory_Count__c}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;"> ${!dealerPrice}</td>
                            </tr>                    
                        </apex:repeat>
                    </table>
            </apex:tab>
        </apex:tabPanel>
    </apex:form> 
</apex:page>
Here is what is displaying, and it should be showing different prices for each product. 
User-added image 
With the discount:
User-added image
 
I need to get 10% this quater Sales_c records for audit purposes. I have a visualforce page and apex class setup but I am getting "Attempt to de-reference a null object" and I cannot figure it out. 

Apex Class:
public class RandomizerMasterTriggerHandler {
    
    
    public List<Sales__c> RandomSales {get;set;}
    public List<Sales__c> sales {get;set;}
    
    public RandomizerMasterTriggerHandler(){
        
        //Number of random sales to be returned
        sales = [select Sales_Year__c, Total_Sale_Line_Item_Amount_del__c, Name, Id, Partner_Account__c, Sale_Status__c from Sales__c where CreatedDate = LAST_QUARTER];
        decimal percentOfSales = .10;
        Double numberOfsales = sales.size() * percentOfSales;
        system.debug('Sales List - ' + sales.size());
        system.debug('Number of Sales - ' + numberofSales);
                     
        //Make sure there are enough records
        if(sales.size() >= numberOfsales){
            System.debug('Sales List size ' + sales.size());
            
            //create a list of strings to pass to our randomizer method
            List<string> salesIDs = new List<string>();
            Map<ID,Sales__c> salesMap = new Map<ID,Sales__c>();
            for(Sales__c s : sales){
                salesIDs.add(s.Id);
                salesMap.put(s.Id,s);
            }
            system.debug('SalesIDs - ' + salesIds);
            system.debug('SalesIDs - ' + salesIds.size());
            system.debug('SalesMap - ' + salesMap);
            system.debug('SalesMap - ' + salesMap.size());
            //create a set to hold the returned ids so that we can make sure there are no dupliates
            Set<Id> usedIds = new Set<Id>();
            string randomID;
            //Now lets get the random sales IDs
            for(Integer i=0; i<numberOfSales; i++){
				randomId = randomizer.getRandomString(salesIDs);
                system.debug('RandomId - ' + randomId);
                //check for duplicates
                while(usedIDs.contains(randomId)){
                    randomId = randomizer.getRandomString(salesIDs);
                }
                usedIDs.add(randomId);
                System.debug('usedIDs - ' + usedIds);
                RandomSales.add(salesMap.get(randomId));
                system.debug('Random Sales - ' + RandomSales);
            }
        }
    }
}
VisualForce page:
<apex:page controller="RandomizerMasterTriggerHandler" cache="true">
    
    <table>
        <tr>
            <th>Sales Number</th><th>Sales ID</th>
        </tr>
        <apex:repeat value="{!RandomSales}" var="s">
            <tr>
                <td><a target="_blank" href="/{!s.Id}">{!s.Name}</a></td>
                <td><a target="_blank" href="/{!s.Id}">{!s.Id}</a></td>
            </tr>
        </apex:repeat>
    </table>
    
</apex:page>

Apex class method for random number:
public class Randomizer {

     //returns a random Integer
     public static Integer getRandomNumber(Integer size){
          Double d = math.random() * size;
          return d.intValue();
     }

     //returns either true or false randomly
     public static Boolean getRandomBoolean(){
          if(math.mod(getRandomNumber(10),2) == 0){
               return true;
          }
          else{
               return false;
          }
     }

     //Get's a random value from a list of strings
     public static String getRandomString(List<String> strings){
          List<Double> ranks = new List<Double>();
          Map<Double,String> rankMap = new Map<Double,String>();

          for(String s : strings){
               Boolean isDup = true;
               Double rank;

               While(isDup){
                    Double x = getRandomNumber(100000);
                    if(!rankMap.containsKey(x)){
                         rank = x;
                         isDup = false;
                    }
               }

               ranks.add(rank);
               rankMap.put(rank,s);
          }

          ranks.sort();
          return rankMap.get(ranks.get(0));
     }

     //Returns a random picklist value 
     public static string getRandomPickListValue(Sobject s_object, String field_name, Boolean allow_blank){
          List<String> Strings = new List<String>();
          if(allow_blank){
               String b = '';
               Strings.add(b);
          }
            Schema.sObjectType sobject_type = s_object.getSObjectType();
            Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
            Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
            List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues();
            for (Schema.PicklistEntry a : pick_list_values) {
                Strings.add(a.getValue());
            }
            return getRandomString(Strings);
     }

     //returns a map of all picklists and multiselect picklists for a givien object
     //the keyset is the field name using proper case
     public static Map<String,List<String>> getPicVals(sObject s_object){
          Map<String,List<String>> valueMap = new Map<String,List<String>>();
          Schema.sObjectType sobject_type = s_object.getSObjectType();
          Schema.DescribeSObjectResult r = sobject_type.getDescribe();
          Map<String, Schema.SObjectField> field_map = r.fields.getMap();

          for(String s : field_map.keyset()){
               List<String> strings = new List<String>();
               Schema.DescribeFieldResult F = field_map.get(s).getDescribe();
               if(f.GetType() == Schema.DisplayType.Picklist || f.GetType() == Schema.DisplayType.MultiPicklist){
                    List<Schema.PicklistEntry> pick_list_values = field_map.get(s).getDescribe().getPickListValues();
                    for (Schema.PicklistEntry a : pick_list_values) {
                         strings.add(a.getValue());
                   }
                   valueMap.put(String.valueOf(field_map.get(s)),strings);
               }
          }
          return valueMap;
     }

     //Returns Lorem Ipsum placeholder text.
     public static String getPlaceholderText(Integer length){
          String firstSentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ';
          List<String> sentenceList = new List<String>();
          sentenceList.add('Vivamus nec lacus eget massa cursus pulvinar. ');
          sentenceList.add('Morbi vel odio eget nunc auctor posuere eget eget ante. ');
          sentenceList.add('Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ');
          sentenceList.add('Pellentesque lacus eros. ');
          sentenceList.add('Sed suscipit tristique varius. ');
          sentenceList.add('Mauris ultricies, nibh eu fermentum accumsan, justo quam pulvinar tellus, sed tempor quam eros sit amet ante. ');
          sentenceList.add('Duis mi libero, cursus nec facilisis ut, commodo eget nunc. ');
          sentenceList.add('Nulla eros augue, iaculis sed volutpat et, sagittis quis sem. ');
          sentenceList.add('Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla placerat accumsan vulputate. ');
          sentenceList.add('Fusce placerat tellus eget tellus faucibus a gravida sapien fermentum. ');

          String s = firstSentence;

          while (s.length() < length+1){
               s += getRandomString(sentenceList);
          }

          s = s.trim();

          while (s.length() >= length-1){
               s = s.substring(0,s.length()-1).trim();
          } 

          s = s.substring(0,s.length()-1).trim();
          s += '.';
          return s;
     }
}

Debug log:
39.0 APEX_CODE,DEBUG;APEX_PROFILING,NONE;CALLOUT,NONE;DB,NONE;SYSTEM,DEBUG;VALIDATION,NONE;VISUALFORCE,NONE;WAVE,INFO;WORKFLOW,NONE 10:10:34.0 (245538)|USER_INFO|[EXTERNAL]|005o0000001bpTU|chelsea.lukowski@titan-intl.com.jitterbit|Central Standard Time|GMT-05:00 10:10:34.0 (275394)|EXECUTION_STARTED 10:10:34.0 (279105)|CODE_UNIT_STARTED|[EXTERNAL]|066K00000002BGc|VF: /apex/RandomizerVisualforcePage 10:10:34.0 (47826025)|SYSTEM_MODE_ENTER|true 10:10:34.0 (52730566)|USER_DEBUG|[13]|DEBUG|Sales List - 22 10:10:34.0 (52744364)|USER_DEBUG|[14]|DEBUG|Number of Sales - 2.2 10:10:34.0 (52759612)|USER_DEBUG|[21]|DEBUG|Sales List size 22 10:10:34.0 (53290767)|USER_DEBUG|[30]|DEBUG|SalesIDs - (a2HK0000001LJQzMAO, a2HK0000001LJR9MAO, a2HK0000001LJR4MAO, a2HK0000001LJREMA4, a2HK0000001LJUIMA4, a2HK0000001LJV6MAO, a2HK0000001LJV7MAO, a2HK0000001LJUcMAO, a2HK0000001LJUmMAO, a2HK0000001LJVGMA4, ...) 10:10:34.0 (53301778)|USER_DEBUG|[31]|DEBUG|SalesIDs - 22 10:10:34.0 (53496404)|USER_DEBUG|[32]|DEBUG|SalesMap - {a2HK0000001LJIUMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=3250.00, Name=S-00845, Id=a2HK0000001LJIUMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44bAAA}, a2HK0000001LJQzMAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00846, Id=a2HK0000001LJQzMAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44bAAA}, a2HK0000001LJR4MAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00847, Id=a2HK0000001LJR4MAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJR9MAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00848, Id=a2HK0000001LJR9MAO, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJREMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00849, Id=a2HK0000001LJREMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJRiMAO=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=1500.00, Name=S-00850, Id=a2HK0000001LJRiMAO, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUIMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00851, Id=a2HK0000001LJUIMA4, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUNMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00852, Id=a2HK0000001LJUNMA4, Partner_Account__c=001K000001JtsjiIAB, Sale_Status__c=Submitted, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUSMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00853, Id=a2HK0000001LJUSMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, a2HK0000001LJUXMA4=Sales__c:{Sales_Year__c=2017, Total_Sale_Line_Item_Amount_del__c=0.00, Name=S-00854, Id=a2HK0000001LJUXMA4, Partner_Account__c=001K000001JtseEIAR, Sale_Status__c=Open, RecordTypeId=012o0000000q44aAAA}, ...} 10:10:34.0 (53512075)|USER_DEBUG|[33]|DEBUG|SalesMap - 22 10:10:34.0 (67031844)|USER_DEBUG|[40]|DEBUG|RandomId - a2HK0000001LJUrMAO 10:10:34.0 (67082996)|USER_DEBUG|[46]|DEBUG|usedIDs - {a2HK0000001LJUrMAO} 10:10:34.0 (67272025)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object Class.RandomizerMasterTriggerHandler.<init>: line 47, column 1
I have a custom object called AS400_Report__c, I have an apporval process associated to this report. I want the record owner to match the Assigned to user in the Approval Process. I am thinking that I will need a trigger, but I am not sure how to reference ProcessInstance. Help?
I want to be able to change the status of a record when the record is reassigned through an Approval Process. I am told this needs to be done through a trigger, but I am not sure how to start the trigger. Any sugesstions?
We integrate pdf's into a junction salesforce object called PDF_Uploader__c, then I have a before insert trigger that creates a record(AS400_Report__c) from the attachment name and then moves the attachment to the newly created record. If I attach the pdf manually one at a time, the trigger works perfectly. If I use our integration system(Jitterbit) and try to insert 2 attachments, it creates two records from only one of the attachments, instead of creating two records with an attachment in each. I user a master trigger and trigger handler class to accomplish this. What am I doing wrong?
public void createAS400ReportRecord(){
        List<AS400_Report__c> reportList = new List<AS400_Report__c>();
        Map<Id,AS400_Report__c> reportMap = new Map<Id,AS400_Report__c>();
        string attachmentNameWithoutExtension = '';
        list<string> splitList = new list<string>();
        Set<String>reportKeySet = new Set<String>();
    	List<AS400_Report__c> recordsToCreate = new List<AS400_Report__c>();
        Attachment a;
        
        for(sObject sObj : Trigger.new){
            a = (Attachment)sObj;
            if(string.isBlank(a.Name)){
				continue;
            }
        if(a.ParentId.getSObjectType() == PDF_Uploader__c.getSObjectType() && a.Description == 'AS400 Documents'){
                system.debug('In Loop1: ' + a.Name);
                splitList = a.Name.split('\\.'); //Need to get rid of .pdf
                attachmentNameWithoutExtension = splitList[0];
                 reportKeySet.add(attachmentNameWithoutExtension);  
            
        system.debug('In Loop2: ' + splitList[0]);
            }
            //system.debug(a.Name);
        }
        
        for(sObject sObj : Trigger.new){
            a = (Attachment)sObj;
                AS400_Report__c report = new AS400_Report__c();
            	report.Name = attachmentNameWithoutExtension;
                report.Status__c = 'New';
                report.Created_Date_Time__c = date.Today();            
                reportList.add(report);
            system.debug(report.Name);
        }
        insert reportList;
        system.debug(reportList.size());
            //2. Query the report from the set created above
            reportList = [SELECT Id,Name
                           FROM AS400_Report__c
                          Where Name = :reportKeySet];
        	system.debug('Report Size: ' + reportList.size());
    
    		//3. Loop through the reports and create map of key
            Map<String,AS400_Report__c> mapreport = new Map<String,AS400_Report__c>();
            for(AS400_Report__c r : reportList){
                Mapreport.put(r.Name,r);
            }
           //4.Loop thorugh attachments and use the map above to cop attachment
            for(sObject sObj : Trigger.new){
                a = (Attachment)sObj;
                if(string.isBlank(a.Name)){
                    continue;
                }
                if(a.ParentId.getSObjectType() == PDF_Uploader__c.getSObjectType()){
                    splitList = a.Name.split('\\.'); //Need to get rid of .pdf
                	attachmentNameWithoutExtension = splitList[0];
                    if(Mapreport.containsKey(attachmentNameWithoutExtension)){
                        a.ParentId = mapreport.get(attachmentNameWithoutExtension).Id;
                    }
                    system.debug(a.ParentId);
                }
            } 
    }

 
I am wanting to copy an attachment from one object to another and then delete the attachment from the orignial record once it is copied.  These objects are not related in any way. I know I need a trigger to accomplish this. I have an integration process that uploads attachments to an object called PDF_Uploader__c, this is a place holder. When the attachment is created under the Notes & Attachments section, a record is created under AS400_Report__c using the attachment name as the record Name, when this happens I would like the attachment to also copy from PDF_Uploader_c to the new AS400_Report__c record. Then delete the attachment from PDF_Uploader__c. The attahcment names are unique. Any suggestions?????
I have a visualforce component on our Home Page Layout with links, we only want the component to be visible i you have the permission set assign to your profile. How can this be done or can it be done?
I need some guidence, we have reports that are created as PDF's dailey/montly/yearly from an ERP system. These reports get reviewed and approved. We would like to use Salesforce to store the files and approvals. Is there a way to upload pdf's from a server to Salesforce and attach it to a record? What would be the best way to do this if it can be done? 
I need to assign a case to a queue when the status is changed, but then allow the users to accept the case and change the owner to themseleves or allow a user in the queue to assign the case to another user. I tried process builder, but after the case was assigned to the queue, users were not able to set the owner, it keep going back to the queue. I understand why it keeps doing that. I need help with a way to accomplish this. I assumed a trigger/class would probably be my best bet, any help would be appreciated.
I have a batch job that seems to take a long time to process. Is there anyway I can fix the job so that it does not take so long to update, is there something I can change to fix this?
 
global class batchAccountUpdate implements Database.Batchable<sObject>,Database.Stateful{
    
    String query;
     
     Public static void RunMe(){
        batchAccountUpdate fbatch = new batchAccountUpdate();
        Id batchInstanceId = Database.executeBatch(fbatch, 200);
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        //String query = 'select id,Account_Column_Key__c,Account__c,Previous_Year_Volume_YTD__c from Commission_Account__c ';
        return Database.getQueryLocator('select id,Account_Column_Key__c,Account__c,Previous_Year_Volume_YTD__c from Commission_Account__c');
    }
   
    global void execute(Database.BatchableContext BC, List<Commission_Account__c> scope) {
        List<Commission_Account__c> commAcctList=new List<Commission_Account__c>();
        for(Commission_Account__c commAcct:scope){
            try{
                decimal ii=0;
            
                List<Titan_Invoice__c> invList=[select id,Commission_Key__c,quantity__c,invoice_date__c from Titan_Invoice__c where Commission_Key__c=:commAcct.Account_Column_Key__c];
                
                for(Titan_Invoice__c inv:invList){
                    date d=date.valueof('2015-01-01');
                    integer day=system.now().day();
                    integer month=system.now().month();
                    system.debug('=11===='+day);
                    
                    string ytdDate='2015-'+month+'-'+day;
                    date e=date.valueof(ytdDate);
                    
                    if(inv.Invoice_Date__c>=d && inv.Invoice_Date__c<=e){
                    ii=ii+inv.quantity__c;
                    
                    }
           		}
        	commAcct.Previous_Year_Volume_YTD__c=ii;
        	commAcctList.add(commAcct);
            }catch(exception e){
            
            }
        }
        database.update(commAcctList,false);
    }

    global void finish(Database.BatchableContext BC) {
    }
 }

 
I have a trigger to copy attachments that are attached by a certain profile from a customer object Product_Engineering_Memo__c to the related Case. I need help with the test class. I keep getting an error System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Here is my trigger:
trigger CopyProductEngineeringAttchmentToCase on Attachment (before insert) {
    // collect a set of Sales Order 'parent' IDs from the attachments inserted
    Set<Id> engMemoIds = new Set<Id>();
    
    Id profileId=userinfo.getProfileId();
    String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
    
    for(Attachment file : Trigger.new) {

        // only collect those that are for the Product_Engineering_Memo__c object (others can be ignored)
        if(file.ParentId.getSObjectType() == Product_Engineering_Memo__c.getSObjectType() && ('Titan Pricing Analyst'.Equals(profileName))){
            engMemoIds.add(file.ParentId);
        }
    }


    if(!engMemoIds.isEmpty()) {

        // find the Opportunity to which the Service_Order__c relates
        Map<Id,Product_Engineering_Memo__c> memoMap = new Map<Id,Product_Engineering_Memo__c>([Select New_Wheel_request__c From Product_Engineering_Memo__c Where Id IN :engMemoIds]);        

        List<Attachment> attachments = new List<Attachment>();

        for(Attachment file : Trigger.new) {
            Attachment newFile = file.clone();
            newFile.ParentId = memoMap.get(file.ParentId).New_Wheel_request__c;
            attachments.add(newFile);
        }
        // finally, insert the cloned attachments
        insert attachments;
    }


}

My test class:
@isTest
public class CopyProductEngineeringAttachToCaseClass {

    
    static testMethod void CopyAttachToCaseClass() {
                
        String userID = '005o0000001c1vd';      
        // -- Create and insert Account instance 
        Account acc = new Account(Name = 'Test Account',Phone = '217-222-1111',Ship_Via__c = 'PPD', Channel_of_Distribution__c = 'Aftermarket',Market_Code__c = 'Aftermarket',Market_Segment__c = 'Aftermarket');
        insert acc;
        
        //create and insert Contact
        Contact con = new Contact(AccountId = acc.Id,LastName = 'TestLastName',FirstName = 'TestFristName');
        insert con;        
                
        // -- Create and insert Memo instance 
        Product_Engineering_Memo__c memo1 = new Product_Engineering_Memo__c();
        memo1.date__c = date.TODAY();
        memo1.Customer_Name_LOC__c = acc.id;
        memo1.Customer_Contact__c = con.id;
        memo1.Item__c = 'Testing this trigger';
        memo1.Customer_Prints__c = 'TestPrints';
        memo1.Use_Application__c = 'TestApplication';
        memo1.Annual_Usage__c = 'TestUsage';
        memo1.Paint_Codes__c = 'OTHER';
        memo1.Stage__c = 'Quote';
        insert memo1;
        
        Case c = new case(Status = 'New',Memo__c = memo1.Name);
        insert c;
		        
        // -- Create and insert Attachment instances and relate to Memo      
        Attachment att1 = new Attachment();
        att1.Name       = 'Unit Test Attachment 1';
        att1.body       = Blob.valueOf('Unit Test Attachment Body 1');
        att1.parentId   = memo1.id;
        insert att1;
                
        // -- Retrieve saved attachments
        List<Attachment> attachments = [select id, name, body from Attachment where parent.id=:c.id];
        System.assertEquals(1, attachments.size());            
        }   
}

 
I am creating a Visualforce page that creates a report with images. There are 2 objects, Grizz_Report__c(Parent) and (Visit_Report__c(child). Based on the Grizz_Report__c object, it should pull all the visit_reports__c associated and any images attached under notes and attachments on those visit_report__c. I have the page setup to pull all the visit_report__c records just fine, but I can't figure out how to pull the images attached from those visit_report__c records and display them on the report. Any help would be appriciated. Thank you!

This is my VF page:
<apex:page standardController="Grizz_Report__c" sidebar="false" showHeader="false" extensions="FieldTechReportClass" renderAs="pdf">
    <apex:form >
        <h1>
            Field Tech Report Name:<apex:outputField value="{!Grizz_Report__c.Name}"/><br/>
        </h1>
        <h2>
            Week Starting Date: <apex:outputField value="{!Grizz_Report__c.Week_Starting_Date__c}"/><br/>
            Week Ending Date: <apex:outputField value="{!Grizz_Report__c.Week_Ending_Date__c}"/><br/>            
        </h2>    
        <h3>
            Test Program Related: <apex:outputField value="{!Grizz_Report__c.Test_Program_related__c}"/><br/>
        </h3>    
        <br/>
        <br/>
                
            <table width="100%">
                <apex:repeat value="{!Grizz_Report__c.Visit_Reports__r}" var="vr">  
                <tr>
                
                    <th>Activity Type:</th>
                    <th>Reason for Activity:</th>
                    <th>Account:</th>
                    <th>Activity Reoprt Name:</th>
                    <th>Activity Detail:</th>
                    <th>Activity Date:</th>
                    
                </tr>
                <tr>
                
                    <td><apex:outputField value="{!vr.Activity_Type__c}"/></td>
                    <td><apex:outputField value="{!vr.Reason_for_Activity__c}"/></td>
                    <td><apex:outputField value="{!vr.Account__c}"/></td>
                    <td><apex:outputField value="{!vr.Name}"/></td>
                    <td><apex:outputField value="{!vr.Activity_Detail__c}"/></td>
                    <td><apex:outputField value="{!vr.Date__c}"/></td>
                    <tr>
                        <th>Images:</th>
                        <td><apex:image url="{!imageURL}" width="100"/></td>
                    </tr>
                </tr>
                </apex:repeat>
            </table>
    </apex:form>
</apex:page>
This is my class so far. The image will pull from the GrizzReport object but not from the visit report
public class FieldTechReportClass {
    
    String recId;
    public String imageURL {get;set;}
    //public List<Visit_Report__c> visitReport {get;set;}
    //public Grizz_Report__c grizzReport {get;set;}
    
    public FieldTechReportClass(ApexPages.StandardController controller) {
        recId = controller.getId();
        //grizzReport = (grizz_report__c)controller.getRecord();
        //visitReport = [SELECT ID FROM Visit_Report__c WHERE Field_Tech_Report__c =: grizzReport.ID];
    }
        
    public String getFileId() {
        
        imageURL='/servlet/servlet.FileDownload?file=';
        
        //for(visit_report__c visit : visitReport){
            List<Attachment> attachedFiles = [select Id from Attachment where parentId =:recId];
                if(attachedFiles.size() > 0 ) {
                    imageURL = imageURL+attachedFiles[0].Id;              
                }
               
                return imageURL;    
        
    }
}


 
How do you notify a case team member that they have been added to a case? I tried a workflow but it only seems to work if you update the case, not if you add a case team member. I thought about a trigger but don't know where to begin. Any help would be greatly appricieated. I am surprised this is not built in functionality. 
I am working on a visualforce page that allows a user to uppdate an opportunity and opportunityLineItems and give them the option of attaching a file. The problem I am running into is that if you don't attach a file I get the error below. The user needs to be able to add or not add the attachment. Any suggestions?

This is the error:
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [File Name, Body]: [File Name, Body]
Error is in expression '{!saveIt}' in component <apex:commandButton> in page orderonhand: Class.OrderOnHandClass.saveIt: line 30, column 1
Class.OrderOnHandClass.saveIt: line 30, column 1

This is the Visualforce Page:
<apex:page standardController="Opportunity" extensions="OrderOnHandClass">
    <apex:form >
        <apex:pageBlock >
        
            <apex:pageBlockSection title="Opportunity Details">
                <apex:inputCheckbox value="{!opportunity.Order_on_Hand__c}"/>
                <apex:inputField value="{!Opportunity.PO_Number__c}"/>
                <apex:inputField value="{!Opportunity.Order_Ship_To_Location__c}"/>
                
            </apex:pageBlockSection> 
            
            <apex:pageBlockSection title="Opportunity Product Details">
                <apex:pageBlockTable var="OLI" value="{!OLIs}" id="newProduct">
                    <apex:column value="{!OLI.ProductCode}"/>
                    <apex:column headerValue="Quantity">        
                        <apex:inputfield value="{!OLI.Quantity}"/>        
                    </apex:column>
                    <apex:column headerValue="Order Quantity if Different">        
                        <apex:inputfield value="{!OLI.Order_Quantity_if_Different__c}"/>        
                    </apex:column>
                    <apex:column headerValue="Approved Price">        
                        <apex:outputfield value="{!OLI.Approved_Price__c}"/>        
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection> 
            
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!saveIt}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
           
            <apex:pageBlockSection title="Attachment" >
            Attach PO: <apex:inputfile value="{!a.body}" filename="{!a.name}"></apex:inputfile>
            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
</apex:page>
This is the Class:
public class OrderOnHandClass {

    public ApexPages.StandardController sc;
    public Opportunity Opp {get;set;}
    public List<OpportunityLineItem> OLIlist2 {get ;set;}
    public Attachment a {get;set;}
      
    public OrderOnHandClass(ApexPages.StandardController sc) { 
        this.Opp = (Opportunity)sc.getRecord();
        OLIlist2 = [Select Name, ID,ProductCode, Quantity,Approved_Price__c, OpportunityId,Order_Quantity_if_Different__c FROM OpportunityLineItem WHERE OpportunityId =:Opp.Id];
        this.a = new Attachment();
       
        }
            
    public List<OpportunityLineItem> getOLIs() {
        return OLIlist2;
    }

    public PageReference saveIt() {
        
            opp.stageName = 'Order Received';
            update Opp;
             
            update OLIlist2;
       
       
        if(a.Id == Null){
            a.parentId = opp.Id;
        insert a;
        }else{
            Return Null;
            }
            
        String p = ApexPages.currentPage().getParameters().get('param');
            if(p == null){
                PageReference pageRef = new PageReference('https://cs41.salesforce.com/'+opp.Id);
                return pageRef;
            }
            else{
                return null;
            }     
    }
    }


 
I need help creating a trigger, below are the details.

Commission_Program__c that is a Parent Object with Commission_Product__c as the Child
Commission_Product__c is a Parent Object with Commission_Acocunt__c as the Child
 
When an Titan_Invoice__c is created I need a Commission_Account__c created based on the Titan_Invoice__r.Account__r.Channel_of_Distribution__c matching the Commission_Program__r.Customer_Type__c
and  
Commission_Program__r.Active equals True
and
Titan_Invoice__r.Product__c matching the Commission_Product__r.Product_Description__c.
 
The Commission_Account__c should only be created once and be assiciated with the correct Commission Product. I did create a key field on Commission_Account_c called Account_Column_key__c that is a formula field populating a unique string. 

Hopefully this makes since. I need help getting started with creating the Commission_Acocunt__c trigger. We want to track commission based on the invoice that are populating from our ERP system. 
 

 
I am trying to create a trigger that sends an email to multiple Account Team Memebers based on their account team member role when a Call is Logged. The email would only send to those users that have the account team Role of Ag Manager, Tyre Manager, Track Manager, or Wheel Manager. I sends when I log a call, but only to one user and not all users listed in the account team section with the matching roles.  
​trigger TaskEmailAccountTeam on Task (after insert, after update) {
    
    List<Messaging.SingleEmailMessage> atm = new List<Messaging.SingleEmailMessage>();  
    EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'Log_a_Call'];
    for(task t : Trigger.new){
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();       
        if(t.Email_Account_Team__c == True) {
            
            List<AccountTeamMember> recips = new List<AccountTeamMember>(
                [SELECT UserId,TeamMemberRole  
                 FROM AccountTeamMember 
                 WHERE AccountId = :t.AccountId AND (TeamMemberRole ='Ag Manager' OR TeamMemberRole ='Tyre Manager' OR TeamMemberRole ='Track Manager' OR TeamMemberRole ='Wheel Manager')]);
                    recips.addAll(recips);
            
            for(AccountTeamMember rid : recips){
                mail.setTargetObjectId(rid.UserId);
                mail.setUseSignature(true);
                mail.setBccSender(false);
                mail.setSaveAsActivity(false);
                mail.setTemplateId(et.Id);
            }
        }
        
        atm.add(mail);
    }    
    Messaging.sendEmail(atm);
}

 
I am trying to create a lightning componet for my Warranty Claim Case layout. On the case layout, I want to show a card of each record from a related object(Warranty_Claim_Line_Item__c) with a preview of the files attached to each of those records. I have the component setup to show the cards but the images are repeating for each record. I just need some advise on how to get only the images associated to each Warranty_Claim_Line_Item__c on the corresponding card. Below is my code. 
 
<aura:component implements="flexipage:availableForRecordHome,force:appHostable,lightning:actionOverride,force:hasRecordId" controller="warrantyLineItemRecordsCtrl">
   <aura:attribute name="lineItems" type="Warranty_Claim_Line_Item__c[]"/>
    <aura:attribute name="recordId" type="Id"/>  
    <aura:attribute name="filesIds" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.loadLineItems}"/>
    <aura:iteration items="{!v.lineItems}" var="l" indexVar="key">
        <lightning:card title="{!l.Name}">
            <aura:set attribute="actions">
                <lightning:button label="Edit" onclick="{!c.edit}" name="{!l.Id}"/>
            </aura:set>
            
            <div class="slds-grid slds-p-left_medium">
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Tire Description</h4>
                        <p><strong>Product Description</strong>:</p><p> {!l.Product__r.Name}</p>
                        <p><strong>Product Weight</strong>:<br/> {!l.Product_Weight__c} LBS</p>
                        <p><strong>Application Use</strong>: {!l.Application__c}</p>
                        <p><strong>Serial Number</strong>: {!l.Serial__c}</p>
                        <p><strong>Manufacturer Date</strong>: {!l.Manufacturer_Date__c}</p>
                        <p><strong>Removed Serial</strong>:</p>
                        <div class="row">
                        </div>
                    </div>
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Purchasing Information</h4>
                        <p><strong>How You Got Your Tire</strong>: {!l.Original_Purchase__c}</p>
                        <p><strong>Purchase Date</strong>: {!l.Purchase_Date__c}</p>
                        <p><strong>Purchased New/Used</strong>:{!l.Purchased_New_or_Used__c}</p>
                        <p><strong>Selling Dealer</strong>: {!l.Selling_Partner_Account_Name__c}</p>
                        
                        <h4 class="slds-text-heading_small">Original Equipment Information</h4>
                        <p><strong>Make</strong>: {!l.Machine_Make__c}</p>
                        <p><strong>Model</strong>: {!l.Machine_Model__c}</p>
                        <p><strong>Year</strong>: {!l.Machine_Year__c}</p>
                        <p><strong>Equipment Hours</strong>: {!l.Machine_Hours__c}</p>
                        <p><strong>Equipment Serial Number</strong>: {!l.Machine_Serial_Number__c}</p> 
                        
                        <h4 class="slds-text-heading_small">Proof of Purchase</h4>
                        <div class="row"></div>
                        <h4 class="slds-text-heading_small">Service and Labor Costs</h4>
                        <p>{!l.Service_and_Labor_Cost__c}</p>                
                    </div>
                    <div  class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Issue with Tire</h4>
                        <p><strong>Defect Location</strong>: {!l.Defect_Location__c}</p>
                        <p><strong>Defect Type</strong>: {!l.Defect_Type__c}</p>
                        <p><strong>Tire Position</strong>: {!l.Tire_Position__c}</p>
                        <h4 class="slds-text-heading_small">Inspection Condition</h4>
                        <p><strong>Tire Hours</strong>: {!l.Tire_Hours__c}</p>
                        <p><strong>Tread Depth</strong>: {!l.Tread_Depth__c}</p>
                        <p><strong>Inflation</strong>: {!l.Tire_Inflation__c}</p>
                        <p><strong>Additional Comments</strong>: {!l.Issue_Additional_Comments__c}</p>
                        <h4 class="slds-text-heading_small">Evidence of Condition</h4>
                        <div>                            
                            <aura:iteration items="{!v.fileIds}" var="t">
                                <lightning:fileCard fileId="{!t.ContentDocumentId}" description="{!t.ContentDocument.title}"/>
                            </aura:iteration>
                        </div>
                        <h4 class="slds-text-heading_small">Proof of Stubble Stomper Purchase</h4>
                        <div class="row"></div>
                    </div>
                </div>
        </lightning:card>
    </aura:iteration>
    
</aura:component>
 
({
    loadLineItems : function(component, event, helper) {
        var action = component.get("c.getLineItems");
        action.setParams({
            MasterRecordId: component.get("v.recordId")
        });
        action.setCallback(this, function(response){
            if(response.getState()==="SUCCESS" && component.isValid()){
                component.set("v.lineItems",response.getReturnValue());
                console.log(JSON.parse(JSON.stringify(response.getReturnValue())));
            }
        });getWarrantyWithContent
        
        $A.enqueueAction(action);
        
        
        var action = component.get("c.fetchFiles");
        action.setParams({
            MasterRecordId : component.get("v.recordId")            
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state == "SUCCESS"){
                var result = response.getReturnValue()
                component.set("v.filesIds",result);
                console.log(result);
            }
        });	
        $A.enqueueAction(action); 
    }, 
    
     edit : function(component, event, helper) {
       var editRecordEvent = $A.get("e.force:editRecord");
         var recordId = event.getSource().get("v.name");
         
         console.log("record id: " + recordId);
        editRecordEvent.setParams({
            "recordId": recordId
        });
        editRecordEvent.fire();
    
    }
    
})
 
@AuraEnabled
    public static List<ContentDocumentLink> fetchFiles(String MasterRecordId){
        System.debug('MasterRecordId - - - - - - ' + MasterRecordId);
        return  [SELECT ContentDocumentId,ContentDocument.title,ContentDocument.LatestPublishedVersion.Warranty_Type__c 
                 FROM ContentDocumentLink 
                 WHERE ContentDocument.LatestPublishedVersion.Warranty_Type__c = 'Evidence' 
                 AND  LinkedEntityId IN (Select Id FROM Warranty_Claim_Line_Item__c WHERE Warranty_Case__c =: MasterRecordId)];        
    }

 
I need some advise. I am creating a visualforce page where a user can search for a product and see a price, then they can select a percentage to take off that price and the page would recalculate the price times that percentage. I can get the searh to work and a price to show up but it displays the same price for all products.

This is the Class i currently have:
public class ProductInventoryMobileController {
    
    public string searchstring {get;set;}
    public list<Inventory__c> invList {get;set;}
    
    public double discountsearchstring {get;set;}
    public list<Product2> prodList {get;set;}
    public Double dealerPrice {get; set;}
    
    public void search(){
        if(searchstring != Null){
            system.debug('Search String -' + searchstring);
            string searchquery = 'select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id from Inventory__c where Lookup_Key__c LIKE \'%'+searchstring+'%\' ORDER BY Product__r.ProductCode ASC';
            invList = Database.query(searchquery); 
        }else{
            invList = Database.query('select Lookup_Key__c,Product__r.ProductCode,Product__r.Name,Weight_Per_U_M__c,Available__c,Warehouse__c,Warehouse_City__c,Product__r.Standard_Price__c,id from Inventory__c ORDER BY Product__r.ProductCode ASC');
        }
    }
    
    public List<Product2> searchProduct(){        
        string searchquery = 'select Name, ProductCode,Search_String__c,Inventory_Count__c, Standard_Price__c from Product2 where Standard_Price__c < 99999.99 AND ProductCode LIKE \'%'+searchstring+'%\' ORDER BY ProductCode ASC';
        system.debug('Discount String - ' + discountsearchstring);
        dealerPrice = 0;
        for(Product2 p: database.query(searchquery) ){
            if(discountsearchstring != 0.0){
        		dealerPrice = discountsearchstring * p.Standard_Price__c;
                system.debug('dealer price - '+ dealerPrice); 
            }else {
                dealerPrice = p.Standard_Price__c;
                system.debug('dealer price - '+ dealerPrice);
            }
        }
        prodList = database.query(searchquery);
        return ProdList;
    }
    
    public pageReference returnProducts(){
        searchProduct();
        return null;
    }
    
    public void clearProducts(){
        searchstring = '';
        prodList.clear();
    }
    
    public void clear(){
        searchstring = '';
        invList.clear();
    }
}
This is the visualforce page:
<apex:page Controller="ProductInventoryMobileController" standardStylesheets="false" readOnly="true" docType="html-5.0">
    
    <apex:form >
        <apex:tabPanel switchType="client" selectedTab="sch" id="dataTabPanel">
            <apex:tab label="Inventory" name="Inventory Search" id="sch">
                <br/>
                <apex:inputText value="{!searchstring}" label="Input"/> 
                <apex:commandButton value="Search" action="{!search}"/> 
                <apex:commandButton value="Clear" action="{!clear}"/> 
                <p>
                    Search Results
                </p> 
                <c:ProductInventoryMobile />
                <table>
                    <tr>
                        <th>Product Code</th>
                        <th>Available</th>
                        <th>List Price</th>
                        <th>Warehouse</th>
                        <th>Weight Per U/M</th>
                        
                    </tr>
                    <apex:repeat value="{!invList}" var="i">
                        <tr>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Product__r.ProductCode}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Available__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">${!i.Product__r.Standard_Price__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Warehouse__c}</td>
                            <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!i.Weight_Per_U_M__c}</td>
                        </tr>                    
                    </apex:repeat>
                </table>
            </apex:tab>
            <apex:tab label="Pricing" name="Pricing Calculator" id="sch2">
                <br/>
                <apex:inputText value="{!searchstring}" label="Input"/> 
                <apex:commandButton value="Search" action="{!returnProducts}"/> 
                <apex:commandButton value="Clear" action="{!clearProducts}"/> 
                <br/>
                <apex:outputLabel for="discount" value="On-Factor:"></apex:outputLabel>&nbsp;&nbsp;&nbsp;
                    <apex:selectList id="discount" value="{!discountsearchstring}" size="1" label="On-Factor:">
                        	<apex:SelectOption itemValue="0.0" itemLabel=""/>
                            <apex:SelectOption itemValue=".45" itemLabel="45"/>
                            <apex:SelectOption itemValue=".44" itemLabel="44"/>
                            <apex:SelectOption itemValue="54" itemLabel="54"/>
                            <apex:SelectOption itemValue="60" itemLabel="60"/>
                     <apex:actionSupport event="onchange" action="{!returnProducts}"/>
                    </apex:selectList>
                
                <p>
                    Search Results
                </p>
                    <table>
                        <tr>
                            <th>Product Code</th>
                            <th>Inventory</th>
                            <th>Price</th> 
                        </tr>
                        <apex:repeat value="{!prodList}" var="p" id="list">
                            <tr>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.ProductCode}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;">{!p.Inventory_Count__c}</td>
                                <td style="page-break-inside: avoid;border:1px solid black;padding: 7px;word-wrap: break-word;text-align:center;"> ${!dealerPrice}</td>
                            </tr>                    
                        </apex:repeat>
                    </table>
            </apex:tab>
        </apex:tabPanel>
    </apex:form> 
</apex:page>
Here is what is displaying, and it should be showing different prices for each product. 
User-added image 
With the discount:
User-added image
 
I have a batch job that seems to take a long time to process. Is there anyway I can fix the job so that it does not take so long to update, is there something I can change to fix this?
 
global class batchAccountUpdate implements Database.Batchable<sObject>,Database.Stateful{
    
    String query;
     
     Public static void RunMe(){
        batchAccountUpdate fbatch = new batchAccountUpdate();
        Id batchInstanceId = Database.executeBatch(fbatch, 200);
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        //String query = 'select id,Account_Column_Key__c,Account__c,Previous_Year_Volume_YTD__c from Commission_Account__c ';
        return Database.getQueryLocator('select id,Account_Column_Key__c,Account__c,Previous_Year_Volume_YTD__c from Commission_Account__c');
    }
   
    global void execute(Database.BatchableContext BC, List<Commission_Account__c> scope) {
        List<Commission_Account__c> commAcctList=new List<Commission_Account__c>();
        for(Commission_Account__c commAcct:scope){
            try{
                decimal ii=0;
            
                List<Titan_Invoice__c> invList=[select id,Commission_Key__c,quantity__c,invoice_date__c from Titan_Invoice__c where Commission_Key__c=:commAcct.Account_Column_Key__c];
                
                for(Titan_Invoice__c inv:invList){
                    date d=date.valueof('2015-01-01');
                    integer day=system.now().day();
                    integer month=system.now().month();
                    system.debug('=11===='+day);
                    
                    string ytdDate='2015-'+month+'-'+day;
                    date e=date.valueof(ytdDate);
                    
                    if(inv.Invoice_Date__c>=d && inv.Invoice_Date__c<=e){
                    ii=ii+inv.quantity__c;
                    
                    }
           		}
        	commAcct.Previous_Year_Volume_YTD__c=ii;
        	commAcctList.add(commAcct);
            }catch(exception e){
            
            }
        }
        database.update(commAcctList,false);
    }

    global void finish(Database.BatchableContext BC) {
    }
 }

 
I have a trigger to copy attachments that are attached by a certain profile from a customer object Product_Engineering_Memo__c to the related Case. I need help with the test class. I keep getting an error System.AssertException: Assertion Failed: Expected: 1, Actual: 0

Here is my trigger:
trigger CopyProductEngineeringAttchmentToCase on Attachment (before insert) {
    // collect a set of Sales Order 'parent' IDs from the attachments inserted
    Set<Id> engMemoIds = new Set<Id>();
    
    Id profileId=userinfo.getProfileId();
    String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
    
    for(Attachment file : Trigger.new) {

        // only collect those that are for the Product_Engineering_Memo__c object (others can be ignored)
        if(file.ParentId.getSObjectType() == Product_Engineering_Memo__c.getSObjectType() && ('Titan Pricing Analyst'.Equals(profileName))){
            engMemoIds.add(file.ParentId);
        }
    }


    if(!engMemoIds.isEmpty()) {

        // find the Opportunity to which the Service_Order__c relates
        Map<Id,Product_Engineering_Memo__c> memoMap = new Map<Id,Product_Engineering_Memo__c>([Select New_Wheel_request__c From Product_Engineering_Memo__c Where Id IN :engMemoIds]);        

        List<Attachment> attachments = new List<Attachment>();

        for(Attachment file : Trigger.new) {
            Attachment newFile = file.clone();
            newFile.ParentId = memoMap.get(file.ParentId).New_Wheel_request__c;
            attachments.add(newFile);
        }
        // finally, insert the cloned attachments
        insert attachments;
    }


}

My test class:
@isTest
public class CopyProductEngineeringAttachToCaseClass {

    
    static testMethod void CopyAttachToCaseClass() {
                
        String userID = '005o0000001c1vd';      
        // -- Create and insert Account instance 
        Account acc = new Account(Name = 'Test Account',Phone = '217-222-1111',Ship_Via__c = 'PPD', Channel_of_Distribution__c = 'Aftermarket',Market_Code__c = 'Aftermarket',Market_Segment__c = 'Aftermarket');
        insert acc;
        
        //create and insert Contact
        Contact con = new Contact(AccountId = acc.Id,LastName = 'TestLastName',FirstName = 'TestFristName');
        insert con;        
                
        // -- Create and insert Memo instance 
        Product_Engineering_Memo__c memo1 = new Product_Engineering_Memo__c();
        memo1.date__c = date.TODAY();
        memo1.Customer_Name_LOC__c = acc.id;
        memo1.Customer_Contact__c = con.id;
        memo1.Item__c = 'Testing this trigger';
        memo1.Customer_Prints__c = 'TestPrints';
        memo1.Use_Application__c = 'TestApplication';
        memo1.Annual_Usage__c = 'TestUsage';
        memo1.Paint_Codes__c = 'OTHER';
        memo1.Stage__c = 'Quote';
        insert memo1;
        
        Case c = new case(Status = 'New',Memo__c = memo1.Name);
        insert c;
		        
        // -- Create and insert Attachment instances and relate to Memo      
        Attachment att1 = new Attachment();
        att1.Name       = 'Unit Test Attachment 1';
        att1.body       = Blob.valueOf('Unit Test Attachment Body 1');
        att1.parentId   = memo1.id;
        insert att1;
                
        // -- Retrieve saved attachments
        List<Attachment> attachments = [select id, name, body from Attachment where parent.id=:c.id];
        System.assertEquals(1, attachments.size());            
        }   
}

 
I am creating a Visualforce page that creates a report with images. There are 2 objects, Grizz_Report__c(Parent) and (Visit_Report__c(child). Based on the Grizz_Report__c object, it should pull all the visit_reports__c associated and any images attached under notes and attachments on those visit_report__c. I have the page setup to pull all the visit_report__c records just fine, but I can't figure out how to pull the images attached from those visit_report__c records and display them on the report. Any help would be appriciated. Thank you!

This is my VF page:
<apex:page standardController="Grizz_Report__c" sidebar="false" showHeader="false" extensions="FieldTechReportClass" renderAs="pdf">
    <apex:form >
        <h1>
            Field Tech Report Name:<apex:outputField value="{!Grizz_Report__c.Name}"/><br/>
        </h1>
        <h2>
            Week Starting Date: <apex:outputField value="{!Grizz_Report__c.Week_Starting_Date__c}"/><br/>
            Week Ending Date: <apex:outputField value="{!Grizz_Report__c.Week_Ending_Date__c}"/><br/>            
        </h2>    
        <h3>
            Test Program Related: <apex:outputField value="{!Grizz_Report__c.Test_Program_related__c}"/><br/>
        </h3>    
        <br/>
        <br/>
                
            <table width="100%">
                <apex:repeat value="{!Grizz_Report__c.Visit_Reports__r}" var="vr">  
                <tr>
                
                    <th>Activity Type:</th>
                    <th>Reason for Activity:</th>
                    <th>Account:</th>
                    <th>Activity Reoprt Name:</th>
                    <th>Activity Detail:</th>
                    <th>Activity Date:</th>
                    
                </tr>
                <tr>
                
                    <td><apex:outputField value="{!vr.Activity_Type__c}"/></td>
                    <td><apex:outputField value="{!vr.Reason_for_Activity__c}"/></td>
                    <td><apex:outputField value="{!vr.Account__c}"/></td>
                    <td><apex:outputField value="{!vr.Name}"/></td>
                    <td><apex:outputField value="{!vr.Activity_Detail__c}"/></td>
                    <td><apex:outputField value="{!vr.Date__c}"/></td>
                    <tr>
                        <th>Images:</th>
                        <td><apex:image url="{!imageURL}" width="100"/></td>
                    </tr>
                </tr>
                </apex:repeat>
            </table>
    </apex:form>
</apex:page>
This is my class so far. The image will pull from the GrizzReport object but not from the visit report
public class FieldTechReportClass {
    
    String recId;
    public String imageURL {get;set;}
    //public List<Visit_Report__c> visitReport {get;set;}
    //public Grizz_Report__c grizzReport {get;set;}
    
    public FieldTechReportClass(ApexPages.StandardController controller) {
        recId = controller.getId();
        //grizzReport = (grizz_report__c)controller.getRecord();
        //visitReport = [SELECT ID FROM Visit_Report__c WHERE Field_Tech_Report__c =: grizzReport.ID];
    }
        
    public String getFileId() {
        
        imageURL='/servlet/servlet.FileDownload?file=';
        
        //for(visit_report__c visit : visitReport){
            List<Attachment> attachedFiles = [select Id from Attachment where parentId =:recId];
                if(attachedFiles.size() > 0 ) {
                    imageURL = imageURL+attachedFiles[0].Id;              
                }
               
                return imageURL;    
        
    }
}


 
I am working on a visualforce page that allows a user to uppdate an opportunity and opportunityLineItems and give them the option of attaching a file. The problem I am running into is that if you don't attach a file I get the error below. The user needs to be able to add or not add the attachment. Any suggestions?

This is the error:
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [File Name, Body]: [File Name, Body]
Error is in expression '{!saveIt}' in component <apex:commandButton> in page orderonhand: Class.OrderOnHandClass.saveIt: line 30, column 1
Class.OrderOnHandClass.saveIt: line 30, column 1

This is the Visualforce Page:
<apex:page standardController="Opportunity" extensions="OrderOnHandClass">
    <apex:form >
        <apex:pageBlock >
        
            <apex:pageBlockSection title="Opportunity Details">
                <apex:inputCheckbox value="{!opportunity.Order_on_Hand__c}"/>
                <apex:inputField value="{!Opportunity.PO_Number__c}"/>
                <apex:inputField value="{!Opportunity.Order_Ship_To_Location__c}"/>
                
            </apex:pageBlockSection> 
            
            <apex:pageBlockSection title="Opportunity Product Details">
                <apex:pageBlockTable var="OLI" value="{!OLIs}" id="newProduct">
                    <apex:column value="{!OLI.ProductCode}"/>
                    <apex:column headerValue="Quantity">        
                        <apex:inputfield value="{!OLI.Quantity}"/>        
                    </apex:column>
                    <apex:column headerValue="Order Quantity if Different">        
                        <apex:inputfield value="{!OLI.Order_Quantity_if_Different__c}"/>        
                    </apex:column>
                    <apex:column headerValue="Approved Price">        
                        <apex:outputfield value="{!OLI.Approved_Price__c}"/>        
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection> 
            
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!saveIt}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
           
            <apex:pageBlockSection title="Attachment" >
            Attach PO: <apex:inputfile value="{!a.body}" filename="{!a.name}"></apex:inputfile>
            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
</apex:page>
This is the Class:
public class OrderOnHandClass {

    public ApexPages.StandardController sc;
    public Opportunity Opp {get;set;}
    public List<OpportunityLineItem> OLIlist2 {get ;set;}
    public Attachment a {get;set;}
      
    public OrderOnHandClass(ApexPages.StandardController sc) { 
        this.Opp = (Opportunity)sc.getRecord();
        OLIlist2 = [Select Name, ID,ProductCode, Quantity,Approved_Price__c, OpportunityId,Order_Quantity_if_Different__c FROM OpportunityLineItem WHERE OpportunityId =:Opp.Id];
        this.a = new Attachment();
       
        }
            
    public List<OpportunityLineItem> getOLIs() {
        return OLIlist2;
    }

    public PageReference saveIt() {
        
            opp.stageName = 'Order Received';
            update Opp;
             
            update OLIlist2;
       
       
        if(a.Id == Null){
            a.parentId = opp.Id;
        insert a;
        }else{
            Return Null;
            }
            
        String p = ApexPages.currentPage().getParameters().get('param');
            if(p == null){
                PageReference pageRef = new PageReference('https://cs41.salesforce.com/'+opp.Id);
                return pageRef;
            }
            else{
                return null;
            }     
    }
    }


 
I need help creating a trigger, below are the details.

Commission_Program__c that is a Parent Object with Commission_Product__c as the Child
Commission_Product__c is a Parent Object with Commission_Acocunt__c as the Child
 
When an Titan_Invoice__c is created I need a Commission_Account__c created based on the Titan_Invoice__r.Account__r.Channel_of_Distribution__c matching the Commission_Program__r.Customer_Type__c
and  
Commission_Program__r.Active equals True
and
Titan_Invoice__r.Product__c matching the Commission_Product__r.Product_Description__c.
 
The Commission_Account__c should only be created once and be assiciated with the correct Commission Product. I did create a key field on Commission_Account_c called Account_Column_key__c that is a formula field populating a unique string. 

Hopefully this makes since. I need help getting started with creating the Commission_Acocunt__c trigger. We want to track commission based on the invoice that are populating from our ERP system. 
 

 
I am wanting to email selected attachment from the Notes and Attachment Section on an Opportunity. I have created a VF page and Apex Class, but I am having problems with the Wrapper Class. It does not email at all.

Apex Class
public class email_class{
    
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string opportunityId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
    
    public class Attachmentwrapper
        {
            public Attachment acc{get; set;}
            public Boolean selected {get; set;}
            public Attachmentwrapper(Attachment a)
            {
                acc = a;
            }
        }
    
               
    public email_class(ApexPages.StandardController controller) {
        opportunityId = ApexPages.currentPage().getParameters().get('id');
    }
    
     List<Attachmentwrapper> AttachmentList = new List<Attachmentwrapper>();
     List<Attachment> selectedAttachments = new List<Attachment>();
       
        public List<Attachmentwrapper> getAttachments()
        {
        for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :opportunityId])
        {      
            AttachmentList.add(new Attachmentwrapper(a));
             }
            return AttachmentList;
        }
    
    Public PageReference send(){
       
    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
        mail.setToAddresses(new String[] {emailTo});
        string [] ccaddress;
            if(emailCC != null && emailCC.trim() != ''){
            ccaddress = emailCC.split(',',0);
            mail.setCcAddresses(ccaddress);
            }
        mail.setSubject(subject);
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setPlainTextBody(email_body);
        mail.setWhatId(opportunityId);// Set email file attachments 

        //selectedAttachments.clear();
        for(Attachmentwrapper accwrapper : AttachmentList){
        if(accwrapper.selected == true){
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :opportunityID]){
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(a.Name);
        efa.setBody(a.Body);
        fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);
       
         selectedAttachments.add(accwrapper.acc);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
         return null;
         }
}       
       /* public List<Attachment> GetSelectedAttachments()
        {
            if(selectedAttachments.size()>0)
            return selectedAttachments;
            else
            return null;
        }  */  
             
        PageReference pageRef = new PageReference('/' + opportunityId);
        pageRef.setRedirect(true);
        return pageRef;
    }
}

VF page
<apex:page standardController="Opportunity" extensions="email_class">
    <apex:form >
           
        <apex:pageBlock title="Email Details">
        
            <apex:pageBlock title="Reciepient">
                <b>TO: </b><br/><apex:inputText value="{!emailTo}"/><p/>
                <b>CC: </b><br/><apex:inputText value="{!emailCC}"/><br/>
                <br/>
                <b>Subject: </b><br/><apex:inputText value="{!subject}" maxlength="200"/><br/>
                <br/>
                <b>Body: </b><br/><apex:inputTextArea value="{!email_body}" rows="10" cols="100"/>
            </apex:pageBlock>          
                    
        <apex:pageBlock title="Attachments">
        <apex:pageBlockTable value="{!opportunity.Attachments}" var="wrap">
            <apex:column headerValue="Select">
            <apex:inputCheckbox value="{!opportunity.IsChecked__c}"/>
            </apex:column>
       <apex:column value="{!wrap.createddate}"/>
       <apex:column value="{!wrap.name}"/>
       <apex:column value="{!wrap.description}"/>
       </apex:pageBlockTable><p/>
       </apex:pageblock>
                
       <apex:commandButton value="Send Email" action="{!send}"/>
       <apex:commandButton value="Canel" action="{!cancel}"/>
            
       </apex:pageBlock>
                           
    </apex:form>    
</apex:page>

 

I have create a Visualforce Page and Apex Class to send an email from Opportunities with an attachment from the Notes and Attachments section. It works to send all the Attachments in the Notes and Attachments section, I want to be able to choose which attchments get sent. Any ideas on how I can select the Attachment and only send the ones I want. My Class is below. 

 

Apex Class

 public class email_class{

    public email_class(ApexPages.StandardController controller) {

    }
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string opportunityId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
       
    Public PageReference send(){
    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
            mail.setToAddresses(new String[] {emailTo}); 
            mail.setCcAddresses(new String[] {emailCC});   //set the cc address
            mail.setSubject(subject);
            mail.setBccSender(false);
            mail.setUseSignature(false);
            mail.setPlainTextBody(email_body);
            mail.setWhatId(opportunityId);// Set email file attachments 
            
       List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

            for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :opportunityId]){  // Add to attachment file list  
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();  
                efa.setFileName(a.Name); 
                efa.setBody(a.Body); 
                fileAttachments.add(efa);}
                mail.setFileAttachments(fileAttachments);// Send email
                
                
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        return null;
        }
}

 

I have created a Visualforce page and Apex Class to be able to send an email from an Opportunity with Attachments that are in the Notes & Attachments section. The page allows them to pick an attachment to send with the email. The email will send but does not include the attachment. I know I am missing something, any help would be appriciated.

Apex Class
public class email_class{

    public email_class(ApexPages.StandardController controller) {

    }
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string opportunityId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
       
    Public PageReference send(){
    
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
            mail.setToAddresses(new String[] {emailTo}); 
            mail.setCcAddresses(new String[] {emailCC});   //set the cc address
            mail.setSubject(subject);
            mail.setBccSender(false);
            mail.setUseSignature(false);
            mail.setPlainTextBody(email_body);
            mail.setWhatId(opportunityId);// Set email file attachments 
            
       List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

            for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :opportunityId]){  // Add to attachment file list  
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();  
                efa.setFileName(a.Name); 
                efa.setBody(a.Body); 
                fileAttachments.add(efa);}
                mail.setFileAttachments(fileAttachments);// Send email
                
                
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        return null;
        }
}



VF page
<apex:page standardController="Opportunity" extensions="email_class">
    <apex:form >
           
        <apex:pageBlock title="Email Details">
            <b>To: </b> <apex:inputText value="{!emailTo}"/><p/>
            <b>CC: </b> <apex:inputText value="{!emailCC}" /><p/>  
            <b>Enter Subject: </b> <apex:inputText value="{!subject}" maxlength="200"/><p/>            
            <b>Enter Body: </b> <apex:inputTextArea value="{!email_body}" rows="10" cols="100"/><p/>
          
        <apex:pageBlock title="Attachments">
        <apex:pageBlockTable value="{!opportunity.Attachments}" var="Att">
            <apex:column headerValue="Select">
            <apex:inputCheckbox value="{!opportunity.Send_Email_with_Quote__c}"/>
            </apex:column>
       <apex:column value="{!Att.createddate}"/>
       <apex:column value="{!Att.name}"/>
       <apex:column value="{!Att.description}"/>
       </apex:pageBlockTable><p/>
       </apex:pageblock>
                
       <apex:commandButton value="Send Email" action="{!send}"/>
       <apex:commandButton value="Canel" action="{!cancel}"/>
            
       </apex:pageBlock>
                           
    </apex:form>    
</apex:page>

 
I need to create a trigger that updates the Inventory_On_Hand__c field on  custom object Oreder_Product__c, with the value of the Available__c field from the object call Inventory__c. The matching point between the two is the product number, which is on both objects as a field called Product__c. I do not know where to begin. Any help would be appriciated. 
I need help on how to populate a lookup field on a case based on the Account Owners Delegated Approver.

We have a lookup field(Pricing_Analyst__c) on a case(Product Substitution Request). 

Conditions to be met are:
Status = "New" - picklist field
Record Type = "Product Substitution Request" or "012q00000008phM"

Field to update:
Pricing_Analyst__c to be equal to the Account Owners Delegated Approver.

It can be a (before insert, before update) or (after insert) trigger. Any help would be appreciated.