src/cm/media/js/lib/yui/yui_3.10.3/docs/datatable/datatable-dsget.html
author Yves-Marie Haussonne <ymh.work+github@gmail.com>
Fri, 09 May 2014 18:35:26 +0200
changeset 656 a84519031134
parent 525 89ef5ed3c48b
permissions -rw-r--r--
add link to "privacy policy" in the header test

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Example: DataTable + DataSource.Get + JSON Data</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
    <script src="../../build/yui/yui-min.js"></script>
    
</head>
<body>
<!--
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-->
<div id="doc">
    <div id="hd">
        <h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1>
    </div>
    

            <h1>Example: DataTable + DataSource.Get + JSON Data</h1>
    <div class="yui3-g">
        <div class="yui3-u-3-4">
            <div id="main">
                <div class="content"><style scoped>
/* css to counter global site css */
.example table {
    width: auto;
}
.example caption {
    display: table-caption;
}
.example th,
.example td {
    border: 0 none;
    text-transform :none;
}
</style>

<div class="intro">
    <p>
        This example shows how to populate a DataTable with data from the
        Yahoo! Local webservice retrieved via a YQL query. First we create a
        DataSource.Get instance pointing to YQL, then using the
        DataTableDataSource plugin we can load data for pizza places near our
        office.
    </p>

    <p>
        In this example, we render the DataTable first, then load data into it
        in a separate call.
    </p>
</div>

<div class="example yui3-skin-sam">
    <div id="pizza"></div>

<script>
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function (Y) {

    var url = "http://query.yahooapis.com/v1/public/yql?format=json" +
                  "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
        query = "&q=" + encodeURIComponent(
                'select * from local.search ' +
                'where zip = "94089" and query = "pizza"'),
        dataSource,
        table;

    dataSource = new Y.DataSource.Get({ source: url });

    dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
        schema: {
            resultListLocator: "query.results.Result",
            resultFields: [
                "Title",
                "Phone",
                {
                    key: "Rating",
                    locator: "Rating.AverageRating",
                    parser: function (val) {
                        // YQL is returning "NaN" for unrated restaurants
                        return isNaN(val) ? -1 : +val;
                    }
                }
            ]
        }
    });

    table = new Y.DataTable({
        columns: [
            "Title",
            "Phone",
            {
                key: "Rating",
                formatter: function (o) {
                    if (o.value === -1) {
                        o.value = '(none)';
                    }
                }
            }
        ],
        summary: "Pizza places near 98089",
        caption: "Table with JSON data from YQL"
    });
    
    table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

    table.render("#pizza");

    table.datasource.load({ request: query });
});
</script>

</div>

<h2>Populating Your DataTable with Remote Data Using DataSource.Get</h2>

<p>
    Your table can be easily popluated with remote JSON data from a JSONP
    webservice by creating a DataSource instance and using the
    DataTableDataSource plugin to load the data into a DataTable.
</p>

<p>Start with the <code>use()</code> statement:</p>

<pre class="code prettyprint">YUI().use(&quot;datatable&quot;, &quot;datasource-get&quot;, &quot;datasource-jsonschema&quot;, &quot;datatable-datasource&quot;, function(Y) {
});</pre>


<p>
    Next create a DataSource.Get instance pointing to YQL. The <a
    href="http://developer.yahoo.com/yql/console/">YQL Console</a> makes it
    easy to determine the REST URL we want to send. You also need to define the
    correct schema for the DataSourceJSONSchema plugin.
</p>

<pre class="code prettyprint">var dataSource = new Y.DataSource.Get({
    source: &quot;http:&#x2F;&#x2F;query.yahooapis.com&#x2F;v1&#x2F;public&#x2F;yql?&quot;+
        &quot;q=select%20*%20from%20local.search%20where%20zip%3D%2794089%27%20&quot;+
        &quot;and%20query%3D%27pizza%27&amp;format=json&amp;&quot;+
        &quot;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&quot;
});

dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
    schema: {
        resultListLocator: &quot;query.results.Result&quot;,
        resultFields: [ &quot;Title&quot;, &quot;Phone&quot;, &quot;Rating&quot; ]
    }
});</pre>


<p>
    This is a good time to call <code>sendRequest</code> to make sure the data returns as
    expected.
</p>

<pre class="code prettyprint">dataSource.sendRequest({
    callback: {
        success: function(e) {
            Y.log(e);
        }
    }
});</pre>


