I'm trying to built a page to ask questions with a stream on top, so I need ajax to avoid the reload. It is actually simple. On top is a node with the stream and I add to blocks beneath.
- A table with the questions, number of votes for the questions and an "add vote" button
- A form to add a new node "question with 0 votes"
I have two problems.
A)When I click on the submit button of the 2. Block I add a question, I can update the table with the new question, but the add question form is not being emptied.
B)When I add a vote on the table (currently an ajax call from a checkbox) I get the database to have an increased counter and as far as I could check the callback delivers the new table, but the old one is never replaced. I thought it was the cache, but I even managed to avoid using the cached one, still no replacement. I get a few headers allready sent notices, but I don't understand why. I just want the form to be replaced by the new one.
(don't mind me getting a view instead of just a database result, it's just to built the table)
function questions_list_voting_form($form, &$form_state){
global $user;
$form['#prefix'] = '<div id="questions-list-table">';
$form['#suffix'] = '</div>';
$form['table'] = array(
'#tree' => TRUE,
'#theme' => 'table',
'#header' => array(t("Title"),t("Votes"),t("Add vote")),
);
$view = views_get_view('questions_view');
}
$view->is_cacheable = FALSE;
$view->execute('block');
foreach ($view->result as $row){
//['rows']['row-'.$row->nid]
$question = array('#markup'=>$row->node_title);
$vote = array('#markup'=>$row->field_data_field_votes_field_votes_value);
$addvote = array(
'#type'=>'checkbox',
'#return_value' => 'add_vote'.$row->nid,
'#ajax' => array(
'callback' => 'ajax_addvote_callback',
'wrapper' => 'question-list-table',
'effect' => 'slide',
));
$tab_arr = array(
'question' => &$question,
'vote' => &$vote,
'addvote'.$row->nid => &$addvote
);
$tab_rows = array(
array('data' => &$question),
array('data' => &$vote),
array('data' => &$addvote),
);
$form['table'][] = $tab_arr;
$form['table']['#rows'][] = $tab_rows;
$form['redirect'] = FALSE;
$form['#rebuild'] =TRUE;
unset($question);
unset($vote);
unset($addvote);
}
return $form;
}
function questions_list_voting_form_submitx($form, $form_state){
if(substr($form_state['triggering_element']['#value'],0,8) == 'add_vote'){
$tmp_node = node_load(substr($form_state['triggering_element']['#value'],8,2)); //question node
$tmp_node->field_votes['und'][0]['value']++;
node_save($tmp_node);
}
}
function ajax_addvote_callback($form, &$form_state){
questions_list_voting_form_submitx($form, $form_state);
$form_state['no_redirect'] = TRUE; // avoid redirect?? maybe not working
$form_state['input'] = array('test'=>'etch'); //something to avoid cache
$form = drupal_build_form('questions_list_voting_form', $form_state);
$form_html = drupal_render($form);
return $form_html;
}