-
Using hook_form_alter() and #after_build to set maxlength on emvideo title field
A fellow Drupal user posted an issue to the Embedded Media Field project. The user was trying to set the maxlength from 35 characters to some other number for the ‘title’ field within each embedded video widget. I faced the same issue with a site. The client wanted to be able to add more lengthy captions to each video they uploaded. I added the embedded video field (YouTube) as an “unlimited” video field.
The solution involves using hook_form_alter() and the #after_build property.
1234567891011121314151617181920212223242526272829/*** Implementation of hook_form_alter().*/function mymodule_form_alter(&$form, &$form_state, $form_id) {switch ($form_id) {case 'vgallery_node_form':$form['#after_build'][] = '_vgallery_after_build';break;}}/*** Custom after_build callback handler for the video gallery node form*/function _vgallery_after_build($form, &$form_state) {_vgallery_set_title_maxlength($form['field_vgallery_videos']);return $form;}/*** Set the maxlength on the title field of a video gallery emvideo element*/function _vgallery_set_title_maxlength(&$elements) {foreach (element_children($elements) as $key) {if (isset($elements[$key]['emvideo']['title'])) {$elements[$key]['emvideo']['title']['#maxlength'] = 255;}}} -
Moving a field into a (different) group/fieldset using hook_form_alter()
The following demonstrates how to move a field into a different fieldset within a form using hook_form_alter() and a special #after_build form property.
123456789101112131415161718function mymodule_form_alter(&$form, $form_state, $form_id) {if ($form_id == 'status_node_form' && $form['nid']['#value']) {$form['send_notification'] = array('#type' => 'submit','#value' => t('Send Notification'),'#submit' => array('mymodule_notify_submit'),);$form['#after_build'][] = 'mymodule_notification_afterbuild';}}function mymodule_notification_afterbuild($form, $form_state) {// Add the notifications button to the "Notifications" field group// (defined in the content type field manager)$form['group_notifications']['send_notification'] = $form['send_notification'];unset($form['send_notification']);return $form;} -
Show a timestamp as a date in the Drupal user’s timezone
12345$ts = 1288639479;$local_zone = date_default_timezone_name(TRUE);$newdate = date_make_date($ts, 'UTC', DATE_UNIX);date_timezone_set($newdate, timezone_open($local_zone));print date_format_date($newdate, 'custom', 'm/d/Y H:i'); -
db_query() and db_placeholders() example #1
Have you ever wondered how to properly build a query like this in Drupal:
1SELECT nid, type, title FROM node n WHERE n.type IN('page','story');This requires the use of db_placeholders() to create the placeholder ‘ ‘, ‘ ‘, etc.
1$result = db_query('SELECT nid, type, title FROM {node} n WHERE n.type IN(' . db_placeholders($node_types, 'text') . ')', $node_types);where $node_types is an array of node types.
-
Automatically create a Drupal node when a user registers
Sometimes projects come up that have requirements that cannot be solved with an out-of-the-box Drupal install. A project I worked on some time ago required that I store a node every time a user registered for an account. The details of the project are a little fuzzy for me now, so I’ll just skip right to the example.
1234567891011121314function mymodule_user($op, &$edit, &$account, $category = NULL){switch($op){case 'insert':// Automatically create the note settings (content profile) node for this new user$newnode = new stdClass();$newnode->title = "Note settings user {$account->uid}";$newnode->uid = $account->uid;$newnode->type = 'note_settings';$newnode->status = 1;$newnode = node_submit($newnode);node_save($newnode);break; //insert}}This example shows how simple it is to programmatically create a node, and also shows the proper way to hook into the user system.
-
Programmatically displaying an image using an imagecache preset
The following illustrates one way to render an image using an Imagecache preset. Naturally, if your imagefield has multiple uploads you could wrap this in a foreach.
1234$path = $node->field_pgallery_images[0]['filepath'];$alt = $node->field_pgallery_images[0]['data']['alt'];$title = $node->field_pgallery_images[0]['data']['title'];print theme('imagecache', ‘presetname’, $node->field_pgallery_images[0]['filepath'], $alt, $title, $attributes); -
States in key|value format
The following is a list of the United States in key|value format. It’s useful when creating a select list in Drupal.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758AL|AlabamaAK|AlaskaAS|American SamoaAZ|ArizonaAR|ArkansasCA|CaliforniaCO|ColoradoCT|ConnecticutDE|DelawareDC|District of ColumbiaFL|FloridaGA|GeorgiaGU|GuamHI|HawaiiID|IdahoIL|IllinoisIN|IndianaIA|IowaKS|KansasKY|KentuckyLA|LouisianaME|MaineMH|Marshall IslandsMD|MarylandMA|MassachusettsMI|MichiganMN|MinnesotaMS|MississippiMO|MissouriMT|MontanaNE|NebraskaNV|NevadaNH|New HampshireNJ|New JerseyNM|New MexicoNY|New YorkNC|North CarolinaND|North DakotaMP|Northern Marianas IslandsOH|OhioOK|OklahomaOR|OregonPW|PalauPA|PennsylvaniaPR|Puerto RicoRI|Rhode IslandSC|South CarolinaSD|South DakotaTN|TennesseeTX|TexasUT|UtahVT|VermontVI|Virgin IslandsVA|VirginiaWA|WashingtonWV|West VirginiaWI|WisconsinWY|Wyoming -
Countries in key|value format
The following is a list of countries in key|value format. It’s useful when creating a select list in Drupal.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241AF|AfghanistanAL|AlbaniaDZ|AlgeriaAS|American SamoaAD|AndorraAO|AngolaAI|AnguillaAQ|AntarcticaAG|Antigua And BarbudaAR|ArgentinaAM|ArmeniaAW|ArubaAU|AustraliaAT|AustriaAZ|AzerbaijanBS|BahamasBH|BahrainBD|BangladeshBB|BarbadosBY|BelarusBE|BelgiumBZ|BelizeBJ|BeninBM|BermudaBT|BhutanBO|BoliviaBA|Bosnia And HerzegovinaBW|BotswanaBV|Bouvet IslandBR|BrazilIO|British Indian Ocean TerritoryBN|Brunei DarussalamBG|BulgariaBF|Burkina FasoBI|BurundiKH|CambodiaCM|CameroonCA|CanadaCV|Cape VerdeKY|Cayman IslandsCF|Central African RepublicTD|ChadCL|ChileCN|ChinaCX|Christmas IslandCC|Cocos (keeling) IslandsCO|ColombiaKM|ComorosCG|CongoCD|Congo, The Democratic Republic Of TheCK|Cook IslandsCR|Costa RicaCI|Cote D'ivoireHR|CroatiaCU|CubaCY|CyprusCZ|Czech RepublicDK|DenmarkDJ|DjiboutiDM|DominicaDO|Dominican RepublicTP|East TimorEC|EcuadorEG|EgyptSV|El SalvadorGQ|Equatorial GuineaER|EritreaEE|EstoniaET|EthiopiaFK|Falkland Islands (malvinas)FO|Faroe IslandsFJ|FijiFI|FinlandFR|FranceGF|French GuianaPF|French PolynesiaTF|French Southern TerritoriesGA|GabonGM|GambiaGE|GeorgiaDE|GermanyGH|GhanaGI|GibraltarGR|GreeceGL|GreenlandGD|GrenadaGP|GuadeloupeGU|GuamGT|GuatemalaGN|GuineaGW|Guinea-bissauGY|GuyanaHT|HaitiHM|Heard Island And Mcdonald IslandsVA|Holy See (vatican City State)HN|HondurasHK|Hong KongHU|HungaryIS|IcelandIN|IndiaID|IndonesiaIR|Iran, Islamic Republic OfIQ|IraqIE|IrelandIL|IsraelIT|ItalyJM|JamaicaJP|JapanJO|JordanKZ|KazakstanKE|KenyaKI|KiribatiKP|Korea, Democratic People's Republic OfKR|Korea, Republic OfKV|KosovoKW|KuwaitKG|KyrgyzstanLA|Lao People's Democratic RepublicLV|LatviaLB|LebanonLS|LesothoLR|LiberiaLY|Libyan Arab JamahiriyaLI|LiechtensteinLT|LithuaniaLU|LuxembourgMO|MacauMK|Macedonia, The Former Yugoslav Republic OfMG|MadagascarMW|MalawiMY|MalaysiaMV|MaldivesML|MaliMT|MaltaMH|Marshall IslandsMQ|MartiniqueMR|MauritaniaMU|MauritiusYT|MayotteMX|MexicoFM|Micronesia, Federated States OfMD|Moldova, Republic OfMC|MonacoMN|MongoliaMS|MontserratME|MontenegroMA|MoroccoMZ|MozambiqueMM|MyanmarNA|NamibiaNR|NauruNP|NepalNL|NetherlandsAN|Netherlands AntillesNC|New CaledoniaNZ|New ZealandNI|NicaraguaNE|NigerNG|NigeriaNU|NiueNF|Norfolk IslandMP|Northern Mariana IslandsNO|NorwayOM|OmanPK|PakistanPW|PalauPS|Palestinian Territory, OccupiedPA|PanamaPG|Papua New GuineaPY|ParaguayPE|PeruPH|PhilippinesPN|PitcairnPL|PolandPT|PortugalPR|Puerto RicoQA|QatarRE|ReunionRO|RomaniaRU|Russian FederationRW|RwandaSH|Saint HelenaKN|Saint Kitts And NevisLC|Saint LuciaPM|Saint Pierre And MiquelonVC|Saint Vincent And The GrenadinesWS|SamoaSM|San MarinoST|Sao Tome And PrincipeSA|Saudi ArabiaSN|SenegalRS|SerbiaSC|SeychellesSL|Sierra LeoneSG|SingaporeSK|SlovakiaSI|SloveniaSB|Solomon IslandsSO|SomaliaZA|South AfricaGS|South Georgia And The South Sandwich IslandsES|SpainLK|Sri LankaSD|SudanSR|SurinameSJ|Svalbard And Jan MayenSZ|SwazilandSE|SwedenCH|SwitzerlandSY|Syrian Arab RepublicTW|Taiwan, Province Of ChinaTJ|TajikistanTZ|Tanzania, United Republic OfTH|ThailandTG|TogoTK|TokelauTO|TongaTT|Trinidad And TobagoTN|TunisiaTR|TurkeyTM|TurkmenistanTC|Turks And Caicos IslandsTV|TuvaluUG|UgandaUA|UkraineAE|United Arab EmiratesGB|United KingdomUS|United StatesUM|United States Minor Outlying IslandsUY|UruguayUZ|UzbekistanVU|VanuatuVE|VenezuelaVN|Viet NamVG|Virgin Islands, BritishVI|Virgin Islands, U.s.WF|Wallis And FutunaEH|Western SaharaYE|YemenZM|ZambiaZW|Zimbabwe -
Custom Voting API Calculation
The Voting API is really nice when used in conjunction with a module like Fivestar. It takes all of the complexity out of setting up a voting/rating system. On occasion, however, you need it to do some things that aren’t built in. Using the VotingAPI’s API, I’ll show you how to trigger a function (send an email, write a message to the screen, etc.) when a piece of content receives a fifth vote of four stars or greater. That is, a node may have four votes of five stars, and two votes of two stars. As soon as the next greater-than-four vote goes in, we want to do something about it. In our case, the client wants to receive an email when a node is popular, and has had five four-star-or-greater votes.
-
Show Menu Description Field in Node Add/Edit Form
Many components in Drupal have an optional title or description field. This text usually displays when a user hovers over an item. We had an interesting request: a client wanted to have a box that displayed text which would change every time you roll over a menu item. This can be accomplished using just a small amount of jQuery, and Drupal’s built-in menu handling. The menu system in Drupal can handle descriptions on each menu item, however you have to do this through the menu admin. The problem is that the client needed to be able to edit these descriptions at will.