• Nishant Sharma
  • NEWBIE
  • 70 Points
  • Member since 2015
  • Developer
  • V2Force


  • Chatter
    Feed
  • 1
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 26
    Replies
Hello,
I am trying to write a simple trigger. It has been tested in the sandbox and all looks good.

I have put the trigger and test below. Both are in the change set.

What am i doing wrong?

Trigger
trigger CreateEnrolment on Opportunity (after insert, after update) {
List<enrolment__c> createenrolment = new List <enrolment__c> ();
    
for (Opportunity o: trigger.new) {
if (o.isWon == true) {
createenrolment.add(
new enrolment__c(
Campaign_Medium__c = o.Campaign_Medium__c,
Campaign_Name__c = o.Campaign_Name__c,
Product__c = o.Product__c,
Opportunity__c = o.id,
Account__c = o.AccountId,
Call_Centre__c = o.Call_Centre__c,
Who_Enrolled__c = UserInfo.getUserId()));
}
}
 
try {
insert createenrolment;
}
catch (Exception Ex){
system.debug(Ex);
}
}

Test
@isTest(SeeAllData=false)
private class Testcreateenrolment{
 
 
@isTest(SeeAllData=false)
private static void Testcreateenrolment() {
 
List<enrolment__c> createenrolment = new List <enrolment__c> ();
 
createenrolment.add(
new enrolment__c(
Campaign_Medium__c = 'Campaign_Medium__c',
Campaign_Name__c = 'Campaign_Name__c',
Product__c = '01t90000004q3PH',
Account__c = '00190000014B4x7',
Call_Centre__c = 'Call_Centre__c',
Who_Enrolled__c = '00590000001Symm'));
 
try {
insert createenrolment;
}
catch (Exception Ex){
system.debug(Ex);
}
}
}
 
I do not see "Unlock Record" button for applicable user (user with modify all data permission), even if record is locked.  Did anyone else face similar issue?

Any resolution.
I have used forcetk library, in lightning component for uploading file in SFDC and that works perfectly fine with large files (~25MB), with Locker Service disabled.

However, when LockerService is enabled, it just stop working.

On Technical note:
I have made few changes in forcetk library to make it work for normal operations, but file upload aka createBlob is still an issue. If I go little deep, problem with file upload is, Locker Service restricts XMLHttpRequest global reference and hence end up responding bad request. Not sure, if there is any secure way of making XMLHttpRequest for file upload.
I have also tried this this link:
http://webcache.googleusercontent.com/search?q=cache:yDEYXecmDHMJ:peterknolle.com/file-upload-lightning-component/+&cd=1&hl=en&ct=clnk&gl=in

But that just let me upload file with small size and take LOT of processing time (as it process blob and pass the binary file as base64string).

Now, to summarize, what is the best way/tool to upload file in lightning component with Locker Service Enabled.
Not sure, what is wrong with following code. While validating, it give me following error:
The campingList component isn't handing the added item correctly.

Here is the code:
1. camping.cmp
<aura:component >
    <c:campingHeader />
    <c:campingList />
</aura:component>
2. CampingList.cmp
<aura:component controller="CampingListController">
    
    <aura:attribute name="items" type="Camping_Item__c[]"/>
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="addItem" action="{!c.handleAddItem}" event="c:addItemEvent"/>
    
    <c:campingListForm />
    
    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Expenses</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="item">
                    <c:campingListItem item="{!item}"/>
                    <br/>
                </aura:iteration>
            </div>
        </section>
    </div>
    
</aura:component>

3. campingListController.js
({
    // Load expenses from Salesforce
    doInit: function(component, event, helper) {
        
        // Create the action
        var action = component.get("c.getItems");
        
        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    
    handleAddItem : function(component, event, helper) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(event.getParam("item")))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})

4. componentListHelper.js
({
    createCamping: function(component,item) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(item))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})
5. campingListForm.cmp
<aura:component >
    
    <aura:attribute name="newItem" type="Camping_Item__c"
                    default="{ 'sobjectType': 'Camping_Item__c',
                             'Name': '',
                             'Packed__c': false,
                             'Price__c': '0',
                             'Quantity__c': '0' }"/>
    
    <aura:registerEvent name="addItem" type="c:addItemEvent"/>
    
    <div aria-labelledby="newitemform">
        <fieldset class="slds-box slds-theme--default slds-container--small">
            
            <legend id="newitemform" class="slds-text-heading--small 
                                            slds-p-vertical--medium">
                Add Camping Item
            </legend>
            
            <form class="slds-form--stacked">
                
                <div class="slds-form-element slds-is-required">
                    <div class="slds-form-element__control">
                        <ui:inputText aura:id="name" label="Camping Item Name"
                                      class="slds-input"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Name}"
                                      required="true"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:inputCheckbox aura:id="packed" label="Packed?"
                                      class="slds-checkbox"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Packed__c}"/>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputCurrency aura:id="price" label="Price"
                                          class="slds-input"
                                          labelClass="slds-form-element__label"
                                          value="{!v.newItem.Price__c}" />
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputNumber aura:id="quantity" label="Quantity"
                                        class="slds-input"
                                        labelClass="slds-form-element__label"
                                        value="{!v.newItem.Quantity__c}"/>
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:button label="Create Camping Item"
                               class="slds-button slds-button--brand"
                               press="{!c.submitForm}"/>
                </div>
                
            </form>
            
        </fieldset>
    </div>
    
