34
Visualforce + jQuery Force.com上でjQueryを有効活用 Riezel Ramos, Salesforce.com, Associate Sales Support Engineer Kaz Kawamura, Salesforce.com, Technical Solution Architect

Visualforce + jQuery

Embed Size (px)

DESCRIPTION

2012年12月6日 Cloudforce Japan Developer Zone内のシアターで講演された資料です。

Citation preview

Page 1: Visualforce + jQuery

Visualforce + jQuery Force.com上でjQueryを有効活用

Riezel Ramos, Salesforce.com, Associate Sales Support Engineer Kaz Kawamura, Salesforce.com, Technical Solution Architect

Page 2: Visualforce + jQuery

Safe harbor Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.

Page 3: Visualforce + jQuery

今日の内容

・Javascript + jQuery ・Javascript + jQuery + Visualforce

・Javascript + jQuery + Visualforce + Imagination

Page 4: Visualforce + jQuery

自己紹介 ライゼール ラモス (Riezel Ramos)

・出身: フィリピン

・会社: Salesforce.com

・仕事: Sales Support       

Engineer

・その他名前: ライズ、ライコ、雷子

河村 嘉之(Kaz Kawamura)

・会社: Salesforce.com

・仕事: Technical Solution Architect

この本の著者

Page 5: Visualforce + jQuery

Javascript + jQuery

Page 6: Visualforce + jQuery

Javascriptのないインターネット

・地図: 検索にリダイレクトされる

・Youtube: ビデオが動かない ・Facebook : メッセージとチャットが動かない

・Twitter : Tweetできない

Page 7: Visualforce + jQuery

Javascriptがあるから、ウェブがインターアクティブになった

Page 8: Visualforce + jQuery

Javascriptの役割:HTMLドキュメントを操作するため

ウェブページ

HTML: 構造

Javascript: アクション

CSS: スタイル

<body>            <div>                      <input  type=“text”  id=“in1”/>            </div> </body> <script  type=“text/javascript”>          var  foo  =  document.getElementById(“in1”);�        foo.addEventListener(“click”,  alert(“アロハ!”),  false);�</script> <style>          body{                      background:  pink;          } </style>

Page 9: Visualforce + jQuery

問題:JavascriptだけでDOMの操作が難しい!

よく使うJavascriptの機

能をいくつまとめて、提

供しています。

Page 10: Visualforce + jQuery

jQueryでJavascriptをシンプルにする

Javascript

var x = document.getElementById(‘in1’);

jQuery

