class-acf-field-select.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. <?php
  2. if ( ! class_exists( 'acf_field_select' ) ) :
  3. class acf_field_select extends acf_field {
  4. /*
  5. * __construct
  6. *
  7. * This function will setup the field type data
  8. *
  9. * @type function
  10. * @date 5/03/2014
  11. * @since 5.0.0
  12. *
  13. * @param n/a
  14. * @return n/a
  15. */
  16. function initialize() {
  17. // vars
  18. $this->name = 'select';
  19. $this->label = _x( 'Select', 'noun', 'acf' );
  20. $this->category = 'choice';
  21. $this->defaults = array(
  22. 'multiple' => 0,
  23. 'allow_null' => 0,
  24. 'choices' => array(),
  25. 'default_value' => '',
  26. 'ui' => 0,
  27. 'ajax' => 0,
  28. 'placeholder' => '',
  29. 'return_format' => 'value',
  30. );
  31. // ajax
  32. add_action( 'wp_ajax_acf/fields/select/query', array( $this, 'ajax_query' ) );
  33. add_action( 'wp_ajax_nopriv_acf/fields/select/query', array( $this, 'ajax_query' ) );
  34. }
  35. /*
  36. * input_admin_enqueue_scripts
  37. *
  38. * description
  39. *
  40. * @type function
  41. * @date 16/12/2015
  42. * @since 5.3.2
  43. *
  44. * @param $post_id (int)
  45. * @return $post_id (int)
  46. */
  47. function input_admin_enqueue_scripts() {
  48. // bail early if no enqueue
  49. if ( ! acf_get_setting( 'enqueue_select2' ) ) {
  50. return;
  51. }
  52. // globals
  53. global $wp_scripts, $wp_styles;
  54. // vars
  55. $min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
  56. $major = acf_get_setting( 'select2_version' );
  57. $version = '';
  58. $script = '';
  59. $style = '';
  60. // attempt to find 3rd party Select2 version
  61. // - avoid including v3 CSS when v4 JS is already enququed
  62. if ( isset( $wp_scripts->registered['select2'] ) ) {
  63. $major = (int) $wp_scripts->registered['select2']->ver;
  64. }
  65. // v4
  66. if ( $major == 4 ) {
  67. $version = '4.0.13';
  68. $script = acf_get_url( "assets/inc/select2/4/select2.full{$min}.js" );
  69. $style = acf_get_url( "assets/inc/select2/4/select2{$min}.css" );
  70. // v3
  71. } else {
  72. $version = '3.5.2';
  73. $script = acf_get_url( "assets/inc/select2/3/select2{$min}.js" );
  74. $style = acf_get_url( 'assets/inc/select2/3/select2.css' );
  75. }
  76. // enqueue
  77. wp_enqueue_script( 'select2', $script, array( 'jquery' ), $version );
  78. wp_enqueue_style( 'select2', $style, '', $version );
  79. // localize
  80. acf_localize_data(
  81. array(
  82. 'select2L10n' => array(
  83. 'matches_1' => _x( 'One result is available, press enter to select it.', 'Select2 JS matches_1', 'acf' ),
  84. 'matches_n' => _x( '%d results are available, use up and down arrow keys to navigate.', 'Select2 JS matches_n', 'acf' ),
  85. 'matches_0' => _x( 'No matches found', 'Select2 JS matches_0', 'acf' ),
  86. 'input_too_short_1' => _x( 'Please enter 1 or more characters', 'Select2 JS input_too_short_1', 'acf' ),
  87. 'input_too_short_n' => _x( 'Please enter %d or more characters', 'Select2 JS input_too_short_n', 'acf' ),
  88. 'input_too_long_1' => _x( 'Please delete 1 character', 'Select2 JS input_too_long_1', 'acf' ),
  89. 'input_too_long_n' => _x( 'Please delete %d characters', 'Select2 JS input_too_long_n', 'acf' ),
  90. 'selection_too_long_1' => _x( 'You can only select 1 item', 'Select2 JS selection_too_long_1', 'acf' ),
  91. 'selection_too_long_n' => _x( 'You can only select %d items', 'Select2 JS selection_too_long_n', 'acf' ),
  92. 'load_more' => _x( 'Loading more results&hellip;', 'Select2 JS load_more', 'acf' ),
  93. 'searching' => _x( 'Searching&hellip;', 'Select2 JS searching', 'acf' ),
  94. 'load_fail' => _x( 'Loading failed', 'Select2 JS load_fail', 'acf' ),
  95. ),
  96. )
  97. );
  98. }
  99. /*
  100. * ajax_query
  101. *
  102. * description
  103. *
  104. * @type function
  105. * @date 24/10/13
  106. * @since 5.0.0
  107. *
  108. * @param $post_id (int)
  109. * @return $post_id (int)
  110. */
  111. function ajax_query() {
  112. // validate
  113. if ( ! acf_verify_ajax() ) {
  114. die();
  115. }
  116. // get choices
  117. $response = $this->get_ajax_query( $_POST );
  118. // return
  119. acf_send_ajax_results( $response );
  120. }
  121. /*
  122. * get_ajax_query
  123. *
  124. * This function will return an array of data formatted for use in a select2 AJAX response
  125. *
  126. * @type function
  127. * @date 15/10/2014
  128. * @since 5.0.9
  129. *
  130. * @param $options (array)
  131. * @return (array)
  132. */
  133. function get_ajax_query( $options = array() ) {
  134. // defaults
  135. $options = acf_parse_args(
  136. $options,
  137. array(
  138. 'post_id' => 0,
  139. 's' => '',
  140. 'field_key' => '',
  141. 'paged' => 1,
  142. )
  143. );
  144. // load field
  145. $field = acf_get_field( $options['field_key'] );
  146. if ( ! $field ) {
  147. return false;
  148. }
  149. // get choices
  150. $choices = acf_get_array( $field['choices'] );
  151. if ( empty( $field['choices'] ) ) {
  152. return false;
  153. }
  154. // vars
  155. $results = array();
  156. $s = null;
  157. // search
  158. if ( $options['s'] !== '' ) {
  159. // strip slashes (search may be integer)
  160. $s = strval( $options['s'] );
  161. $s = wp_unslash( $s );
  162. }
  163. // loop
  164. foreach ( $field['choices'] as $k => $v ) {
  165. // ensure $v is a string
  166. $v = strval( $v );
  167. // if searching, but doesn't exist
  168. if ( is_string( $s ) && stripos( $v, $s ) === false ) {
  169. continue;
  170. }
  171. // append
  172. $results[] = array(
  173. 'id' => $k,
  174. 'text' => $v,
  175. );
  176. }
  177. // vars
  178. $response = array(
  179. 'results' => $results,
  180. );
  181. // return
  182. return $response;
  183. }
  184. /*
  185. * render_field()
  186. *
  187. * Create the HTML interface for your field
  188. *
  189. * @param $field - an array holding all the field's data
  190. *
  191. * @type action
  192. * @since 3.6
  193. * @date 23/01/13
  194. */
  195. function render_field( $field ) {
  196. // convert
  197. $value = acf_get_array( $field['value'] );
  198. $choices = acf_get_array( $field['choices'] );
  199. // placeholder
  200. if ( empty( $field['placeholder'] ) ) {
  201. $field['placeholder'] = _x( 'Select', 'verb', 'acf' );
  202. }
  203. // add empty value (allows '' to be selected)
  204. if ( empty( $value ) ) {
  205. $value = array( '' );
  206. }
  207. // prepend empty choice
  208. // - only for single selects
  209. // - have tried array_merge but this causes keys to re-index if is numeric (post ID's)
  210. if ( $field['allow_null'] && ! $field['multiple'] ) {
  211. $choices = array( '' => "- {$field['placeholder']} -" ) + $choices;
  212. }
  213. // clean up choices if using ajax
  214. if ( $field['ui'] && $field['ajax'] ) {
  215. $minimal = array();
  216. foreach ( $value as $key ) {
  217. if ( isset( $choices[ $key ] ) ) {
  218. $minimal[ $key ] = $choices[ $key ];
  219. }
  220. }
  221. $choices = $minimal;
  222. }
  223. // vars
  224. $select = array(
  225. 'id' => $field['id'],
  226. 'class' => $field['class'],
  227. 'name' => $field['name'],
  228. 'data-ui' => $field['ui'],
  229. 'data-ajax' => $field['ajax'],
  230. 'data-multiple' => $field['multiple'],
  231. 'data-placeholder' => $field['placeholder'],
  232. 'data-allow_null' => $field['allow_null'],
  233. );
  234. if ( $field['aria-label'] ) {
  235. $select['aria-label'] = $field['aria-label'];
  236. }
  237. // multiple
  238. if ( $field['multiple'] ) {
  239. $select['multiple'] = 'multiple';
  240. $select['size'] = 5;
  241. $select['name'] .= '[]';
  242. // Reduce size to single line if UI.
  243. if ( $field['ui'] ) {
  244. $select['size'] = 1;
  245. }
  246. }
  247. // special atts
  248. if ( ! empty( $field['readonly'] ) ) {
  249. $select['readonly'] = 'readonly';
  250. }
  251. if ( ! empty( $field['disabled'] ) ) {
  252. $select['disabled'] = 'disabled';
  253. }
  254. if ( ! empty( $field['ajax_action'] ) ) {
  255. $select['data-ajax_action'] = $field['ajax_action'];
  256. }
  257. // hidden input is needed to allow validation to see <select> element with no selected value
  258. if ( $field['multiple'] || $field['ui'] ) {
  259. acf_hidden_input(
  260. array(
  261. 'id' => $field['id'] . '-input',
  262. 'name' => $field['name'],
  263. )
  264. );
  265. }
  266. if ( ! empty( $field['query_nonce'] ) ) {
  267. $select['data-query-nonce'] = $field['query_nonce'];
  268. }
  269. // append
  270. $select['value'] = $value;
  271. $select['choices'] = $choices;
  272. // render
  273. acf_select_input( $select );
  274. }
  275. /*
  276. * render_field_settings()
  277. *
  278. * Create extra options for your field. This is rendered when editing a field.
  279. * The value of $field['name'] can be used (like bellow) to save extra data to the $field
  280. *
  281. * @type action
  282. * @since 3.6
  283. * @date 23/01/13
  284. *
  285. * @param $field - an array holding all the field's data
  286. */
  287. function render_field_settings( $field ) {
  288. // encode choices (convert from array)
  289. $field['choices'] = acf_encode_choices( $field['choices'] );
  290. $field['default_value'] = acf_encode_choices( $field['default_value'], false );
  291. // choices
  292. acf_render_field_setting(
  293. $field,
  294. array(
  295. 'label' => __( 'Choices', 'acf' ),
  296. 'instructions' => __( 'Enter each choice on a new line.', 'acf' ) . '<br />' . __( 'For more control, you may specify both a value and label like this:', 'acf' ) . '<br /><span class="acf-field-setting-example">' . __( 'red : Red', 'acf' ) . '</span>',
  297. 'name' => 'choices',
  298. 'type' => 'textarea',
  299. )
  300. );
  301. // default_value
  302. acf_render_field_setting(
  303. $field,
  304. array(
  305. 'label' => __( 'Default Value', 'acf' ),
  306. 'instructions' => __( 'Enter each default value on a new line', 'acf' ),
  307. 'name' => 'default_value',
  308. 'type' => 'textarea',
  309. )
  310. );
  311. // return_format
  312. acf_render_field_setting(
  313. $field,
  314. array(
  315. 'label' => __( 'Return Format', 'acf' ),
  316. 'instructions' => __( 'Specify the value returned', 'acf' ),
  317. 'type' => 'radio',
  318. 'name' => 'return_format',
  319. 'layout' => 'horizontal',
  320. 'choices' => array(
  321. 'value' => __( 'Value', 'acf' ),
  322. 'label' => __( 'Label', 'acf' ),
  323. 'array' => __( 'Both (Array)', 'acf' ),
  324. ),
  325. )
  326. );
  327. acf_render_field_setting(
  328. $field,
  329. array(
  330. 'label' => __( 'Select multiple values?', 'acf' ),
  331. 'instructions' => '',
  332. 'name' => 'multiple',
  333. 'type' => 'true_false',
  334. 'ui' => 1,
  335. )
  336. );
  337. }
  338. /**
  339. * Renders the field settings used in the "Validation" tab.
  340. *
  341. * @since 6.0
  342. *
  343. * @param array $field The field settings array.
  344. * @return void
  345. */
  346. function render_field_validation_settings( $field ) {
  347. acf_render_field_setting(
  348. $field,
  349. array(
  350. 'label' => __( 'Allow Null?', 'acf' ),
  351. 'instructions' => '',
  352. 'name' => 'allow_null',
  353. 'type' => 'true_false',
  354. 'ui' => 1,
  355. )
  356. );
  357. }
  358. /**
  359. * Renders the field settings used in the "Presentation" tab.
  360. *
  361. * @since 6.0
  362. *
  363. * @param array $field The field settings array.
  364. * @return void
  365. */
  366. function render_field_presentation_settings( $field ) {
  367. acf_render_field_setting(
  368. $field,
  369. array(
  370. 'label' => __( 'Stylized UI', 'acf' ),
  371. 'instructions' => __( 'Use a stylized checkbox using select2', 'acf' ),
  372. 'name' => 'ui',
  373. 'type' => 'true_false',
  374. 'ui' => 1,
  375. )
  376. );
  377. acf_render_field_setting(
  378. $field,
  379. array(
  380. 'label' => __( 'Use AJAX to lazy load choices?', 'acf' ),
  381. 'instructions' => '',
  382. 'name' => 'ajax',
  383. 'type' => 'true_false',
  384. 'ui' => 1,
  385. 'conditions' => array(
  386. 'field' => 'ui',
  387. 'operator' => '==',
  388. 'value' => 1,
  389. ),
  390. )
  391. );
  392. }
  393. /*
  394. * load_value()
  395. *
  396. * This filter is applied to the $value after it is loaded from the db
  397. *
  398. * @type filter
  399. * @since 3.6
  400. * @date 23/01/13
  401. *
  402. * @param $value (mixed) the value found in the database
  403. * @param $post_id (mixed) the $post_id from which the value was loaded
  404. * @param $field (array) the field array holding all the field options
  405. * @return $value
  406. */
  407. function load_value( $value, $post_id, $field ) {
  408. // Return an array when field is set for multiple.
  409. if ( $field['multiple'] ) {
  410. if ( acf_is_empty( $value ) ) {
  411. return array();
  412. }
  413. return acf_array( $value );
  414. }
  415. // Otherwise, return a single value.
  416. return acf_unarray( $value );
  417. }
  418. /*
  419. * update_field()
  420. *
  421. * This filter is appied to the $field before it is saved to the database
  422. *
  423. * @type filter
  424. * @since 3.6
  425. * @date 23/01/13
  426. *
  427. * @param $field - the field array holding all the field options
  428. * @param $post_id - the field group ID (post_type = acf)
  429. *
  430. * @return $field - the modified field
  431. */
  432. function update_field( $field ) {
  433. // decode choices (convert to array)
  434. $field['choices'] = acf_decode_choices( $field['choices'] );
  435. $field['default_value'] = acf_decode_choices( $field['default_value'], true );
  436. // Convert back to string for single selects.
  437. if ( ! $field['multiple'] ) {
  438. $field['default_value'] = acf_unarray( $field['default_value'] );
  439. }
  440. // return
  441. return $field;
  442. }
  443. /*
  444. * update_value()
  445. *
  446. * This filter is appied to the $value before it is updated in the db
  447. *
  448. * @type filter
  449. * @since 3.6
  450. * @date 23/01/13
  451. *
  452. * @param $value - the value which will be saved in the database
  453. * @param $post_id - the $post_id of which the value will be saved
  454. * @param $field - the field array holding all the field options
  455. *
  456. * @return $value - the modified value
  457. */
  458. function update_value( $value, $post_id, $field ) {
  459. // Bail early if no value.
  460. if ( empty( $value ) ) {
  461. return $value;
  462. }
  463. // Format array of values.
  464. // - Parse each value as string for SQL LIKE queries.
  465. if ( is_array( $value ) ) {
  466. $value = array_map( 'strval', $value );
  467. }
  468. // return
  469. return $value;
  470. }
  471. /*
  472. * translate_field
  473. *
  474. * This function will translate field settings
  475. *
  476. * @type function
  477. * @date 8/03/2016
  478. * @since 5.3.2
  479. *
  480. * @param $field (array)
  481. * @return $field
  482. */
  483. function translate_field( $field ) {
  484. // translate
  485. $field['choices'] = acf_translate( $field['choices'] );
  486. // return
  487. return $field;
  488. }
  489. /*
  490. * format_value()
  491. *
  492. * This filter is appied to the $value after it is loaded from the db and before it is returned to the template
  493. *
  494. * @type filter
  495. * @since 3.6
  496. * @date 23/01/13
  497. *
  498. * @param $value (mixed) the value which was loaded from the database
  499. * @param $post_id (mixed) the $post_id from which the value was loaded
  500. * @param $field (array) the field array holding all the field options
  501. *
  502. * @return $value (mixed) the modified value
  503. */
  504. function format_value( $value, $post_id, $field ) {
  505. if ( is_array( $value ) ) {
  506. foreach ( $value as $i => $val ) {
  507. $value[ $i ] = $this->format_value_single( $val, $post_id, $field );
  508. }
  509. } else {
  510. $value = $this->format_value_single( $value, $post_id, $field );
  511. }
  512. return $value;
  513. }
  514. function format_value_single( $value, $post_id, $field ) {
  515. // bail early if is empty
  516. if ( acf_is_empty( $value ) ) {
  517. return $value;
  518. }
  519. // vars
  520. $label = acf_maybe_get( $field['choices'], $value, $value );
  521. // value
  522. if ( $field['return_format'] == 'value' ) {
  523. // do nothing
  524. // label
  525. } elseif ( $field['return_format'] == 'label' ) {
  526. $value = $label;
  527. // array
  528. } elseif ( $field['return_format'] == 'array' ) {
  529. $value = array(
  530. 'value' => $value,
  531. 'label' => $label,
  532. );
  533. }
  534. // return
  535. return $value;
  536. }
  537. /**
  538. * Validates select fields updated via the REST API.
  539. *
  540. * @param bool $valid
  541. * @param int $value
  542. * @param array $field
  543. *
  544. * @return bool|WP_Error
  545. */
  546. public function validate_rest_value( $valid, $value, $field ) {
  547. // rest_validate_request_arg() handles the other types, we just worry about strings.
  548. if ( is_null( $value ) || is_array( $value ) ) {
  549. return $valid;
  550. }
  551. $option_keys = array_diff(
  552. array_keys( $field['choices'] ),
  553. array_values( $field['choices'] )
  554. );
  555. $allowed = empty( $option_keys ) ? $field['choices'] : $option_keys;
  556. if ( ! in_array( $value, $allowed ) ) {
  557. $param = sprintf( '%s[%s]', $field['prefix'], $field['name'] );
  558. $data = array(
  559. 'param' => $param,
  560. 'value' => $value,
  561. );
  562. $error = sprintf(
  563. __( '%1$s is not one of %2$s', 'acf' ),
  564. $param,
  565. implode( ', ', $allowed )
  566. );
  567. return new WP_Error( 'rest_invalid_param', $error, $data );
  568. }
  569. return $valid;
  570. }
  571. /**
  572. * Return the schema array for the REST API.
  573. *
  574. * @param array $field
  575. * @return array
  576. */
  577. public function get_rest_schema( array $field ) {
  578. /**
  579. * If a user has defined keys for the select options,
  580. * we should use the keys for the available options to POST to,
  581. * since they are what is displayed in GET requests.
  582. */
  583. $option_keys = array_diff(
  584. array_keys( $field['choices'] ),
  585. array_values( $field['choices'] )
  586. );
  587. $schema = array(
  588. 'type' => array( 'string', 'array', 'int', 'null' ),
  589. 'required' => ! empty( $field['required'] ),
  590. 'items' => array(
  591. 'type' => array( 'string', 'int' ),
  592. 'enum' => empty( $option_keys ) ? $field['choices'] : $option_keys,
  593. ),
  594. );
  595. if ( empty( $field['allow_null'] ) ) {
  596. $schema['minItems'] = 1;
  597. }
  598. if ( empty( $field['multiple'] ) ) {
  599. $schema['maxItems'] = 1;
  600. }
  601. if ( isset( $field['default_value'] ) && '' !== $field['default_value'] ) {
  602. $schema['default'] = $field['default_value'];
  603. }
  604. return $schema;
  605. }
  606. }
  607. // initialize
  608. acf_register_field_type( 'acf_field_select' );
  609. endif; // class_exists check