Results:
<pre class="code prettyprint">{
    &quot;query&quot;: {
        ...
        &quot;results&quot;: {
            &quot;Result&quot;:[
                {
                    &quot;Title&quot; : &quot;Giovannis Pizzeria&quot;,
                    &quot;Phone&quot; : &quot;(408) 734-4221&quot;,
                    ...
                    &quot;Rating&quot;: {
                        &quot;AverageRating&quot;: &quot;4&quot;,
                        ...
                    }
                },
                {
                    &quot;Title&quot; : &quot;Pizza&quot;,
                    &quot;Phone&quot; : &quot;(800) 555-1212&quot;,
                    ...
                    &quot;Rating&quot;: {
                        &quot;AverageRating&quot;:&quot;NaN&quot;,
                        ...
                    }
                },
                ...
            ]
        }
    }
}</pre>


<p>
    Uh oh. The <code>Rating</code> data we're receiving is an object rather than a single value.  It looks like <code>Rating.AverageRating</code> is what we want, but it's a numeric string, and sometimes the unfortunate value "NaN".
</p>

<p>
    We'll add a <code>locator</code> to the schema to extract the <code>Rating.AverageRating</code>
    value for our <code>Rating</code> data field, and also a <code>parser</code> that will convert
    the numeric string into a real number, using <code>-1</code> for restaurants that
    haven't received a rating yet.  It's a good policy to store the table model
    data as the appropriate type.
</p>

<pre class="code prettyprint">schema: {
    resultListLocator: &quot;query.results.Result&quot;,
    resultFields: [
        &quot;Title&quot;,
        &quot;Phone&quot;,
        {
            key: &quot;Rating&quot;,
            locator: &quot;Rating.AverageRating&quot;,
            parser: function (val) {
                return isNaN(val) : -1 : +val;
            }
        }
    ]
}</pre>


<p>
    Now that the DataSource is created properly, define the columns that you
    want your table to show. These columns map directly to the parameter names
    returned in the data.  We'll add a formatter to the <code>Rating</code> column to
    deal with those <code>-1</code>s, instead displaying "(none)".
</p>

<pre class="code prettyprint">var cols = [
    &quot;Title&quot;,
    &quot;Phone&quot;,
    {
        key: &quot;Rating&quot;,
        formatter: function (o) {
            &#x2F;&#x2F; formatters can either return the new content or update o.value
            if (o.value === -1) {
                o.value = &quot;(none)&quot;;
            }
        }
    }
];</pre>


<p>
    Now you are ready to create a DataTable using the columns you have defined.
    When you plug the instance with the DataTableDataSource plugin, point to
    your DataSource instance. After you render the table, load the data via the
    plugin.
</p>

<pre class="code prettyprint">var table = new Y.DataTable({
    columns : cols,
    summary : &quot;Pizza places near 98089&quot;,
    caption : &quot;Table with JSON data from YQL&quot;
});

table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

