ACF populate choises from database into the choices box in the backend - wordpress

How can i fill the choises from the database instead of static? See attachement:

I made this function into my function.php, so i only have to add my options in a custum table,like countries for example.
function makeChoiceArrayForACF($postid){
$datafromdbase = someFunctionToGetDataFromDbase();
$newdbasearray = array();
foreach ($datafromdbase as $key => $value){
$newdbasearray[$key] = $key;
}
$new = array(
'multiple' => 0,
'allow_null' => 1,
'choices' =>
$newdbasearray,
'default_value' =>
array(),
'ui' => 0,
'ajax' => 0,
'placeholder' => '',
'return_format' => 'array',
'type' => 'select',
'instructions' => '',
'required' => 1,
'conditional_logic' => 0,
'wrapper' =>
array(
'width' => '',
'class' => '',
'id' => '',
),
);
$my_post = array(
'ID' => $postid,
'post_content' => serialize($new),
);
wp_update_post( $my_post );
}
add_action('init', 'admin_only');
function admin_only() {
if( !is_admin() )
return;
makeChoiceArrayForACF(16611);
}

Related

Add checkboxes in fieldset

i have this fieldset and these checkboxes inside...
function repository_search_filter_form($form, &$form_state){
$form['global_fieldset_container']['global_fieldset_by_metadata'] = array (
'#type' => 'fieldset',
'#title' => t('By Metadata'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$form['global_fieldset_container']['global_fieldset_by_case_study'] = array (
'#type' => 'fieldset',
'#title' => t('By case study'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$by_casestudy_options = array(
'1' =>'option1',
'2' => 'option2',
);
}
$form['global_fieldset_container']['global_fieldset_by_case_study']['bycasestudy'] = array(
'#type' => 'checkboxes',
'#options' => $by_casestudy_options
);
return $form;
}
i want in fieldset "global_fieldset_by_metadata" to add some dynamic checkboxes but in a callback function....
function ajaxforms_basic_callback($form, $form_state) {
$commands = array();
$form_filter = drupal_get_form('repository_search_filter_form');
$by_metadata_options = array(
'1' => 'Metadata1',
'2' => 'Metadata2',
);
$form_filter['global_fieldset_container']['global_fieldset_by_metadata']['bymetadata'] = array(
'#type' => 'checkbox',
'#options' => $by_metadata_options,
);
$form_filter = drupal_render($form_filter);
$commands[] = ajax_command_replace(".filter", $form_filter);
}
But the results are a empty checkbox...
PS. I tried and "checkboxes" in "#type" but i havent results in fieldset.

Drupal Form autocomplete

I wanted to have a textfield in a form that autocompletes from the database. I have been reading the tutorials and trying to get it to work but thus far not much luck. I am farely new to Drupal so I'm mostly unsure what I am doing xD
My code thus far:
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('Add List'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('My form'),
'type' => MENU_CALLBACK,
);
// path with autocomplete function for casters
$items['caster/autocomplete'] = array(
'title' => t('Autocomplete for casters'),
'page callback' => '_caster_autocomplete',
'access arguments' => array('use autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
function my_module_form() {
return drupal_get_form('my_module_my_form');
}
function _caster_autocomplete($string) {
$matches = array();
$results = db_select('warnoun', 'w')
->fields('w', array('full_name'))
->condition('full_name', '%' . db_like($string) . '%', 'LIKE')
->execute();
// save the query to matches
foreach ($results as $result) {
$matches[$result->full_name] = check_plain($result->full_name);
}
// Return the result to the form in json
drupal_json_output($matches);
}
function my_module_my_form($form_state) {
$form['points'] = array(
'#type' => 'select',
'#title' => t('Points'),
'#required' => TRUE, // Added
'#options' => array(
0 => t('15'),
1 => t('25'),
2 => t('35'),
3 => t('50'),
),
);
$form['caster'] = array(
'#type' => 'textfield',
'#title' => t('Caster'),
'#maxlength' => 50,
'#autocomplete_path' => 'caster/autocomplete',
'#required' => TRUE,
);
$entries = db_query('SELECT id, short_name FROM factions ORDER BY id ASC');
$options = array();
foreach ($entries as $entry){
$options[$entry->id] = t($entry->short_name);
}
$form['faction'] = array(
'#type' => 'select',
'#title' => t('Faction'),
'#options' => $options,
);
// Simple Submit Button
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#required' => TRUE, // Added
);
return $form;
}
So basically there is a table called warnoun with a column full_name and it's with that content that I want to autocomplete the textfield caster.
Any idea what I'm missing/doing wrong?
Cheers

Drupal 7 - Submit function not triggered on theme table

I want to be able to select items from two select lists and then submit (which will take me to another form.
The following is the code I have however the submit function (submit_function) does not appear to get triggered (it just refreshes the form). What am I doing wrong?
function myfunction($form, &$form_state)
{
$output = drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);
$header = array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
);
$rows = array(
array(
'columnone' => array(
'data' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
),
'columntwo' => array(
'data' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
),
'columnthree' =>array(
'data' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
)
),
),
);
$output['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#weight' => 2,
);
return $output;
}
That is quite normal, you are mixing form elements with static renderable elements. A drupal_get_form function expects a form build.
What you need to create is your custom form theme table which outputs a theme within a form build. Here is some sample code that could help you further:
function YOURMODULE_theme()
{
// define a table form theme
return array(
'YOURMODULE_table_form' => array(
'render element' => 'element'
),
);
}
function theme_YOURMODULE_table_form($vars)
{
$element = $vars['element'];
$form_keys = false;
$rows = array();
// loop through each row form elements
foreach (element_children($element) as $key) {
if (!$form_keys) {
$form_keys = array();
// retrieve the form keys for each row
foreach (element_children($element[$key]) as $f_key) {
$form_keys[$f_key] = isset($element[$key][$f_key]['#title'])
? $element[$key][$f_key]['#title']
: '';
}
}
$row = array();
foreach ($form_keys as $fieldkey => $fieldname) {
// render each field in a separate row
$row[] = array(
'data' => drupal_render($element[$key][$fieldkey])
);
}
$rows[] = $row;
}
// return a build for the table
return theme('table', array(
'header' => $vars['element']['#header'],
'rows' => $rows,
'empty' => isset($vars['element']['#empty'])
? $vars['element']['#header']
: '',
));
}
And the form using your logic:
function myfunction($form, &$form_state)
{
$form['table'] = array(
'#theme' => 'YOURMODULE_table_form',
'#header' => array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
),
'#tree' => true,
);
$form['table'][0] = array(
'columnone' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
'columntwo' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
'columnthree' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
),
);
return $form;
}

