Saturday, 22 August 2015

Simple Contact Search using Angular JS + Bootstrap

This post explains you a basic use of Angular JS + Salesforce Remote Objects + Bootstrap Css.

app.js

var myapp = angular.module("myAngularMVC",[]);
myapp.controller("myAngularMVCController",function($scope)
{
 
 $scope.fetch = function(contactName)
 { 
     var wh = new SObjectModel.contact();
     
     wh.retrieve({where: {Name: {eq: contactName }}}, function(err, records, event)
     {
         if(err) 
         {
             alert(err.message);
         }
         else 
         {
             var ul = document.getElementById("contactsList");
             ul.innerHTML = '';
             records.forEach(function(record) 
             {
                 var whText = record.get("Name");
                 whText += " -- ";
                 whText += record.get("Phone");
                 
                 var li = document.createElement("li");
                 li.appendChild(document.createTextNode(whText));
                 ul.appendChild(li);
             });
         }
     });
 };
});

Visualforce Page

<apex:page>
<script src="{!URLFOR($Resource.angulardemo,'vendor/angular.min.js')}"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="{!URLFOR($Resource.angulardemo,'app/app.js')}"/>

<div ng-app="myAngularMVC">
    <apex:remoteobjects>
        <apex:remoteobjectmodel fields="Id,Name" jsshorthand="contact" name="Contact">
            <apex:remoteobjectfield jsshorthand="phone" name="Phone"/>
        </apex:remoteobjectmodel>
    </apex:remoteobjects>

    <div ng-controller="myAngularMVCController">
        <form class="form-inline">
            <div class="form-group">
            <label for="exampleInputName2">Contact Name</label>
               <input class="form-control" ng-model="contactName" placeholder="Enter Name to search" type="text"/>
            </div>
            <button class="btn btn-default" ng-click="fetch(contactName)" type="submit">Search</button>    
            <ul id="contactsList"></ul>
        </form>
    </div>
</div>
</apex:page>

Preview