table.render(&quot;#pizza&quot;);

table.datasource.load();</pre>


<p>
    One final change you can make is to split the URL between the DataSource
    <code>source</code> value and the <code>request</code> value sent to the DataTableDataSource
    plugin. Splitting the URL this way facilitates making future requests to
    the same DataSource.  You can see this in the <a href="#fullcode">Full Code
    Listing</a> below.
</p>

<h2 id="fullcode">Full Code Listing</h2>
<p>
<strong>Note:</strong> be sure to add the <code>yui3-skin-sam</code> classname to the
page's <code>&lt;body&gt;</code> element or to a parent element of the widget in order to apply
the default CSS skin. See <a href="http://yuilibrary.com/yui/docs/tutorials/skins/">Understanding Skinning</a>.
</p> <!-- You need this skin class -->
<pre class="code prettyprint">&lt;body class=&quot;yui3-skin-sam&quot;&gt; &lt;!-- You need this skin class --&gt;</pre>


<pre class="code prettyprint">&lt;div id=&quot;pizza&quot;&gt;&lt;&#x2F;div&gt;

&lt;script&gt;
YUI().use(&quot;datatable&quot;, &quot;datasource-get&quot;, &quot;datasource-jsonschema&quot;, &quot;datatable-datasource&quot;, function (Y) {

    var url = &quot;http:&#x2F;&#x2F;query.yahooapis.com&#x2F;v1&#x2F;public&#x2F;yql?format=json&quot; +
                  &quot;&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&quot;,
        query = &quot;&amp;q=&quot; + encodeURIComponent(
                &#x27;select * from local.search &#x27; +
                &#x27;where zip = &quot;94089&quot; and query = &quot;pizza&quot;&#x27;),
        dataSource,
        table;

    dataSource = new Y.DataSource.Get({ source: url });

    dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
        schema: {
            resultListLocator: &quot;query.results.Result&quot;,
            resultFields: [
                &quot;Title&quot;,
                &quot;Phone&quot;,
                {
                    key: &quot;Rating&quot;,
                    locator: &quot;Rating.AverageRating&quot;,
                    parser: function (val) {
                        &#x2F;&#x2F; YQL is returning &quot;NaN&quot; for unrated restaurants
                        return isNaN(val) ? -1 : +val;
                    }
                }
            ]
        }
    });

    table = new Y.DataTable({
        columns: [
            &quot;Title&quot;,
            &quot;Phone&quot;,
            {
                key: &quot;Rating&quot;,
                formatter: function (o) {
                    if (o.value === -1) {
                        o.value = &#x27;(none)&#x27;;
                    }
                }
            }
        ],
        summary: &quot;Pizza places near 98089&quot;,
        caption: &quot;Table with JSON data from YQL&quot;
    });
    
    table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

    table.render(&quot;#pizza&quot;);

    table.datasource.load({ request: query });
});
&lt;&#x2F;script&gt;</pre>


<h3>Lighten the module payload</h3>

<p>
    The <code>datatable</code> module includes a number of features not used in this
    example.  For a smaller module payload, use the <code>datatable-base</code> module.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; datatable-base includes only basic table rendering, but in this case,
&#x2F;&#x2F; that&#x27;s enough.
YUI().use(&quot;datatable-base&quot;, &quot;datasource-get&quot;, &quot;datasource-jsonschema&quot;, &quot;datatable-datasource&quot;, function(Y) {

    ...

    var table = new Y.DataTable({
        columns : cols,
        summary : &quot;Pizza places near 98089&quot;,
        caption : &quot;Table with JSON data from YQL&quot;
    });

    table.plug(Y.Plugin.DataTableDataSource, { datasource: dataSource });

    table.render(&quot;#pizza&quot;);

    table.datasource.load();

});</pre>

</div>
            </div>
        </div>

        <div class="yui3-u-1-4">
            <div class="sidebar">
                

                
                    <div class="sidebox">
                        <div class="hd">
                            <h2 class="no-toc">Examples</h2>
                        </div>

                        <div class="bd">
                            <ul class="examples">
                                
                                    
                                        <li data-description="This example illustrates simple DataTable use cases.">
                                            <a href="datatable-basic.html">Basic DataTable</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="DataTable loaded with JSON data from a remote webservice via DataSource.Get">
                                            <a href="datatable-dsget.html">DataTable + DataSource.Get + JSON Data</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="DataTable loaded with XML data from a remote webservice via DataSource.IO.">
                                            <a href="datatable-dsio.html">DataTable + DataSource.IO + XML Data</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Custom format data for display.">
                                            <a href="datatable-formatting.html">Formatting Row Data for Display</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="DataTable with nested column headers.">
                                            <a href="datatable-nestedcols.html">Nested Column Headers</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="DataTable with column sorting.">
                                            <a href="datatable-sort.html">Column Sorting</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="DataTable with vertical and/or horizontal scrolling rows.">
                                            <a href="datatable-scroll.html">Scrolling DataTable</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Using DataTable&#x27;s recordType attribute to create calculated, sortable columns.">
                                            <a href="datatable-recordtype.html">Sortable generated columns</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Populating one DataTable from details in the data of another.">
                                            <a href="datatable-masterdetail.html">Master and detail tables</a>
                                        </li>
                                    
                                
                                    
                                        <li data-description="Checkbox column that retains checked state when sorting.">
                                            <a href="datatable-chkboxselect.html">Checkbox select column</a>
                                        </li>
                                    
                                
                                    
                                
                            </ul>
                        </div>
                    </div>
                

                
                    <div class="sidebox">
                        <div class="hd">
                            <h2 class="no-toc">Examples That Use This Component</h2>
                        </div>

                        <div class="bd">
                            <ul class="examples">
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                
                                    
                                        <li data-description="Shows how to instantiate multiple Panel instances, and use nested modality to interact with a Datatable.">
                                            <a href="../panel/panel-form.html">Creating a Modal Form</a>
                                        </li>
                                    
                                
                            </ul>
                        </div>
                    </div>
                
            </div>
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

<script>
YUI.Env.Tests = {
    examples: [],
    project: '../assets',
    assets: '../assets/datatable',
    name: 'datatable-dsget',
    title: 'DataTable + DataSource.Get + JSON Data',
    newWindow: '',
    auto:  false 
};
YUI.Env.Tests.examples.push('datatable-basic');
YUI.Env.Tests.examples.push('datatable-dsget');
YUI.Env.Tests.examples.push('datatable-dsio');
YUI.Env.Tests.examples.push('datatable-formatting');
YUI.Env.Tests.examples.push('datatable-nestedcols');
YUI.Env.Tests.examples.push('datatable-sort');
YUI.Env.Tests.examples.push('datatable-scroll');
YUI.Env.Tests.examples.push('datatable-recordtype');
YUI.Env.Tests.examples.push('datatable-masterdetail');
YUI.Env.Tests.examples.push('datatable-chkboxselect');
YUI.Env.Tests.examples.push('panel-form');

</script>
<script src="../assets/yui/test-runner.js"></script>



</body>
</html>