How to redirect after view rendering is complete in cakephp 2.3

I am using cakephp 2.3 and required to redirect user after the excel sheet is downloaded successfully. I am using the cake $this->response->type for setting the view as excel sheet generator.
public function admin_export_excel($task_lists = array()) {
$task_ids = $task_lists;
$global_task_array = array();
$this->loadModel('Task');
//-> For each task-id run the loop for fetching the related data to generate the report.
foreach ($task_ids as $index => $task_id) {
//-> Check if the task exists with the specified id.
$this->Task->id = $task_id;
if (!$this->Task->exists())
throw new NotFoundException('Task not found.');
//-> Now check if the logged user is the owner of the specified task.
$task_count = $this->Task->find('count', array('conditions' => array('Task.id' => $task_id,
'Task.user_id' => $this->Auth->user('id'))));
if ($task_count == 0)
throw new NotFoundException('Task not accessable.');
$task_data = $this->Task->find('first', array(
'conditions' => array(
'Task.id' => $task_id
),
'contain' => array(
'TaskForm' => array(
'fields' => array('TaskForm.id', 'TaskForm.reference_table')
),
'Project' => array(
'fields' => array('Project.id', 'Project.project_name')
),
'User' => array(
'fields' => array('User.id', 'User.company_name')
),
'Timezone' => array(
'fields' => array('Timezone.id', 'Timezone.name')
)
)
)
);
// debug($task_data);
$global_task_array[$index] = $task_data;
//-> End of Custom else conditions
unset($task_data);
}
$this->set('global_task_array', $global_task_array);
$this->response->type(array('xls' => 'application/vnd.ms-excel'));
$this->response->type('xls');
$this->render('admin_export_excel');
}
and my view file is
$this->PhpExcel->createWorksheet();
$this->PhpExcel->setDefaultFont('Calibri', 13);
$default = array(
array('label' => __('Task Id'), 'width' => 'auto'),
array('label' => __('Unique Code'), 'width' => 'auto'),
array('label' => __('Site Name'), 'width' => 'auto'),
array('label' => __('Area'), 'width' => 'auto'),
array('label' => __('Location'), 'width' => 'auto'),
array('label' => __('Sub Location'), 'width' => 'auto'),
array('label' => __('About Task'), 'width' => 'auto')
);
$this->PhpExcel->addTableHeader($default, array('name' => 'Cambria', 'bold' => true));
$this->PhpExcel->setDefaultFont('Calibri', 12);
foreach ($global_task_array as $index => $raw) {
$data = array(
$raw['Task']['id'],
$raw['Task']['unique_code'],
$raw['Task']['site_name'],
$raw['Task']['area'],
$raw['Task']['location'],
$raw['Task']['sub_location'],
$raw['Task']['about_task']
);
$this->PhpExcel->addTableRow($data);
}
$this->PhpExcel->addTableFooter();
$this->PhpExcel->output('Task-' . date('d-m-Y') . '.xlsx');
I have tried to use the cake afterFilter method for to redirect the user to other action after the excel sheet is generated but its not working.
public function afterFilter(){
parent::afterFilter();
if($this->request->params['action'] == 'admin_export_excel'){
$this->redirect(array('controller' => 'tasks', 'action' => 'index','admin' => true));
}
}
Any help will be appreciated. Thanks

My Node Type wont Show It's Fields

I am trying to create my first drupal module that creates a simple node type wcNames. This node type has two fields, firstname & lastname.
I could get my module create the DB table for node type and add it in node_type table, but when I open node/add/wc-name fields firstname and lastname don't appear.
Below is my code. Please suggest.
<?php
// wc_name.install file
/*
* hook_schema Implementation: Creates the DB and it's fields
*/
function wc_name_schema(){
$schema['wc_name_names'] = array(
'fields' => array(
'nmid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
'firstname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
'lastname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
),
'primary key' => array('nmid'),
'unique keys' => array(),
'indexes' => array(
'nmid' => array('nmid'),
),
);
return $schema;
}
//function wc_name_install(){ } // Use this function to set variables for the module.
function wc_name_uninstall(){
//unset variables if any set
// Delete all wc_name nodes
db_delete('node')->condition('type', 'wc_name')->execute();
// Delete all wc_name tables
db_drop_table('wc_name_names');
}
?>
<?php
// wc_name.module
/*
* Implementation of _node_info(): define node
*/
function wc_name_node_info(){
return array(
'wc_name' => array(
'name' => t('wcName'),
'base' => 'wc_name',
'base' => 'page',
'description' => t("A smaple module to save names."),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => FALSE,
)
);
}
function wc_name_menu() {
$items = array();
$items['wc_name'] = array(
'title' => 'wcNames',
'page callback' => 'wc_name',
// 'access arguments' => array('access wcNames'),
);
}
?>
<?php
// wc_name_form.inc
function wc_name_form($node, &$form_state){
// Add fields
$form['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['firstname'],
);
$form['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['lastname'],
);
return $form;
}
?>
What am I missing?
Try this:
function createTextFieldByName($type, $fieldname, $fieldlabel)
{
$field = field_info_field($fieldname);
if (empty($field)) {
$field = array(
'field_name' => $fieldname,
'type' => 'text',
'entity_types' => array('node'),
'translatable' => TRUE,
);
$field = field_create_field($field);
}
$instance = field_info_instance('node', $fieldname, $type);
if (empty($instance)) {
$instance = array(
'field_name' => $fieldname,
'entity_type' => 'node',
'bundle' => $type,
'label' => $fieldlabel,
);
$instance = field_create_instance($instance);
return $instance;
}
return null;
}
$type =
array(
'type' => 'MY_TYPE',
'name' => t('NAME'),
'base' => 'node_content',
'description' => t("DESCRIPTION"),
'custom' => 1,
'modified' => 1,
'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);
createTextFieldByName($type,'firstname','First name');
createTextFieldByName($type,'lastname','Last name');

Resources