• Kishan Kumar 77
  • NEWBIE
  • 15 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 10
    Replies
User-added image
I need to add the delete option as well. I have given user the CRED permissions through a permission set even though the user cannot see the delete option.

Please suggest what else can I do to add the delete option.
How do I write a test class for a class that uses a query from custom label using a past date. I am running a query that fetches records of a custom object with a where clause as 
Select Id, Name, etc from custom_object__c where systemmodstamp >= 2014-11-15T13:00:00.000Z and systemmodstamp <= 2014-11-15T22:00:00.000Z.

Please help me to write a test class so that it satisfies the code coverage requirement.
 Write a trigger to add “.invalid” suffix at the end of an email id for all the user as below :
Ex : Email Id : Raj@gmail.com.invalid

Also, I need to write a function that removes the ".invalid" added to the Email id.
Ex- Email id-Raj@gmail.com
1st requirement- if the number starts with B then it's length should be 6 only and it should be of format  e.g-B12345.

2nd requirement- the number should start from DE and it should be of length 7 only. For example-DE12345. There cannot be alphabets in between for example- DE123V4.

Both rules have to be applied on same field
It should be of length 8 only. And it can accept only numbers no alphabet no special characters
I have an object as teacher_student__c .Whenever a student is linked to a teacher, check whether the student already has a teacher with same subject assigned to him/her and if already exists, then throw an error 'A teacher is already assigned to this student for the subject.
This is the code that I have tried. Please help me complete it.

trigger OneToOne on Certification_Request__c (before insert, before update, after insert, after update) {
for (Certification_Request__c q : [SELECT Due_Date__c,Employee__c,Employee_s_Email__c,Status__c from Certification_Request__c]) {
        if(q.Due_Date__c<date.today() && (q.Status__c!='Approved' || q.Status__c!='Rejected'))
        {
            
        }

}
---------------------js file-----------------------------
import { LightningElement, track } from 'lwc';
import getOppList from '@salesforce/apex/customSearchController.getOppList';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'
export default class CustomSearch extends LightningElement {
    @track opportunity;
    sVal='';
    receivedMessage;
    @track record = [];
    @track columns=[
        {label: 'Name', fieldName: 'Name',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'Name'
            } 
        },
        sortable: true },
          {label: 'Account Name', fieldName: 'AccountId',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'AccountId.Name'
            } 
        }, 
        sortable: true},
        {label: 'Stage Name', fieldName: 'StageName',type: 'picklist'},
        {label: 'Type', fieldName: 'Type',type: 'picklist'},
        {label: 'Amount', fieldName: 'Amount',type: 'currency'},
        {label:'Action',type:'button',typeAttributes: {
            label: 'Send Opp',
            name: 'Send',
            disabled: false,
            value: 'send',
            iconPosition: 'left'
        }
    }
    ];
    // update sVal var when input field value change
    updateSeachKey(event) {
        this.sVal = event.target.value;
    }
 
    // call apex method on button click 
    handleSearch() {
        // if search input value is not blank then call apex method, else display error msg 
        if (this.sVal !== '') {
            getOppList({
                    searchKey: this.sVal
                })
                .then(result => {
                    // set @track opportunities variable with return contact list from server  
                    this.opportunity = result;
                })
                .catch(error => {
                    // display server exception in toast msg 
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                    // reset contacts var with null   
                    this.opportunity = null;
                });
        } else {
            // fire toast event if input field is blank
            const event = new ShowToastEvent({
                variant: 'error',
                message: 'Search text missing..',
            });
            this.dispatchEvent(event);
        }
    }
    handleRowAction(event){
        const row = event.detail.row;
        let actionName = event.detail.action.name;
        switch(actionName) {
            case 'Send':
            this.record = row;
            const calloutURI = 'https://herokuapp.com';
            fetch(calloutURI, {
                method: "POST",
                headers: {
                    "Accept": "application/json"
                  },
                  body:  JSON.stringify(record)
            })
            .then((response) => {
                       return response.json(); 
                })
                .then(responseJSON => {
                    console.log(responseJSON);
                    console.log(record);
                })
                .catch(error => {
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                });
        }
    }
}
-------------------html file---------------------------
<template>
   <div class="slds-m-around_medium">
     
        <div class="slds-m-bottom_small">
            <lightning-input type="text"
               value={sVal}
               label="Search Opportunity"
               onchange={updateSeachKey}
               ></lightning-input>
         </div>
         
         <lightning-button label="Search"
            onclick={handleSearch}
            variant="brand"></lightning-button>
            
            <lightning-datatable data={opportunity} columns={columns} key-field="id" onrowaction={handleRowAction}>
            </lightning-datatable>
