Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hafriedlander/9404561 to your computer and use it in GitHub Desktop.
Save hafriedlander/9404561 to your computer and use it in GitHub Desktop.
MemberAutocompleteField (example of SilverStripe 3.1 ajax-based autocomplete)
<?php
class MemberAutocompleteField extends TextField {
private static $allowed_actions = array('suggest');
public $maxSuggestionsNum = 50;
public function Field($properties = array()) {
Requirements::javascript("mysite/javascript/MemberAutocompleteField.js");
return parent::Field($properties);
}
public function getAttributes() {
$attrs = parent::getAttributes();
$custom = array(
'class' => $attrs['class'] . ' member-autocomplete text',
'data-source' => parse_url($this->Link(), PHP_URL_PATH).'/suggest'
);
return array_merge($attrs, $custom);
}
public function suggest($request) {
if (!Permission::check('CMS_ACCESS_LeftAndMain')) return Convert::raw2json(array());
$searchString = trim($request->requestVar('term'));
//NOTE: using the LOWER function will mean that indexes will not work on this column.
$SQL_filter = 'LOWER(' . sprintf("\"Member\".\"Email\") LIKE LOWER('%%%s%%')",
Convert::raw2sql($searchString)
);
$tagObjs = DataObject::get('Member', $SQL_filter, $this->tagSort, "", $this->maxSuggestionsNum);
$tagArr = ($tagObjs) ? array_values($tagObjs->map('ID', 'Email')->toArray()) : array();
return Convert::raw2json($tagArr);
}
public function dataValue() {
return $this->value ? Member::get()->filter('Email', $this->value)->first()->ID : null;
}
function setValue($value, $obj = null) {
if ($value && is_numeric($value)) $value = Member::get()->byID($value)->Email;
parent::setValue($value, $obj);
}
}
(function($){
$('input.member-autocomplete').entwine({
onadd: function(){
var source = this.attr('data-source');
this.autocomplete({
source: source,
minLength: 3
});
}
})
}(jQuery))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment