Skip to content

Instantly share code, notes, and snippets.

@amphibian
Created September 22, 2011 20:21
Show Gist options
  • Save amphibian/1235914 to your computer and use it in GitHub Desktop.
Save amphibian/1235914 to your computer and use it in GitHub Desktop.
Quickie fieldtype for a dropdown where each value can only be selected in a single entry.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
/*
Distinct Dropdown fieldtype
- Requires the P&T fieldpack to be installed
- Won't work inside a Matrix row
- Won't work in SafeCracker, as we can't access the current entry_id
(at least I don't think?)
- Idea could be ported to multiselect, checkbox group, and radio fields
*/
if (! class_exists('Pt_dropdown_ft'))
{
require PATH_THIRD.'pt_dropdown/ft.pt_dropdown.php';
}
class Distinct_dropdown_ft extends Pt_dropdown_ft {
var $info = array(
'name' => 'Distinct Dropdown',
'version' => '1.0'
);
function _display_field($data, $field_name)
{
$this->prep_field_data($data);
// Has this value already been used?
$sql = "SELECT $this->field_name
FROM exp_channel_data
WHERE $this->field_name != '' AND $field_name != '--'";
// Are we editing an existing entry?
if($entry_id = $this->EE->input->get('entry_id'))
{
$sql .= " AND entry_id != '".$this->EE->db->escape_str($entry_id)."'";
}
$existing = $this->EE->db->query($sql);
if($existing->num_rows() > 0)
{
$js = "$('";
foreach($existing->result_array() as $row)
{
$val = $row[$field_name];
$js .= 'select[name="'.$this->field_name.'"] option[value="'.$val.'"], ';
// Instead of setting "disabled" via JS, we could do this:
// unset($this->settings['options'][$data]);
// But it's nicer to see the option disabled
}
$js = rtrim($js, ', ');
$js .= "').attr('disabled', 'disabled');";
$this->EE->javascript->output($js);
}
// Add a nullifier so that if we've selected all of our options
// We have something to deselect to
$options = array_merge(array('--' => '--'), $this->settings['options']);
return form_dropdown($field_name, $options, $data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment