Web development includes non-design aspects of building web sites: writing markup and coding.
Define controller in Drupal 11
3 Dec, 2024
The issue comes down to picking ControllerBase or ContainerInjectionInterface. Here is a simple explanation between the two paths of ControllerBase vs ContainerInjectionInterface.
Get dom element height in JavaScript
5 Nov, 2024
Get the total height of an element, optionally including its margins.
PHP: Detect mime type by extension
27 Oct, 2024
If you're working in a PHP environment and want to detect MIME types by file extension, using Symfony's Mime component is a great choice. Here’s how to set it up and use it:
navigation.goBack() does not refresh context/state in react native
21 Oct, 2024
To ensure that navigation.goBack() refreshes context or state in React Native, add logic to refresh or reload data when the screen is focused after navigating back.
Get mimetype from takePictureAsync() in Expo React Native
18 Oct, 2024
takePictureAsync() from expo-camera does not directly return the MIME type. It only returns the URI, base64, width, height, and other metadata. To get the MIME type, you can determine it based on the...
JavaScript: get char count from the end of a string
17 Oct, 2024
You can count the asterisks at the end of a string, in JavaScript, using this snippet. This uses match() with the regex \*+$ to find the sequence of asterisks at the end of the string. If there's a...
PHP: use docstring to mark function deprecated
15 Oct, 2024
To mark a PHP function as deprecated and provide an alternative in the docstring, use the @deprecated tag. This makes it clear to developers that the function is deprecated and specifies the...
Dialog form fieldsets to show in columns not rows in CKEditor 4
13 Sep, 2024
Instead of stacking elements vertically in rows, we use an hbox layout, which arranges the child elements horizontally (in a single row). hbox is CKEditor's way of arranging elements in a horizontal...
Equal width columns except the last one, using flex in CSS
13 Sep, 2024
To create CSS flex columns with equal width except for the last one, you can use this combination of flexbox properties.
Append to HTML with JavaScript
13 Sep, 2024
To append content to an HTML element using JavaScript, you can use appendChild() for DOM elements or innerHTML for strings.
JSHint: Expected an identifier and instead saw ']'.(E030)
6 Sep, 2024
The JSHint error "Expected an identifier and instead saw ']'. (E030)" usually occurs when there is a syntax issue in your JavaScript code involving square brackets ([]). The least obvious is that you...
CKEditor 4: Add edit button to context menu
6 Sep, 2024
This code snippet adds a custom "Edit" button to the CKEditor context menu, specifically for a widget with the class "my-widget." It first creates a new menu group called myWidgetGroup and then...
CKEditor 4: Save dialog form data/state
6 Sep, 2024
The example contains a CKEditor 4 widget with a dialog that allows users to edit widget properties. The dialog loads existing widget data into form fields. When the dialog is submitted, the form data...
Flex 100% width in CSS for a row
6 Sep, 2024
To set a flex container with flex-direction: row and ensure it takes up 100% width, you can do it like in this snippet. With flex-direction: row, the flex items (the children) will be aligned in a...
Preact update state on resize event
22 Aug, 2024
You can create a Preact component that rerenders every time the window is resized by using window.addEventListener('resize'). The general approach involves setting up an event listener in a useEffect...
Parse Url in JavaScript
22 Aug, 2024
To parse a URL in JavaScript, you can use the built-in URL object. This provides an easy way to extract and manipulate different parts of a URL.
Preact: Add delay to updating a string
22 Aug, 2024
To add a delay to updating a string based on state in Preact, you can use the useEffect hook in combination with setTimeout. This allows you to delay the state update by a certain amount of time...
CSS: next flex item to go to new line
16 Aug, 2024
To force the next flex item to go to a new line in a CSS flex container, you can use the break-after property.
Filter Array of Objects Based on an Array of IDs in JavaScript
16 Aug, 2024
To filter a list of objects based on a list of IDs in JavaScript, you can use the filter method combined with the includes method. First, you have an array of IDs and another array of objects where...
Get path from url in JavaScript
10 Aug, 2024
To add a path to an existing URL in JavaScript, you can use the URL object and its methods.
Optional character in regex
10 Aug, 2024
In regex, the question mark ? makes the preceding character, group, or class optional, allowing it to appear zero or one time. For example, colou?r matches both 'color' and 'colour'. It's a versatile...
Trim whitespace in JavaScript
10 Aug, 2024
In JavaScript, you can trim whitespace from the beginning and end of a string using the trim() method. This example shows you how it will remove any leading and trailing whitespace characters (spaces...
React: Append to an object in state
10 Aug, 2024
In React, appending to an object in the state involves updating the state with a new object that includes the existing properties and the new ones. This pattern ensures that you immutably update the...
Run after "set" in Preact
10 Aug, 2024
When using useState in Preact (or React), the setState function doesn't accept a callback as a second parameter, unlike in some other libraries. Instead, the proper way to execute code after a state...
CSS: selector from custom attribute and its value
10 Aug, 2024
In CSS, you can select elements based on custom attributes and their values using attribute selectors. To select an element with a specific value of a custom attribute, you use the [attribute="value...
CSS: Differentiate between keyboard and mouse focus
10 Aug, 2024
In CSS, you can differentiate between keyboard and mouse focus using different pseudo-classes and selectors. :focus-visible - This pseudo-class targets elements that should be visibly focused,...
Add outline offset in Tailwind 2
10 Aug, 2024
Tailwind CSS 2 doesn't natively support the outline-offset utility, so you'll need to add it through a custom plugin. Use the utility-first approach by extending the configuration in the tailwind....
Check if object parameter is defined in ES6
6 Aug, 2024
The simplest way, but this approach only works if you are sure that the values of test.test and test.test2 are not falsy (i.e., not 0, null, undefined, false, NaN, or an empty string ''). If you need...
Check for empty object in JavaScript
6 Aug, 2024
To check if an object is empty in JavaScript, you can use several methods. You might prefer using Object.keys() to check if an object is empty because it offers clarity, readability, and conciseness...
Iterate array in JavaScript or ES6+
6 Aug, 2024
The forEach method is preferred in JavaScript for its readability and simplicity. It provides a more concise and clear way to iterate over arrays compared to traditional loops, avoiding the need for...
querySelector to test against the root element in JavasScript
6 Aug, 2024
Instead of querySelector you should use matches(). The matches() method in JavaScript is used to determine if an element would be selected by a specified CSS selector. This method returns true if the...
Responsive grid with infinite columns in CSS
5 Aug, 2024
Creating an infinite grid using grid-template-columns: repeat(auto-fit, minmax(minimum, 1fr)) is a common CSS technique to build responsive grid layouts. This method allows the grid to adjust the...
Limit text to n lines in CSS
5 Aug, 2024
To limit a div to a maximum of two rows of text in CSS, you can use the combination of line-clamp, display: -webkit-box, and other related properties. In this example I set the width to 50px for the...
Convert object to array in JavaScript
19 Jul, 2024
In JavaScript, you can convert an object to an array in several ways depending on what part of the object you want to convert (keys, values, or entries). You can add a check to ensure that the...
Get first parameter value alphabetically from array of arrays
13 Jun, 2024
Using this solution we find and display the item from an array of associative arrays that has any specified attribute (like title, name, etc.) which comes first alphabetically. This approach can be...
Order objects in array by property in JavaScript
12 Jun, 2024
In JavaScript, you can sort arrays of objects by a specified property using custom functions that handle both string and integer properties, and can sort in either ascending or descending order. The...
Using addEventListener in Preact
12 Jun, 2024
This example demonstrates how to add and properly clean up event listeners in a Preact functional component using the useEffect hook. A button element is referenced using useRef, and event listeners...
React Native: Run only when internet is connected
25 Apr, 2024
To run code in React Native only when a network connection is available, you can use the NetInfo module from the @react-native-community/netinfo package. This module allows you to subscribe to...
React Native Bullet List Component
24 Mar, 2024
In React Native, standard list components are not available by default. This code snippet showcases a custom bullet list component designed to fill this gap. With custom styles and a simple yet...
structuredClone in React Native
18 Mar, 2024
This snippet is about deep cloning objects in React Native. React Native does not have a direct equivalent to the structuredClone() method because it doesn't have the same browser environment and...
Generating UUIDs in React Native
13 Mar, 2024
You cannot use the regular uuid package directly in React Native due to its dependency on crypto.getRandomValues, which is not supported in the React Native environment. This code snippet introduces...
Drupal 7: Ensure Default Display Tab Visibility in Views UI Edit Form
13 Mar, 2024
This code snippet utilizes hook_form_alter to ensure that the 'Default' display tab remains visible in the Views UI edit form of Drupal 7, allowing users to easily access and modify default display...
Drupal 7: Print all hook_menu items
12 Mar, 2024
In Drupal 7, there isn't a specific function provided by the core API to directly fetch all hook_menu() items from the database. However, you can achieve this by querying the menu_router table as...
PHP: Strip double whitespace, keeping only one space
11 Mar, 2024
In PHP, the task of stripping double whitespace while retaining only one space involves utilizing regular expressions or string manipulation functions. The regular expression /\\s+/ serves as a key...
Add multiple styles to one element in React Native
11 Mar, 2024
In React Native, you can add multiple styles to one element by passing an array of styles to the style prop.
External Images in React Native with Expo
10 Mar, 2024
Expo's Image component simplifies the process of integrating images into React Native applications by supporting various image formats and sources. Whether sourcing images locally from the project...
Icon Button Grid: Achieving Equal Spacing in React Native
10 Mar, 2024
The snippet utilizes flex properties to organize React Native FABs (Floating Action Buttons) and empty views in a row, ensuring equal spacing between them. Additionally, the implementation of the...
Filter by array key, using pattern in PHP
8 Mar, 2024
To filter an array by key using a pattern in PHP, you can use functions like array_filter() and regular expressions. In this example, preg_match() is used to check if the key matches the defined...
PHP: string contains (case-insensitive)
7 Mar, 2024
To check if a string contains another string in PHP in a case-insensitive manner, you can use the stripos() function. stripos() returns the position of the first occurrence of a substring in a string...
CodeIgniter 4: Add Nullable Field in Migration
7 Mar, 2024
To add a field that can have a value of null in a CodeIgniter 4 migration, you can specify the field as nullable. The 'null' => true option in the field definition specifies that the field can...
CodeIgniter 4: Save to log
26 Feb, 2024
In this snippet we're using log_message() to log messages of different severity levels (error, debug, info). Depending on the condition, we log different messages. Ensure that logging is enabled and...
Vanilla JavaScript trigger click event
24 Feb, 2024
To trigger a click event using vanilla JavaScript, you can use the click() method on the element you want to simulate a click for. For more information: https://developer.mozilla.org/en-US/docs/Web/...
Center inline block vertically in CSS
22 Feb, 2024
In this layout structure, the parent element is set to display as inline-block, creating a container that adapts to the size of its content. Similarly, the content within the parent element is styled...
Iterate objects in JavaScript
21 Feb, 2024
In JavaScript, for iterating over objects, I recommend using the Object.entries() method, introduced in ECMAScript 2017 (ES8) and supported by modern browsers. This method provides key-value pairs in...
Deep merge in JavaScript
21 Feb, 2024
Deep merging in JavaScript refers to the process of merging two or more objects deeply, ensuring that nested structures, including arrays, are merged recursively. While JavaScript provides the spread...
React Native get SQLite table rows
17 Feb, 2024
To retrieve rows from a SQLite database in a React Native Expo project, you can use the expo-sqlite package along with JavaScript's asynchronous capabilities.
Overwrite button text for Screen Readers
16 Feb, 2024
If you use the aria-label attribute to provide alternative text for a button, screen readers will prioritize reading out the content of the aria-label attribute over the visible text on the button.
CodeIgniter 4: Add migration file
14 Feb, 2024
To add a migration file in CodeIgniter 4, you can use the command-line interface provided by CodeIgniter's CLI tool called spark.
Remove all but first n array items in JavaScript
10 Feb, 2024
To remove all but the first n elements from an array in JavaScript, you can use the splice() method or array slicing. The splice() method in JavaScript is used to change the contents of an array by...
JavaScript one-liner to get unique array values
9 Feb, 2024
This snippet uses a combination of Set and Array.from() to filter out duplicate values and convert the result back into an array. When you initialize a Set with an array, it automatically removes any...
JavaScript: Get index by value in array
9 Feb, 2024
In JavaScript, if you want to get the index of an element in an array based on its value, you can use the indexOf() method. If the value is not found in the array, the indexOf() method will return -1...
Element scroll offset in JavaScript
7 Feb, 2024
This code snippet demonstrates how to retrieve the horizontal (x) and vertical (y) scroll coordinates of an element using the scrollLeft and scrollTop properties, respectively. One common use case...
strtotime() from timestamp in PHP
7 Feb, 2024
In PHP, the most common and straightforward method to convert datetime strings to timestamps is by using the strtotime() function. So even when this seems like a pointless exercise, you might...
JavaScript: Move all elements from a div to another div
7 Feb, 2024
In this snippet we move/clone dom elements with all children for later usage.
Regex: Matching SSH Public Key
4 Feb, 2024
To match an SSH public key using regular expressions (regex), you can use the following pattern. SSH public keys typically start with "ssh-rsa" or another algorithm identifier, followed by the key...
Regex: Matching Roman Numerals
4 Feb, 2024
This regex is useful for validating and extracting Roman numerals in a given text or input. It's particularly handy in applications where you need to identify and work with Roman numerals, such as...
Regex: Matching HTML Self-Closing Tags
4 Feb, 2024
The following snippet employs a PCRE (Perl Compatible Regular Expressions) pattern to specifically identify and match self-closing HTML tags.
This pattern breaks down as follows:
< and >:...
Regex: select, if character is present
4 Feb, 2024
If you're looking to use regular expressions (regex) to check if a specific character is present in a string, you can use the following pattern in most programming languages: the ? quantifier makes...
PHP: Use regex to remove part of a string
4 Feb, 2024
If you want to remove certain patterns from a string in PHP using regular expressions, you can use the preg_replace function. Clone this snippet and replace "/pattern/" with the actual regular...
DateTime from timestamp in PHP
3 Feb, 2024
The PHP code snippet creates a DateTime object using a Unix timestamp. The "@" symbol before the timestamp is how DateTime is interpreting the value as a Unix timestamp rather than a regular date...
Get last item of array in JavaScript
31 Jan, 2024
This snippet explains how to get last item of an array. The example retrieves the last item of the array by determining its index through subtracting one from the array's length. This approach...
CKEditor 4: How to remove empty paragraphs
31 Jan, 2024
In CKEditor 4 when you have a combination of some elements, it's possible you get a paragraph (p tag) that you can't delete with simple backspace. It is still possible to remove it and there are 2...
Strip URL Parameters in PHP
31 Jan, 2024
There are 2 methods you can use for this. The parse_url method involves breaking down the URL into components using PHP's built-in function, allowing for selective extraction of the scheme, host, and...
Vanilla JavaScript equivalent of jQuery addClass
20 Jan, 2024
The addClass function in jQuery and the classList.add method in vanilla JavaScript both serve the purpose of adding one or more CSS classes to HTML elements. jQuery's addClass is succinct and...
Vanilla JavaScript equivalent of jQuery show/hide
20 Jan, 2024
To achieve a show/hide functionality in vanilla JavaScript equivalent to jQuery's show() and hide() functions, you can utilize CSS classes or inline styles. In the example provided, a CSS class named...
Vanilla JavaScript equivalent of jQuery selector
20 Jan, 2024
The difference between querySelectorAll in vanilla JavaScript and jQuery's selector lies in their syntax and underlying implementation. querySelectorAll is a native JavaScript method that allows for...
JavaScript: recur every minute
20 Jan, 2024
If you want to make a function or a piece of code in JavaScript execute every minute, you can use the setInterval function. The setInterval function in JavaScript is used to repeatedly execute a...
JavaScript: get group that contains item in a grouped array
15 Jan, 2024
You have an original array and another array where the elements are grouped in threes. You want to find the group in the second array that corresponds to a given element from the original array.
Split array to groups of 3 in JavaScript
15 Jan, 2024
Split array to groups of 3. For convenience there are two methods. Both variations achieve the task of splitting an array into groups of three elements in JavaScript. The first variation uses a more...
Redirect to another page with JavaScript
11 Jan, 2024
JavaScript redirection, exploring the different methods and scenarios where it can be applied. Whether you prefer a silent redirect or a documented exploration of pages, these snippets provide the...
Parse an HTML string with JavaScript
11 Jan, 2024
DOMParser API provides a more flexible way to parse HTML strings into a document object, facilitating efficient manipulation and extraction of information within a web page. After which you can use...
Get attribute value from getElementsByTagName()
11 Jan, 2024
To retrieve the value of an attribute using getElementsByTagName() in JavaScript, you first use the document.getElementsByTagName("tag") method, replacing "tag" with the HTML tag of the elements you'...
Last element of array in JavaScript
2 Jan, 2024
Accessing the last element of an array in JavaScript, as demonstrated by the code snippet, is a fundamental technique for practical programming tasks. It allows you to retrieve and utilize the latest...
PHP Replace HTML Tags in String
31 Dec, 2023
Stripping or replacing HTML tags in a string using PHP is a common practice for various reasons. For instance, it helps enhance security by removing HTML tags from user-generated content, mitigating...
PHP: How to break function?
30 Dec, 2023
In PHP, you can use the return statement to exit a function and return a value if needed. The return statement not only returns a value but also exits the function immediately.
User How to define your own custom hook_watchdog in Drupal 7
12 Dec, 2023
To define a custom hook_watchdog in Drupal 7, you'll need to create a custom module. The hook_watchdog function allows you to log messages to the watchdog database table, which is useful for...
Add a suffix to each item of a PHP array
12 Dec, 2023
Using preg_filter to add a suffix ("_suffix") to each item in the array. Use this one-liner to for good performance and easy solution. There are other solutions, but this is the preferred one.
Add a prefix to each item of a PHP array
12 Dec, 2023
Utilizes preg_filter to add the specified prefix to each item in the array. There are other methods, but this is fast and a single-liner.
Decode: Content-Transfer-Encoding: 8Bit in PHP
12 Dec, 2023
"Content-Transfer-Encoding: 8Bit" is a header used in email messages to indicate the type of encoding used for the content. If you're trying to decode a message with this encoding, you'll need to...
Render html of a view in Drupal 7
23 Nov, 2023
Programmatically rendering a view in Drupal involves a structured series of steps. Initially, the target view is loaded using the views_get_view() function, specifying its machine name and the...
Count object keys in javascript
23 Nov, 2023
In JavaScript, you can count the number of keys in an object using the Object.keys() method and then .length is used to get the number of keys in the object.
Delete view programmatically in Drupal 7
18 Nov, 2023
There is a function called views_delete_view, that does just that. The only thing is that views_delete_view() function in Drupal 7 takes a view object as its argument, not a machine name.
PHP: Get last quarter start and end timestamps
14 Nov, 2023
The code snippet use the DateTime class to calculate the start and end timestamps for the previous quarter. The calculations take into account the current month and adjust it to correctly identify...
Start and end days of week based on the first day of the week
13 Nov, 2023
This PHP code snippet provides a convenient way to determine the start and end days of the current week based on a user-specified first day. By setting the `$week_start_day` variable (0 for Sunday, 1...
JavaScript event when pressing escape key
7 Nov, 2023
Capturing the "Escape" key press with an event listener is a common practice in web development, especially for modals or dialogs. Example useful cases of using the event: It provides a better user...
Drupal 7: Add a filter programmatically to view
27 Oct, 2023
How to add a filter programmatically to a view in Drupal 7 using the hook_views_pre_view alter hook. This is useful when you want to modify the behaviour of a view by adding a filter condition...
Different theme for anonymous user in drupal 7
26 Oct, 2023
in Drupal 7, you can achieve the goal of applying a different theme to anonymous users using Role Theme Switcher module. "Role Theme Switcher" allows you to set different themes for different user...
Convert milliseconds to time (H:i:s) in PHP
24 Oct, 2023
This snippet takes a number of milliseconds and converts it into a time format displaying hours, minutes, and seconds. The result is a formatted time string in the "H:i:s" format. This way, if you...
Convert time (H:i:s) to milliseconds in PHP
24 Oct, 2023
Convert a time in the format H:i:s (hours:minutes:seconds) to milliseconds in PHP. In this code, we first split the time string into hours, minutes, and seconds using the explode function. Then, we...
Three dots add objects together (spread operator)
19 Oct, 2023
You can use the spread operator (...) to add objects or merge them together. This operator allows you to copy the properties of one object into another. The code always creates a new object. In this...
Negate a selector in CSS
19 Oct, 2023
To negate a selector in CSS, you can use the :not() pseudo-class. This allows you to select elements that do not match a specific criteria. It's mostly used with overwrites. This is widely supported...
Get body tag/element in JavaScript
7 Oct, 2023
You don't have to find the body by tag name. This code will give you a reference to the element of the current HTML document, which you can then manipulate or access as needed in your JavaScript...
React: Append to array in state
7 Oct, 2023
The spread operator (...) is a versatile tool in JavaScript that simplifies common operations like copying, merging, and adding elements to arrays and objects. It's widely used in modern JavaScript...
isset() equivalent in JavaScript
7 Oct, 2023
In JavaScript, there isn't a built-in isset() function like you might find in some other programming languages. However, you can check if a variable is defined or not by using conditional statement.
Split string with characters in PHP
30 Sep, 2023
Split string with characters in PHP. You can achieve this by taking a string $str, split it into chunks of 2 characters each with colons in between, and then remove any trailing colon from the...
Center content inside a div in CSS
7 Sep, 2023
Center content, both horizontally and vertically, inside a div. To center text both horizontally and vertically inside a div block using Flexbox and defining both width and height, you can follow...
Accessibility: When to Use role="button"
4 Sep, 2023
In HTML, you should use the role="button" attribute when you want to indicate that an element on your web page acts like a button if it's not a traditional HTML element. This is particularly...
Decode HTML Entities in PHP
25 Aug, 2023
HTML entities are special codes used to represent characters that have reserved meanings or are difficult to include directly in HTML code. These entities, like & for "&" or < for "<,"...
Rotate an image to its EXIF Orientation in PHP
19 Aug, 2023
While iPhones and many modern cameras save images with orientation information in their EXIF data, the correct display of these images can sometimes be an issue on other devices or in browsers. Being...
CKEditor 4 allowedContent link
5 Aug, 2023
The allowedContent configuration option in CKEditor is used to define what HTML elements and attributes are allowed to be used in the editor's content. This feature helps maintain consistent and safe...
Entity View Alter in Drupal 7
5 Aug, 2023
In Drupal 7, you can use the hook_entity_view_alter() function to alter the rendering of entities before they are displayed. This hook allows you to modify the display of entity content without...
Create New Custom Display Drupal 7
5 Aug, 2023
To define a new custom display for an entity in Drupal 7, you'll need to create a custom module and implement hook_entity_info_alter().
Use CSS to add chevron right
1 Aug, 2023
To add a chevron right icon using CSS, you can use a pseudo-element like ::before or ::after to create the shape and style it accordingly. Using the content property is necessary when adding an icon...
Executing a Single Value Query in Drupal 7
30 Jul, 2023
To retrieve a single value from the database in Drupal 7, you can use the db_query() function along with the appropriate SQL query and utilize the fetchField() method to obtain the desired result.
Multidimensional values as key and value pairs in PHP
6 Jul, 2023
The PHP code snippet demonstrates how to extract last names as keys and first names as values from a multidimensional array using the array_column function. The array, named $records, contains...
Converting ISO Date to Timestamp in PHP
6 Jul, 2023
Example of how to convert an ISO date to a timestamp in PHP. It introduces the strtotime() function, which is a powerful tool for parsing textual datetime descriptions. By following the step-by-step...
Convert File URI to Relative Path in Drupal 7
6 Jul, 2023
This code snippet demonstrates how to convert a file URI to a relative path in Drupal 7 using the drupal_realpath() function. By providing the file URI as input, the function returns the...
Implement relationship in hook_views_data in Drupal 7
27 Jun, 2023
In Drupal 7, you can use the hook_views_data hook to define custom tables and relationships for Views. When implementing relationships, you need to define the relationship key in your hook_views_data...
Use keydown instead of keyup to prevent scrolling with space-bar
25 Jun, 2023
To prevent scrolling with the spacebar using the keydown event instead of keyup, you can listen for the spacebar key using JavaScript and prevent the default behavior of the key if it is pressed down...
Vanilla JavaScript equivalent of jQuery :visible
25 Jun, 2023
In jQuery, the :visible selector is used to select elements that are currently visible on the web page. The code snippet checks if an element has a non-zero width, a non-zero height, or non-zero...
Vanilla JavaScript equivalent of jQuery each
14 May, 2023
In jQuery, you can use the $.each() method to loop through a collection of elements or objects. In vanilla JavaScript, you can achieve the same functionality using the forEach() method, which is...
Vanilla JavaScript equivalent of jQuery parent
14 May, 2023
To use these, you first need to get a reference to the child element whose parent you want to get. You can use a method such as getElementById(), querySelector(), or getElementsByClassName() to get a...
Vanilla JavaScript equivalent of jQuery hasClass
14 May, 2023
Both the native JavaScript and jQuery methods achieve the same result of checking whether an element has a particular class. However, the syntax and implementation are different between the two. In...
Get current focused element in JavaScript
14 May, 2023
When developing a webpage or web application, it can be useful to know which element is currently in focus. This information can be used to provide visual feedback or to perform actions based on the...
"do-while" loop in PHP
30 Apr, 2023
A "do-while" loop is a type of loop construct used in programming to execute a block of code repeatedly until a certain condition is met. The code inside the "do" block will be executed at least once...
Clearing Cache in Drupal 10
28 Apr, 2023
The snippet shows how to clear Drupal 10 cache programmatically. You can do that for all of the cache or one by one using the ID of the cache that you want to clear.
Get Full/Absolute URL in Drupal 10
27 Apr, 2023
Get the full/absolute URL of a page in Drupal 10 using the Url class. This snippet covers how to get the URL of the current page, a specific route, or an external website, and how to convert the URL...
Load a File by URI in Drupal 10
27 Apr, 2023
Load a file entity in Drupal 10 by using its Uniform Resource Identifier (URI). This snippet provides a simple code example that demonstrates how to load a file entity by URI and check if it was...
Move a Key to the End of a PHP Array
27 Apr, 2023
When working with associative arrays in PHP, there may be times when you need to reorder the elements of the array. For example, you may want to move a specific key and its value to the end of the...
Use hook menu show admin theme in Drupal 7
27 Mar, 2023
In Drupal 7, you can use the hook_menu() function to define a menu item and specify its callback function. To show a specific admin theme for a menu item, you can use the theme callback parameter in...
Differences using the + operator and the array_merge() function in PHP
27 Mar, 2023
In PHP, you can combine two or more arrays using the + operator or the array_merge() function. While both approaches combine arrays, there are some differences to consider.
Vanilla JavaScript equivalent of jQuery text
17 Feb, 2023
The Vanilla JS equivalent of jQuery's text() method would be to set the textContent property of a DOM element.
Vanilla JavaScript equivalent of jQuery css
17 Feb, 2023
In jQuery, you can set CSS properties on an element using the css() method. To achieve the same thing in vanilla JavaScript, you can use the style property of the element.
Vanilla JavaScript equivalent of jQuery attr
17 Feb, 2023
In jQuery, the attr method is used to get or set the value of an attribute for an element. In vanilla JavaScript, you can use the getAttribute and setAttribute methods to achieve the same...
Is the current page an admin page in Drupal 7
8 Feb, 2023
It's preferable to determine if the page is an admin page by checking the active theme, as it provides a comprehensive solution, rather than relying on the URL path. This approach assumes that the...
Vanilla JavaScript equivalent of jQuery click
13 Jan, 2023
In vanilla JavaScript, the equivalent of the jQuery click function would be the onclick property. The onclick property in JavaScript is an event property of HTML elements that allows you to specify a...
in_array equivalent in JavaScript
12 Jan, 2023
In JavaScript, the equivalent of the PHP function in_array() is the includes() method, which is used to check if an array contains a certain value.
Get all nodes with attribute that exists in xPath
10 Jan, 2023
Get all nodes that have a defined attribute in xPath. Explanation of commands:
"//" selects nodes in the document from the current node that match the selection no matter where they are.
"*" is a...
Copy text to clipboard in JavaScript
2 Jan, 2023
Certainly! Copying text to the clipboard in JavaScript can be accomplished using the Clipboard API. This API allows web developers to interact with the user's clipboard, allowing them to read from...
Vanilla JS equivalent of jQuery prepend
2 Jan, 2023
Insert content to the beginning of an element. Vanilla JS equivalent prepends to a single element, to prepend to multiple elements you need a loop. Same applies to append.
Vanilla JS equivalent of jQuery find
30 Dec, 2022
The Vanilla JavaScript equivalent of jQuery's .find() method is the .querySelectorAll() method. The function allows us to search through the descendants of these elements in the DOM tree and...
Redirect all subdomains to main domain using .htaccess
13 Nov, 2022
Redirect all subdomains to main domain using .htaccess. Using some sort of a mass-hosting provider, you never know what they might change in your DNS automatically. This is a backup solution to make...
Convert time to utc from timezone in PHP
11 Nov, 2022
Working with timezones can be tricky and if you do migration of data from/to somewhere. You might have to correct timezones. This snippet shows how you can change dates based on timezone difference.
Iterate through entities in Drupal 9
11 Nov, 2022
You can iterate through entities using entitiyQuery. In this simple snippet you can see that the only condition is type. So using this exact one you can iterate through entities in a certain node...
Get node url in Drupal 9 Twig
31 Oct, 2022
You need to get content url using path, to make sure all translations work and you are going into the correct absolute path. This snippet shows how to get link for nodes by id.
Paragraphs from csv in Drupal 9
27 Oct, 2022
Create and add paragraphs programmatically to nodes. After trying to use migrate and feeds. Including migration from field collection to paragraphs or ECK. The final solution for me was to do it...
Drupal 9: Redirect all traffic to https with .htaccess
23 Oct, 2022
Using .htaccess to force redirect traffic from http to https is the most simple way in Apache. If you have more access to your server, you can do it in VirtualHosts configuration. With redirecting...
Get view url in Drupal 9 Twig
12 Oct, 2022
Instead of hard-coded URL, it's better to use URL function so the other data url parameters/data won't be lost.
string to upper in Twig
12 Oct, 2022
The upper filter is used to convert a string into uppercase. This function takes a string as parameter and converts all the lowercase alphabets present in the string to uppercase. All other numeric...
useRef hook in React
27 Jul, 2022
The useRef Hook allows you to persist values between renders. First example would be to use the hook to update values without causing the component to re-render.
useEffect hook in React
26 Jul, 2022
React hook useEffect is used in functional components to implement life-cycle callbacks. The Effect Hook lets you perform side effects in function components, but some people argue that DOM events...
useState hook in React
25 Jul, 2022
useState is a hook what you use in a React function to create a state variable. This is not used if you use React class components. useState has tricks you must know about.
TypeScript: Error when loading image (png)
18 Jun, 2022
In react you can import image and use it in JSX, so that the compiler knows to load the asset. Apparently by default TypeScript doesn't support image files to be loaded. So you have to add new...
Show Logo image on AppBar in Material UI
18 Jun, 2022
Most sites or apps show a logo on the left corner of the screen. In Material ui there is AppBar component. The official examples don't have this snippet. Link to the official documentation: https://...
Install Preact
12 Jun, 2022
Installing Preact two ways shown. At first the official way did not work for me. I had to fix permissions for the global node modules, official solution. Then the alternative way worked, and after...
PHP - str_replace() all variations
14 May, 2022
Collection of all variants of str_replace function like functionality. Examples providing all kinds of solutions for your needs. From simple string replacement to regular expressions.
PHP: Zendesk api attach file to ticket
19 Apr, 2022
You can't directly add a file to a ticket, but y can upload a file and attach it to a ticket comment. The attachment appears in the ticket comment. You can only attach the uploaded file to a ticket...
PHP: OneSky api get translations
21 Dec, 2021
Example where we download via api and parse translations. In multiple language export there is only one format "I18NEXT_MULTILINGUAL_JSON". That format does cut phrase ids using "." as a separator....
PHP: Imagick rotate and merge
1 Dec, 2021
Rotate and merge image using data from css transform. In this code example the input data comes from javascript where visually image is rotated using css transform property. CSS transform and Imagick...
PHP: Imagick resize / scale image
1 Dec, 2021
Change the size of an image by resize or scale an image. The resizeImage method is an inbuilt function in PHP which is used to scale an image to the desired dimensions.
PHP: Imagick transparent background
30 Nov, 2021
In order to work with transparent images, you have to define image as transparent. Do that immediately after creating an instance, by setting the object's default background color with...
PHP: Imagick read image files from URL
24 Nov, 2021
The code example shows how to read an image from url to Imagick. Imagick doesn't take in url directly, but it has a method for reading file as binary content. So we just need to get the content form...
MQL5 for GeSHi
1 Oct, 2021
MQL5 language file for GeSHi (Generic Syntax Highlighter). I used C++ langague file to base this on, since MQL is based on C++. I don't think it's the best possible highlight and ideally would use...
Javascript: object keys and values to html table
14 Jun, 2021
Convert javascript object into html table, where keys are in the first column and values are in the second column. This uses plain javascript so you can use it anywhere.
PHP error: class 'DateTimeZone' not found
1 Mar, 2021
DateTimeZone class is built into php. If you get error that it's missing, then it's namespace problem.
go-pg: Output generated SQL
7 Sep, 2020
go-pg is PostgreSQL client and ORM for Golang. To show generated queries we have to implement some hooks. There are multiple posts about this in issues, this is an exact working example of it.
Removes last item from array in Vue
23 Jul, 2020
Removing array element from vue property caused a tricky anomaly for me. I was trying different methods delete didn't work, splice worked but always removed the last item from array. Finally I...
Explode / split string in ES6
15 Jul, 2020
How to split string in ES6. I would suggest the method of using split function from lodash. In modern JavaScript frontend you use a lot of dependencies and lodash is used in almost every project....
Validate Date in JavaScript
15 Apr, 2020
How to find out if a Date is indeed a valid Date. Simply instance check will not do it, the date might be "Invalid Date".
Setup Gin (golang) + React + Webpack
25 Mar, 2020
Simple blank "Hello, World!" setup combining Gin (golang) + React + Webpack. Create files with these codes, download dependencies and run.
PHP connect to Azure DB
11 Feb, 2020
This snippet shows you how to connect to Azure database for you to run some scripts for an example. In this example we use ODBC class not through PDO. You need to download two packages from your...
"L SEP" or "LSEP" character shows up in browser
11 Jan, 2020
This character appears mostly when you have copied code from somewhere. Some syntax highlighters are poorly made and when you copy code you get bad utf-8 symbols along with it. It doesn't show on...
React Semantic UI: Simple drag and drop file field
23 Nov, 2019
An example of a simple dropzone using Semantic UI. Is achieved by using "react-dropzone", which does not provide theming.
React: Address Search using Google Places API
23 Nov, 2019
This snippet shows you how you can use google places api in react to create address autocomplete dropdown. There are other service providers than google, but google supports business names in...
React: reset state when you click current menu router
19 Nov, 2019
Use this snippet when you have created a menu using BrowserRouter from 'react-router-dom' and you need to reset the state when you click on the current menu item (same url path as you are currently...
React file upload using FormData and fetch.
13 Nov, 2019
You can create input fields or use libraries like react-dropzone in React very easily. You still need to get the files from the form and send them to backend for saving. This snippet is the upload...
Trim Array Whitespace in PHP
23 Oct, 2019
This snippet shows you how to trim whitespaces from each array value in PHP. Expects all array values to be strings.
Append a file to FormData from file input in React ES6
8 Oct, 2019
You can use FormData to send form data using AJAX, including files. This is for you if you have to manually add files, you don't take them from a form, for some reason. This snippet is a react...
Get filename from file type input in React ES6
2 Oct, 2019
Get file name from file input and save it into state. You might need to use this when you hide your html file input and use button or some other element to trigger the click on the file input.
Get FormData using ref in React ES6
1 Oct, 2019
Get form data using ref attribute on form tag. This could be useful in some cases. The error that I was tackling before I found this solution: "Uncaught TypeError: Failed to construct 'FormData':...
Simple file field with React Semantic UI
24 Sep, 2019
Snippet of a simple file field with original Semantic UI for React. Semantic UI is still missing a file field component. Other solution would be to use react-dropzone for creating a dropzone.
Encode, decode and output JSON in PHP
11 Sep, 2019
This class provides several static functions for handling JSON data in PHP. These functions include options for encoding, decoding, and outputting JSON, and are intended to be independent of the user...
React, Semantic UI and DataTables.net
27 Aug, 2019
Working example of Semantic UI variation of "DataTables.net" on ES6 variation of React.
PHP: Check string for a specific word
6 Aug, 2019
The fastest string parsing is using existing functions, in this case you can use the strpos() which is used to find the occurrence of one string inside another one. When you need a stripos() for a...
PHP Output Buffering
24 Jul, 2019
Output buffering catches all echo-s, print-s and other output to stdOut. Then you can call a function on script shutdown to output all of the content. You can buffer output and stop scripts from...
ERROR in Entry module not found: Error: Can't resolve './src' in '/var/www/your-project'
8 Jul, 2019
When you get this error from your webpack project "ERROR in Entry module not found: Error: Can't resolve './src' in '/var/www/your-project'", you have probably used application directory different...
CodeIgniter 3: Using mssql with PHP 7 on Linux
6 Jul, 2019
Connect to mssql server in CodeIgniter 3. This will probably apply on any php version, just I had v 7.3 at this point. The setup is really easy, I even used mssql on my linux machine locally.
Set Up Laravel, PHP 7.3, Nginx, and MySQL with Docker
11 May, 2019
Another way to setup Laravel expecting that you have git and composer installed on your machine. Presented in configuration file examples for fastest reading/setup.
Subtract time in Python
3 Apr, 2019
Examples of time subtraction in Python. Using the best date-time library called Pendulum. You can use add or subtract to alter time.
Show all errors for development in PHP
26 Mar, 2019
Usually in default errors are disabled for production. Sometimes you have error 500 for an example and you need to see the error message. For an example in Drupal 7 you can put this in settings.php...
Create and Post HTML Form using Javascript
20 Mar, 2019
This snippet creates html form and submits it, the same way as browser submits form "with redirect". If you need the redirect not an ajax solution, for example credit card payment.
HMAC SHA1 in Python 2
11 Mar, 2019
HMAC (a keyed-hash message authentication code) is used to verify API request. HMAC is constructed by concatenating form parameter key and value pairs into a string ordered by alphabetic order of the...
Enable HTTP/2 in Apache Web Server
28 Feb, 2019
HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent exchanges on the same connection...
PHP: Send json with post request
26 Nov, 2018
Instead of curl I like to use http request function from a long and stable framework
PHP: http request function, alternative to curl or file_get_contents. Because I find curl to be tedious. Using...
Convert to Integer in JavaScript
8 Nov, 2018
There are multiple ways to convert values to integer in javascript. Using Math.trunc gives the most accurate results.
Magento 2: Module is not listing
18 Oct, 2018
When you copy a custom module to app/code directory. Magento does not pick it up automatically. You need to run this.
React ES6: Styled Components
6 Oct, 2018
Styled components are the best way to give some visual aid to your components. The heavy lifting should be done by a library, it can be either material design, bootstrap, semantic, etc... To adjust...
Number to words in PHP
24 Jul, 2018
Helper function for converting numbers to words. There is same function available in PHPs NumberFormatter class, but using it is not always possible, since it's not enabled by default.
Tables content to exclude on DB export in Drupal 7
24 Jul, 2018
Exclude content from these tables, to get clean db backup(backup_migrate module usage). You can even use git to store your database, when you don't export cache tables.
Migrate Field Collection in Drupal 7
25 Jun, 2018
You can use migrate to import field collections. It has full support. You just need to define the host entity, where you have defined the field collection.
Load a file by uri in Drupal 7
16 May, 2018
This snippet shows you how to load a file by uri. Basically this option is available with file_load_mulitple only.
Field group alter to add html in Drupal 7
4 May, 2018
Field group lets you do some amazing forms. Still when you have empty element or the form just is too long and needs some custom modifications, you can then use prefix and suffix from form api to...
Delete all terms from all vocabularies in Drupal 7
26 Mar, 2018
Delete all taxonomy terms from all vocabularies in Drupal 7. This is ran by Drush, but you can run it from wherever Drupal is initialised.
PHP: http request function, alternative to curl or file_get_contents
12 Mar, 2018
Handles any HTTP request correctly. This is a flexible and powerful HTTP client implementation of GET, POST, PUT or any other HTTP requests. The reason I built this was due to use of url arguments...
Drupal 7 commerce add product variation types programmatically
12 Mar, 2018
Example for how to create product variation types programmatically.
jQuery form submit error detection
20 Dec, 2017
Snippet shows you how to catch errors like 404 when you submit form using jQuery.
PHP: First x characters of a string
2 Nov, 2017
Get first n amount of characters from a string. You could use substr for that, but you will get empty results when there are special characters. Thus multibyte string method is the right way to go.
PHP: Instagram to RSS feed
2 Aug, 2017
Instagram gives out json feed. You can use this little php snippet to create rss feed from the given json. The script leverages paging, which enables you to control the items count in the output feed...
React: Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`
25 Jul, 2017
Testing React components with Jest I got an error: "Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.". I am using Link from react-...
Webpack: Remove comments from compressed css
1 Jun, 2017
You can minify css with optimize-css-assets-webpack-plugin, but by default some comments are left untouched. If you want to remove all comments you have to use an option for the cssnano, that is used...
Javascript: move item to end of array (of objects), by property value
29 May, 2017
The snippet shows how to move item to the end of array. In a case where we have an array of objects and we want to move the array item by property value. In this example I am using lodash/underscore...
PHP: Encode Url for Curl
23 May, 2017
This snippet encodes urls for curl. If you use special letters like äõöü in url, then you get a bit different url parsing from browsers than curl in PHP. You would think that you could use php's own...
401 Unauthorized Error with https redirection
22 May, 2017
Got an unauthorized error from htaccess passwords after https redirection implementation. This was an unexpected result, but I guess what happens is that you are redirected to access denied page...
PHP: Fix url query parameters starting with "&" instead of "?"
19 May, 2017
Snippet shows you how to fix url query parameters starting with "&" instead of "?". This can be useful when you have to use "parse_url" function. It cannot detect query parameters when they start...
WordPress: force https using .htaccess
19 May, 2017
Since Google says https gives websites a small ranking benefit and Let's Encrypt gives free certs, more and more sites have been converted. This is a more thurral snippet of https redirection. It has...
JavaScript ES6: Clone Object or Array
13 May, 2017
Whether you're using vanilla JavaScript or popular frameworks like React, the ability to create deep copies of objects proves invaluable. Take control of your data structures, sidestepping unintended...
React: Wait for full render in snapshot testing
5 May, 2017
If you use full render not shallow in your tests, your tests might be rendered before the actual component and its subcomponents are fully loaded. In that case you need to delay the output, while...
Highcharts: full width lines
19 Apr, 2017
Highcharts has paddings and spacings that will make the area charts line appear inside of the chart element. To get full width line you need to disable some spacings and lines. You have to disable...
Highcharts: Hide highcharts.com link from footer
23 Mar, 2017
Highcharts comes with a credits link by default. This snippet shows how to hide the link using the configurations.
Highcharts: display no data message on top of the grid
22 Mar, 2017
No data is actually a module that needs to be loaded separately from the highcharts library. For some reason highcharts no data message is displayed below the grid. There is an easy fix of enabling...
Highcharts: Create a vertical line on highlighted value
21 Mar, 2017
You can create a vertical line on highlighted value in Highcharts. This might give a better visual when you have multiple lines. You could also use "shared: true" option in your tooltip to display...
webpack: Minify CSS in production
14 Mar, 2017
You can achieve this by adding a library that supports css minify to "webpack.config.js". In this snippet I use "optimize-css-assets-webpack-plugin" which uses cssnano for minimizing by default. The...
Python 2: Save directory to Amazon S3 using boto
27 Feb, 2017
You can save files to Amazon with Python using library called boto. Boto is a Python interface to Amazon Web Services and we need just a tiny part of it. If you have very large files you have to...
SQLAlchemy custom column names for queries
20 Feb, 2017
To get custom columns from a query you can use the with_entities() method to restrict which columns you'd like to return in the result. Use label() method to give AS value to your query. To use...
Python write to tmp directory
10 Feb, 2017
Snippet shows you how to write to temporary directory. You can either write a single file, or do stuff in a directory. In any case you should remove the files and folders after you have done your...
Python: Get timestamp in seconds
27 Jan, 2017
Get timestamp in seconds as integer in Python using the time library.
PHP: Check url for valid response code 200
9 Jan, 2017
Check the HTTP Status Code of the website header using PHP. Check that url is giving valid response code of 2xx. You can modify this for different purposes. For detecting 404 not found only or...
Soap request with NTLM authentication
6 Dec, 2016
NTLM authentication is often used for SOAP requests, especially when connecting to Microsoft services. The PHP SoapClient does not support NTLM out of the box, so you will need to use a third-party...
PHP: Download large file from url without loading it to memory
5 Dec, 2016
This snippet shows you how to download a file from url without loading it to memory. When you use file_get_contents() and file_set_contents() you load the content to memory and then to file. The...
Filename from path in PHP
22 Nov, 2016
Snippet shows you how to get filename from a path in PHP. Filename and extension separately. Can be used for extending filenames with timestamp or anything.
Select a random file from directory in PHP
22 Nov, 2016
Select a random file from directory. This can be useful if you want to display a random image on your website. For an example a background image randomly from a directory in your files.
Delete object key and value in javascript
12 Oct, 2016
Deleting object value with key in javascript. For this you can use the delete operator. Permits you to remove a property from an object.
Get body tag using PHP Dom Document
22 Sep, 2016
To use a DOMDocument and get the contents of the body in PHP, you can use the DOMDocument class, which provides a way to parse and manipulate XML and HTML documents. Here is an example of how to use...
Validate AJAX requests in Zend 1
26 Aug, 2016
How to validate AJAX requests in Zend Framework. There is a function in request class, to use instead of comparing the $_SERVER['HTTP_X_REQUESTED_WITH'] directly. This can be beneficial for security...
Radio Buttons in MDL (Material Design Lite)
19 Jul, 2016
Material Design includes beautification of radio buttons as well. These need javascript, if you use ajax to load you content, you need to call for dom update.
Text Input in MDL (Material Design Lite)
8 Jul, 2016
There are multiple ways to display text input field. You can use lable or not, you can do some validation with regular expression. Also you can show pretty inline form errors. For more information go...
File Upload in MDL (Material Design Lite)
1 Jul, 2016
Since there is no File Upload form functionality in MDL, we need to create some css, html and js. I have tried to make it as simple as possible.
Checkbox in MDL (Material Design Lite)
29 Jun, 2016
This snippet shows how to convert checkbox type inputs to MDL (Material Design Lite). There are separate classes for checkboxes in Material Design.
jQuery: Using selectionStart, selectionEnd, setSelectionRange
21 Jun, 2016
Using selectionStart, selectionEnd, setSelectionRange in jQuery example. You can't use DOM commands on jQuery objects directly, you have to get the first value of the object.
Hide drawer menu on large screens in MLD (Material Design Lite)
17 Jun, 2016
To hide drawer menu on large screens in MLD you have to add a class "mdl-layout--no-desktop-drawer-button" to the layout since the drawer icon is automatically rendered.
Select tag in MDL (Material Design Lite)
17 Jun, 2016
This snippet shows how to convert select tag to MDL (Material Design Lite). To achieve this you have to use text fields classes.
Python: convert po to mo
19 May, 2016
This snippet shows you how to convert po files to mo files. Po is the raw plain-text translation file with key value storage format. Mo files are compiled po files, binary format allows you to read...
Directo class
17 May, 2016
Class for fetching and sending data between http://www.directo.ee/ API. This class includes pulling data from Directo and posting xml with php array to xml generation.
Python: Read and decode json file
11 May, 2016
Read and decode json file in Python. You can use the same method for regular json strings.
Python: Pretty Print Array
11 May, 2016
Pretty print array, meaning that you print array, dictionary, object or any non string format in human-friendly way. This is great for terminal / command line. When you are looking for something for...
PHP: Trim Array
5 May, 2016
This snippet shows you how to trim an array with single line of code. This can be achieved by using "array_map".
jQuery: Input - focus and select all
18 Apr, 2016
How to focus and select all using javascript. This snippet shows it in an example of "jQuery: Toggle input text using checkbox". For an example you can extend this to any event or action where you...
jQuery: Toggle input text using checkbox
18 Apr, 2016
Snippet shows how to toggle input text using checkbox. Sometimes you need to show text field only when a checkbox is checked, that can be called conditional text field. So you need a checkbox and a...
jQuery: Run something after $.each has completed
12 Apr, 2016
JavaScript runs asynchronously, that means when you initialize $.each every bit of code that comes after that will not be executed when $.each has finished. Sometimes you need your code to be...
Minify JavaScript from command line
8 Mar, 2016
This snippet shows how to minify javascript files from command line. Minifying JavaScript is useful in many respects. Most important are security and performance. Security is increased due to the...
Get previous / next element using JavaScript
8 Mar, 2016
This snippet shows how to get element next to your element / selector. This a part of dom traversal. Using javascript for next element parsing can be used to create some powerful dynamic content. I...
Drupal 7: Wrapping group by content in Views
24 Feb, 2016
You can use "group by" in views to group data by a field. When you start writing css for it, or even use accordion. You need to wrap the rows into a container. This can be achieved by creating a...
SimplePie Error: timed out after 10001 milliseconds
8 Feb, 2016
SimplePie is set to 10 seconds timeout in default. So if the feed has problem with speed then you can increase the time. The exact error that I got was "cURL error 28: Operation timed out after 10001...
Python: Get Current Time with Timezone
3 Feb, 2016
Get current time with timezone in Python. This can be achieved using a library named arrow. It's a datetime library for correct and easy calculations using only one library.
Python generate HMAC-SHA-256 from string
2 Feb, 2016
Generating HMAC (Hash-based Message Authentication Code) involves the use of a "private" key, which is a secret key known only to the sender and the receiver. This key is used to create a digital...
SQLAlchemy: Add Column Collation to Column Creation
1 Feb, 2016
Add column collation to column creation in SQLAlchemy. Optional, a column-level collation for use in DDL and CAST expressions. Renders using the COLLATE keyword supported by SQLite, MySQL, and...
Running Django on Apache and MySQL
30 Jan, 2016
If you plan to use Python for your web backend then you might want to consider Django as there are many good libraries that you need for web development.
SQLAlchemy: Create Table Column using Decimal and Tinyint
29 Jan, 2016
Using SQLAlchemy to create table columns. To use numeric data types you have to use mysql dialects.
PHP: Days since today or days between two dates
13 Jan, 2016
How to find out the amount of between two dates. For an example how many days have passed since a defined date.
Get every other member of array in PHP
11 Jan, 2016
Using a loop to check the index of the element in the array is even or odd to get every other element. Examples of getting even or odd members of an array, using foreach loop and "modulo operation"....
Enable Phar in PHP 7
10 Jan, 2016
Phar is included in PHP 7 amongst other updates. It's no longer external module. You have to turn off the "readonly" parameter. Since it disables Phar write support by default.
Cache json from curl request in PHP
5 Jan, 2016
When you create a simple request without any special REST client, you can do it just by using curl. When you need to do curl request, it's not a good practise to do it on every page load. So the...
Explode multiple delimiters PHP
4 Jan, 2016
To explode multiple delimiters PHP you have to use regular expression. Add your delimiters in the parentheses separated by pipe. You might have to escape your characters if they have meaning in PCRE...
PHP: Detect delimiter of CSV file
9 Dec, 2015
Using PHP to read csv file is a common thing to do. Sadly there is no solid standard on delimiters, depends on fully from where you get your csv file. Usually simple csv exports are a bit different...
Change line item price programmatically in Drupal 7
29 Nov, 2015
Changing line item price is not as easy as you could think. It can seem that the price has changed, but there are multiple places where you have to actually change it. Especially when you compute the...
AddThis: Popup instead of hover box
25 Nov, 2015
AddThis is an awesome social sharing tool. It is fully customizable. I suggest using addthis module for loading add this library, this has performance options for the javascript loading.
Check if current user has node edit permission in Drupal 7
19 Nov, 2015
Just a snippet that shows how to check if current user has edit permissions for some node in Drupal 7. Using node_access function like in the example you are also able to check permissions for...
Add .tpl.php files to your module in Drupal 7
9 Nov, 2015
This nifty little snippet will scan your module for tpl.php files. Include template files from your module. Override default template in custom module. I usually have a single module where I keep my...
Running Python on Apache
8 Nov, 2015
Using Python in the web. Setup Apache the way that you can run Python backend on it.
Check if Python module is installed on your system
7 Nov, 2015
Check if a python module is installed or not on the system. The simplest way to do it is in terminal.
Select next as well in PhpStorm
6 Oct, 2015
Select next, is a functionality well needed in everyday programming. For an example, if you have a function that defines a variable and the variable is used multiple times. You would like to select...
PHP: Replace all whitespaces with a single space
8 Sep, 2015
You can replace all whitespaces (space, new lines, etc.) with a single space using regular expression find and replace.
Set PhpStorm to always show line numbers
4 Sep, 2015
PhpStorm by default does not display line numbers. Working with version control or when debugging stuff, you usually get line number of the code where the error appears. So it would make sense that...
Uninstall modules programmatically in Drupal 7
13 Jul, 2015
Snippet shows how to uninstall modules programmatically. This is not deleting the files, but doing a full uninstall.
Get cursor position in CKEditor
12 Jun, 2015
Get cursor position in CKEditor is simple if you know some facts. You have to have the instance initiated, so simple jQuery ready would not work. You can get selection and use that functionality to...
My perfect web server configuration on localhost
17 May, 2015
Apache default configuration can be a bit slow in case of today's standard web applications. Especially on local environment where you develop your application, class, framework or plain old PHP from...
Get GET parameters in Drupal 7
23 Mar, 2015
Getting URL query parameters array where unwanted elements are removed. For that you can use drupal_get_query_parameters function. In default q parameter will be removed. That parameter includes...
PHP: Get values by key in multidimensional array
5 Mar, 2015
How to get values by key name in multidimensional array. You have to iterate it recursively. This is the first time I can use Iterator classes of PHP and I already can think multiple problems this...
Post data to external url in Drupal 7
4 Mar, 2015
Sending data using POST to external url should be done by using drupal_http_request.
PHP: Memory management
22 Feb, 2015
If you are using larger files like bigger data files or images, memory might become an issue. Even if not, it's always good practice to use optimal amount of memory. Clearing memory is just a part of...
Edit field output before it is rendered in Drupal 7 using hook
18 Feb, 2015
Edit field output after the field module has performed the operation. This gives you possibility to alter the field output before rendered in your module. This works with display suite and other...
Create htpasswd file from command line in Linux
17 Feb, 2015
Create or generate .htpasswd file from command line in Linux. The file is used for password protected websites in Apache. The easiest way to create one is to generate it from terminal.
Drupal 7 - file_save entity wrapper file uri
10 Feb, 2015
Since this snippet includes a lot of information the title is simply a bunch of keywords. Basically we are using file uri to determine if it exists and is managed or needs to be saved as new managed...
Get values / Rendering of fields in Drupal 7
5 Feb, 2015
The idea would be that you don't take any values directly from node_load result. You can either use entity wrapper(is not a part of this tutorial) or field get and view functions.
Entity metadata wrapper (entity_metadata_wrapper) in Drupal 7
3 Feb, 2015
Entity API provides wrapper classes that make dealing with the values of an entity's properties and fields easier. This post is to make the information easy to learn by examples.
Uncaught TypeError: Cannot read property 'msie' of undefined
29 Jan, 2015
I had an error in "jquery.ui.mouse.min.js" when using jQuery 1.9 (or newer) with jQuery UI 1.8 (or older). This jquery plugin is used to restore deprecated functionalities in jQuery and removed as of...
Apache: *.localhost vhosts wildcard subdomains
5 Dec, 2014
This "tutorial" is how I created wildcard subdomains in my localhost. So I get domains like "http://bt.localhost". This bit is from my http.conf or apache.conf depending on your system. There also...
Php pcre regex or operator tutorial
2 Nov, 2014
PCRE regular expression operator OR. In regular expressions "or" is known as "alternatives". Create a subgroup using parenthesis.
PHP - Replace using regex
29 Oct, 2014
Search and replace using regular expression in PHP using preg_replace function. It is very powerful way to search and replace. I suggest using some online regular expression tool to test out your...
Embed PDF in HTML
24 Oct, 2014
In general we are going to embed pdf in html. For this tutorial I am going to use PDF.js. It is a web platform for parsing and rendering PDF files. Canvas support is one of the main things that is...
Load menu item first child in Drupal 7
24 Oct, 2014
This is how you can load menu items children. Also the example / snippet is about how you can get the first child, but the menu has to be in a single language tough. It takes access and being hidden...
Get a single query result as string in Drupal 7
30 Sep, 2014
This snippet shows you how to get a single query result as string in Drupal 7, using select from database abstraction layer.
Install phpMyAdmin for Apache (on Arch Linux)
23 Sep, 2014
Install phpMyAdmin for Apache on Arch Linux so that it would open under "pma.localhost". This works on other distributions as well just use your specific package manager to download the packages and...
Get node menu item (mlid) by node id (nid) in Drupal 7
25 Aug, 2014
There are many functions for menus, but since Drupal is not hierarchical but is modular, that's why menu doesn't have node requirement and the opposite way around. So this snippet shows how to get...
Compress web using gzip / mod_deflate
5 Aug, 2014
Compress site using mod_deflate to reduce bandwidth and loading time, also Google Speed suggests it. List of compressible mime-types to compress. You should not compress mime types that compress...
Install web server (Apache, PHP, MariaDB) on Arch Linux
23 Jun, 2014
This tutorial shows how to set up Apache, PHP and MariaDB (drop-in replacement for MySQL). You can use pacman instead of yaourt on installing the server, since yaourt doesn't come with Arch in...
PHP array of iso country list
28 May, 2014
PHP array of iso country list. This list includes Kosovo (KV) and Democratic People's Republic of Korea (KP). That I found hard to find from somewhere else.
Validate UTF-8 strings in PHP
7 May, 2014
This function checks whether a string is valid UTF-8. You can ensure that the string you operate is a valid UTF-8 string. preg_match fails on strings containing invalid UTF-8 byte sequences. It does...
Create contextual links in Drupal 7
1 May, 2014
This snippet shows you how to create contextual links in Drupal 7. If you don't know what contextual links are then those are the links in front end that come up from the ratchet.
Install Drupal using Drush
29 Apr, 2014
How to install any version of Drupal using Drush the Drupal Shell. You can replace the version name with the version you like. Also feel free to replace words in caps to get an installation that you...
Protect site with password using htaccess
28 Apr, 2014
Protect site with password using htaccess. The htpasswd file is just a text file that includes usernames and password hashes. You can generate those by using online tools for generating htaccess...
Rebuild menu in Drupal 7
24 Mar, 2014
Sometimes menu gets messed up and all the new links go on the admin menus first level. Or you have other reasons to rebuild menu. You also need devel module to do this.
Create custom pane programmatically for Panels in Drupal 7
24 Mar, 2014
This shows code examples of what I had to do to create custom pane programmatically for Panels in Drupal 7. In this example I create new pane where you can pick your node and display it.
Use Drupal to run queries on other databases.
14 Mar, 2014
First you need to add the connection information of the other database. This way you can use drupal database abstraction layer for altering any database.
Group views by first letter in Drupal
10 Mar, 2014
This tutorial describes how you can group the results of a view by first letter of their title. This might not suit for you in two cases, first if you need to order them by ascii not utf-8, secondly...
Migrate image from URL in Drupal 7
7 Mar, 2014
There is a module called migrate that enables you to migrate content to Drupal. This snippet shows you how to migrate image from URL to Drupal 7. You have to get file name from the importing source...
Alter node breadcrumbs by hook form your module in Drupal 7
26 Feb, 2014
I had a problem with path breadcrumbs where I couldn't get taxonomy therms through commerce product reference. So I had to disable the path breadcrumb for the node and do it manually. I didn't want...
Views header, footer, before and after using hook_views_pre_render() in Drupal 7
21 Feb, 2014
Add content to view header, footer, before or after using hook_views_pre_render() in Drupal 7. Using hook_views_pre_render gives you the opportunity to use values from executed views query.
Change field instance programmatically in Drupal7
20 Feb, 2014
Change or update field instance programmatically in Drupal 7. For more information check out Field CRUD API in drupal.org.
Check if variable is a jQuery object
2 Jan, 2014
Checking that variable is a jQuery object. We are going to use instanceof and it returns true if the statement is true.
Use hook_page_build() instead of hook_init() to add CSS or JS to every page.
2 Jan, 2014
Use hook_page_build() instead of hook_init() to add CSS or JS to every page. The reason is that hook_init() runs on every request that goes to Drupal (AJAX requests, private file requests, boost /...
Convert text or HTML to plain-text in PHP
25 Nov, 2013
Encodes special characters in a plain-text string for display as HTML. Validates strings as UTF-8, if not UTF-8 it returns an empty string. It prevents CSS attacks on IE 6.
Install web server (Apache, PHP, MariaDB) on Linux Debian Wheezy
20 Nov, 2013
This tutorial shows how to prepare a Debian Wheezy web server. This is just a simple setup of basic web server. I myself did it to set up a development environment for myself.
Change date format for better exposed filters in Drupal 7
15 Nov, 2013
This snippet shows you how to change date format for better exposed filters in Drupal 7. I was not able to use strtotime with the default setting.
Install module programmatically in Drupal 7
14 Nov, 2013
Installing module programmatically in Drupal 7 can be achieved with just one step, using module_enable function.
Check if text contains cyrillic characters in PHP
5 Nov, 2013
Check if text contains cyrillic characters in PHP. This example shows you how to do exactly that.
Converts URLs in text into links in Drupal 7
5 Nov, 2013
Converts URLs in text into links in Drupal 7 automatically. Three types of "links" get converted. URLs like http://example.com, e-mail addresses like name@example.com and urls without the "http://"...
jQuery Catch Form Submit
29 Oct, 2013
Form submitting is really simple with jQuery. You can use submit function to submit form or catch a form submission and do something else.
Get taxonomy vid by machine name Drupal 7
7 Oct, 2013
This snippet shows how to get taxonomy vocabulary id (vid) by machine name of taxonomy vocabulary Drupal 7.
Using image_scale_and_crop in Drupal 7
3 Oct, 2013
This snippet shows you an example of using image_scale_and_crop function to scale and crop image as in image styles.
Get words in string as array in PHP
16 Sep, 2013
How to split words in string to an array using regular expressions. You can use this for search indexing for an example.
Useful hooks and functions in Drupal 7
2 Sep, 2013
List of useful hooks and functions in Drupal 7. You can find here something new or just bookmark it for your reference.
Change or add file icons to Drupal 7
21 Aug, 2013
Change or add file icons to Drupal 7. First you have to define your mime type of a file, if it isn't done already. Then add icon URL to that mime type (16x16).
Alter URL GET parameters using JavaScript
14 Aug, 2013
This function alters url get parameters using javascript. The function takes to consideration all aspects of url (parameter existis, hash, parameter doesn't exist). For an example if you need to be...
How to create time field in Drupal 7
8 Aug, 2013
This example shows you how to create time field using date module and Field API in Drupal.
Read or parse feeds with PHP
7 Aug, 2013
This tutorial shows how to parse RSS feeds with PHP. From the libraries and methods that I have tested and used SimplePie is by far the best PHP RSS parser. It supports most common RSS modules out of...
Convert file size in bytes to nice (human-readable) format in PHP.
6 Aug, 2013
This snippet shows you how to convert file size in bytes to nice (human-readable) format in PHP. If the size is less than 1 MB, show the size in KB, if it's between 1 MB - 1 GB show it in MB, etc.
Alter filter in views exposed filters using form_alter in Drupal 7
30 Jul, 2013
This example shows how to alter filter in views exposed filters using form_alter in Drupal 7.
Get img tag image url from html using regex in PHP
25 Jul, 2013
Snippet about getting img tag image url from html using regex in PHP. Example below.
Customize Views RSS Feed Title in Drupal
14 Jul, 2013
This snippet shows you how to customize views RSS feed title in Drupal. This example shows you how to create title for taxonomy feed, so that the title would be the term with it's parents.
Use colorbox programmatically in Drupal
12 Jul, 2013
How to use colorbox module programmatically. Colorbox module provides with loading inline content, explained here: https://drupal.org/node/1971564. Since that didn't work for me, I tok a different...
Exclude current node from view
12 Jul, 2013
This tutorial shows you how to exclude current node from view. For an example, if you need a block that shows related content by taxonomy then you want to exclude current node from the list.
Create lists using theme through render in Drupal 7
7 Jun, 2013
This snippets shows you how to create lists the right way using theme_item_list.
Add body class programmatically from your module in Drupal 7
28 May, 2013
This simple snippet shows you how to add body class programmatically from your module in Drupal 7.
Creating views programmatically in Drupal 7
20 May, 2013
Creating views view in your module is really simple.
Convert time to other time zone in PHP
7 May, 2013
Convert time and date from one time zone to another in PHP. Don't ever manage time adding or subtracting seconds, there is more to datetime than meets the eye.
Remove HTML elements using DOMDocument in PHP
19 Apr, 2013
This snippet shows how to remove HTML elements using DOMDocument in PHP. The problem is that you can't do it in the same loop.
Using DOMDocument to parse HTML in PHP
15 Apr, 2013
This snippet is about parsing HTML with PHP. It's hard to parse HTML, because people write incorrect HTML syntax very often. This code forces DOMDocument to read and later write HTML. So your changes...
Form API - Skip form validation for button in Drupal 7
5 Apr, 2013
Sometimes you have to make button that skips form field validations. For an example Cancel button. This snippets shows how to skip form validation for button. Works in Drupal 7.
Translate taxonomy terms in Drupal 7
3 Apr, 2013
How to translate localized taxonomy terms in Drupal 7.
jQuery - Check if selector is disabled
7 Mar, 2013
You can use "is" to see if the form element is disabled.
Change page title programmatically in Drupal 7
19 Feb, 2013
How to override page title in your theme, after all modules have done their jobs.
Message before leaving the page - JavaScript / jQuery
8 Feb, 2013
How to display message before closing the page or moving to another page. Don't use this to annoy people. Sometimes this functionality is still useful, for an example if you have some sort of unsaved...
Remove form elements in Drupal
8 Feb, 2013
This snippet shows how to remove form elements in Drupal. I am using hook_form_alter and access parameter from form api.
jQuery - Animate .prepend
2 Feb, 2013
Rather than simply dumping the HTML into the page you might want it to be animated. You can .hide() the content before doing a .prependTo(), then call .slideDown() on the element.
Drupal - Change page titles in template.php
27 Jan, 2013
Changing page titles in your theme. There is also hook_page_title_alter hook. If for some reason you still want to do it your theme, then this is how.
Views query alter - use select in where clause
23 Jan, 2013
How to use select query as where clause in Drupal views module query alter. You can't use hook_views_query_alter, because it places single quotes around the value. So you can't use query instead of...
Localize taxonomy term in Drupal 7
1 Dec, 2012
This snippet shows you how to Localize taxonomy term in Drupal 7.
Remove width and height form img tag using PHP
29 Nov, 2012
Remove width and height attributes from img tag using PHP. Really plain and simple replace width and height attributes with nothing.
Change Drupal calendar events color.
28 Nov, 2012
You can only change event colors by content type or taxonomy terms in Calendar view. More advanced coloring requires some programming.
Convert plain text URLs into links in Drupal
23 Nov, 2012
How to turn plain text URLs into active links in Drupal.
Get URL variables with JavaScript
21 Nov, 2012
This function gets URL variables in JavaScript. Current page url parameters will be parsed into array, that will be returned.
Monochrome Google Maps
19 Nov, 2012
This example shows how to create monocrome Google Maps. Where the map will be using only shades of grey (with or without black and/or white). It might also be called grayscale or black-and-white.
Using jQuery Datepicker in Drupal
25 Oct, 2012
This snippet shows how to use jQuery datepicker in Drupal. Drupal already includes jQuery and jQuery UI in its core. So you just have to make sure it's loaded and then you can use it in your scripts.
PHP range where key and value is same
2 Oct, 2012
Creating range array where key and the value is the same number. I am using array_combine function for that. I give two parameters which are the same array created by range.
Draw Rectangle in HTML5 Canvas Tag
23 Sep, 2012
Drawing a rectangle in canvas tag with rectangle functions.
Field API email field in Drupal
30 Aug, 2012
Creating email field. The field is still textfield, you just have to make validation for the field.
Create your own template files ( tpl.php ) in Drupal 7
23 Aug, 2012
Creating your own template files that you can use in your modules in Drupal 7. Template files are for separating HTML from PHP. This tutorial shows you how to create and use tpl.php files. Template...
Programmatically create menu link language relation in Drupal 7
22 Aug, 2012
Programmatically create menu link language relation in Drupal 7. This example takes a certain taxonomy vocabulary by id and creates language relations to menu links by terms relations. You might need...
Get Years of nodes in Drupal 7
21 Aug, 2012
This query gets node created dates and selects all years of nodes that has been made. Also there are filters: node.status equals 1 is published filter, node.type is content type filter and node...
Make sure your cron runs daily in Drupal
14 Aug, 2012
How to make sure your cron task runs once per day in Drupal? You can set crontab once per day, but you still might want to run cron manually every now and then. Also you might have to change the cron...
PHP - strip defined tags, strip_tags reverse
9 Aug, 2012
Strip tags in PHP strips all tags, except allowed tags. This function strips tags that you define. Also you can define if you want to strip content as well.
Strip tag with class, id or anything else in PHP
23 Jul, 2012
This function strips tags by any identifier without regexp, and without heavy XML parsing. As long as the tag looks exactly the same in source-code it works.
Create table using theme table in Drupal
12 Jul, 2012
Create table using theme table in Drupal. This is the simplest example of creating table. In the code I added link to the documentation. You can do things like add classes, caption, colgroups etc.
Show Drupal 404 page programmatically.
25 Jun, 2012
Show Drupal 404 page programmatically. Just return this function from your page function.
Get MSSQL Field Data Type in PHP
29 May, 2012
Example how to get field types in MSSQL. You can use it on any query, even procedures.
Get date on mouseover from cell in jQuery UI datepicker
14 May, 2012
This snippet shows you how to get date on mouseover from cell in jQuery UI datepicker.
Add node to nodequeue in Drupal 5-7
2 May, 2012
How to add node to nodequeue using a little code. You can make it automatic using Rules and PHP filter module(in core that adds option to add PHP code to textarea).
Translate block title in Drupal 7
2 May, 2012
Translate block title in Drupal 7 using this theme hook.
Detect character encoding in PHP
26 Apr, 2012
Detect character encoding in PHP and convert string to UTF-8.
SQL query examples in Drupal 7
20 Apr, 2012
Drupal SQL query examples, includes regular query and select, insert, update and insert or update using abstraction layer. Explanations of different data return types like fetchAssoc, fetchAll and...
Page title for taxonomy term pages in Drupal
6 Apr, 2012
How to fix page titles for taxonomy term pages. It creates title from term hierarchy. You have to remove the views title override.
Get or load taxonomy term(s) in Drupal 7
6 Apr, 2012
Load taxonomy term object by name or tid. Also how to get term parents from top to bottom.
Get current URL using jQuery
5 Apr, 2012
This shows you how to get the path of the current URL and assign it to a variable. This is achieved by taking url from location object. The location object also has other properties, like host, hash...
Term name in right language in Drupal using i18n
13 Mar, 2012
How to get term name in right language in Drupal? Internationalization (i18n) module is used for localization.
Drupal 7 multi-site on localhost (XAMPP or Windows example)
3 Mar, 2012
How I set up my multi-site in localhost so that my different sites would be in different sub-folders. I did it on my windows machine.
Get all MSSQL tables using PHP
17 Feb, 2012
How to get all tables names that are in a certain table.
Remove language links from node links in Drupal 7
9 Feb, 2012
How to remove language links from node links in Drupal 7
Change file name after saving in Drupal 7
26 Jan, 2012
How to change file name programmatically after file is saved in Drupal 7.
Filter feeds log by Importer in Drupal 7
23 Jan, 2012
First you need to create a filter to your views. Add "Feeds log: Importer id" filter to All entries display / tab. Then this code snippet alters the form so there won't be textfield, but selection.
Remove views view filter programmatically in Drupal
16 Jan, 2012
How to remove views view filter programmatically in Drupal.
Language select field in Drupal 7
19 Dec, 2011
This code snippet is about creating languages form field in Drupal 7 using field api.
Get MySQL column types in PHP
14 Dec, 2011
How to get MySQL columns data of a table in PHP. The data includes name, type, null allowed or not, key, default value and extra for auto_increase and such.
Add field to entity programmatically in Drupal 7
13 Dec, 2011
How you can add field to an entity programmatically in Drupal 7.
Add body classes in Drupal 7
8 Dec, 2011
Adding body classes in Drupal 7. Just a little code snippet that can be useful in some cases.
Checkboxes as radio buttons using jQuery
4 Dec, 2011
Make a group of checkboxes behave like radiobuttons.
Display Entity Construction Kit (ECK) form programmatically
29 Nov, 2011
How to display eck form anywhere you wish, just few lines of PHP can make you a big head ache.
Redirect based on country in Drupal 7
15 Nov, 2011
Redirect users to their main language first visit. I needed it only on the front page, but you can simply remove the if statement if you need the functionality on every page. The language detection...
Create ajax forms in Drupal 7
23 Oct, 2011
How to create forms that are submitted via ajax. To understand this tutorial you have to have a basic knowledge of Drupal programming and its form api.
Check if URL is external or internal in PHP
11 Oct, 2011
Check if URL is external or internal in PHP. We are going to use parse_url PHP native function. Function parse_url parses a URL and returns an associative array containing any of the various...
How to redirect everything to index.php
8 Oct, 2011
How to redirect everything to certain page like index.php or root.
Round numbers in JavaScript
1 Oct, 2011
This snippet shows you how to round a number to a specified number of decimal places in JavaScript.
Selecting from multiple tables using ActiveRecord in CodeIgniter
22 Sep, 2011
Selecting from multiple tables using ActiveRecord in CodeIgniter. Basics are the same as in query. You select multiple tables, relate tables and select the output fields.
Change breadcrumb in Drupal
19 Sep, 2011
To change breadcrumb in module you can use two functions. You can change breadcrumbs separators or the whole logic using theme_breadcrumb in your templates template.php file.
Embed views view in Drupal 6 - 7
18 Sep, 2011
This function embeds views view in Drupal. This function doesn't display the title of the view.
Get taxonomy term depth in Drupal 7
8 Sep, 2011
How to get taxonomy term depth or level in Drupal 7.
Get vid by vocabulary name in Drupal 6
8 Sep, 2011
How to get vid - vocabulary id by vocabulary name in Drupal 6. You can get it by using this little function.
Get PHP script execution time
22 Aug, 2011
How to test execution time of any part of the code in PHP. Basically you have to start counting microseconds before you code execution and stop after. This snippet shows how to do the counting.
Get taxonomy vocabulary id by machine name in Drupal
20 Aug, 2011
How to get taxonomy vocabulary id(vid) by machine name in Drupal.
Set page title for view in Drupal
20 Aug, 2011
Sometimes it's hard to set the title you want for your views. So you have to do this programmatically in your module. This snippet shows you how.
Drupal 7 views prerender
17 Aug, 2011
How to edit views content before rendering the view. This is what you need in your Drupal 7 module.
Hide or remove /node page in Drupal
9 Aug, 2011
How to hide default /node page from viewers. It's useful to do this if you don't use the page. People might access to some unwanted places.
WYSIWYG module, br instead of p tags in Drupal 7
8 Aug, 2011
How to make enter insert br tag instead of p tag. Works when using WYSIWYG module and ckeditor or tinymce.
Custom admin menu, page shows child menus in Drupal
8 Aug, 2011
This menus page shows child menus under that menu item.
Change search page title in Drupal
7 Aug, 2011
This snippet shows how to change page title on search page. For this example the title will be the content of search box(search string).
Drupal include module file
4 Aug, 2011
How to include module file to anywhere. For an example if you want to spread up your functions in different files for structure and readability then this is the right way of including module files.
Print level 2 sub-menu of main menu in Drupal 7
29 Jul, 2011
How to print sub-menus or any level menus in Drupal 7. You get only sub-menus of the current page you are on.
Remove css from theme in Drupal
27 Jul, 2011
I used theme hook called theme_css_alter. There is an array where are the css files. Foreach loop to go through them and unset ones that shouldn't be there. This one goes to your themes template.php...
Menu delimiters in Drupal
22 Jul, 2011
Menu delimiters or separators in Drupal. Tested on Drupal version 6.
Group search results by content type in Drupal 7
21 Jul, 2011
By placing this code to your themes template.php file, you get search results grouped by node/content type.
Add block to anywhere in Drupal 7
19 Jul, 2011
This snippet shows you how to load a blocks content programmatically. You can use this way to display a block anywhere you want.
Redirect form submit in Drupal 7
18 Jul, 2011
This snippet shows how to redirect form after submitting and saving in Drupal 7. You can also use Rules module for this.
JavaScript in Drupal 7
17 Jul, 2011
JavaScript libraries, basics and examples for Drupal 7. JavaScript is provided using the Library API.
Creating roles programmatically in Drupal 7
16 Jul, 2011
This little snippet shows you how to create roles programmatically in Drupal 7.
Adding custom content types in Drupal 7
16 Jul, 2011
Creating content types programmatically in Drupal 7. If you add this code to install hook then this way you can define your own content types in a module for an example.
Save file or image programmatically in Drupal 7
10 Jul, 2011
Save file or image programmatically. First get file from directory or URL. Then save the image and assign it to the field you wish.
Get files content type in PHP
8 Jul, 2011
This snippet gets content type of a file form external url. This snippet uses curl to download the file and get the content type.
Drupal language switcher theme
7 Jul, 2011
How to create custom language switcher. You can write your own tags and classes to get completely custom language switcher.
jQuery send form via AJAX using post method
29 Jun, 2011
This snippet sends form with id contactform using ajax via post method. When it's send and result is returned. It writes result into #feedback-form.
Always have latest jQuery version
29 Jun, 2011
To always have latest jQuery version, you can use this fast loading jQuery library from Google.
Get nodes by content type in Drupal
23 Jun, 2011
How to get node ids of certain content type in Drupal.
Add dependencies to Drupal modules
21 Jun, 2011
To add add dependencies to Drupal modules you have to open your modules .info file. Add new line "dependencies[] = module_machine_name" and you are done.
Order Views Programmatically in Drupal
19 Jun, 2011
How to order views programmatically. You might need to do this on special occasions. This hook initializes before query is built so it goes for all data, not just current page.
Create Drupal Page Programmatically
17 Jun, 2011
This snippet is a code from my module that just makes a simple menu item into my admin menu in Drupal 7. I am using menu_hook function to achieve this.
Add your css stylesheet to TinyMCE at admin panel in WordPress
1 Jun, 2011
Adding your css stylesheet to TinyMCE editor in WordPress admin panel.
Remove RSS feed from head tag in WordPress
30 May, 2011
How to remove RSS feed from head tag in your template.
Get and save jQuery window scroll position
24 May, 2011
Getting and save window scroll position with jQuery. You also need cookie plugin to store the position value in cookies, so it can be used after browser page changes.
How to create a widget in WordPress
23 May, 2011
How to make a widget that has one textbox and custom html output in WordPress.
Get node path alias in Drupal
15 May, 2011
How to get node path alias in Drupal. All you need to know is node id(nid).
get_posts multiple categories in WordPress
12 May, 2011
How to get posts from multiple categories using get_posts function.
Drupal get comment form
10 May, 2011
How to place Drupal node comment form to anywhere in your module or theme.
MySQL Query Into Array in PHP
8 May, 2011
How to turn MySQL query into an array in PHP. Print query results on screen. This is useful for determining contents of a table.
Get Years in PHP
3 May, 2011
How to get current, last and coming year in PHP. Simple examples of how you can get different years. Currently the years are calculated from the server time.
Get text area value or text with jQuery
29 Apr, 2011
This snippet shows how to get html element textareas value or text with jQuery.
Getting Base URL in WordPress
26 Apr, 2011
This example shows you how to get base URL of your wordpress powered website. It takes the value from your site information which can be modified and was set during the installation of WordPress.
ColorBox for Ajax loaded content in Drupal 7
22 Apr, 2011
ColorBox for images is loaded on first load, so all images loaded by ajax are colorBox free. To enable ColorBox for ajax loaded images you have to scan the html for images after load is complete....
Enable or disable comments using node_save in Drupal 7
21 Apr, 2011
You can enable or disable comments programmatically. Get node using node_load, set comment value and save node.
Drupal Snippet: "Automatic alias" checkbox checked in default
17 Apr, 2011
First find this line:
$form['path']['pathauto_perform_alias'] = array(
Then add:
'#value' => 1,
Switching Images With Arrows in JavaScript
7 Apr, 2011
This tutorial shows how to make image switcher with javascript. You can switch images by using arrows.
Getting Taxonomy Terms Names in Drupal 7
6 Apr, 2011
This tutorial shows how to get taxonomy terms names in Drupal 7. First how to get all taxonomy terms, how to get categories by a parent and with a little effort, you can turn it into a treeview.
Create Nodes programmatically using node_save in Drupal 7
17 Mar, 2011
I needed to get some xml data and generate nodes out of them. This shows how I created nodes programmatically from my module in Drupal 7. I also suggest looking into creating a node using entity...
Get Drupal 7 Profile Fields with profile2_load
14 Mar, 2011
How to get profile fields in Drupal 7. Profile fields are made with Profile2 module.
How to Create Drupal Module
12 Mar, 2011
This beginners tutorial shows how to create a durpal module. We will set up a module, create a menu item and a "Hello World" page.
Get Full/Absolute URL in Drupal
11 Mar, 2011
How to get full/absolute url of the page you are currently visiting.
Searchbox Background Text with jQuery
24 Feb, 2011
This tutorial shows how to create background text to your search box that will dissapear on click/focus.
Include External JavaScript Files to Drupal
22 Feb, 2011
This Drupal API tutorial shows you how you can include external javascript files.
PHP: Add Zeros Before Number
20 Feb, 2011
This tutorial shows how to add or append zeros before numbers. You might need this if you want to make folders named by numbers and you want them to be in right order when browsing the folder with...
jQuery - Send Single Form Field via Post on Blur
19 Feb, 2011
This tutorial shows how to send a single form field/input of a form. We are going to use jQuerys ajax features to do that.
Get Values of Checkboxes Group with jQuery
9 Feb, 2011
This tutorial shows you how to get values of checkbox array using jQuery. You can use this to send selected checkboxes values with ajax or add those to url variable(like in this example). If you...
jQuery Change Image src Attribute
4 Feb, 2011
You can use these examples to change img tags src attribute or any attribute of any tag.
IE Only CSS Files in Drupal
29 Dec, 2010
How to make Internet Explorer only CSS files for Drupal themes.
Installing App Engine Python SDK on Ubuntu
20 Dec, 2010
Installing Google App Engine SDK on Ubuntu or any linux distribution.
Installing Yii Framework
17 Dec, 2010
How to install and set up Yii framework application to your hosting.
Add Text to Image in PHP
15 Dec, 2010
This tutorial shows how you can add text to images with PHP. You can use it to make banners with dynamic content for an example.
How to echo or print arrays in PHP
6 Dec, 2010
Examples of parsing array values on screen. Some examples for beginners.
Custom Node Layout in Drupal
6 Dec, 2010
This tutorial shows you how to make a custom node layout. Which is a custom placement of node fields. Also we do it without any coding.
HTML Symbol Codes Table
30 Nov, 2010
HTML symbol codes are used to replace symbols so they would fit in ASCII codes. Also to remove certain symbols so content wouldn't interfere with HTML.
Drupal Tutorial: Multiple Nodes on One Page
30 Nov, 2010
This tutorial shows how to show multiple nodes on one page. Just like front page but not with a checkbox but different content type. Views are used for this.
Storing Images in MySQL With PHP
12 Nov, 2010
Easy to understand tutorial on how to upload, store and display images in mysql database.
Writing Text in Canvas Tag
20 Oct, 2010
How to put, render, write or draw text in canvas tag using drawText function in JavaScript.
Draw Circle in HTML5 Canvas Tag
19 Oct, 2010
Drawing a circle in canvas tag with arc function is actually really simple, but you have to have a browser that supports HTML5.
What’s New in HTML5?
19 Oct, 2010
HTML5 introduces a number of new elements and attributes that reflect typical usage on modern websites. The new standard incorporates features like video playback and drag-and-drop that have been...
Create Treeview Using Recursion in PHP
9 Oct, 2010
An easy example of recursion. PHP treeview can be used to create hierarchical lists like menus including sub-menus, category trees, taxonomy trees or site maps. This tutorial shows you how to...
Converting CodeIgniter Query to JSON
24 Sep, 2010
This tutorial shows you how you can generate JSON from SQL data that comes from model. Converting query to JSON is really simple in PHP and even simpler in CodeIgniter.
CodeIgniter Login With Google Using OpenID
20 Sep, 2010
How to make login system for CodeIgniter using OpenID. This example uses Google Accounts for login.
CodeIgniter - Cache Any Code Into a File
19 Sep, 2010
This tutorial shows you how you can cache code in CodeIgniter, by saving string or plain text into a file.
Round Corners for HTML Divs in CSS
12 Sep, 2010
This tutorial shows you how to make round corners for divs. From scratch with and without jQuery UI library.
100% layout with footer bottom of the page
3 Sep, 2010
This tutorial shows how you can make 100% height and width layouts with footer that stays always at the bottom of the page.
Add Form Fields With jQuery
26 Aug, 2010
This tutorial is about adding form fields, more precisely how to add textboxes dynamically with JavaScript. To make the code easier I use jQuery library.
Loading AJAX Page / Dynamic Content
25 Aug, 2010
Tutorial about loading page with AJAX between any HTML tags. We are using jQuery JavaScript library to do this.
Generate RSS 2.0 Feeds with CodeIgniter
22 Aug, 2010
In this tutorial we will make RSS 2.0 feeds from latest posts in your site.
Writing App Engine RSS Feeds
18 Aug, 2010
This tutorial shows how to make RSS feeds in Python for Google App Engine.
Delete Row From Datastore in AppEngine
16 Aug, 2010
Fourth part of AppEngine Forms. This time we delete added rows from database.
AppEngine Edit Form in Python
16 Aug, 2010
Third part of AppEngine Forms. This time we are making edit from.
AppEngine Forms in Python
16 Aug, 2010
Tutorial about making forms in AppEngine with Python. First part.
Submit AppEngine Forms Using POST in Python
16 Aug, 2010
Second part of AppEngine Forms. This time we will try to get our data through post and save the data to database.
HTML Lists Examples
8 Aug, 2010
This tutorial shows different kinds of HTML lists. There are lists with bullets, numbers, etc...
Login, Register and Logout in Python for AppEngine
3 Aug, 2010
This tutorial shows how to make Log In, Log Out and Register links for Google App Engine in Python.
Get Self/Base URL in Python
1 Aug, 2010
This tutorial shows you how to get your domain name(base url) from address bar in Google AppEngine, using self and urlparse
HTML Contact Form
25 Jul, 2010
How to make HTML contact form. First part of pop-up AJAX form submission that also works with no JavaScript.
Popup Contact Form With jQuery UI
25 Jul, 2010
Making beautiful pop-up contact form with jQuery and jQuery UI. If JavaScript is disabled the form is usual.
CakePHP Routing - URL With Parameters Only
25 Jul, 2010
This tutorial shows how to do URL routing in CakePHP, if you need your URL to be without controller and view.
Dynamic Layout With Dynamic Menu in CakePHP
24 Jul, 2010
This tutorial shows how you can attach dynamic menu or any content to layout that you still want to call from controllers.
Installing CakePHP
22 Jul, 2010
This tutorial shows how to install CakePHP. After this tutorial you can start making web application.
PHP Global Variables
15 Jul, 2010
Tutorial about global variables in PHP. How to use global, superglobal in PHP.
jQuery: Create a function
5 Jul, 2010
Tutorial about creating your own functions using jQuery JavaScript library.
Using CSS files in Python on Google App Engine
3 Jul, 2010
This tutorial shows how to use Cascading Style Sheets in Google AppEngine. It's all about url mapping. You have to have some basic setup of a project to follow this tutorial.
AJAX Form Submission in CodeIgniter With jQuery
26 Jun, 2010
Some knowledge of CI and OOP could be handy. This tutorial shows how to submit Ajax forms in CodeIgniter using jQuery. With optional jQuery UI feedback bubbles.
Handling Timestamps in PHP
25 Jun, 2010
This tutorial is about using and converting timestamps in PHP, witch are common formats of storing some timeperiod in database.
Integrating WYSIWYG TinyMCE into CodeIgniter
16 Jun, 2010
This tutorial shows you how to set up WYSIWYG TinyMCE in CodeIgniter. Both versions standalone and jQuery. It's really easy, most time takes the sample code tweaking.
Setting up Netbeans + Google App Engine + Python
13 Jun, 2010
This tutorials shows how to set up NetBeans IDE for writing Python for Google App Engine. Using NetBeans IDE is optional, you can complete the tutorial by skipping all the NetBeans related steps.
Displaying random value from array in PHP
13 Jun, 2010
This beginners tutorial shows and explains how to get random value from array in PHP.