</div>This is the error i am getting and after making changes also it shows the same thing.
</template>
--------------js file----------------------------------------------
import { LightningElement, track } from 'lwc';
import getOppList from '@salesforce/apex/customSearchController.getOppList';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'
export default class CustomSearch extends LightningElement {
    @track opportunity;
    sVal='';
    receivedMessage;
    @track record = [];
    @track columns=[
        {label: 'Name', fieldName: 'Name',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'Name'
            } 
        },
        sortable: true },
          {label: 'Account Name', fieldName: 'AccountId',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'AccountId.Name'
            } 
        }, 
        sortable: true},
        {label: 'Stage Name', fieldName: 'StageName',type: 'picklist'},
        {label: 'Type', fieldName: 'Type',type: 'picklist'},
        {label: 'Amount', fieldName: 'Amount',type: 'currency'},
        {label:'Action',type:'button',typeAttributes: {
            label: 'Send Data',
            name: 'Send',
            disabled: false,
            value: 'send',
            iconPosition: 'left'
        }
    }
    ];
    // update sVal var when input field value change
    updateSeachKey(event) {
        this.sVal = event.target.value;
    }
 
    // call apex method on button click 
    handleSearch() {
        // if search input value is not blank then call apex method, else display error msg 
        if (this.sVal !== '') {
            getOppList({
                    searchKey: this.sVal
                })
                .then(result => {
                    // set @track opportunities variable with return contact list from server  
                    this.opportunity = result;
                })
                .catch(error => {
                    // display server exception in toast msg 
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                    // reset contacts var with null   
                    this.opportunity = null;
                });
        } else {
            // fire toast event if input field is blank
            const event = new ShowToastEvent({
                variant: 'error',
                message: 'Search text missing..',
            });
            this.dispatchEvent(event);
        }
    }
    handleRowAction(event){
        const row = event.detail.row;
        switch(actionName) {
            case 'Send':
            this.record = row;
            const calloutURI = 'https://herokuapp.com';
            fetch(calloutURI, {
                method: "POST",
                headers: {
                    "Accept": "application/json"
                  },
                  body:  JSON.stringify(record)
            })
            .then((response) => {
                       return response.json(); 
                })
                .then(responseJSON => {
                    console.log(responseJSON);
                    console.log(record);
                })
                .catch(error => {
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                });
        }
    }
}
---------------html file---------
<template>
   <div class="slds-m-around_medium">
     
        <div class="slds-m-bottom_small">
            <lightning-input type="text"
               value={sVal}
               label="Search Opportunity"
               onchange={updateSeachKey}
               ></lightning-input>
         </div>
         
         <lightning-button label="Search"
            onclick={handleSearch}
            variant="brand"></lightning-button>
            
            <lightning-datatable data={opportunity} columns={columns} key-field="id" onrowaction={handleRowAction}>
            </lightning-datatable>
</div>
</template>

This is the error i am getting and cannot rectify what's the error.
Thanks in advance!!
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public static Id selectedRec {get;set;}
    public integer totalRecs = 0;
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
    public pageReference FirstPage()
    {
        OffsetSize = 0;
        searchOpportunity();
        return null;
    }
    public pageReference previous()
    {
        OffsetSize = OffsetSize - LimitSize;
        searchOpportunity();
        return null;
    }
    public pageReference next()
    {
        OffsetSize = OffsetSize + LimitSize;
        
        searchOpportunity();
        return null;
    }
    public pageReference LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        
        searchOpportunity();
        return null;
    }
    public boolean getprev()
    {
        if(OffsetSize == 0)
            return true;
        else
            return false;
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs)
            
            return true;
        else
            return false;
    } 
    public static HttpResponse sendData()
    {
        Opportunity op=[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                        
                        from Opportunity
                        
                        where Id = :selectedRec];
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();     
        gen.writeStringField('Name ', op.Name);
        
        gen.writeStringField('Account',op.Account.Name);
        gen.writeStringField('Stage',op.StageName);
        gen.writeStringField('Type',op.Type);
        gen.writeNumberField('Amount',op.Amount);
        gen.writeDateField('Close Date',op.CloseDate);
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        // Sending the http body with JSON
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 201)
        {
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec];  
            o.Integration_Status__c='Not Successful';
            o.Integration_Comments__c=response.getStatus();
            update o;
            System.debug(response.getStatusCode());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Opps! your Callout was not successful'));
        }
        
        else {
            
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec]; 
            
            o.Integration_Status__c='Success';
            o.Integration_Comments__c='Success';
            update o;
            System.debug(response.getStatusCode());
        }
      return response;
    }
    
}
 
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public Id selectedRec {get;set;}
    
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble ]; 
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText];
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
}
1st requirement- if the number starts with B then it's length should be 6 only and it should be of format  e.g-B12345.

2nd requirement- the number should start from DE and it should be of length 7 only. For example-DE12345. There cannot be alphabets in between for example- DE123V4.

