-
Extracting Image “src” Attributes from an HTML String using PHP
Here are a few ways to build an array of image sources extracted from an HTML string. I’m sure there are other ways, but these seem to be reliable.
1234567$doc = new DOMDocument();@$doc->loadHTML($html);$tags = $doc->getElementsByTagName('img');$image_srcs = array();foreach ($tags as $tag) {$image_srcs[] = $tag->getAttribute('src');}1234567$images = array();preg_match_all('/<img[^>]+>/im', $html, $images);$image_srcs = array();foreach ($images[0] as $image) {preg_match('/src="([^"]*)"/im', $image, $matches);$image_srcs[] = $matches[1];} -
Using Xdebug to Trace Functions
I’ve been relying on Xdebug quite a lot in recent years to step through PHP code, analyze stacktraces, inspect variables, profile applications, and more. Recently I needed to find out why a function call was taking so long to execute. Using Xdebug’s trace functionality made this task pretty simple. Here’s how Xdebug describes function tracing:
Xdebug allows you to log all function calls, including parameters and return values to a file in different formats.
Those so-called “function traces” can be a help for when you are new to an application or when you are trying to figure out what exactly is going on when your application is running. The function traces can optionally also show the values of variables passed to the functions and methods, and also return values. In the default traces those two elements are not available.
Having Xdebug trace your function calls is simple enough, and well-documented across the web. You can see my recommended settings at the bottom of this page, and here’s a good resource on the subject: http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/
-
Copying Values Between Fields on Thousands of Entities
In a nutshell, I had a List (text) field that I needed to convert to a Text field (so that I wasn’t locked in to specific values anymore). Instead of trying to modify the field to convert it from one type to another, I decided to create a new Text field and populate it with the data from the List field (modifying it a bit first). Here’s the script I used to do this. Admittedly it could be cleaner, more efficient, etc. but it’ll show you a few things, and it got the job done for me.
If you choose to run with
drush scr update_nodes.php
you can leave out the top 3 bootstrap lines. -
Drupal 7 – Commerce Migration Class
Here’s a migration class I’ve been working on to import 8200 products. The biggest feature of this code is that it will automatically create a single product display node that groups all products who share the same “grouping identifier.” So, in my CSV import file I have a “grouping_identifier” column. If a product is available in ten colors, and they all share the same grouping identifier, a single product display will be created and each of these products will be referenced in it. This will result in a product on the frontend that allows ten different color choices. I don’t have the time right now to explain anything more… please leave a comment if you have a question.
-
Quick Tip: Adding a Reset button to a Drupal form
Using hook_form_alter or hook_form_FORM_ID_alter one can easily add a “Reset” button to a Drupal form.
In this example we’re actually trying to reset anything the user typed after the form loaded. This will not remove the default values.
Here’s a simple example (Drupal 6)
1234567891011121314/*** Implementation of hook_form_alter().*/function mymodule_form_alter(&$form, &$form_state, $form_id) {switch ($form_id) {case 'myform':$form['buttons']['reset_button'] = array('#type' => 'markup','#value' => '<input class="form-button" type="reset" value="Reset">','#weight' => 2000,);break;}}It may not be appropriate for you to put your new reset element into the buttons array. Use dpm() (part of the Devel module) to show what $form looks like. If you don’t understand this, and the code above isn’t working for you, you may try $form[‘reset_button’] = array….
Adjust the value of #weight to move the button around the form. dpm($form) will show you weights (if any) of existing elements so you can make educated decisions about the weight of your new field.
One last note about the ‘#type’ => ‘markup’ line: this is not a requirement, but I like to include it for clarity.
UPDATE:
Here’s what the field might look like for Drupal 7:
1234$form['reset'] = array('#type' => 'markup','#markup' => '<input class="form-submit" type="reset" value="Reset">',); -
Drupal Commerce Add To Cart Form Tweaks / Registration Improvements
In this example I’m showing how to improve the Add to Cart button for Drupal Commerce products to show differently based on whether or not users have already purchased a product, or whether the product is already in their cart.
I’m currently working on a site where users are registering for “programs,” which are synonymous with classes, courses, etc. I’m using the following modules (among others) in this example:
- Drupal Commerce
- Registration
- Commerce Registration
Please understand that when a user registers for a course, they are actually purchasing a product that has a referenced Registration entity.
-
Proximity by City or Zip Code in Drupal 6 with Location and Views
The location module for Drupal 6 is a robust module. On most projects, it gives us 100 percent of what we need. Proximity searching based on zip code is built-in and fairly painless to setup. I’ve recently been tasked to also allow proximity searching based on City. As you might imagine, the request is very similar. Both methods require the use of latitude and longitude (decimals). The difference is that instead of querying the database for latitude and longitude based on zip code (it’s usually termed postal code in Views, Location, etc.), we’re asking for the coordinates of a city. You’ll find that many cities have multiple zip codes, each of which is a row in the location module’s zipcodes database table. In this example, I’m not giving a real honest attempt at solving this issue, but rather I just return the first coordinate that matches the city.
-
Get the Value of the Cheapest Option for an Ubercart Product
This is just a quick code example. Imaging you have an Ubercart attribute that has several options and you’d like to show an “As low as $X.XX” price on the frontend. Here’s a simple solution. Note that if you wanted the lowest price across ALL attributes you could loop through each attribute too (instead of just looking at attributes[1]).
123456789if ($node->attributes[1]->options) {// Get lowest price of all "Units" attribute options$prices = array();foreach ($node->attributes[1]->options as $opt) {$prices[] = $opt->price;}$output .= t('As low as !price', array('!price' => uc_currency_format(min($prices))));} -
Showing a nodeasblock block as full content instead of teaser
By default, the Node As Block module displays a node in teaser mode. If you wish to show the full content, add the following to your template.php file. (note I’ve also added an edit link for good measure)
123456789function mytheme_preprocess_nodeasblock(&$vars) {$node = $vars['node'];$vars['content'] = node_view(node_load($node->nid), FALSE, TRUE, TRUE);// Add an edit linkif (node_access('update', $node)) {$vars['edit_link'] = l('['. t('edit') .']', 'node/'. $node->nid .'/edit', array('title' => t('Edit')));}} -
Sending webform submissions to email based on value of field
We recently did a site for a client that allowed patients to submit a webform to request an appointment. The user could choose their physician and based on their choice, the submission would be emailed to the chosen doctor’s secretary. I originally thought about using the key part of the key|value pair for the select list to store the secretary’s email address, with the doctor’s name. This wouldn’t work, however, because the key could not contain standard email address characters. The solution involved isn’t exactly dynamic, but for a select list that won’t change much (the case here), it’s a fairly elegant solution. Here is the select list and associated code. I created this with the webform UI using a simple select list webform field.