var x = $(‘#in1');

サンプル:http://jquery.com/

Page 11: Visualforce + jQuery

jQueryの良い点

・32KB (minified) ・CSS3のサポート

・クロスブラウザーサポート

・jQuery UI ・jQuery Mobile

・jQuery Plugins

Page 12: Visualforce + jQuery

Javascript + jQuery + force.com

Page 13: Visualforce + jQuery

まずは、jQueryライブラリをVFページから読みましょう

・静的リソースとして、アップロード <script src=“{!$Resource.jQueryFile}”></script>

・CDNを使う

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>

Page 14: Visualforce + jQuery

Apex:includeScript OR script?

<apex:page showHeader="false"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <apex:includeScript value="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"/> </apex:page>

Page 15: Visualforce + jQuery

気を付けましょう!

$j = jQuery.noConflict();  →他のライブラリとconflictしないため(標準Visualforceで使っているライブラリを含む)

Page 16: Visualforce + jQuery

Visualforce v.s. jQuery

ページ 部品

Visualforce jQuery

Page 17: Visualforce + jQuery

Visualforce > jQuery

基本はVFで書いたページ

ボタンを押した時のアクションなどを

JavaScriptで記述

Page 18: Visualforce + jQuery

Visualforceの部品のIDを取るには?

<apex:outputPanel id="thePanel"></apex:outputPanel>

document.getElementById("{!$Component.thePanel}").innerHTML = result;

$("#{!$Component.thePanel}").text(result);

!$Component.コンポーネントのIDを指定

階層がある場合は階層も指定

注意! これは動かない IDに:が入ると

jQueryは別の意味に捉える

実はjQueryとVFの相性はあまり良くな

い…(以下略)

j_id0:thePanel

Page 19: Visualforce + jQuery

Visualforce+jQuery 使いどころ

<apex:form > Weekday <apex:inputCheckBox value="{!weekday}" styleClass="days"/> Satday <apex:inputCheckBox value="{!satday}" styleClass="days"/> Sunday <apex:inputCheckBox value="{!sunday}" styleClass="days"/> <input type="button" id="check" value="check all"/> </apex:form>

$('#check').click(function() { $('.days').attr('checked', 'checked'); });

classを指定して一括処理

生成されるコードではclass属性になる

UIに+αを加える

Page 20: Visualforce + jQuery

Visualforce < jQuery

サーバサイドの機能を呼び出し

ほぼHTMLでそのまま記述

Page 21: Visualforce + jQuery

ページからforce.comにアクセス

• actionSupport • actionFunction

• JavaScript Remoting

Page 22: Visualforce + jQuery

actionSupport

<apex:inputText value="{!recordInputText}"> <apex:actionSupport action="{!refresh}" event="onchange” reRender="parentPanel"> <apex:param assignTo="{!var1}" value="{!recordId}" name="recordParam"/> </apex:actionSupport> </apex:inputText>

コントローラのメソッドを呼び出す

イベントを指定

イベントの発生に合わせて、コントローラのメソッドを呼び出す • JavaScriptを書かずにイベント処理を実現 • 結果はreRenderで

Page 23: Visualforce + jQuery

actionFunction

<apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="showstate"> <apex:param name="firstParam" assignTo="{!state}" value="" /> </apex:actionFunction>

<script> function clickOne(){ methodOneInJavaScript(); } </script>

コントローラのメソッドを指定

名前を付ける

指定した名前でJavaScriptから

呼び出し

コントローラのメソッドに名前を付けてJavaScriptから利用できるようにする • 結果はreRenderで

Page 24: Visualforce + jQuery

JavaScript Remoting

<script> $(function() { HelloRemote.sayHello('World', function(result, event) { $('#out').text(result); }); }); </script> global class HelloRemote {

@RemoteAction global static String sayHello(String name) { return 'Hello ' + name + '!'; } }

コントローラ名.メソッド名で呼び出し 引数を

渡せる コールバック関数

リモートアクセス可能なメソッドをアノテーション

でマーク

よりJavaScriptっぽくコントローラのメソッドを呼べる • より柔軟 • ただしコードは増える

Page 25: Visualforce + jQuery

IDの工夫

<apex:page standardController="Account” recordSetVar="accounts"> <apex:repeat value="{!accounts}" var="account"> <div id=”acct_{!account.id}">{!account.name}</div> </apex:repeat> </apex:page>

<div id=”acct_001A00000090CmoIAE">A商事</div> <div id=”acct_001A000000RQgHkIAL”>B商事</div> <div id=”acct_001A000000EaawzIAB">A商事</div>

IDは一意でなければいけ

ない

SFIDをうまく活用すると一意性を確保するのが容易

Page 26: Visualforce + jQuery

Javascript + jQuery + Visualforce + Imagination

世界征服をしてやろう!!

Page 27: Visualforce + jQuery

Mini Page Hover

・レコード名にhoverをしたら、詳細を表示する

デモ

Page 28: Visualforce + jQuery

Mini Page Hover: コード

var url = $(this).attr(‘href’) + ‘ div.bDetailBlock’; //hoverしているレコードのURLを取得

$(‘#overlay’).load(url, function () { //#overlayのdivにURLをロードする

setTimeout(function () { //overlayを表示する

  $(‘#overlay’).show(); },

200);

});

Page 29: Visualforce + jQuery

Mini Page Hover: コード アドバイス: HTMLで作られているホームページコンポーネントのコードフォーマットが崩れるため、jsbeautifierみたいなツールを使うのがお

勧めです (http://jsbeautifier.org/)

Page 30: Visualforce + jQuery

iPad アンケート作成用ツール デモ

デモ(iPad)

セールスフォース側

iPad側

Page 31: Visualforce + jQuery

iPad アンケート作成用ツール(セールスフォース側) ・jQuery + jQuery UI

$( ".answerUL1" ).sortable({ start: function (e, ui) { },

update: function (e, ui) { /*更新時にこのメッソドを行う */

$( “.answerUL .choiceLabel1”).each( function(){ /* 各選択肢のソート番号を更新する */

$(this).find(".choiceSortNumber").val($(this).index()+1); });

/* apexコントローラーを呼び出し、ソート番号を更新する */ sortChoiceList( /*パラメータ省略 */); } });

<apex:actionFunction action="{!sortChoiceList}" reRender="questionPanel" name="sortChoiceList" oncomplete="initSortable();" > /* パラメータ省略 */

</apex:actionFunction>

Page 32: Visualforce + jQuery

iPad アンケート作成用ツール(セールスフォース側)

アドバイス: reRenderの使い方 ページの一部のみ、更新したい場合、

reRenderでapexタグのidを指定すれば、 指定したDOMしか更新されません。

reRenderを使う時に、できるだけ小さいDOMを 設定しないと、重くなる可能性があります。

<apex:actionFunction action="{!sortChoiceList}"

reRender="questionPanel"

name="sortChoiceList"

oncomplete="initSortable();" /> 選択肢の順番を更新したいため、選択肢を持っているパネルを更新します。全ページを更新したら、重くなりますので、小さい範囲で更新したほうが良いです。

Page 33: Visualforce + jQuery

iPad アンケート作成用ツール(iPad側)

・jQuery + jQuery Mobile ・複数のプラットフォームで見えるページを

モバイル向けのUIで簡単に作成ができるので、

jQuery Mobileで作りました。

apex:repeatでページ、

質問、選択肢を

ループして表示している

Page 34: Visualforce + jQuery