The AppGini Blog
A few tips and tricks to make your coding life a tiny bit better.

Select first item in a lookup dropdown by default

Purpose of this recipe

You have a lookup field in a table. And when adding a new record to the table, you want that field to be set to the first value by default (rather than being empty).

Files to edit

Add the following code to hooks/tablename-dv.js (where tablename is the name of the concerned table). If the file doesn’t exist, create it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
$j(function() {
  // Run this code only if this is a new record
  if($j('[name=SelectedID]').val().length) return;

  setTimeout(function() {
    $j.ajax({
      url: 'ajax_combo.php',
      data: {
        s: '', // search term should be empty
        p: 1, // page number should be 1
        t: 'tablename', // replace with the actual table name
        f: 'lookup_fieldname' // replace with the actual lookup field name
      },
      success: function(data) {
        if(data.results.length < 2) return;
        $j('#lookup_fieldname-container').select2('data', data.results[1]);
      }
    })
  }, 1000); // this delay might be necessary to ensure all select2 is loaded first
})

Change tablename and lookup_fieldname above to the actual table name and lookup field name.