• Simon234
  • NEWBIE
  • 70 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 24
    Questions
  • 5
    Replies
I can't get the attribute trough Lightning Event. By clicking on the button "Get msg" I get `undefined`:

ceEvent.evt:
<aura:event type="COMPONENT">
		<aura:attribute name="message" type="String" default="111"/>
</aura:event>
ceNotifier.cmp:
 
<aura:component>
			<aura:attribute name="msg" type="String"/>
			<aura:registerEvent name="cmpEvent" type="c:ceEvent"/>
			<aura:handler name="cmpEvent" event="c:ceEvent" action="{!c.handleComponentEvent}"/>
			<lightning:button label="Get msg" onclick="{!c.getMsg}" />
			<p>{!v.msg}</p>
		</aura:component>
ceNotifierController.js:
({ 
			handleComponentEvent : function(cmp, event) {
				var cmpEvent = cmp.getEvent("cmpEvent");
				var message = cmpEvent.getParam("message");
				cmp.set("v.msg", message);
				alert(message);
			},
			
			getMsg : function(cmp, event) {
				var cmpEvent = cmp.getEvent("cmpEvent");
				var message = cmpEvent.getParam("message");
				alert(message);
			}, 
		})
ceHandler.cmp:
<aura:component>
			<aura:attribute name="messageFromEvent" type="String"/>
			<aura:handler name="cmpEvent" event="c:ceEvent" action="{!c.handleComponentEvent}"/>
			<aura:registerEvent name="cmpEvent" type="c:ceEvent"/>
			<lightning:button label="Send msg" onclick="{!c.fireComponentEvent}" />
			<c:ceNotifier />
		</aura:component>
ceHandlerController.js:
({
			handleComponentEvent : function(cmp, event) {
				var message = event.getParam("message");
				cmp.set("v.messageFromEvent", message);
				alert(message);
			},
			
			fireComponentEvent : function(cmp, event) {
				var cmpEvent = cmp.getEvent("cmpEvent");
				cmpEvent.setParams({"message" : "Here we go"});
				cmpEvent.fire();
				alert(cmpEvent.getParam("message"));
			}
		})
ceApp.app:
        <aura:application >
			<c:ceHandler/>
		</aura:application>
What am I doing wrong? How do i get an attribute?



 
I have 2 lists. First is all my objects. Second - selected object (I use "Select" button to add my obj to second list but without deliting it in the first list). I can also delete the objects from the second list. But how can I change the "Select" button's style from first list if I delete the element from second list?

cmp:
<aura:attribute name="objs" type="Obj__c[]"/>
<aura:attribute name="selectedObjs" type="Obj__c[]"/>

<div class="slds-grid slds-gutters divMain">
    <div class="slds-col div1Column">
        <aura:iteration items="{!v.objs}" var="obj" indexVar="index">     
            <lightning:layout multipleRows="true" class="layoutBigCardsColumn">
                <div data-index="{!index}" aura:id="divDetailsId">
                    <p><b>about {!obj.Name}</b></p>
                    //I need to change style of this btn:
                    <lightning:button aura:id="buttonSelectId" label="Select" name="{!obj}" class="buttonSelect" onclick="{!c.select}"/>
                </div>
            </lightning:layout>
        </aura:iteration>
    </div>

    <div class="slds-col div2Column">
        <lightning:layout horizontalAlign="center" multipleRows="true" class="layoutCardsColumn">
            <span class="selectedJobsTop">
                <aura:if isTrue="{!v.selectedObjs != null}">
                    <aura:iteration items="{!v.selectedObjs}" var="selectedObj" indexVar="index">
                        <div class="slds-panel__body layoutLittleCards">
                            <p>
                                <b>{!selectedObj.Name}</b>
                                <span class="spanButtonClose">
                                    //When I click "close", I need to change the style of needed "Select" btn:
                                    <lightning:buttonIcon name="{!index}" iconName="utility:close" onclick="{!c.deselect}"/>
                                </span>
                            </p>
                        </div>
                    </aura:iteration>
                </aura:if>
            </span>
        </lightning:layout>
    </div>