Both rules have to be applied on same field
How do I write a test class for a class that uses a query from custom label using a past date. I am running a query that fetches records of a custom object with a where clause as 
Select Id, Name, etc from custom_object__c where systemmodstamp >= 2014-11-15T13:00:00.000Z and systemmodstamp <= 2014-11-15T22:00:00.000Z.

Please help me to write a test class so that it satisfies the code coverage requirement.
I have an object as teacher_student__c .Whenever a student is linked to a teacher, check whether the student already has a teacher with same subject assigned to him/her and if already exists, then throw an error 'A teacher is already assigned to this student for the subject.
---------------------js file-----------------------------
import { LightningElement, track } from 'lwc';
import getOppList from '@salesforce/apex/customSearchController.getOppList';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'
export default class CustomSearch extends LightningElement {
    @track opportunity;
    sVal='';
    receivedMessage;
    @track record = [];
    @track columns=[
        {label: 'Name', fieldName: 'Name',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'Name'
            } 
        },
        sortable: true },
          {label: 'Account Name', fieldName: 'AccountId',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'AccountId.Name'
            } 
        }, 
        sortable: true},
        {label: 'Stage Name', fieldName: 'StageName',type: 'picklist'},
        {label: 'Type', fieldName: 'Type',type: 'picklist'},
        {label: 'Amount', fieldName: 'Amount',type: 'currency'},
        {label:'Action',type:'button',typeAttributes: {
            label: 'Send Opp',
            name: 'Send',
            disabled: false,
            value: 'send',
            iconPosition: 'left'
        }
    }
    ];
    // update sVal var when input field value change
    updateSeachKey(event) {
        this.sVal = event.target.value;
    }
 
    // call apex method on button click 
    handleSearch() {
        // if search input value is not blank then call apex method, else display error msg 
        if (this.sVal !== '') {
            getOppList({
                    searchKey: this.sVal
                })
                .then(result => {
                    // set @track opportunities variable with return contact list from server  
                    this.opportunity = result;
                })
                .catch(error => {
                    // display server exception in toast msg 
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                    // reset contacts var with null   
                    this.opportunity = null;
                });
        } else {
            // fire toast event if input field is blank
            const event = new ShowToastEvent({
                variant: 'error',
                message: 'Search text missing..',
            });
            this.dispatchEvent(event);
        }
    }
    handleRowAction(event){
        const row = event.detail.row;
        let actionName = event.detail.action.name;
        switch(actionName) {
            case 'Send':
            this.record = row;
            const calloutURI = 'https://herokuapp.com';
            fetch(calloutURI, {
                method: "POST",
                headers: {
                    "Accept": "application/json"
                  },
                  body:  JSON.stringify(record)
            })
            .then((response) => {
                       return response.json(); 
                })
                .then(responseJSON => {
                    console.log(responseJSON);
                    console.log(record);
                })
                .catch(error => {
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                });
        }
    }
}
-------------------html file---------------------------
<template>
   <div class="slds-m-around_medium">
     
        <div class="slds-m-bottom_small">
            <lightning-input type="text"
               value={sVal}
               label="Search Opportunity"
               onchange={updateSeachKey}
               ></lightning-input>
         </div>
         
         <lightning-button label="Search"
            onclick={handleSearch}
            variant="brand"></lightning-button>
            
            <lightning-datatable data={opportunity} columns={columns} key-field="id" onrowaction={handleRowAction}>
            </lightning-datatable>
