Drupal 7: File field causes error with Dependable Dropdowns - drupal-7

I'm building a Form in a module using the Form API. I've had a couple of dependent dropdowns that have been working just fine. The code is as follows:
$types = db_query('SELECT * FROM {touchpoints_metric_types}') -> fetchAllKeyed(0, 1);
$types = array('0' => '- Select -') + $types;
$selectedType = isset($form_state['values']['metrictype']) ? $form_state['values']['metrictype'] : 0;
$methods = _get_methods($selectedType);
$selectedMethod = isset($form_state['values']['measurementmethod']) ? $form_state['values']['measurementmethod'] : 0;
$form['metrictype'] = array(
'#type' => 'select',
'#title' => t('Metric Type'),
'#options' => $types,
'#default_value' => $selectedType,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'method-wrapper',
'callback' => 'touchpoints_method_callback'
)
);
$form['measurementmethod'] = array(
'#type' => 'select',
'#title' => t('Measurement Method'),
'#prefix' => '<div id="method-wrapper">',
'#suffix' => '</div>',
'#options' => $methods,
'#default_value' => $selectedMethod,
);
Here are the _get_methods and touchpoints_method_callback functions:
function _get_methods($selected) {
if ($selected) {
$methods = db_query("SELECT * FROM {touchpoints_m_methods} WHERE mt_id=$selected") -> fetchAllKeyed(0, 2);
} else {
$methods = array();
}
$methods = array('0' => "- Select -") + $methods;
return $methods;
}
function touchpoints_method_callback($form, &$form_state) {
return $form['measurementmethod'];
}
This all worked fine until I added a file field to the form. Here is the code I used for that:
$form['metricfile'] = array(
'#type' => 'file',
'#title' => 'Attach a File',
);
Now that the file is added if I change the first dropdown it hangs with the 'Please wait' message next to it without ever loading the contents of the second dropdown. I also get the following error in my JavaScript console:
"Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'handleError'"
What am I doing wrong here?

Related

Drupal: How to update database from Select Option

Hei guys, I'm really new to Drupal and am stuck right now by having selected all the data I need from my database and get to display it inside a drop down list.
Unfortunatly I have no clue on how I can update my database with this specific selected field, as I am not having any value....
$options = array();
foreach ($results as $result) {
$options["name"] = array(
$result->name,
);
}
$options2 = array();
foreach ($results_tour as $result2) {
$options2[$result2->sku] = array(
$result2->title,
);
}
$form['tour'] = array(
'#type' => 'select',
'#options' => $options2,
);
$form['tour_guide'] = array(
'#type' => 'select',
'#title' => t('Tour Guide'),
'#options' => $options,
'#description' => 'Please select a guide for this specific tour'
);
$form['save'] = array(
'#type' => 'submit',
'#value' => 'Speichern',
'#submit' => array('plantours_form_submit'),
);
return $form;
}
function plantours_form_submit($form, $form_state) {
db_update('commerce_line_item')
->fields(array(
'status' => $options["name"]
))
->execute();
}
Don't do it manually, by writing directly to database, but use Drupal commerce api (I guess you are using drupal commerce):
https://www.drupal.org/node/1288414

How to create drupal Batch Operation on Custom Form

I am learing batch operations api. i have tried to create a batch operation using a form here is my hook_form
function batch_form_get_form($form, &$form_state){
$form = array();
$form['select'] = array(
'#title' => 'Select',
'#type' =>'select',
'#options' => array(
'batch1' => 'Batch 1',
'batch2' => 'Batch 2',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit'
);
return $form;
}
here is my form submit function
function batch_form_get_form_submit($form,&$form_state){
$function = 'batch_process_form';
$_SESSION['http_request_count'] =0;
$batch = $function;
batch_set($batch);
dsm ($function);
}
here is my batch process function which i used on batch_set function
function batch_process_form(){
for($i=0; $i<10; $i++){
$operations[] = array('batch_operation_result',array($i));
}
$title = "Batch Started";
$init_message = "Initialing Batch";
$progress_message = "Work in Progress";
$batch = array(
'operations' => $operations,
'title' => $title,
'init_message' => $init_message,
'progress_message' => $progress_message,
);
return $batch;
}
when i tried to run the batch i got the following error
Fatal error: Unsupported operand types in /home/dina/static/d7/includes/form.inc on line 4396
on the line no 4396 of form.inc
$batch_set = $init + $batch_definition + $defaults;
i don't no what i am missing
I think you missed one thing.
In your submit function, instead of
$batch = $function;
try
$batch = $function();
Good luck

CakePHP: Keep the same checkboxes checked after submit

How can I keep the same checkboxes checked after submit? All the other input fields on the form automatically keeps the values. I thought this would also go for checkboxes, but nope.
echo $this->Form->input('type_id', array(
'multiple' => 'checkbox',
'options' => array(
'1' => 'Til salgs',
'2' => 'Ønskes kjøpt',
'3' => 'Gis bort'
),
'div' => false,
'label' => false
));
I believe this can be done in the controller, but how?
Edit:
Since I posted this question I've changed to CakeDcs Search plugin, because I've gotten this to work with that before. Still... I can't get it to work this time.
Adding model and controller code:
AppController
public $components = array('DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => '/',
'loginRedirect' => '/login',
'logoutRedirect' => '/',
'authError' => 'Du må logge inn for å vise denne siden.',
'authorize' => array('Controller'),
),
'Search.Prg'
);
public $presetVars = true; //Same as in model filterArgs(). For Search-plugin.
AdsController
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}
Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'search_field' => array('type' => 'query', 'method' => 'filterSearchField'),
'commune_id' => array('type' => 'value'),
'type_id' => array('type' => 'int')
);
public function filterSearchField($data) {
if (empty($data['search_field'])) {
return array();
}
$str_filter = '%' . $data['search_field'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $str_filter,
$this->alias . '.description LIKE' => $str_filter,
)
);
}
/**
* Sets the fields which will be returned by the search.
*
* #access public
* #return array Database table fields
* #author Morten Flydahl
*
*/
public function setFields() {
return array(
'Ad.id',
'Ad.title',
'Ad.description',
'Ad.price',
'Ad.modified',
'User.id',
'User.first_name',
'User.middle_name',
'User.last_name',
'User.link',
'User.picture_url',
'Commune.name',
'Type.id',
'Type.name'
);
}
You have to set manually the selected option of the input, as an array with "keys = values = intval(checkbox id)"
I cannot explain why this format, but this is the only way I get it to work.
Here is my code:
echo $this->Form->create('User');
// Read the submitted value
$selected = $this->Form->value('User.Albums');
// Formats the value
if (empty($selected)) {
$selected = array(); // avoid mess
} else {
$selected = array_map('intval', $selected);
$selected = array_combine ($selected, $selected);
}
// Renders the checkboxes
echo $this->Form->input('Albums',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $albums, // array ( (int)id => string(label), ... )
'selected' => $selected, // array ( (int)id => (int)id, ... )
));
Hope this helps.
++