</div>
Needed functions from js:
select : function(component, event, helper) {
    let selectedObjs = component.get("v.selectedObjs");
    selectedObjs.push(event.getSource().get("v.name"));
    component.set("v.selectedObjs", selectedObjs);

    let selectButton = event.getSource();   
    selectButton.set("v.disabled", true);
    selectButton.set("v.class", "changeButtonColor");
},

deselect : function(component, event, helper) {
    let objs = component.get("v.objs");
    let selectedObjs = component.get("v.selectedObjs");

    let infos = component.find("buttonSelectId");

    let toDeletIndex =  event.getSource().get("v.name");
    selectedObjs.splice(toDeletIndex, 1);        
    component.set("v.selectedObjs", selectedObjs);

    for(let j=0; j<objs.length; j++){
        for (let i=0; i<selectedObjs.length; i++){
            if((objs[j].Id) == (selectedObjs[i].Id)){
                //I can get here currend array of selected objs,
                //but how can I change style of "Select" btn of removed (from here) obj?
                console.log(selectedObjs[i].Id);
            }           
        }
    }
},

 
I have a callout and batch on other side. Where do I need define steps and listsize: here or there? How to do it right?
@HttpGet
    global static List<Tool__c> getTool(){
        RestRequest req = RestContext.request;
        RestResponse res = new RestResponse();
        RestContext.response = res;
                
        Integer lastIndex = 400;  //I want make last index
        Integer listSize = 200;  //and size for 1 page
		
		//So I want to get 2 steps of 200 records till 400th record.
		//But I get only 200 on callout's side.
        
        Database.QueryLocator q = Database.getQueryLocator([SELECT Name, Price__c FROM Tool__c]);
        Database.QueryLocatorIterator iterator =  q.iterator();
       
        List<Tool__c> totalList = new List<Tool__c>();
        while (iterator.hasNext()) {
            Tool__c t = (Tool__c)iterator.next();
            totalList.add(t);    
        }
        
        List<Tool__c> currentList = new List<Tool__c>();
        Integer last_i;
        if((lastIndex + listSize) <= totalList.size()) {
            last_i = lastIndex + listSize;
        } else{
            last_i = totalList.size();
        }
        
        for(Integer i=lastIndex; i<last_i; i++) {
            currentList.add(totalList.get(i));
        }
        res.responseBody = Blob.valueOf(JSON.serialize(currentList));
        return currentList;
    }

 
I try to use HttpCalloutMock to test my post callout. But I become System.NullPointerException: Attempt to de-reference a null object. I need to test and web token, and posted object. I'm just learning and don't understand how actually use a Mock in this situation. Callout:
public class Token{
public String accessToken{get;set;}    
}

public static String accessTokenBody(){  //our web token (data is in fields)
        Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                                FROM Settings__c
                                WHERE Name = 'OurSettings'];  
        String consumerKey = settings.ConsumerKey__c;
        String consumerSecret = settings.ClientSecret__c;
        String username = settings.Username__c;
        String password = settings.Password__c + settings.SecurityToken__c;
        String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                         '&username=' + username + '&password='+password;
        return request;
    }

public static String GenerateJSON(Type__c t){
//I will send and post it like a record in another org:
    Map<String, String> fieldMap = new Map<String, String>{
                   'Name' => t.Name,
                   'Desc__c' => t.Type_Description__c};    
    String serialized = JSON.serialize(fieldMap);         
    return serialized;
 }

public static HttpRequest httpRequest(String service){
    String requestBody = accessTokenBody();
    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(requestBody);
    ourRequest.setMethod(service);
    ourRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token');
    return ourRequest;
}

public static HttpRequest finalHttpRequest(String token, String method, String endpointUrl){
    HttpRequest finalRequest = new HttpRequest();
    finalRequest.setHeader('Authorization','Bearer ' + token);
    finalRequest.setHeader('Content-Type','application/json');
    finalRequest.setHeader('accept','application/json');
    finalRequest.setMethod(method);
    finalRequest.setEndpoint('https://p21.lightning.force.com/services/oauth2/token' + endpointUrl);
    return finalRequest;
}

public static HttpResponse postCallout(String positionId) {
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('POST');
    HttpResponse response = ourHttp.send(request);      
    Token objAuthenticationInfo = (Token)JSON.deserialize(response.getbody(), Token.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        Type__c typ = [SELECT Id, Name FROM Type__c WHERE Id =: TypeID];
        HttpRequest finalRequest = finalHttpRequest(objAuthenticationInfo.ACCESS_TOKEN, 'POST', '');
        finalRequest.setBody(GenerateJSON(typ));
        HttpResponse finalResponse = ourHttp.send(finalRequest);
        if(finalResponse.getStatusCode() == 200) {
            System.debug('CREATED:  ' + finalResponse.getBody());
            return finalResponse;
        }else {
            return null;
        }
    }
    return null;
}
Mock:
@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
    HttpResponse response = new HttpResponse();
    response.setHeader('Content-Type', 'application/json');
    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, 
                        Password__c, SecurityToken__c
                        FROM Settings__c
                        WHERE Name = 'OurSettings'];
        String serialized = JSON.serialize(settings);
        response.setBody(serialized);
        response.setStatusCode(200);
        return response;
}
}
Test:
@isTest
private class CalloutTest {

@isTest
static void testPostCallout() {              
    Settings__c settings = new Settings__c(Name = 'OurSettings',
                                           ConsumerKey__c = '****',
                                           ClientSecret__c = '*****',
                                           Username__c = '*****',
                                           SecurityToken__c = '****',
                                           Password__c = 'mypassword1');
    insert settings;

    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;

    Type__c typ = new Type__c(Name = 'ttt');
    insert typ;

    Http ourHttp = new Http();
    String requestBody = CalloutJobAdvertisement.accessTokenBody();
    System.debug('request: ' + request);
    System.debug('request2: ' + requestBody);
    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(requestBody);
    ourRequest.setMethod('POST');
    ourRequest.setEndpoint('https://p21.salesforce.com/services/oauth2/token');    
    Test.startTest(); 
    Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
    HttpResponse response = CalloutJobAdvertisement.postCalloutResponseContents(pos.Id);

//Error is here. System.NullPointerException: Attempt to de-reference a null object

    String contentType = response.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualValue = response.getBody();
    System.debug(response.getBody());
    String expectedValue = '{"Name":"ttt"}';
    System.assertEquals(actualValue, expectedValue);
    System.assertEquals(200, response.getStatusCode());
    Test.stopTest(); 
}

public class OAuth2{
    public String ACCESS_TOKEN{get;set;}    
}
}
Coverage is just on my getAccess()httpRequest() and 5 first rows of postCallout() + last row return null;

 
I have a HttpPost methods. And I really don't know how to test it correctly.
My methods:
public static App__c ParseRequest(RestRequest req) {
    App__c app = new App__c();
    String body = req.requestBody.toString();
    app = (App__c)JSON.deserialize(body, App__c.class);
    return app;  
} 

@HttpPost
global static Id doPost() {
    RestRequest req = RestContext.request;        
    App__c app = ParseRequest(req);
    insert app;
    return app.id;
}

My test (just basis):
public static String GenerateJSON(App__c a){
    Map<String, String> fieldMap = new Map<String, String>{'Title__c' => a.Name};       
    String serialized = JSON.serialize(fieldMap);         
    return serialized;
}

@isTest
static void testPost() {
    App__c record = createTestRecord();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/App__c/' + record.Id;
    request.httpMethod = 'POST';
    RestContext.request = request;

    record = (App__c)JSON.deserialize(GenerateJSON(record), App__c.class);

    App__c j = Endpoint.ParseRequest(request);
    record = (App__c)JSON.deserialize(body, App__c.class);
}

static App__c createTestRecord() {
    App__c app = new App__c(
        Title__c = 'Title',
    );
    insert app;
    return app;
}

In App__c j = Endpoint.ParseRequest(request); I become Argument cannot be null. without coverage of:
app = (App__c)JSON.deserialize(body, App__c.class);
    return app;  
} 

@HttpPost
global static Id doPost() {
    RestRequest req = RestContext.request;        
    App__c app = ParseRequest(req);
    insert app;
    return app.id;
}

 
I wrote my Callout, but it create an object only with Id. How can I create an object with all fields?
HttpPost:
public static App__c ParseRequest(RestRequest req) {
    App__c app = new App__c();
    String body = req.requestBody.toString();
    app = (App__c)JSON.deserialize(body, App__c.class);
    return app;  
}

@HttpPost
global static Id doPost() 
{
    RestRequest req = RestContext.request;        
    App__c app = ParseRequest(req);
    insert app;
    return app.id;
}
Callout:
public static void postCallout() {

    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                            FROM Settings__c
                            WHERE Name = 'OurSettings'];  
    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;

    HttpRequest ourRequest = new HttpRequest();
    ourRequest.setBody(request);
    ourRequest.setMethod('POST');
    ourRequest.setEndpoint(System.Label.Job_Advertisement_URL + '/services/oauth2/token');

    Obj__c obj = [SELECT Name, Description__c, Skills__c
                       FROM Obj__c WHERE Name = 'Object'];

    HttpResponse response = ourHttp.send(request);      
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(response.getbody(), OAuth2.class);
    System.debug('BODY: ' + response.getBody());

    if(objAuthenticationInfo.ACCESS_TOKEN != null){

        JSONGenerator gen = JSON.createGenerator(true);    
        gen.writeStartObject();
        gen.writeStringField('title', obj.Name);
        gen.writeStringField('description', obj.Description__c);
        gen.writeStringField('skills', obj.Skills__c);

        String jsonString = gen.getAsString();
        System.debug('jsonMaterials: ' + jsonString);

        Http finalHttp = new Http();
        HttpRequest finalRequest = new HttpRequest();

        finalRequest.setHeader('Authorization','Bearer ' + objAuthenticationInfo.ACCESS_TOKEN);
        finalRequest.setHeader('Content-Type','application/json');
        finalRequest.setHeader('accept','application/json');
        finalRequest.setBody(jsonString);

        finalRequest.setMethod('POST');
        finalRequest.setEndpoint(System.Label.URL + '/services/apexrest/AppEndpoint');
        HttpResponse finalResponse = finalHttp.send(finalRequest);
        System.debug('RESPONSE BODY: '+ finalResponse.getBody());
    }
}

public class OAuth2{
    public String ACCESS_TOKEN{get;set;}    
}

 
Org 2 has GET Method:
@RestResource(urlMapping='/jobShow/*')
global with sharing class RestJob {

    @HttpGet
    global static List<Job__c> getJob(){
        List<Job__c> jobList;
        
        try{
            jobList = [SELECT Description__c 
                          FROM Job__c];  
        } catch(Exception e){
            System.debug('Error: ' + e.getMessage());
        }
        return jobList;     
    } 
}
Org 1 has Remote Site with link to Org 2: https://***.lightning.force.com

Org 1 also has a Callout Method:
public class HttpCalloutJob {
    
    public String getCalloutResponseContents(String url) {
    Http h = new Http();
    HttpRequest req = new HttpRequest();
req.setEndpoint('https://***.lightning.force.com/services/apexrest/jobShow');  //I don't know: is it right Link or not?
    req.setMethod('GET');

    HttpResponse res = h.send(req);   
    System.debug('Body: ' + res.getBody());
    return res.getBody();     
  }
}
Then I try to Execute this part
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://***.lightning.force.com/services/apexrest/jobShow');
req.setMethod('GET');
HttpResponse res = h.send(req);      
System.debug('Body: ' + res.getBody());
in Execute Anonymous Window, and become empty Body. But from workbench all is ok: it's not empty.

I think my link is wrong or I didn't connect my Orgs. How can I fix it?

Hello. I have a controller for VF Page. This code upload a profile's image (we can see it after that) and delete it. What kind of test can help me to check this file? I need to know, is it uploaded or not.

I work with ContentVersion  and ContentDocumentLink :

public class FileUploaderController {
    
    public ContentVersion conVer {get; set;}
    public ContentDocumentLink conDocLink {get; set;}
    public Candidate__c thisCandidate{get; set;}
   
