Guest User

Untitled

a guest
Dec 15th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. $('#contact_id').select2({
  2. ajax: {
  3. url: 'example.com/contacts/select',
  4. dataType: 'json',
  5. delay: 250,
  6. data: function (params) {
  7. return {
  8. q: params.term,
  9. page: params.page
  10. };
  11. },
  12. processResults: function (data) {
  13. return {
  14. results: data
  15. };
  16. },
  17. cache: true
  18. },
  19. minimumInputLength: 3,
  20. maximumSelectionLength: 1
  21. });
  22.  
  23. foreach($contacts as $con) {
  24. $results[] = [
  25. 'id' => $con->contact_id,
  26. 'text' => $con->full_name,
  27. 'org' => [
  28. 'org_id' => $con->organization_id,
  29. 'org_name' => $con->org_name
  30. ]
  31. ];
  32. }
  33.  
  34. return response()->json($results);
  35.  
  36. <select>
  37. <option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
  38. </select>
  39.  
  40. processResults: function (data) {
  41. data = data.map(function (item) {
  42. return {
  43. id: item.id_field,
  44. text: item.text_field,
  45. otherfield: item.otherfield
  46. };
  47. });
  48. return { results: data };
  49. }
  50.  
  51. var data=$('#contact_id').select2('data')[0];
  52. console.log(data.otherfield);
  53.  
  54. $('#select2-box').select2({
  55. placeholder: 'Search Existing Contacts',
  56. ajax: {
  57. url: '/contacts/typeahead',
  58. dataType: 'json',
  59. delay: 250,
  60. data: function(params){
  61. return {
  62. q: params.term,
  63. type: '',
  64. suggestions: 1
  65. };
  66. },
  67. processResults: function(data, params){
  68. //Send the data back
  69. return {
  70. results: data
  71. };
  72. }
  73. },
  74. minimumInputLength: 2
  75. }).on('select2:select', function(event) {
  76. // This is how I got ahold of the data
  77. var contact = event.params.data;
  78.  
  79. // contact.suggestions ...
  80. // contact.organization_id ...
  81. });
  82.  
  83.  
  84.  
  85. // Data I was returning
  86. [
  87. {
  88. "id":36167, // ID USED IN SELECT2
  89. "avatar":null,
  90. "organization_id":28037,
  91. "text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
  92. "suggestions":[
  93. {
  94. "id":28037,
  95. "text":"WWE",
  96. "avatar":null
  97. },
  98. {
  99. "id":21509,
  100. "text":"Kurt Angle",
  101. "avatar":null
  102. },
  103. {
  104. "id":126,
  105. "text":"Mark Calaway",
  106. "avatar":null
  107. },
  108. {
  109. "id":129,
  110. "text":"Ricky Steamboat",
  111. "avatar":null
  112. },
  113. {
  114. "id":131,
  115. "text":"Brock Lesnar",
  116. "avatar":null
  117. }
  118. ]
  119. }
  120. ]
Add Comment
Please, Sign In to add comment