Custom Field with autcomplete

I am trying to build my own node reference custom field - I know several projects out there already do this, I am building this in order to learn... :)
My problem is the autocomplete path, it's not being triggered, I have checked the noderefcreate project and implemented my solution based on that project. But still; nothing is being triggered when I check firebug.
Here is my code:
function nodereference_field_widget_info() {
return array(
'nodereference_nodereference_form' => array(
'label' => t('Node Reference Form'),
'field types' => array('nodereference'),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_DEFAULT,
'default value' => FIELD_BEHAVIOR_DEFAULT,
),
'settings' => array(
'autocomplete_match' => 'contains',
'autocomplete_path' => 'nodereference/autocomplete',
),
),
);
}
function nodereference_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
if ($instance['widget']['type'] == 'nodereference_nodereference_form') {
$widget = $instance['widget'];
$settings = $widget['settings'];
$element += array(
'#type' => 'textfield',
'#default_value' => isset($items[$delta]['nid']) ? $items[$delta]['nid'] : NULL,
'#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'],
);
}
return array('nid' => $element);
}
You need to define method from where auto compete will take suggestions.
It can be done like this:
/**
* implements hook_menu
*/
function your_module_name_menu() {
$items['master_place/autocomplete'] = array(
'page callback' => '_your_module_name_autocomplete',
'access arguments' => array('access example autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
/**
* Auto complete method implementation
* #param $string
*/
function _your_module_name_autocomplete($string) {
$matches = array();
// Some fantasy DB table which holds cities
$query = db_select('target_db_table', 'c');
// Select rows that match the string
$return = $query
->fields('c', array('target_column'))
->condition('c.target_column', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();
// add matches to $matches
foreach ($return as $row) {
$matches[$row->city] = check_plain($row->city);
}
// return for JS
drupal_json_output($matches);
}

Print terms from a specific vocab at page.tpl drupal 7

I used to have a function to create a custom menu by loading all terms from a specific vocab at drupal 6:
function _taxonomy_top_links($vid = NULL) {
$terms = taxonomy_get_tree($vid);
$taxos = array();
foreach ($terms as $term) {
$taxos[] = array('title' => $term->name, 'taxonomy/term/' . $term->tid, 'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description)));
}
return theme('links', $taxos, array('id' => 'menu-'. $vid, 'class' => 'menu clearfix'));
}
This doesn't work at drupal 7 which I guess related to the new field api. How do you grab all terms from a specific vocab to preprocess at page level?
Thanks for any help.
Most of your code should actually work fine, it's the theme part that is incorrect.
$terms = taxonomy_get_tree($vid, 0, NULL, TRUE);
$links = array();
foreach ($terms as $term) {
$uri = entity_uri('taxonomy_term', $term);
$link = array(
'title' => $term->name,
'href' => $uri['path'],
'attributes' => array('rel' => 'tag'),
);
$link += $uri['options'];
if (!empty($term->description)) {
$link['title'] = strip_tags($term->description);
}
$links['tid-' . $term->tid] = $link;
}
$variables = array(
'links' => $links,
'attributes' => array(
'id' => 'menu-' . $vid,
'class' => array('menu', 'clearfix'),
),
);
return theme('links', $variables);

Resources