    public FileUploaderController(ApexPages.StandardController controller){
        thisCandidate = (Candidate__c)controller.getRecord();
        conVer = new ContentVersion();
    }

    public PageReference uploadFile() {
        
        List<ContentVersion> conVerList = new List<ContentVersion>();
        List<ContentDocumentLink> conDocLinkList = new List<ContentDocumentLink>();
        
        if (conVer.VersionData == null) {
            conVer.VersionData = null;
            return null;
        }
        conVerList.add(conVer);
        insert conVerList;              
        thisCandidate.Photo__c = conVer.Id;
        update thisCandidate; 
        
        if (conVer.ContentDocumentId == null) {
            
            Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =: conVer.Id].ContentDocumentId;
            conDocLink = new ContentDocumentLink(
                LinkedEntityId = thisCandidate.Id,
                ContentDocumentId = conDoc,
                ShareType = 'I'
            );
            conDocLinkList.add(conDocLink);
            insert conDocLinkList;
        } 
        conVer.VersionData = null;
        return null;
    }

    public PageReference deleteFile() {
        thisCandidate.Photo__c = null;
        update thisCandidate;
        conVer = new ContentVersion();
        return null;
    }
}
It's a test block for my VF Controller. What is wrong here?
Candidate__c cand = new Candidate__c();
    insert cand;

    PageReference pageRef = Page.UploadCandidatePhotoVF;
        Test.startTest();
        Test.setCurrentPage(pageRef);
        pageRef.getParameters().put('id', cand.Id);
        ApexPages.StandardController stdController = new ApexPages.StandardController(cand);
        FileUploaderController fileUploader = new FileUploaderController(stdController);
        fileUploader.uploadFile();
        Test.stopTest();

 
I have a test class, but it's without Run Test button. And Coverage is 0%. What kind of problem can it be?
I need to check Max Image Size and File Type for creating correct Error ApexPages.Messages. I try do something like this:
if (conVer.FileType != '')
But what can I write there?
I can't choose my last file by record Id (this file was uploaded for this record). How can I do that by SOQL query?
conVersion = [SELECT Id FROM ContentVersion WHERE (Select LinkedEntityId from ContentDocumentId_r =: recId) order by CreatedDate DESC limit 1];

 
Now it loads an Attachment like a File. Can I choose a file from my computer? How can I do that?
public void sss(){        
        Attachment at = [Select Body, Id, Name, OwnerId,ParentId From Attachment LIMIT 1];
 
		ContentVersion conVer = new ContentVersion();
		conVer.ContentLocation = 'S';
		conVer.PathOnClient = at.Name;
		conVer.Title = 'tttt';
		conVer.VersionData = at.Body;
		insert conVer;
        
        Id conDoc = [SELECT ContentDocumentId FROM ContentVersion
                     WHERE Id =:conVer.Id].ContentDocumentId;
                
        ContentDocumentLink cl = new ContentDocumentLink(
            LinkedEntityId = 'a071r00001Hnn2uAAB',
            ContentDocumentId = conDoc, ShareType = 'I');
		insert cl;
    }
VF Page:
<apex:page standardController="Cand__c" extensions="uplClass">
    <apex:form >
      <apex:pageBlock title="Upload Attachment" >
          <apex:inputFile style="width: 100%" value="{!at.Body}" fileName="{!at.Name}" accept="image/*" />
          <apex:commandButton value="But" action="{!sss}" />     
      </apex:pageBlock>
  </apex:form>
</apex:page>

 
I need to create a Button for the Page Layout that links to the Visualforce Page (another page). It's for custom object. How can I do that? Can I use "Buttons, Links, and Actions" to open VF Page? Or I need to create another VF Page?
I don't understand what is wrong in "Convert the Source and Push It to a New Scratch Org" from trail "Convert and Deploy an Existing App". I get this error:
the path specified is not a directory or doesn't contain a package.xml.
Here is what I have in PowerShell: 
User-added image
I have a problem with my trailhead "Quick Start: Salesforce DX".
I'm trying to do this:
sfdx force:org:create -s -f config/project-scratch-def.json -a "default scratch org"

