I have two different views that need to be toggled on a node page. I cannot put these two views together so I have created a form that will basically take the values of the form that I create, and send them as arguments to the view and display the view. I am attempting to do with this ajax. It works fine but the problem is the second time I run the form it does not refresh or update that view.
function photoflight_albums() {
photoflight_gallery_themes();
$output = render(drupal_get_form('photoflight_gallery_form'));
$output .= "<div id='gallery-ajax-wrapper'>";
$output .= views_embed_view('gallery', 'default');
$output .= "</div>";
return $output;
}
//Grabs the node titles
function photoflight_gallery_themes(){
$type = "photo_theme";
$theme_list = array();
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $themes){
$theme_list[$themes->title] = $themes->title;
}
return $theme_list;
}
//Form calls back to the function above to the gallery-ajax-wrapper div output above
function photoflight_gallery_form($form, &$form_state){
$form = array();
$form['themes'] = array(
'#type' => 'select',
'#options' => array(photoflight_gallery_themes()),
'#ajax' => array(
'callback' => 'photoflight_simplest_callback',
'wrapper' => 'gallery-ajax-wrapper',
),
);
//debug($form);
return $form;
}
//Ajax callback
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = $view->preview('default', $args);
return array("#markup" => $output);
}
The issue was that it was removing the HTML element so the second call had no HTML to replace. Changed to either use ajax update or on the call back wrap the return in the div again
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = '<div id="gallery-ajax-wrapper">';
$output .= $view->preview('default', $args);
$output .= '</div>';
return array("#markup" => $output);
}
Related
I am getting my ajax callback in normal custom form, but on form alter its not working.
function sample_ajax_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if ($form_id === 'node_sampleajax_form' || $form_id === 'node_sampleajax_edit_form') {
$form['field_nametrain']= array(
'#title' => t('training name'),
'#type' => 'select',
'#options' => _load_training(),
'#required' => FALSE,
'#ajax' => [
'callback' => [$this, 'changeOptionsAjax'],
// 'callback' => '::changeOptionsAjax',
'wrapper' => 'second_field_wrapper',
],
);
$form['field_namedomain'] = [
'#type' => 'select',
'#title' => t('Domain program'),
'#options' => $this->getOptions($form_state),
'#prefix' => '<div id="second_field_wrapper">',
'#suffix' => '</div>',
];
return $form;
}
}
function _load_training() {
$training = array('- Select domain training -');
$query = db_select("node__field_trainingname", "a");
$query->fields("a", array('field_trainingname_value', 'entity_id'));
$query->orderBy("a.field_trainingname_value");
$result = $query->execute();
while($row = $result->fetchObject()){
$training[$row->entity_id] = $row->field_trainingname_value;
}
return $training;
}
function changeOptionsAjax(array &$form, FormStateInterface $form_state) {
return $form['field_namedomain'];
}
function getOptions(array &$form, FormStateInterface $form_state) {
$cvvv = $form_state->getValue('field_nametrain');
<!-- return ["shgsh", $form_state->get(['field_nametrain'])]; -->
$options = array('- Select subdomain category -');
$query = db_select("node__field_trainingname", "a");
$query->fields("a", array('field_trainingname_value', 'entity_id'));
$query = db_select("node__field_cms", "b");
$query->fields("b", array('field_cms_value', 'entity_id'));
$query->join("node__field_trainingname", "b", "b.entity_id=a.entity_id");
$query->condition("a.entity_id", $cvvv);
$result = $query->execute();
while($row = $result->fetchObject()){
$options[$row->entity_id] = $row->field_cms_value;
}
return $options;
}
On using $this->getOptions($form_state) it represent the error log it is not an object and throws website encounter error in front end. But on custom form no error came only in formalter it throws error.
Kindly suggest me ideas to apply in form_alter of Drupal 8
The .module file, where your form alter hook is located, is not a class, therefore there is no $this. Your custom form however is a class (usually in your_module/src/Form/YourForm.php), that's why it works there but not in the .module file.
Further reading: http://www.php.net/manual/en/language.oop5.basic.php
and What does the variable $this mean in PHP?
In your case you should be able to just call
'#options' => getOptions($form, $form_state),
And more on a side note: I would strongly recommend to do some code refactoring.
In your custom submit handler, firt get the form object from the form state.
$formObj = $formState->getFormObject();
then call submitForm() on the form object and pass the form and form state variables.
$formObj->submitForm($form, $formState);
and finally, you just need to simply trigger the save() function on the object.
$formObj->save($form, $formState);
So the whole solution is something like
function YOR_CUSTOM_SUBMIT_HANLDLER(array $form, FormStateInterface $form_state) {
/** #var Drupal\user\RegisterForm $entity */
$formObj = $form_state->getFormObject();
$formObj->submitForm($form, $form_state);
$formObj->save($form, $form_state);
}
I've created custom node form with only two fields attached. Each field have own "Save" AJAX button. On "Save" button click, everything goes as if it is default node form submission. Here is the full code:
/**
* Form;
*/
function mymodule_custom_form($form, &$form_state) {
$node = node_load(123);
$node->langcode = entity_language('node', $node);
// Store node object in form state
if (!isset($form_state['node'])) {
if (!isset($node->title)) {
$node->title = NULL;
}
node_object_prepare($node);
$form_state['node'] = $node;
}
else {
$node = $form_state['node'];
}
// Basic node information.
// These elements are just values so they are not even sent to the client.
$properties = array('nid', 'vid', 'uid', 'created', 'type', 'language');
foreach ($properties as $key) {
$form[$key] = array(
'#type' => 'value',
'#value' => isset($node->$key) ? $node->$key : NULL,
);
}
// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = array(
'#type' => 'hidden',
'#default_value' => isset($node->changed) ? $node->changed : NULL,
);
// TEST 1 field
field_attach_form('node', $node, $form, $form_state, $node->langcode, array(
'field_name' => 'field_test_1'
));
// Set the form prefix and suffix to support AJAX
$form['field_test_1']['#prefix'] = '<div id="wrapper-field-test-1">';
$form['field_test_1']['#suffix'] = '</div>';
// the submit button
$form['field_test_1']['save'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#name' => 'button-field-test-1',
'#ajax' => array(
'callback' => 'mymodule_custom_form_ajax_submit',
'wrapper' => 'wrapper-field-test-1',
'method' => 'replace',
'effect' => 'fade',
)
);
// TEST 2 field
field_attach_form('node', $node, $form, $form_state, $node->langcode, array(
'field_name' => 'field_test_2'
));
// Set the form prefix and suffix to support AJAX
$form['field_test_2']['#prefix'] = '<div id="wrapper-field-test-2">';
$form['field_test_2']['#suffix'] = '</div>';
// the submit button
$form['field_test_2']['save'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#name' => 'button-field-test-2',
'#ajax' => array(
'callback' => 'mymodule_custom_form_ajax_submit',
'wrapper' => 'wrapper-field-test-2',
'method' => 'replace',
'effect' => 'fade',
)
);
return $form;
}
/**
* Form validate;
*/
function mymodule_custom_form_validate($form, &$form_state) {
$field_name = reset($form_state['triggering_element']['#parents']);
// Validate only the stuff we need
$fields = array(
'field_test_1',
'field_test_2'
);
foreach ($fields as $field => $bundle) {
if ($field_name != $field) {
unset($form_state['values'][$field], $form_state['input'][$field]);
}
}
// $form_state['node'] contains the actual entity being edited, but we must
// not update it with form values that have not yet been validated, so we
// create a pseudo-entity to use during validation.
$node = (object) $form_state['values'];
node_validate($node, $form, $form_state);
entity_form_field_validate('node', $form, $form_state);
}
/**
* Form submit;
*/
function mymodule_custom_form_submit($form, &$form_state) {
// Execute all submit functions
$node = $form_state['node'];
entity_form_submit_build_entity('node', $node, $form, $form_state);
node_submit($node);
foreach (module_implements('node_submit') as $module) {
$function = $module . '_node_submit';
$function($node, $form, $form_state);
}
// Save the node
node_save($node);
$form_state['values']['nid'] = $node->nid;
$form_state['nid'] = $node->nid;
}
/**
* Form ajax submit;
*/
function mymodule_custom_form_ajax_submit($form, &$form_state) {
$field_name = reset($form_state['triggering_element']['#parents']);
// validate the form
drupal_validate_form('mymodule_custom_form', $form, $form_state);
// if there are errors, return the form to display the error messages
if (form_get_errors()) {
$form_state['rebuild'] = TRUE;
return $form[$field_name];
}
// process the form
mymodule_custom_form_submit($form, $form_state);
// Show the processing box
$form[$field_name] = array('#markup' => 'Thanks!');
$form[$field_name]['#prefix'] = '<div id="wrapper-' . str_replace('_', '-', $field_name) . '">';
$form[$field_name]['#suffix'] = '</div>';
// return the confirmation message
return $form[$field_name];
}
The code works perfectly, except that node_save($node) causes The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved. error.
No errors, if I remove it. But I need to save node and trigger all the hooks.
I think the issue caused by this line :
// process the form
mymodule_custom_form_submit($form, $form_state);
in your ajax function, try to use the node_save into your ajax function. mymodule_custom_form_submit is the conventional hook usually used. It seems to be several save process at the same time.
I don't know if you've solved it or not, but I've been stuck in a similar situation.
I avoid the error: The content on this page has either been modified..., modifying changed value in $form_state. In your submit function: mymodule_custom_form_submit, right after node_save($node), Add this line:
$form_state['input']['changed'] = $node->changed;
Drupal 7 full Save & Stay callback function, please add wrapper for form:
function <MODULE_NAME>_node_ajax_save_callback($form, &$form_state){
// If error, return form.
if (form_get_errors()) {
return $form;
}
node_form_submit($form, $form_state);
$form['changed']['#value'] = $form_state['node']->changed;
return $form;
}
I have a node page where I need to create a reply form via ajax for commenting. Commenting in my system is also a kind of node.
When my page first loads it's presented with all comments done and also only one textbox & submit button which is used to add a new comment node. When I click submit button that comment is added via ajax.
Below each comments there is reply option. When I click on this reply, an ajax call is made to bring a new text area & reply button which are coming using same node form that is presented in form above. When this new form is presented I fill it up and submit at that time it's not submitted via ajax instead it redirects to destination URL.
Following is my menu & form alter code.
function mymodule_menu() {
$items['user_reply_comments/%/%'] = array(
'title' => t('Reply to User Comment'),
'page callback' => 'mymodule_user_reply_comment',
'page arguments' => array(1, 2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'ajax_deliver',
'file' => 'includes/mymodule.pages.inc',
);
return $items;
}
function mymodule_form_comment_node_statement_form_alter(&$form, &$form_state, $form_id) {
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'drupal.ajax');
drupal_add_js($base_url. '/' .path_to_theme().'/js/script.js', 'file');
$form['#action'] = url('user_reply_comments/'.$id.'/'.arg(2) .'/ajax');
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_comment_node_statement_form_callback',
'wrapper' => 'comment-replies-' . arg(2),
'method' => 'replace',
'effect' => 'fade',
'event' => 'click',
'progress' => array('type'=> 'throbber',
'message' => "<div></div>",
),
'js' => array(
$base_url. '/' .path_to_theme().'/js/script.js',
),
);
}
/**
* Ajax callback for comment_node_statement_form.
*/
function mymodule_comment_node_statement_form_callback($form, &$form_state) {
/*echo '<pre>';
print_r($form);
exit;*/
//echo ' 1 :' . arg(1) . ' 2:' .arg(2); exit; // sub reply dows not came here
$message_empty = drupal_get_messages();
if(!empty($message_empty) && isset($message_empty ['error'])){
global $base_url;
$command_add = array();
if(user_is_anonymous()){
$command_add = ajax_command_invoke(NULL, "redirect_user", array($base_url));
}
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_before('#content', '<div id="inline-messages" class="messages error">'.$message_empty ['error'] [0].'</div>'),
ajax_command_invoke(NULL, "greyout_reply"),
$command_add
)
);
}
else{
$current_path = TRUE;
$statement_page_reply_form = "";
$pos = strpos($_SERVER['HTTP_REFERER'], "statements");
if($pos !== FALSE){
$current_path = FALSE;
}
// print_r($_SERVER['HTTP_REFERER']);
// print "$$$".$current_path."###"; exit;
// Clear the messages (drupal_set_message() doens't work for some reason).
$_SESSION['messages'] = '';
if($current_path){
$html = "<div class='arrow'>arrow</div>";
}
else{
$html = "";
}
$id = $form['#node']->nid;
if (!empty($form['build_info_args_' . $id]['#value'])) {
$form_state = array(
'build_info' => array('args' => $form['build_info_args_' . $id]['#value']),
'values' => array(),
) + form_state_defaults();
}
$form_state['rebuild'] = TRUE;
//$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$node_comments = views_embed_view('statement_replies', 'block', $id);
if($form['current_url']['#value'] == "dashboard"){
$comment_form['current_url'] = array('#type' => 'hidden', '#value' => "dashboard", '#name' => 'current_url');
$html .= '<div class="dashboard-statements-comments">';
}
if($current_path){
$html .= '<div class="statement-comment-reply-box">'.drupal_render($comment_form).'</div>';
}
else{
$statement_page_reply_form = '<div class="arrow">arrow</div><div class="statement-comment-reply-box">'. drupal_render($comment_form).'</div>';
$num_comments = db_query("SELECT COUNT(cid) AS count FROM {comment} WHERE nid =:nid and status = :status",array (":nid"=>$id, ":status" => '1'))->fetchField();
$statement_page_reply_form .= '<span class="statement_total_replies">'.$num_comments. ' Replies</span>';
$statement_page_reply_form .= '<span class="collapse_reply">COLLAPSE</span>';
}
$html .= '<div class="statement-comment-reply-feed">'.$node_comments.'</div>';
if($form['current_url']['#value'] == "dashboard"){
$html .= '</div>';
}
if($current_path){
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
)
);
}
else{
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_html('.statement_upper_part .reply_form_statement', $statement_page_reply_form),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
ajax_command_invoke(NULL, "alter_elements"),
)
);
}
}
}
/**
* This is function in mymodule.pages.inc
* Callback function for 'user_reply_comment/%/%' path.
*
* Returns the popup modal form consists of reply form
*
* #param $entity_id
* Integer representing node ID
* #param $current_cid
* Integer representing comment ID
*/
function mymodule_user_reply_comment($entity_id, $current_cid, $js = FALSE) {
$logged_in = user_is_logged_in();
$node = node_load($entity_id);
if($node) {
if ($node->type == 'statement' || $node->type == "user_comment") {
$replies = "<div class='arrow'>arrow</div>";
$ajax_css = "";
if ($logged_in) {
$edit = array('nid' => $node->nid);
$form = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);
$replies .= "<div class='statement-comment-reply-box'>";
$replies .= drupal_render($form);
$replies .= "</div>";
}
else{
$ajax_css = ajax_command_invoke(NULL, "views_row_hide_border");
}
$replies .= "<div class='statement-comment-reply-feed'>";
$replies .= "</div>";
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#comment-replies-' . $current_cid, $replies),
ajax_command_invoke(NULL, "show_statement_replies", array('#comment-replies-' . $current_cid)),
ajax_command_invoke(NULL, "toggle_reply_links" , array($current_cid)),
ajax_command_invoke(NULL, "mymodule_user_reply_comment_reply" , array($current_cid, $edit)),
$ajax_css
));
}
}
}
/*
Following is there in script.js file
*/
(function($) {
$.fn.mymodule_user_reply_comment_reply = function(cid, nid) {
var form_class = '.comment-form-' + nid + '--' + cid;
var button = form_class + ' input.form-submit';
console.log('reply thread click.' + cid);
$(button).bind('click', 'upload_reply_image');
/*{
console.log($(this).attr('id'));
return false;
e.preventDefault();
e.stopPropogation();
//Drupal.attachBehaviors($(form_class));
return false;
});//*/
console.log('reply thread out.' + cid);
};
})(jQuery);
/* To toggle between Reply expand/collapse mode in statement/Comment box and their reply box - Start */
(function($) {
$.fn.toggle_reply_links = function(cid) {
jQuery('#close-sub-comments-' + cid).parent().find('a').toggle();
};
})(jQuery);
(function($) {
$.fn.show_statement_replies = function(id) {
jQuery(id).slideDown();
};
})(jQuery);
Thanks in advance.
I think you have wrong path in your code. You need to change this in hook_menu:
$items['user_reply_comments/%/%'] = array(
With this:
$items['user_reply_comments/%/%/ajax'] = array(
At least there's something that doesn't match in my opinion.
Clear your menu cache to see the changes.
Hope that helps.
I am trying to populate the second select box with the all date fields of the first selected content type name in select box. I am using ajax_callback to fetch the selected value by $form_state. I am getting error, which I can't determine why. Can anybody help?
This is the my custom module code.
function mymodule_settings($form, &$form_state){
$content_type_options = array();
$result = db_query("SELECT * FROM {node_type}");
foreach($result as $record){
$content_type_options[$record->type] = $record->name;
}
$form = array();
$form['content_type'] = array(
'#title' => t('Content Types'),
'#description' => t('Select a content type.'),
'#type' => 'select',
'#options' => $content_type_options,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'reg-start-date',
'callback' => 'mymodule_datefields_ajax_callback',
'method' => 'replace',
),
);
$form['checkboxes_fieldset'] = array(
'#title' => t("Start Date"),
'#prefix' => '<div id="reg-start-date">',
'#suffix' => '</div>',
'#type' => 'select',
'#description' => t('Select the date field'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
function mymodule_datefields_ajax_callback($form, $form_state) {
$fieldname = $form_state['triggering_element']['#value'];
$field_query = db_query("SELECT fc.field_name FROM {field_config} fc, {field_config_instance} fci
WHERE fc.field_name = fci.field_name
AND fc.type = 'datetime'
AND fci.bundle = '".$fieldname."'");
$datefield_options = array();
foreach($field_query as $record){
$datefield_options = $record;
}
return $datefield_options;
//dpm($form_state, 'AJAX $form_state');
}
Here is the error, which I am getting in popup -
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
information follows. Path: /module_dev/?q=system/ajax StatusText: OK
ResponseText: Fatal error: Cannot use object of type stdClass as array
in /var/www/module_dev/includes/common.inc on line 5786
I went through the /var/www/module_dev/includes/common.inc on line 5786, and this is the code I find there.
function drupal_render(&$elements) {
// Early-return nothing if user does not have access.
if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
return;
}
// Do not print elements twice.
if (!empty($elements['#printed'])) {
return;
}
// Try to fetch the element's markup from cache and return.
if (isset($elements['#cache'])) {
$cached_output = drupal_render_cache_get($elements);
if ($cached_output !== FALSE) {
return $cached_output;
}
}
// If #markup is set, ensure #type is set. This allows to specify just #markup
// on an element without setting #type.
if (isset($elements['#markup']) && !isset($elements['#type'])) {
$elements['#type'] = 'markup';
}
// If the default values for this element have not been loaded yet, populate
// them.
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
$elements += element_info($elements['#type']);
}
// Make any final changes to the element before it is rendered. This means
// that the $element or the children can be altered or corrected before the
// element is rendered into the final text.
if (isset($elements['#pre_render'])) {
foreach ($elements['#pre_render'] as $function) {
if (function_exists($function)) {
$elements = $function($elements);
}
}
}
// Allow #pre_render to abort rendering.
if (!empty($elements['#printed'])) {
return;
}
// Get the children of the element, sorted by weight.
$children = element_children($elements, TRUE);
// Initialize this element's #children, unless a #pre_render callback already
// preset #children.
if (!isset($elements['#children'])) {
$elements['#children'] = '';
}
// Call the element's #theme function if it is set. Then any children of the
// element have to be rendered there.
if (isset($elements['#theme'])) {
$elements['#children'] = theme($elements['#theme'], $elements);
}
// If #theme was not set and the element has children, render them now.
// This is the same process as drupal_render_children() but is inlined
// for speed.
if ($elements['#children'] == '') {
foreach ($children as $key) {
$elements['#children'] .= drupal_render($elements[$key]);
}
}
// Let the theme functions in #theme_wrappers add markup around the rendered
// children.
if (isset($elements['#theme_wrappers'])) {
foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
$elements['#children'] = theme($theme_wrapper, $elements);
}
}
// Filter the outputted content and make any last changes before the
// content is sent to the browser. The changes are made on $content
// which allows the output'ed text to be filtered.
if (isset($elements['#post_render'])) {
foreach ($elements['#post_render'] as $function) {
if (function_exists($function)) {
$elements['#children'] = $function($elements['#children'], $elements);
}
}
}
// Add any JavaScript state information associated with the element.
if (!empty($elements['#states'])) {
drupal_process_states($elements);
}
// Add additional libraries, CSS, JavaScript an other custom
// attached data associated with this element.
if (!empty($elements['#attached'])) {
drupal_process_attached($elements);
}
$prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
$suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
$output = $prefix . $elements['#children'] . $suffix;
// Cache the processed element if #cache is set.
if (isset($elements['#cache'])) {
drupal_render_cache_set($output, $elements);
}
$elements['#printed'] = TRUE;
return $output;
}
What your AJAX callback should return is the rendering array for a form element that replaces the content of the <div> tag whose CSS ID is set as #ajax[wrapper]. What your AJAX callback is returning is an array of objects, which is not what the render API is expecting. (The render API uses arrays.) That is why you get an error saying that a object cannot be used as array.
See ajax_example_simplest() as example of form builder using AJAX; in particular, see its AJAX callback, ajax_example_simplest_callback().
In short, the code of mymodule_datefields_ajax_callback() should be the following one.
function mymodule_datefields_ajax_callback($form, $form_state) {
return $form['checkboxes_fieldset'];
}
The form builder should use the following code.
function mymodule_settings($form, &$form_state){
$content_type_options = array();
$result = db_query("SELECT * FROM {node_type}");
foreach ($result as $record) {
$content_type_options[$record->type] = $record->name;
}
// $form is already passed as argument; you don't need to initialize it to an empty array.
// $form = array();
$form['content_type'] = array(
'#title' => t('Content Types'),
'#description' => t('Select a content type.'),
'#type' => 'select',
'#options' => $content_type_options,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'reg-start-date',
'callback' => 'mymodule_datefields_ajax_callback',
'method' => 'replace',
),
);
// An AJAX request call to the form builder function has been done.
if (!empty($form_state['values']['content_type'])) {
// Use $form_state['values']['content_type'] to get the option list.
// Set the value of $date_options with that list.
$field_query = db_query("query to execute");
$date_options = array();
foreach ($field_query as $record) {
$date_options[$record->field_name] = $record->field_name;
}
}
else {
$date_options = array();
}
$form['checkboxes_fieldset'] = array(
'#title' => t("Start Date"),
'#prefix' => '<div id="reg-start-date">',
'#suffix' => '</div>',
'#type' => 'select',
'#options' => $date_options,
'#description' => t('Select the date'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
$date_options is an array with the format value => string_to_show; it's is the same format you used for $content_type_options.
I'm trying to set a site up so I can upload images using a web form in Code Igniter(CI). I'm not getting any errors but the file is not being saved either. I wanted to know if those that were successful in uploading images could help explain what might be the issue?
View:
<?php
echo form_open_multipart('admin/galleryUpload') . "\n";
echo "<div class='span-8'><span class='text'>Image:</span>" . form_upload('uploadImg') . "</div>";
foreach ($gallery as $picture)
{
$order[] = $picture->order;
}
$order[] = count($order) + 1;
echo "<div class='span-6 last'><span>Image Order #:</span>" . form_dropdown('order', $order) . "</div><div class='span-14'> </div>";
$conf = array('name' => 'alt_text', 'size' => '75');
echo "<div class='span-14 last'><span>Discription:</span>" . form_input($conf) . "<br /></div>";
echo form_hidden('propertyID', "$propertyID");
echo form_submit('upload', 'Upload');
echo form_close();
?>
Controller:
class Admin extends Controller
{
function galleryUpload()
{
if (! $this->session->userdata('is_admin'))
{
redirect('admin/index');
}
else
{
$this->load->model('admin_model');
$this->admin_model->imgUpload();
}
}
}
Model:
class Admin_model extends Model
{
function imgUpload()
{
$id = $this->input->post('propertyID');
$order = $this->input->post('order');
$alt_text = $this->input->post('alt_text');
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
//'upload_path' => '../' . $this->imgPath($id),
'upload_path' => '../img/galleries/temp/',
'max_size' => '5000', // 5MB files max
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->imgPath($id) . '/thumbs',
'maintain_ratio' => TRUE,
'width' => '60'
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}
From the user guide:
By default the upload routine expects the file to come from a form
field called userfile, and the form must be a multipart type
So you either have to change the name of the form field to userfile:
form_upload('userfile')
or pass the name of your form field to do_upload:
$this->upload->do_upload('uploadImg');