How to add one or more custom submit handlers to a Drupal form
The information in this post relates to Drupal 5.x.
In Drupal 5 it's possible, and easy, to play with a form's submit handlers: you can replace an existing handler with your own and you can even add multple handlers if you want.
In human terms, this means that you can change the function that is called when a certain form is submitted and has passed the validation handler (the function responsible for validating the form input).
Why would you want to do this?
You might want to do some stuff before a node is inserted, like insert the same data into an external database. Maybe you want to change the submitted information before it's handled by Drupal. Maybe you want to send a mail to a certain user when a certain type of node is updated with certain information.
Or maybe you want to interrupt the normal flow and just do something totally different than normally intended.
Whatever you want to do, you can do it all by using your own submit handlers. Here's how:
Each form has a #submit property. The value of that property is the name of the function that is to be called on submit. If this property is not present, Drupal will look for a function called form_id_submit. If that one isn't found either, Drupal will look for a function called #base_submit.
Tip: chapter 10 of Pro Drupal Development does a great job of describing the Form API in detail.
If you want to override this value, simply replace the #submit value with a function name of your choice. You need to do this by implementing a form_alter hook. This means creating a function that will be called when a your form is called, making sure to respect the naming convention and the function"s signature (number and order of parameters)
Example:
function mymodule_form_alter($form_id, &$form){
switch($form_id){
case 'some_form_id':
// code in here will be called when form 'some_form_id' is built.
// this is your chance to modify it before its html is rendered.
break;
}
}
The code to modify the submit handler:
$form['#submit'] = 'mymodule_my_own_submit_handler';
Now, what's cool is that you can queue up multiple submit handlers, meaning that you can have multiple functions called one after the other, upon a form submit. To do this, simply put them in an array and assign it to the #submit property:
$form['#submit'] = array( 'mymodule_my_own_submit_handler', 'mymodule_my_second_submit_handler', 'mymodule_my_third_submit_handler');
If you simply want to add a submit handler, but want to make sure it is executed before the default handler, you need to do something like this:
// add an additional submit handler to the #submit array.
// use array_merge to make sure the new handler is the first one in the array
$form['#submit'] = array_merge(array("mymodule_my_handler" => array()), $form['#submit']);
Putting it all together:
function mymodule_form_alter($form_id, &$form){
switch($form_id){
case 'some_form_id':
$form['#submit'] = 'mymodule_my_own_submit_handler';
break;
}
}
Have fun.
Comments
Spot on mate with the additional handler in the submit. Very useful.
Right, I agree its right on. It took me sometime to understand about the Multiple handlers and reading this post made me recall the experience. Miami florida condos
The plan advocates diversification of energy sources, including renewables, as well as fuel switching to improve energy efficiency. signs of a cheating spouse
Thanks. Took me a bit of time to figure out but in the end it's quite straightforward.
Thanks
I was greatly interested with what you have shared and posted with us. Thanks for this anyway.
Search
That is amazing..!! Thanks
Performance is the physical expression of music. Often, a musical work is performed once its structure and instrumentation are satisfactory to its creators, however, as it gets performed, it can evolve and change. how to get your ex back
We will guide you, and help you with your study plans, ensuring your success in examinations and the smooth navigation of your chosen career path during these turbulent economic times
Regards,
Research Paper Help
Lifesaver!
So cool to be able to chain submit handers! Thanks for posting this, excatly what I was looking for. Now I can process a single select value where the OG form handler was expecting multiple values.
-M
Thanks so much! I've been looking for this site for an hour! I didn't know how to add a submit handler rather than override the original one. I don't aspire to completely replace the functionality of the node module...
So, that was amazingly helpful. God bless you!
you're quite welcome :)
Great post!
One question though, how would I do something with say, for example, an additional field that I add in the form_alter hook?
Example: I'm altering a simple form that normally asks for a First and Last name, but I am writing a simple module that adds an additional Title field.
If I use something like:
$form['#submit'] = array_merge(array("my_module_handler" => array()), $form['#submit']);
Can I pass something like $form_values['title'] through to the handler as an argument to save into a custom table?
I know the article clearly states that the information is for Drupal 5.x, but those using Drupal 6.x need to use the following code:
$form['#submit'] = array('my_form_handler');
The only difference is that all form handlers, regardless it it's one or many, must be in an array. I hope someone finds this helpful.
Thanks, I'll try it. I am using D6.
Hello, this is working for drupal 6.x also. now i have another problem. When i do
[code]
function modulename_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'modulename1_node_form') {
$form['#submit'][] = 'modulename_getpkid';
}
return $form;
}
function modulename_getpkid(&$form, &$form_state) {
$sid = $form_state['values']['sid'];
print $sid;die;
}
[/code]
it is not working. do you have any idea why ? what i m trying is to save values of latest id stored in database by pressing submit button.
Hats off for the _form_alter idea, man. I was trying to find a way to have a form with two submit buttons, where one submits to the form itself (it's a multistep) and another one that jumps to a different URL, but sending the values via POST to that URL. Here's how I'll do it:
I'll intercept the form submission, and according to the value of the $form['op'] (the button pressed), I will change the $form['#action'] property. Hope it will work. Thanks for the inspiration.
The only difference is that all form handlers, regardless it it's one or many, must be in an array. I hope someone finds this helpful
скачать игры бесплатно навсегда - скачать бесплатные игры, бесплатные игры скачать бесплатно, игры скачать бесплатно, бесплатные игры компьютер скачать мини игры бесплатно. Игровой сайт tainik.ru
http://classsex.ru/sex/154.jpg
http://opapizda.com/img/44/index.jpg
http://tdq.in/images/1/499.jpg
3gp порно
жесткое порно групповуха
порно 6
хочу посмотреть порно ролики
посмотреть порно со школьницами
порно секс миньет
зад порно
порнофильмы почтой
правильный секс
www eroz ru порно галереи
Порно Ftp Ресурс
Костанай Секс
Порно Москва Где
Секс Анастасии Заваратнюк
Порно Фильмы Avi
Цервицит Секс
Секс Порно Ретро
Карта сайта
Бикини Фото Порно
Порно Фото Маленьких Школьниц
Женщина Ебет Мужчину
Карта сайта
Жосткий Анальный Секс
Порево Училок - домашнее женщина фильм
Беслатноя Парнуха
Порно Пожилые Толстые
Частные Галереи Секса
Карта сайта
Порно Молоденьких Девочек
Пиписьки Сиськи Женские
Секс Со Старыми Бабами
Где Порно
U Porno - зрел женщины фильм
Жора Ебанный Насос
Секс Порно Xxx
Альбом Порно Фото
Карта сайта
Карта сайта
Видео Порно Китаянки
Porn Freaks
Sex Positions
Порно Фото Димы Билана
Эротика Бдсм
60 Попок
Эротика 12 Лет
Карта сайта
Tv Online Эротика
Compaг=ero Presidente
Porno Kutak
Фото Крутых Тёлок
Порно Ани Лорак
Kim Kardashian Sex
Порно Фотогалерея Любительская
Эротика Жопа
Гомель Секс
Частное Фото Секс Сайт
Посмотреть Видео Порно Клипы
секс порно обои
хочу секса спб
x секс
лена порно фото
огромные сиськи 10 размер
lesbian sex yabb
секс клуб екатеринбург
нестандартный секс
порно фото латекс
выборгский порно фестиваль
faq секса
порнуха жирных
секс проект
клитор знаменитости
ссылки порнография
порно смарт
лимас сиськи
cекс эротика
эротика фильм онлайн смотреть
секс ролики посмотреть
http://classsex.ru/sex/403.jpg
http://opapizda.com/img/10/index.jpg
http://tdq.in/images/1/403.jpg
фильм сиськи
беспатный секс
порно фильм беплатно
порно модели секс
фото ебли молодых
Порно фильм короткие
Секс массаж видео
Дикое порно
Порно жанны фриске
Порно еротика секс
Порно роллик
Видео ролик футбол финты
Порно клипы большие сиськи
Анна маранцева секс помощь
Телки сайт
Секс знакомства санкт петербург
Порно звезды клипы
Казахстанский секс сайт
Приколы секс картинки
Тыкал писькой под лобок
Секс знакомства ярославль
Xxx porno video ru
Порно анна николь смит
Горячий Секс Видео
Порно вчетвером
Грудь попка
Www porno world ru
зрелых эротика видео
Эротика секс картинки
Прсмотр порно
Www секс госпожа ru
Домашнее порно почтой
лучьшие порно
порно vhs
шведское порно
проблемы первого секса
порно фото девушек культуристок
хочется секса песня
сиськи теща
порно гинекологический кабинет
porno video gratuit
военные гей секс
мужской стриптиз видео
уэлш порно
пизда марии шараповой
bigtit sex
секс досуг сказка
старческий секс
порно фото секс учительницей
дагестанское порно
порно мультяшки картинки
girl порно
http://classsex.ru/sex/71.jpg
http://opapizda.com/img/6/index.jpg
http://tdq.in/images/1/344.jpg
укр секс
секс после развода
алина кабаева секс
порно фото видео изнасилования
москва геи секс
Самоучитель стриптиза видео
голая порно видео
Парень ищет секс харьков
Порно леной берковой
Музей секса фото
Жена секс рабыня
Памелла андерсон секс
Порнофильмы почтой
Хард порно
Порно тюрьма
Видео мужико порно
Бикини попки
Wap секс
Порнушка эротика
Порно влагалище крупно
Порно сильвия сайнт
Знакомства секс питер объявления
Sex shop почтой
Секс порно обои
Порно кодак
Порно анал сиськи
Секс клипы фото
Молодежное порно
Клубничка секс
домашнее девушки видео
Фото госпожа секс
Секс знакомства icq
Порно фото вечеринки
Ссылки порно ролики
Порно секс груды
Женские частные попки
Порно видео ирен феррари
Жесткое порно фото анал
Посмотреть порно видео лизбиянок
Порно пирсинг
Порно щкольниц
Ивано франковск отдых секс
онлайн парнуха видео
Www порнография ru
Ftp гей порно
Афро порно
Секс обевление
инцест девочка видеофильм
Диффченки sex aerobica
Размеры вагины
Мини порно
Порно секс групповуха
секс новое
секс оли бузовой
xxx порно эротика
фото грязи секс
семенович порно видео
ебёт 15 летнюю
секси бельё
секс 800р
порно медосмотр
бeсплaтноe порно видeо смотрeть
большие отвисшие сиськи фото
секс порно видео клипы
порно итальянок
беркова занимается сексом
porn stars
жосткое порно видео
порно архангельска
секс отель
http://classsex.ru/sex/216.jpg
http://opapizda.com/img/35/index.jpg
http://tdq.in/images/1/680.jpg
Домашнее порно эротика
Секс шахзода
Снимусь порно
Www porno mail ru
Порно фото анастасии заворотнюк
Best ero
Пухленькие попки
Малолетние пизды
Ищу пару секс
Жесткое порно смотреть online
Порно подрочить фото
Трансексуал порно
Wicked sex party
Секс нижний тагил
Симулятор порно
Полнометражные порнофильмы
Старая госпожа заставила лизать пизду
Римляне секс
Порно тётя
Эротика порно фото хххх
Эротика фитнес
Порно соседка
Музыкальные видео ролики
зрел девушки видеоролик
Пара хочет секса
Йоханнесбург секс
Черная волосатая пизда эротика
Секс родителей
Порно анима
Порно сайты посмотреть видео
Готичное порно
Большие сиськи медсестры
Большие сиськи попки
Порно сайты мира
Смотреть жёсткие порно ролики
Magic porn biz
Порно санкт петербург видео
Porno pfoto
Sex medikcom ru
Бабки секс
ThanX
http://classsex.ru/sex/175.jpg
http://opapizda.com/img/6/index.jpg
http://tdq.in/images/1/943.jpg
bb.txt open error
интернет казино список - Goldfishka (Голдфишка), интернет казино рулетка, игровые интернет казино, интернет автоматы казино, интернет казино игровые автоматы. Сайт goldfishka.tv
Thx for this explanation,but what about the Drupal 6 Verion? I think it doesn't work well.
Can't get the custom submit to work with my fire extinguishers drupal site... any ideas?
Thanks,
Rick
Very informative, thank you. I’ve been blogging on and off for almost 3 years, but have never had much of a focus – I tend to just write about whatever is on my mind when I feel like writing.
Cheers!..
350-018 | 640-864 | 646-364 | 642-384 | 642-447 | 642-374 | 640-863 | 642-437 | 646-671 | 646-230 |
That is very good comment you shared.Thank you so much that for you shared those things with us.Im wishing you to carry on with ur achivments.All the best.custom printed folders
Great code techniques here; will be very useful for my dog clothes fashion app.
Hi all,
I have a big problem, I am converting an entire drupal 5 site to drupal 6 but i am having big problems because most of hooks in d6 don't exist..I am trying to add add custom submit handlers for my custom nodes forms but when i send form functions are not invoked..Where is the problem?
best vibration plate
Add one or more custom submit handlers in Drupal .... own handlers to interrupt the normal flow and perform custom actions on the form data
best pressure washers
I think that thanks for the valuable information and insights you have so provided here.
find hosting
Pretty nice post. I just stumbled upon your weblog and wanted to say that I've really enjoyed browsing your blog posts.
joomla developers
Interesting topic what you have shared with us. Your writing skill is really very appreciative. I love when you share your views through the best articles.Keep sharing and posting articles like these.This article has helped me a lot.Keep posting this stuff.
Ansoo Lake
I am trying to add add custom submit handlers for my custom nodes forms but when i send form functions are not invoked..Where is the problem ...
best sat nav uk
Post new comment