But become an Error: You do not have access to the [scratchorginfo] object

I make all right, step by step. Connected status is "Connected". How can I fix it?

I have a trigger. If a user who creates a record isn't 'Manager' (UserRole.Name) - record's OwnerId change to GroupQueue.Id. I have a correct test method for scenario, where user-creator is 'Manager', but I don't know how to test if he isn't. I get an error "System.AssertException: Assertion Failed: Expected: 0,Actual 1" here. My code works right. I just can't make this test method. How can I fix it?

Helper:
public static void beforeInsert(List<Obj__c> : newList) {   //for before insert trigger

        Map<Id, User> userMap = new Map<Id, User>([SELECT Id FROM User WHERE UserRole.Name = 'Manager']);        
        Group groupQueue = [SELECT Id FROM Group WHERE Type = 'Queue' AND Name = 'Object Queue' LIMIT 1];
		
 		for(Obj__c obj: newList){
		 		if(!userMap.containsKey(obj.OwnerId)){
					obj.OwnerId = groupQueue.Id;
		 		} 
		}
	}
Test:
@isTest
    private static void createObjByNotManager(){
        
        UserRole userRole = new UserRole(Name = 'Somebody else');
        insert userRole;
        
        Profile profileId = [SELECT Id FROM Profile LIMIT 1];

        User user = new User(
            UserRoleId = userRole.Id,
            LastName = 'Test Code',
			Email = 'test@test.com',
			Alias = 'Tcode',
			Username = 'test1234444@testzsdfsdtfsdf.com',
			CommunityNickname = 'test12',
			LocaleSidKey = 'en_US',
			TimeZoneSidKey = 'GMT',
			ProfileID = profileId.Id,
			LanguageLocaleKey = 'en_US',
			EmailEncodingKey = 'UTF-8'
        );
        insert user;
        
		Group testGroup = new Group(Name = 'Object Queue', Type = 'Queue');
        insert testGroup;
        insert new QueueSobject(QueueId = testGroup.Id, SObjectType = 'Obj__c');
        
        Obj__c obj = new Obj__c(
            Name = 'Test Object'
        );
        System.runAs(user) {
            insert obj;
		}
        
        List<Obj__c> objList = [SELECT OwnerId FROM Obj__c WHERE OwnerId =: testGroup.Id];
        System.assertEquals(positionList.size(), 1);
    }

I can't break this loop:

List<User> userList = [SELECT Id FROM User WHERE UserRole.Name = 'X'];

     for(Obj__c obj: Trigger.new){
         for(User user : userList){
             if(obj.CreatedById != user.Id){
                 obj.OwnerId = user.Id;
             }
         }     
     }
I need to reassign an object if user's Role != 'X'.
We have a few users with Role 'X'. We need to reassign an object to one from these users, if it's created not by one of them. But my loop choose the last one and change owner even if owner is already correct (with Role 'X'). How can I fix it?
List<User> userList = [SELECT Id FROM User WHERE UserRole.Name = 'X'];

     for(Obj__c obj: Trigger.new){
         for(User user : userList){
             if(obj.CreatedById != user.Id){
                 obj.OwnerId = user.Id;
             }
         }     
     }

 