</aura:component>
6. campingListFormController
({    
    
    submitForm : function(component, event, helper) {
        
        var validCamping = true;

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

        
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price) || isNaN(price) || (price <= 0.0)){
            validCamping = false;
            priceField.set("v.errors", [{message:"Camping Item price can't be blank."}]);
        }
        else {
            priceField.set("v.errors", null);
        }
        
        var quantityField = component.find("quantity");
        var quantity = quantityField.get("v.value");
        if ($A.util.isEmpty(quantity) || isNaN(quantity) || (quantity <= 0)){
            validCamping = false;
            quantityField.set("v.errors", [{message:"Camping Item quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }

        if(validCamping){
            
            helper.createItem(component);
        }
    },
})

7. campingListFormHelper.js
({
    
     createItem : function(component) {
        var newItem = component.get("v.newItem");
        var addEvent = component.getEvent("addItem");
        addEvent.setParams({"item" : newItem});
        addEvent.fire();
        component.set("v.newItem",
                     { 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Packed__c': false,
                    'Price__c': 0,
                    'Quantity__c': 0});
    }
})

8. addItemEvent.evt
<aura:event type="COMPONENT" description="Event template">
    <aura:attribute name="item" type="Camping_Item__c"/>
</aura:event>

It works well, when I test this app. any thought? Can anyone share the working code for this module?


 
So I have a scenario that, we are migrating Article from external system to Salesforce, and while doing migration, I need to set value for certain system fields i.e. CreatedById, CreatedDate. I know, I can do that for by Contacting Salesforce and salesforce will enable this feature for me. But that is not the case while migrating Articles.

Salesforce has provided different import wizard for importing Article and that is not accepting value for system fields.

​Please suggest.

Is there any specific permission required to setup Chatter Answer moderator? Please note, I am NOT referring, Chatter Moderator OR Community Moderator.

And if there is no any specific permission involved, who can moderate Chatter Answer content? We have option in Chatter Answer to mark Question and Reply as flag (spam, Inappropriate, Hateful)

Kindly suggest.

FYI, I am enabled chatter answer for my community.

Not sure, what is wrong with following code. While validating, it give me following error:
The campingList component isn't handing the added item correctly.

Here is the code:
1. camping.cmp
<aura:component >
    <c:campingHeader />
    <c:campingList />
</aura:component>
2. CampingList.cmp
<aura:component controller="CampingListController">
    
    <aura:attribute name="items" type="Camping_Item__c[]"/>
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="addItem" action="{!c.handleAddItem}" event="c:addItemEvent"/>
    
    <c:campingListForm />
    
    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Expenses</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="item">
                    <c:campingListItem item="{!item}"/>
                    <br/>
                </aura:iteration>
            </div>
        </section>
    </div>
    
</aura:component>

3. campingListController.js
({
    // Load expenses from Salesforce
    doInit: function(component, event, helper) {
        
        // Create the action
        var action = component.get("c.getItems");
        
        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    
    handleAddItem : function(component, event, helper) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(event.getParam("item")))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})

4. componentListHelper.js
({
    createCamping: function(component,item) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(item))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})
5. campingListForm.cmp
<aura:component >
    
    <aura:attribute name="newItem" type="Camping_Item__c"
                    default="{ 'sobjectType': 'Camping_Item__c',
                             'Name': '',
                             'Packed__c': false,
                             'Price__c': '0',
                             'Quantity__c': '0' }"/>
    
    <aura:registerEvent name="addItem" type="c:addItemEvent"/>
    
    <div aria-labelledby="newitemform">
        <fieldset class="slds-box slds-theme--default slds-container--small">
            
            <legend id="newitemform" class="slds-text-heading--small 
                                            slds-p-vertical--medium">
                Add Camping Item
            </legend>
            
            <form class="slds-form--stacked">
                
                <div class="slds-form-element slds-is-required">
                    <div class="slds-form-element__control">
                        <ui:inputText aura:id="name" label="Camping Item Name"
                                      class="slds-input"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Name}"
                                      required="true"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:inputCheckbox aura:id="packed" label="Packed?"
                                      class="slds-checkbox"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Packed__c}"/>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputCurrency aura:id="price" label="Price"
                                          class="slds-input"
                                          labelClass="slds-form-element__label"
                                          value="{!v.newItem.Price__c}" />
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputNumber aura:id="quantity" label="Quantity"
                                        class="slds-input"
                                        labelClass="slds-form-element__label"
                                        value="{!v.newItem.Quantity__c}"/>
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:button label="Create Camping Item"
                               class="slds-button slds-button--brand"
                               press="{!c.submitForm}"/>
                </div>
                
            </form>
            
        </fieldset>
    </div>
    