</div>This is the error i am getting and after making changes also it shows the same thing.
</template>
--------------js file----------------------------------------------
import { LightningElement, track } from 'lwc';
import getOppList from '@salesforce/apex/customSearchController.getOppList';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'
export default class CustomSearch extends LightningElement {
    @track opportunity;
    sVal='';
    receivedMessage;
    @track record = [];
    @track columns=[
        {label: 'Name', fieldName: 'Name',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'Name'
            } 
        },
        sortable: true },
          {label: 'Account Name', fieldName: 'AccountId',type: 'url', 
        typeAttributes: { 
            label: {
                fieldName: 'AccountId.Name'
            } 
        }, 
        sortable: true},
        {label: 'Stage Name', fieldName: 'StageName',type: 'picklist'},
        {label: 'Type', fieldName: 'Type',type: 'picklist'},
        {label: 'Amount', fieldName: 'Amount',type: 'currency'},
        {label:'Action',type:'button',typeAttributes: {
            label: 'Send Data',
            name: 'Send',
            disabled: false,
            value: 'send',
            iconPosition: 'left'
        }
    }
    ];
    // update sVal var when input field value change
    updateSeachKey(event) {
        this.sVal = event.target.value;
    }
 
    // call apex method on button click 
    handleSearch() {
        // if search input value is not blank then call apex method, else display error msg 
        if (this.sVal !== '') {
            getOppList({
                    searchKey: this.sVal
                })
                .then(result => {
                    // set @track opportunities variable with return contact list from server  
                    this.opportunity = result;
                })
                .catch(error => {
                    // display server exception in toast msg 
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                    // reset contacts var with null   
                    this.opportunity = null;
                });
        } else {
            // fire toast event if input field is blank
            const event = new ShowToastEvent({
                variant: 'error',
                message: 'Search text missing..',
            });
            this.dispatchEvent(event);
        }
    }
    handleRowAction(event){
        const row = event.detail.row;
        switch(actionName) {
            case 'Send':
            this.record = row;
            const calloutURI = 'https://herokuapp.com';
            fetch(calloutURI, {
                method: "POST",
                headers: {
                    "Accept": "application/json"
                  },
                  body:  JSON.stringify(record)
            })
            .then((response) => {
                       return response.json(); 
                })
                .then(responseJSON => {
                    console.log(responseJSON);
                    console.log(record);
                })
                .catch(error => {
                    const event = new ShowToastEvent({
                        title: 'Error',
                        variant: 'error',
                        message: error.body.message,
                    });
                    this.dispatchEvent(event);
                });
        }
    }
}
---------------html file---------
<template>
   <div class="slds-m-around_medium">
     
        <div class="slds-m-bottom_small">
            <lightning-input type="text"
               value={sVal}
               label="Search Opportunity"
               onchange={updateSeachKey}
               ></lightning-input>
         </div>
         
         <lightning-button label="Search"
            onclick={handleSearch}
            variant="brand"></lightning-button>
            
            <lightning-datatable data={opportunity} columns={columns} key-field="id" onrowaction={handleRowAction}>
            </lightning-datatable>
</div>
</template>

This is the error i am getting and cannot rectify what's the error.
Thanks in advance!!
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public static Id selectedRec {get;set;}
    public integer totalRecs = 0;
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText LIMIT :LimitSize OFFSET :OffsetSize];
                totalRecs = OppList.size();
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
    public pageReference FirstPage()
    {
        OffsetSize = 0;
        searchOpportunity();
        return null;
    }
    public pageReference previous()
    {
        OffsetSize = OffsetSize - LimitSize;
        searchOpportunity();
        return null;
    }
    public pageReference next()
    {
        OffsetSize = OffsetSize + LimitSize;
        
        searchOpportunity();
        return null;
    }
    public pageReference LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        
        searchOpportunity();
        return null;
    }
    public boolean getprev()
    {
        if(OffsetSize == 0)
            return true;
        else
            return false;
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs)
            
            return true;
        else
            return false;
    } 
    public static HttpResponse sendData()
    {
        Opportunity op=[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                        
                        from Opportunity
                        
                        where Id = :selectedRec];
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();     
        gen.writeStringField('Name ', op.Name);
        
        gen.writeStringField('Account',op.Account.Name);
        gen.writeStringField('Stage',op.StageName);
        gen.writeStringField('Type',op.Type);
        gen.writeNumberField('Amount',op.Amount);
        gen.writeDateField('Close Date',op.CloseDate);
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        
        // Sending the http body with JSON
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonS);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() != 201)
        {
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec];  
            o.Integration_Status__c='Not Successful';
            o.Integration_Comments__c=response.getStatus();
            update o;
            System.debug(response.getStatusCode());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Opps! your Callout was not successful'));
        }
        
        else {
            
            Opportunity o= [select Integration_Comments__c,Integration_Status__c from Opportunity
                            where Id =:selectedRec]; 
            
            o.Integration_Status__c='Success';
            o.Integration_Comments__c='Success';
            update o;
            System.debug(response.getStatusCode());
        }
      return response;
    }
    
}
 
public with sharing class OppSearch {
    
    public List<Opportunity> OppList { get; set; }
    
    public String searchText { get; set; }
    public Id selectedRec {get;set;}
    
    public OppSearch()
    {
        
        OppList = new List<Opportunity>();
        
    }
    
    public PageReference searchOpportunity()
        
    {
        OppList = new List<Opportunity>();
        
        if(String.isBlank(searchText))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter some value'));
        }
        
        
        
        if(String.isNotBlank(searchText))
        {
            if(searchText.isNumeric())
            {
                Decimal searchstringDouble = decimal.valueOf(searchText);
                
                OppList = [select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                           
                           from Opportunity
                           
                           where Amount=:searchstringDouble ]; 
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            else {
                String newSearchText = searchText+'%';
                
                OppList =[select Id,Name,Account.Name,StageName,Type,Amount,CloseDate
                          
                          from Opportunity
                          where Name like:newSearchText or Account.Name like:newSearchText
                          or StageName like:newSearchText or Type like:newSearchText];
                
                if(OppList.size()==0)
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Search failed as criteria do not match'));
                }
                
            }
            
        }
        return null;
    }
}