Search code examples
dynamicappceleratorpicker

How to dynamically populate a Picker using Alloy with Appcelerator?


Is there a way to populate a picker dynamically? This works for option dialogs:

view.xml:

<OptionDialog id="distributionPointsOptionDialog">
 <Options>
    <Option id="{dp}"></Option> 
 </Options>
</OptionDialog>

controller.js:

var dp = [];
for (var j in _data) {
    if (_data[j].country == country) {
        dp.push(_data[j].city + "-" + _data[j].dp_name);
        }
}
$.distributionPointsOptionDialog.options = dp;

Is there a way to do the same for a multi-column picker? I tried unsuccessfully to populate a single-column picker.

controller.js:

var fs = Ti.Filesystem;
var installedFonts = fs.getFile(fs.resourcesDirectory+ "/fonts").getDirectoryListing();
Ti.API.info("list of resourcesDirectory fonts: " + JSON.stringify(installedFonts));
var fonts = [];
for (var j in installedFonts) {
    fonts.push(installedFonts[j]);
}
$.testPicker.column = fonts;

views.xml:

<Picker id="testPicker" selectionIndicator="true" height="Ti.UI.SIZE" width="70%" visible="true" zIndex="200" useSpinner="true">
<Column>
   <Row title="{fonts}"></Row>
</Column>
</Picker>

This results in an error:

ERROR] :      message = "undefined is not an object (evaluating '$model.__transform')";

Solution

  • There are couple of wrong things with your implementation.

    1. useSpinner property has been deprecated, so please remove that from your code.
    2. The way you are implementing Options & Pickers is a process of Alloy-Model binding.
    3. For dynamic Options, you can simply use below code:

    <OptionDialog id="distributionPointsOptionDialog"></OptionDialog> $.distributionPointsOptionDialog.options = ['Helvetica', 'Arial', 'Times New Roman'];

    1. <Option id="{dp}"></Option> - this syntax is used for Model data binding

    2. For Picker, use below code:

    var fonts = []; fonts[0]=Ti.UI.createPickerRow({title:'Helvetica'}); fonts[1]=Ti.UI.createPickerRow({title:'Arial'}); fonts[2]=Ti.UI.createPickerRow({title:'Times New Roman'}); fonts[3]=Ti.UI.createPickerRow({title:'Georgia'}); $.testPicker.add(fonts);

    OR

    var column = Ti.UI.createPickerColumn(); column.add( Ti.UI.createPickerRow({ title: 'Helvetica' }) ); column.add( Ti.UI.createPickerRow({ title: 'Arial' }) ); column.add( Ti.UI.createPickerRow({ title: 'Times New Roman' }) ); column.add( Ti.UI.createPickerRow({ title: 'Georgia' }) ); $.testPicker.columns = [column];

    For Pickers, in short, you can either use $.testPicker.add() method, or you can set columns like this $.testPicker.columns = [column1, column2, column1, ...]

    Read more here How to add Columns or Rows in Pickers

    or

    How to add column(s) in Picker