</aura:component>
6. campingListFormController
({    
    
    submitForm : function(component, event, helper) {
        
        var validCamping = true;

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

        
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price) || isNaN(price) || (price <= 0.0)){
            validCamping = false;
            priceField.set("v.errors", [{message:"Camping Item price can't be blank."}]);
        }
        else {
            priceField.set("v.errors", null);
        }
        
        var quantityField = component.find("quantity");
        var quantity = quantityField.get("v.value");
        if ($A.util.isEmpty(quantity) || isNaN(quantity) || (quantity <= 0)){
            validCamping = false;
            quantityField.set("v.errors", [{message:"Camping Item quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }

        if(validCamping){
            
            helper.createItem(component);
        }
    },
})

7. campingListFormHelper.js
({
    
     createItem : function(component) {
        var newItem = component.get("v.newItem");
        var addEvent = component.getEvent("addItem");
        addEvent.setParams({"item" : newItem});
        addEvent.fire();
        component.set("v.newItem",
                     { 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Packed__c': false,
                    'Price__c': 0,
                    'Quantity__c': 0});
    }
})

8. addItemEvent.evt
<aura:event type="COMPONENT" description="Event template">
    <aura:attribute name="item" type="Camping_Item__c"/>
</aura:event>

It works well, when I test this app. any thought? Can anyone share the working code for this module?


 
Not sure, what is wrong with following code. While validating, it give me following error:
The campingList component isn't handing the added item correctly.

Here is the code:
1. camping.cmp
<aura:component >
    <c:campingHeader />
    <c:campingList />
</aura:component>
2. CampingList.cmp
<aura:component controller="CampingListController">
    
    <aura:attribute name="items" type="Camping_Item__c[]"/>
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="addItem" action="{!c.handleAddItem}" event="c:addItemEvent"/>
    
    <c:campingListForm />
    
    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Expenses</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="item">
                    <c:campingListItem item="{!item}"/>
                    <br/>
                </aura:iteration>
            </div>
        </section>
    </div>
    
</aura:component>

3. campingListController.js
({
    // Load expenses from Salesforce
    doInit: function(component, event, helper) {
        
        // Create the action
        var action = component.get("c.getItems");
        
        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.items", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    
    handleAddItem : function(component, event, helper) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(event.getParam("item")))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})

4. componentListHelper.js
({
    createCamping: function(component,item) {
        
        var action = component.get("c.saveItem");
        action.setParams({
            "item": JSON.parse(JSON.stringify(item))
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                var items = component.get("v.items");
                items.push(response.getReturnValue());
                component.set("v.items", items);
            }
        });
        $A.enqueueAction(action);
    }
})
5. campingListForm.cmp
<aura:component >
    
    <aura:attribute name="newItem" type="Camping_Item__c"
                    default="{ 'sobjectType': 'Camping_Item__c',
                             'Name': '',
                             'Packed__c': false,
                             'Price__c': '0',
                             'Quantity__c': '0' }"/>
    
    <aura:registerEvent name="addItem" type="c:addItemEvent"/>
    
    <div aria-labelledby="newitemform">
        <fieldset class="slds-box slds-theme--default slds-container--small">
            
            <legend id="newitemform" class="slds-text-heading--small 
                                            slds-p-vertical--medium">
                Add Camping Item
            </legend>
            
            <form class="slds-form--stacked">
                
                <div class="slds-form-element slds-is-required">
                    <div class="slds-form-element__control">
                        <ui:inputText aura:id="name" label="Camping Item Name"
                                      class="slds-input"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Name}"
                                      required="true"/>
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:inputCheckbox aura:id="packed" label="Packed?"
                                      class="slds-checkbox"
                                      labelClass="slds-form-element__label"
                                      value="{!v.newItem.Packed__c}"/>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputCurrency aura:id="price" label="Price"
                                          class="slds-input"
                                          labelClass="slds-form-element__label"
                                          value="{!v.newItem.Price__c}" />
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <div class="slds-form-element__control">
                        <ui:inputNumber aura:id="quantity" label="Quantity"
                                        class="slds-input"
                                        labelClass="slds-form-element__label"
                                        value="{!v.newItem.Quantity__c}"/>
                        
                    </div>
                </div>
                
                <div class="slds-form-element">
                    <ui:button label="Create Camping Item"
                               class="slds-button slds-button--brand"
                               press="{!c.submitForm}"/>
                </div>
                
            </form>
            
        </fieldset>
    </div>
    