How can I make more methods in this Helper class, not just public static void?
I also need a method for checking the update of Stage__c field (when we update another fields - Trigger shouldn't be started).

Helper:
public with sharing class JobTriggerHelper {
    
    public static void create(List<Job__c> jobList){
        
        List<Task> taskList = new List<Task>();
        
        for(Job__c job : jobList){ 
            if(job.Stage__c == 'Closed'){
                Task t = new Task(
                     Subject = 'Closed',
                taskList.add(t);
            }
                    
            try{
               insert taskList; 
            } catch(DMLException e){
               jobApp.addError('Error message');
            }       
        }
      }  
    }
Trigger:
trigger JobTrigger on Job__c (after insert, after update) {
    
    if(Trigger.isAfter){
        if(Trigger.isInsert || Trigger.isUpdate){
            JobTriggerHelper.create(Trigger.new);
        }
      } 
    }
I have 2 lists. First is all my objects. Second - selected object (I use "Select" button to add my obj to second list but without deliting it in the first list). I can also delete the objects from the second list. But how can I change the "Select" button's style from first list if I delete the element from second list?

cmp:
<aura:attribute name="objs" type="Obj__c[]"/>
<aura:attribute name="selectedObjs" type="Obj__c[]"/>

<div class="slds-grid slds-gutters divMain">
    <div class="slds-col div1Column">
        <aura:iteration items="{!v.objs}" var="obj" indexVar="index">     
            <lightning:layout multipleRows="true" class="layoutBigCardsColumn">
                <div data-index="{!index}" aura:id="divDetailsId">
                    <p><b>about {!obj.Name}</b></p>
                    //I need to change style of this btn:
                    <lightning:button aura:id="buttonSelectId" label="Select" name="{!obj}" class="buttonSelect" onclick="{!c.select}"/>
                </div>
            </lightning:layout>
        </aura:iteration>
    </div>

    <div class="slds-col div2Column">
        <lightning:layout horizontalAlign="center" multipleRows="true" class="layoutCardsColumn">
            <span class="selectedJobsTop">
                <aura:if isTrue="{!v.selectedObjs != null}">
                    <aura:iteration items="{!v.selectedObjs}" var="selectedObj" indexVar="index">
                        <div class="slds-panel__body layoutLittleCards">
                            <p>
                                <b>{!selectedObj.Name}</b>
                                <span class="spanButtonClose">
                                    //When I click "close", I need to change the style of needed "Select" btn:
                                    <lightning:buttonIcon name="{!index}" iconName="utility:close" onclick="{!c.deselect}"/>
                                </span>
                            </p>
                        </div>
                    </aura:iteration>
                </aura:if>
            </span>
        </lightning:layout>
    </div>
</div>
Needed functions from js:
select : function(component, event, helper) {
    let selectedObjs = component.get("v.selectedObjs");
    selectedObjs.push(event.getSource().get("v.name"));
    component.set("v.selectedObjs", selectedObjs);

    let selectButton = event.getSource();   
    selectButton.set("v.disabled", true);
    selectButton.set("v.class", "changeButtonColor");
},

deselect : function(component, event, helper) {
    let objs = component.get("v.objs");
    let selectedObjs = component.get("v.selectedObjs");

    let infos = component.find("buttonSelectId");

    let toDeletIndex =  event.getSource().get("v.name");
    selectedObjs.splice(toDeletIndex, 1);        
    component.set("v.selectedObjs", selectedObjs);

    for(let j=0; j<objs.length; j++){
        for (let i=0; i<selectedObjs.length; i++){
            if((objs[j].Id) == (selectedObjs[i].Id)){
                //I can get here currend array of selected objs,
                //but how can I change style of "Select" btn of removed (from here) obj?
                console.log(selectedObjs[i].Id);
            }           
        }
    }
},

 
I have a problem with my trailhead "Quick Start: Salesforce DX".
I'm trying to do this:
sfdx force:org:create -s -f config/project-scratch-def.json -a "default scratch org"

But become an Error: You do not have access to the [scratchorginfo] object

I make all right, step by step. Connected status is "Connected". How can I fix it?

Hello. I need to convert a Lead with LeadConvert and change an opp's Name like this: 'AccountName + DateTime.now'. How can I do that? This doesn't work:

for (Lead lead : Trigger.new) { 
        if (lead.isConverted == false && lead.Status == 'Closed - Converted') {
            lc.setLeadId(lead.Id);   
            lc.setConvertedStatus(convertStatus.MasterLabel);
            lcList.add(lc);
            
            String s = String.valueOf(lc.getAccountId());
         	String b = String.valueOfGmt(Datetime.now());
            lc.setOpportunityName(s + b);
            
            List<Database.LeadConvertResult> lcrList = Database.convertLead(lcList,false);
     }
I become 'null+DateTime.now'. How can I take AccName before Database.convertLead? :( 

How I should write "<apex:inputFile value=" in Apex for Contact? I need a custom value or standard, like in "Document" - "<apex:inputFile value="{!document.body}"  filename="{!document.name}"/>"?

Sorry, I'm new.