Hi..
I´ve written a small module which provides a block with a link. Now, when i click the link, i want to call a piece of code which updates some data in the database. Before that i want the "clicker" to confirm that.
But i don´t know
- how i can run a piece of code by a click on a link
- how to confirm that

Is there anybody who can help me?

Comments

jergason’s picture

hook_menu() might be the answer to your first question. You basically list any urls that you want your module to respond to, and what functions you should execute for each url. You could have your link point to a URL like "www.example.com/my_module/execute_code". Then in hook_menu(), define a menu item with a path of "my_module/execute_code" and a callback to the the function you want to execute. The callback tells Drupal which function to execute. You can even include parameters through the callback arguments.
To confirm, look at the confirm_form function in the API. It creates a form with the option to confirm or cancel.

iterator’s picture

Ok thank you. But i have still a problem.
My menu callback looks like this:

function mymodule_foo(){
  db_query('UPDATE {foo} SET bar = %d', 10);
}

How do i confirm that with confirm_form?

iterator’s picture

Is it impossible to do that in drupal?

jergason’s picture

That is a good question. To do that you need to delve into form submission, which can be a bit intimidating at first. There is some great documentation for learning about forms here, and especially here.
Basically, you will want your callback function to return the form generated by confirm_form, and then you need a separate submit function that will update the database if they confirm. Something like this maybe:

//this is still your callback
function mymodule_foo() {
  //drupal_get_form is used to render the form into html code
  return drupal_get_form('my_confirm_form');
}

function my_confirm_form($form_state) {
  //instead of building the form ourselves, we use confirm_form to automatically generate it
  $form = array();
  return confirm_form($form, 'Do you really want to wear those pants?', 'http://newpants.com', NULL, 'Yes', 'No');
}

//submit handler gets called when form is submitted, so code to be executed upon form submission goes here
function my_confirm_form_submit($form, &$form_state) {
  db_query('UPDATE {foo} SET bar = %d', 10);
}

Does this make sense? Your callback returns a form, and when you submit the form, it calls my_confirm_form_submit, which executes the code contained there.