</aura:component>
6. campingListFormController
({    
    
    submitForm : function(component, event, helper) {
        
        var validCamping = true;

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

        
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price) || isNaN(price) || (price <= 0.0)){
            validCamping = false;
            priceField.set("v.errors", [{message:"Camping Item price can't be blank."}]);
        }
        else {
            priceField.set("v.errors", null);
        }
        
        var quantityField = component.find("quantity");
        var quantity = quantityField.get("v.value");
        if ($A.util.isEmpty(quantity) || isNaN(quantity) || (quantity <= 0)){
            validCamping = false;
            quantityField.set("v.errors", [{message:"Camping Item quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }

        if(validCamping){
            
            helper.createItem(component);
        }
    },
})

7. campingListFormHelper.js
({
    
     createItem : function(component) {
        var newItem = component.get("v.newItem");
        var addEvent = component.getEvent("addItem");
        addEvent.setParams({"item" : newItem});
        addEvent.fire();
        component.set("v.newItem",
                     { 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Packed__c': false,
                    'Price__c': 0,
                    'Quantity__c': 0});
    }
})

8. addItemEvent.evt
<aura:event type="COMPONENT" description="Event template">
    <aura:attribute name="item" type="Camping_Item__c"/>
</aura:event>

It works well, when I test this app. any thought? Can anyone share the working code for this module?


 
Hi Dears,

       How can i enable multiple currrency in the Developer edition (corporate currency)
Hi

I need to set boolean field depending upon the values of another field in same object. So for example - If X.name = 'XYZ' then set the boolean field to True otherwise it is false. What is the best approach to tackle this issue ?

Thanks
RSF
  • July 05, 2015
  • Like
  • 0
SELECT Id, AccountId, (SELECT Id,Core__c FROM Properties__r where Core__c !=null ) FROM Contact WHERE Accountid IN : accountIds

This is my Query..Any limit i have to put in inner query....

This is my trigger.......
trigger updateAccCorefrmProperty on Property__c (after insert, after update, after delete) {


      Set<Id> accountIds = new Set<Id> ();                   
      Map<id,List<Property__c>> mpAccProperty = new  Map<id,List<Property__c>>();     
      Set<String>  PropCores= new Set<String>();
      List<Account> accountListToUpdate = new List<Account>();
      List<Account> accountListToUpdate2 = new List<Account>();
      set<id>  contactId= new set<id> ();
      set<id>  accountwithoutProp = new set<id> ();
                
        if(Trigger.IsInsert ) {
            for(Property__c prp: [SELECT Contact__c, core__c, Contact__r.Accountid from Property__c WHERE Id IN : Trigger.new] )
            {
                if(prp.Contact__c!=null && prp.core__c !=null && prp.Contact__r.Accountid !=null)
                accountIds.add(prp.Contact__r.Accountid);
            }
        
        }
        
        if( Trigger.IsUpdate ) {
            for(Property__c prp: Trigger.new )
            {
               if(prp.Contact__c!=null && prp.core__c !=null)
                contactId.add(prp.Contact__c); 
            }
            
            for(Property__c prp: Trigger.old)
            {
               if(prp.Contact__c!=null && prp.core__c !=null)
                contactId.add(prp.Contact__c); 
            }
            
             for(Contact con: [select id, AccountId from Contact where id in : contactId and AccountId != null])
                accountIds.add(con.Accountid);
       
        }
        
        
        
        if(Trigger.IsDelete ){
            for(Property__c prp :Trigger.old){
                if(prp.Contact__c!=null && prp.core__c !=null)
                contactId.add(prp.Contact__c);        
            }

            for(Contact con: [select id, AccountId from Contact where id in : contactId and AccountId != null])
            accountIds.add(con.Accountid);
        }    
   
        for(Contact conT: [SELECT Id, AccountId, (SELECT Id,Core__c FROM Properties__r where Core__c !=null limit 2000) FROM Contact WHERE Accountid IN : accountIds]){
            if(conT.Properties__r != null && conT.Properties__r.Size() > 0) {
                if(mpAccProperty.containskey(cont.AccountId)){
                List<Property__c> lstProperty= mpAccProperty.get(cont.AccountId);
                lstProperty.addall(conT.Properties__r);
                }
                else{
                mpAccProperty.put(cont.AccountId,conT.Properties__r);}  
            }
            system.debug('wwwwwwwconT.Properties__r.Size()www'+conT.Properties__r.Size());
            if( conT.Properties__r.Size() == 0) {  
                accountwithoutProp.add(cont.AccountId);
                system.debug('wwwwwwwwww'+accountwithoutProp);
            } 
        }
        
        for(Id accId: mpAccProperty.keyset()){
            if(accountwithoutProp.contains(accId))
                accountwithoutProp.remove(accid);
        }
        
           
        String new_propCore;
        for(Id accId: mpAccProperty.keyset()){
            new_propCore='';
            PropCores.clear();
            for(Property__c prop: mpAccProperty.get(accId))
            PropCores.add(prop.core__c);

            new_propCore=String.Join(new List<String>(PropCores),',');
            
            if(!String.IsBlank(new_propCore))
            accountListToUpdate.add(new Account(Id=accId,core__c=new_propCore));         

        }
        if(accountwithoutProp!=null && accountwithoutProp.size()>0){
            for(Id accwithoutPropId : accountwithoutProp){
                accountListToUpdate.add(new Account(Id=accwithoutPropId,core__c=''));
            }
        }
        
        
        //if(accountListToUpdate2.size()>0)
        //update accountListToUpdate2;

        if(accountListToUpdate.size()>0)
        update accountListToUpdate;//update Impacted account 
        
        
}



>>>>>>>>>>>>>

ny using batch m updating Properties...and this trigger fires
Hi ,
I have the list of records in account object ,I want to display all the records in drop-down menu  ,when I Click the particular record
in drop-down menu  say for Example Burlington Textiles Corp of America, It will display the detailed page of the account with related contact and opportunity  ,Any Help would be greatly Appriciated //
Hi All,

At what situation are we going to use upsert operation.

Regards,
Suresh.
  • April 03, 2015
  • Like
  • 0
Hello,
I am trying to write a simple trigger. It has been tested in the sandbox and all looks good.

I have put the trigger and test below. Both are in the change set.

What am i doing wrong?

Trigger
trigger CreateEnrolment on Opportunity (after insert, after update) {
List<enrolment__c> createenrolment = new List <enrolment__c> ();
    
for (Opportunity o: trigger.new) {
if (o.isWon == true) {
createenrolment.add(
new enrolment__c(
Campaign_Medium__c = o.Campaign_Medium__c,
Campaign_Name__c = o.Campaign_Name__c,
Product__c = o.Product__c,
Opportunity__c = o.id,
Account__c = o.AccountId,
Call_Centre__c = o.Call_Centre__c,
Who_Enrolled__c = UserInfo.getUserId()));
}
}
 
try {
insert createenrolment;
}
catch (Exception Ex){
system.debug(Ex);
}
}

Test
@isTest(SeeAllData=false)
private class Testcreateenrolment{
 
 
@isTest(SeeAllData=false)
private static void Testcreateenrolment() {
 
List<enrolment__c> createenrolment = new List <enrolment__c> ();
 
createenrolment.add(
new enrolment__c(
Campaign_Medium__c = 'Campaign_Medium__c',
Campaign_Name__c = 'Campaign_Name__c',
Product__c = '01t90000004q3PH',
Account__c = '00190000014B4x7',
Call_Centre__c = 'Call_Centre__c',
Who_Enrolled__c = '00590000001Symm'));
 
try {
insert createenrolment;
}
catch (Exception Ex){
system.debug(Ex);
}
}
}
 

I don't know where I am going wrong. I am being redirected to other Vfpage yet niether URL changes nor I am able to fetch the values from one Vfpage to other.

And I am using single controller for both Vfpages. Agony is I am getting two develpment mode windows of two visualforce page; when I click "edit".

Vfpage one 

<apex:page controller="WrapperAccountextension">
   <apex:form >
        <apex:pageBlock title="Account List">
        
            <apex:pageBlockButtons >
                <apex:commandButton value="Edit" action="{!geteditormoz}" rerender="out"/>
            </apex:pageBlockButtons>
           
            <apex:pageBlockTable value="{!Accountsz}" var="Acc">
                <apex:column headerValue="Action">
                   
                    <apex:inputCheckbox value="{!Acc.selected}"/>
                </apex:column>
                
                <apex:column value="{!Acc.con.Name}" />
                <apex:column value="{!Acc.con.Phone}" />
                <apex:column value="{!Acc.con.Fax}"/>
                <apex:column value="{!Acc.con.AnnualRevenue}"/>
                <apex:column value="{!Acc.con.AccountNumber}"/>
            </apex:pageBlockTable>
        
        </apex:pageBlock>
        </apex:form>
</apex:page>

 

=========================================================================================================================================================================================================================================================================================================================Vfpage two:-

<apex:page controller="WrapperAccountextension">
<apex:form >
 <apex:pageblock mode="InlineEdit">
        <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!rasavez}"/>
        </apex:pageBlockButtons>
      
               <apex:pageBlockTable value="{!selectedAccountsz}" var="Rec" id="out" title="Selected Accounts" columnsWidth="400px,400px">
                    <apex:column headerValue="Account Name">
                        <apex:outputField value="{!Rec.name}"/>
                    </apex:column>   
                    <apex:column headerValue="Phone">
                        <apex:outputField value="{!Rec.Phone}"/>
                    </apex:column>             
                    <apex:column headerValue="Fax">
                    <apex:outputField value="{!Rec.Fax}"/>
                    </apex:column>
                    <apex:column headerValue="Annual Revenue">
                    <apex:outputField value="{!Rec.AnnualRevenue}"/>
                    </apex:column>
                    <apex:column headerValue="Account Number">
                    <apex:outputfield value="{!Rec.AccountNumber}"/>
                    </apex:column>
                </apex:pageBlockTable>   
               
          </apex:pageblock>
</apex:form>
</apex:page>

=========================================================================================================================================================================================================================================================================================================================Controller:-

public class WrapperAccountextension {


Public pagereference rasavez(){

Update selectedAccountsz;
return null;
}

Public Pagereference editmoderz(){

return null;
}

public PageReference geteditormoz(){
Pagereference ldkedit = New PageReference('/apex/WrapperAccountlsteditera');
processSelectedz();

ldkedit.setRedirect(true);

return ldkedit;
}
    
 public List<cAccountz> accListz {get; set;}
  public List<Account> selectedAccountsz{get; set;}
//Adding the Records to inner class and to get the values for page block table.
  public List<cAccountz> getAccountsz(){
        if(accListz == null){
            accListz = new List<cAccountz>();
            for(Account acc : [select Id, Name, Phone,Fax,AnnualRevenue,AccountNumber from Account limit 25]){
                  accListz.add(new cAccountz(acc));
            }
         }
       return accListz;
   }  
//on button click it will show the list of records what we have selected.
  public PageReference processSelectedz(){     
  
  
        selectedAccountsz= new List<Account>();
        for(cAccountz cCon : getAccountsz()) {
            if(cCon.selected == true){
                selectedAccountsz.add(cCon.con);
                
            }
        }            
        return null;
   }
  //  Inner class for capture the records
  public class cAccountz {
        public Account con {get; set;}
        public Boolean selected {get; set;}
        public cAccountz(Account c) {
            con = c;
            selected = false;
        }
   }
     
}

 

Thanks and Regards,

Razzzaq.

Hi folks,
    Can anyone tell me how to redirect one visualforce page to another visualforce page automatically ?
below is my visualforce page :
<apex:page standardController="Account" extensions="AccountDownload" 
contentType="application/msWord/#Test-{!NOW()}.doc"
   recordSetVar="accounts" sidebar="false"  cache="true"> 
    
    <html xmlns:w="urn:schemas-microsoft-com:office:word">
        <head>
            
        
        </head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
         
        <body>                       
            <apex:form >
                <apex:pageBlock title="Archiver For Account">
                     <div style="text-align:left" >          
                         <apex:pageBlockTable value="{!accounts}" var="ac" >
                             <apex:column headerValue="AccountName">
                                 <apex:outputText >{!ac.Name}</apex:outputText>
                             </apex:column>
                             <apex:column headerValue="Account Number">
                                 <apex:outputText >{!ac.AccountNumber}</apex:outputText>
                             </apex:column>
                             <apex:column headerValue="AccountType">
                                 <apex:outputText >{!ac.Type}</apex:outputText>
                             </apex:column>
                             <apex:column headerValue="Phone Number">
                                 <apex:outputText >{!ac.Phone}</apex:outputText>
                             </apex:column>                                       
                         </apex:pageBlockTable>  
                      </div>           
                    </apex:pageBlock>
    
               <apex:outputText value="hi dude,"/>
           </apex:form>
           
        </body>
        <script>
 
            function redirect(){
                window.location.href='https://c.ap1.visual.force.com/apex/AccountasTextfile'; 
            }
 
            window.onload = window.setTimeout(redirect(),5000);
 
        </script>
    </html>
</apex:page>

My question is once the document is downloaded then it will automatically redirect to another page as mentioned above.
I have tried using action attribute,calling redirect method from constructor. but nothing happen.
Finally I got the idea is using javascript we can redirect automatically.
but it dosent work for me.

Someone please tell me what I have to modify.



Thanks in advance
Karthick
Hi All,

My test class compiles succussfully. However, I receive an error while running it. I have no idea where I have done wrong. Please help.

Class.LC_DisplayFolderElementsController.displayFolderElements: line 99, column 1
Class.LC_DisplayFolderElementsController.<init>: line 77, column 1
Class.Test_LC_DisplayFolderElementsController.myUnitTest: line 49, column 1

Apex Class Code:
public with sharing class LC_DisplayFolderElementsController {
  
  public Consumer_Inquiries__c CI;
  public Access_Token__c gats;
  public captureFileElements cfe;
  
  public list<displayAttachments> Box_Attachments{get;set;}
  public list<FileEntries> Files;
  
  public boolean displayIFrame{get;set;}
  public displayAttachments dat;
  
  
  public LC_DisplayFolderElementsController(apexpages.standardController sc){
    gats = new Access_Token__c();
    CI = new Consumer_Inquiries__c();
    cfe = new captureFileElements();
    displayIFrame = false;
    dat = new displayAttachments();
        
    Id CIID = apexpages.currentPage().getParameters().get('ID');
    CI = [Select Id, Name, RecordTypeID, Folder_ID__c, (select Id, Name, ContentType from Attachments) from Consumer_Inquiries__c Where Id =: CIID];
    
    list<RecordType> RTList = new list<RecordType>();
    RTList = [Select Id, Name from RecordType Where sObjectType = 'Consumer_Inquiries__c' and Name = 'Regulatory Complaint'];
    RecordType RCRT;
    if(RTList != Null && RTList.size() > 0){
      for(RecordType rt : RTList){
        RCRT = rt;
      }
    }
    
    gats = [Select Id, Name, Token__c, Refresh_Token__c, LastmodifiedDate From Access_Token__c];
    Box_Attachments = new list<displayAttachments>();
    Files = new list<FileEntries>();
    if(CI != Null){//Adding the Existing Attachments into list for the Specific CI 
      for(Attachment att : CI.attachments){
        dat = new displayAttachments();
        dat.Attachment_Name = att.name;
        dat.FileID = '';
        dat.location = 'Salesforce';
        string Extension;
        if(att.name != Null && att.name != ''){
          integer IndexValue= att.name.lastIndexOf('.');
          if(IndexValue > -1){
            Extension = att.name.substring(IndexValue+1,att.name.length());// to show the actual file extension from salesforce
          } 
        }
        dat.Type = Extension;
        Box_Attachments.add(dat);
      }
    }
    
    if(Box_Attachments != Null && Box_Attachments.size() > 0){
      displayIFrame = true;
    }else{
      displayIFrame = false;
    }
    
    list<Firm_s_Child__c> FolderMapList = new list<Firm_s_Child__c>();
    FolderMapList = [Select Id, Name, Box_Folder_ID__c from Firm_s_Child__c Where Reference_ID__c =: CIID and Type__c = 'Consumer Inquiry'];
    if(FolderMapList != Null && FolderMapList.size() > 0){
      displayFolderElements(FolderMapList[0].Box_Folder_ID__c);
    }else{
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please try after some time as the folder has not yet created.'));
    }  
  }

  public void displayFolderElements(string FolderID){//Folder Id is picked up from Box Folder ID Map Table
    HTTPResponse res = new HTTPResponse();
    HTTPRequest req = new HTTPRequest();
    gats = [Select Id, Name, Token__c, Refresh_Token__c, LastmodifiedDate From Access_Token__c];
    req.setEndpoint('https://api.box.com/2.0/folders/'+FolderID+'/items');//Request URL for Folder Elements
    req.setHeader('Authorization','Bearer '+gats.Token__c);
    req.setMethod('GET');
    HTTP getFolderItems = new HTTP();
    res = getFolderItems.send(req);//Sending the request to get the actual response
    string bodystring = res.getBody();
    system.debug('The JSON Body is'+res.getBody());
    if(res.getStatusCode() == 200){
      cfe = (captureFileElements)JSON.deserialize(bodyString,captureFileElements.class);// Parsing the above request
      Files = cfe.entries;
  
      
      for(FileEntries fe : Files)
      {////Adding the Box Files into list for the Specific CI
        string str;
        integer dotIndex;
        
        dat = new displayAttachments();
        dat.Attachment_Name = fe.name;
        dat.FileID = fe.id;
        dat.location = 'Box';
        
        if(fe.name.contains('.')){
          str = fe.name;
          dotIndex = fe.name.lastIndexOf('.');
          system.debug('The dot Index is'+dotIndex);
          system.debug('The Type could be '+str.substring(dotIndex+1,str.length()));
          string str2 = str.substring(dotIndex+1,str.length());
          dat.Type = str2;
        }
        Box_Attachments.add(dat);
        if(Box_Attachments != Null && Box_Attachments.size() > 0){
          displayIFrame = true;
        }else{
          displayIFrame = false;
        }
      }
    }else{
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please try after some time as the folder has not yet created.'));
    }
    system.debug('The box Attachments are'+Box_Attachments);
  }
  
  public class displayAttachments{
    public string Attachment_Name{get;set;}
    public string FileID{get;set;}
    public string Type{get;set;}
    public string location{get;set;}
    
    public displayAttachments(){
      Attachment_Name = '';
      FileID = '';
      Type = '';
      location = '';
    }
  }
  
  /* File Wrapper*/
  public class captureFileElements{
    public integer total_count;
    public list<FileEntries> entries;
    public integer offset;
    public integer limit2;
    public list<Orders> Order;
    
    public captureFileElements(){
    }
  }
  /* File Wrapper*/
  /* File Wrapper*/
  public class FileEntries{
    public string Type;
    public string id;
    public string sequence_id;
    public string etag;
    public string sha1;
    public string name;
  }
  /* File Wrapper*/
  /* File Wrapper*/
  public class orders{
    public string by1;
    public string direction;
  }
  /* File Wrapper*/
}


Test Class:
@isTest(seealldata=true)
private class Test_LC_DisplayFolderElementsController{
     static testMethod void myUnitTest(){
        List<Account> accList = new list<Account>();
        Account a = new Account();
        a.Name = 'TestAcc';
        a.Firm_ID__c = 'Test';
        insert a;
        accList.add(a);
        
        list<Attachment> AttachmentList = new list<Attachment>();
        list<Consumer_Inquiries__c> ciList = new list<Consumer_Inquiries__c>();
        list<Case> caseList = new list<Case>();
        
        caseList = LC_TestDataUtility.createCases(1);
        ciList = LC_TestDataUtility.createConsumerInquiries(accList);
        system.assertEquals(1, ciList.size());
        system.assertEquals(1, caseList.size());
        
        list<Firm_s_Child__c> fc1 = new list<Firm_s_Child__c>();
        List<Box_Folder_ID_Map__c> BoxFolderIDList = [select Actual_Firm__c, Reference_ID__c, Firm_ID__c, Type__c, Created_Date__c from Box_Folder_ID_Map__c where Actual_Firm__c =: a.id and Reference_ID__c =: a.id and Type__c = 'Account' limit 1];
        system.debug('box folder id list value-->'+BoxFolderIDList );
        Firm_Dates__c fd = new Firm_Dates__c();
        fd.Box_Folder_ID_Map__c = BoxFolderIDList[0].id;
        fd.Folder_ID__c = '098745434';
        insert fd;
        
        Firm_s_Child__c fc = new Firm_s_Child__c();
        fc.Case_Reference__c = caseList[0].id;
        fc.Consumer_Inquiries_Reference__c = ciList[0].id;
        fc.Firm_Date__c = fd.id;
        fc.Type__c = 'Consumer Inquiry';
        fc.Box_Folder_ID__c = '09875432587';
        insert fc;
                
        fc1.add(fc);
        system.debug('fc1 value-->'+fc1);
        set<Id> parentIds = new set<Id>();
        parentIds.add(ciList[0].Id);
        AttachmentList = LC_TestDataUtility.createAttachments(parentIds);
        system.debug('consumer inquiry value-->'+ciList);
        
        Test.startTest();
        LC_DisplayFolderElementsController.displayAttachments obj1 = new LC_DisplayFolderElementsController.displayAttachments();
        LC_DisplayFolderElementsController.captureFileElements obj2 = new LC_DisplayFolderElementsController.captureFileElements();
        LC_DisplayFolderElementsController.FileEntries obj3 = new LC_DisplayFolderElementsController.FileEntries();
        Apexpages.currentPage().getParameters().put('ID',ciList[0].Id);
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        if(!fc1.isEmpty()){ 
        Apexpages.standardController sc = new Apexpages.standardController(fc1[0]);
        
        LC_DisplayFolderElementsController obj = new LC_DisplayFolderElementsController(sc);
        obj.displayFolderElements(fc1[0].Box_Folder_ID__c);
        
        LC_DisplayFolderElementsController.orders obj4 = new LC_DisplayFolderElementsController.orders();
        LC_DisplayFolderElementsController.displayAttachments obj5 = new LC_DisplayFolderElementsController.displayAttachments();
        }
        Test.stopTest();
     }
}
I'm actually creating a knowledge article from my apex class and I need to provide access to our external users (i.e. community / portal users) so that they could access these newly created knowledge articles. I tried setting the channels by marking IsVisibleInPrm, IsVisibleInPkb, IsVisibleInCsp, IsVisibleInApp fields as true for the knowledge article and the related sObjects. But it seems that these fields are not writeable.

Can we set the Channels (i.e. all isVisible fields) for any of the published knowledge articles from apex so that it is accessible to the portal/community users?