Install sub-theme without creating blocks Currently when installing a sub-theme (not sure if this applies to a theme too) blocks from existing themes are copied to the new sub-theme in the Blocks layout section. Is there a way to prevent this from happening? I want to install a sub-theme and then manually add just the blocks I need.

They're not really "copied". They're the same blocks from your theme, but moved to the available regions of your subtheme after enabling it (iirc, they move to similarly named regions, disabled if none found).

What you could do is export the configuration. Drupal also keeps track of the active theme and block positions in the config. You could position blocks in the old theme and export the config for that. Then when you move to the new theme, you reposition the blocks and export again. Whenever you feel like switching over, you simply reimport the config you like.

I'm not so familiar with the config management in the UI, but this can be done with Git and Drush cex/cim quite easily.


Single content type with urls that can differ A site I am working on has a content type called property with a large number of fields within where the data is brought in from a 3rd party API.

Currently we use pathauto for generating alias urls of our content and has admirably filled our needs, except for the property content type which has a number of conditions which can determine what its url is and I am unsure that pathauto can do what is required.

We are using Drupal 8, latest version.

A properties url will contain the location, the listing type (sale, rental, auction or new-home) and the title of the property in its url.

So for example, a property with title ABC which is been sold in henley would have a url along the lines of http://example.com/property-for-sale/henley/abc.

But a property xyz on auction in basingstoke would be along the lines of http://example.com/auctions/basingstoke/xyz

Is there a hook/module or Drupal way (Views?) of handling this please? IF I remember Drupal 7 had hook_url_inbound_alter but I cannot find this in the D8 API.

Any enlightenment would be appreciated.

Grateful Grasshopper/John

If your Location, Listing type, and title are Fields in your Content type you can use Pathauto Patterns options (/admin/config/search/path/patterns) to automatically generate the aliases from values in nodes.

You use tokens available for the content type to construct the pattern. You can browse through (a very long) list of tokens to find the one you're looking for. Maybe it would be something like:

[node:field_type]/[node:field_location]/[node:title]


How to load a node given a menu link id? I have this id via $link->getParent():

menu_link_content:6cf83fce-228f-42da-bc39-bea06c767510

How do I get the node id of that menu link?

Something like:

if ('entity.node.canonical' == $link->getRouteName()) {
  $params = $link->getRouteParameters();
  $nid = $params['node'];
}


Hooks placements in Drupal I am trying to place some hooks, but I don't even think they are being called.

THEMENAME_menu_alter(&$items)

and

THEMENAME_user_view_access($account)

are the hooks I am placing in my template.php file. However, they don't seem to be reacting to it. And yes, I am converting the dummy THEMENAME placeholder to the name of my theme in use.

But my real question is: are these hooks just for use in Custom Modules? Or can they be called in from template.php too?

If its just for custom modules then I guess that would explain why it's not reacting. But even so how is one suppose to know if a certain hook is only for a module or not?

P.S: I have also tried clearing the cache several times.

By Default you can consider all hooks can be extendible using custom modules...

Hook Documentation says

  Hooks are how modules can interact with the core code of Drupal. They
  make it possible for a module to define new urls and pages within the
  site (hook_menu), to add content to pages (hook_block, hook_footer,
  etc.), to set up custom database tables (hook_schema), and more.

In template.php you can override functions which are exposed by hook_theme or functions like theme_*

There exists a good documentation that explains which functions you can override using template.php..


How can I hide titles with render()? I'm using the Devel module, and the following snippet of code to insert its links into my theme.

<?php echo render($page['devel']); ?>

The result is a h2 element with the Development title in it, and then followed by the links as expected.

I want to hide the title, is it possible at all?

This is what I ended up doing.

    <?php if(array_key_exists('menu_devel', $page['devel'])):?>
        <?php foreach($page['devel']['menu_devel'] as $link):?>
            <?php if(is_array($link) && array_key_exists('#title', $link)):?>

<a href="<?php echo $link['#href'];?>"><?php echo $link['#title'];?>

            <?php endif;?>
        <?php endforeach;?>
    <?php endif;?>

Does this seem acceptable, or is there a preferred way to do this in Drupal?

This is what I ended up doing, and it works 100%:

    <?php if(array_key_exists('menu_devel', $page['devel'])):?>
        <?php foreach($page['devel']['menu_devel'] as $link):?>
            <?php if(is_array($link) && array_key_exists('#title', $link)):?>

<a href="<?php echo $link['#href'];?>"><?php echo $link['#title'];?>

            <?php endif;?>
        <?php endforeach;?>
    <?php endif;?>


Am I missing a step with using Features? I've made changes to a Panel variant on my local site and wish to push it to the remote site, but I am having trouble doing this - the changes to the variant are not appearing on my remote site.

Here's what I am doing:

In Features I find the Page Manger section with my variants. I check them all, increment the version number and hit download.
I unzip the downloaded .tar file and place the Feature files within my folder structure: modules>>features>>module_name. I overwrite the existing files in there.
Using Git, I push these to my remote site (all's good with this step - I see the CSS changes I pushed as well)
On the remote site I access features and see that my module's features are overwritten. I check it's check box and hit Save Settings.

But nothing changes when I look at my variants - my changes do not appear.

Is there a step I am missing here?

Features can sometimes be finicky. Often times, just clearing caches after reverting will cause your changes to go into effect. In other cases, it can be necessary to revert the specific item (such as views or rules).

Personally, I haven't used Page Manager with features, but the general concepts apply consistently across the board.


Side-by-side contact form and GMap using panels I need a "contact us" page which has a contact form and google map side by side.
Thus, I enabled the core "Contact" module and installed GMap module. I also installed
Panels module and ctools module to create a page with two columns layout.

I successfully added the contact form into the left column of the panel page, but I failed to add the map into the right column. I thought I can easily add a gmap block into the column, but I could not find any block provided by the GMap module.

How can I do that ? Can I create a block which displays the map by using views.
I don't want to write custom codes.

I found a way:

I enabled "GMap Macro Builder" which comes with the GMap module.
Added a text format by enabling filter "GMap Macro expander" at the page "admin/config/content/formats/add" and named the text format as "Gmap Macro".
Created a map macro at the page "map/macro" to paste into a node.
Created a node at "node/add/page" by pasting the macro text copied from the step 3 into the node body, chose a text format "Gmap Macro" which was created from the step 2 and gave a title 'Location'.
Created a panel page with two columns layout and url "contact-us". Added the contact form to the left column.
Added the existing node "Location" created from the step 4 into the right column.
Created a main menu link with the path "contact-us" which is the panel page url.

Finally, I got a contact form with a google map side-by-side.

Required modules:
1. Chaos Tool Suite ( Chaos tools and Page Manager enabled )
2. Panels ( Panels only enabled )
3. GMap ( GMap and GMap Macro Builder enabled )


How to handle enabling new modules with Drush via makefile At work we are moving to getting our new sites set up in git and doing local development. So far I've created a drush make file along with an installation profile, and I have this scripted via puppet so that when a user does a fresh clone of a repository it will download all of the packages and run a basic site install. This works OK.

Now, my question is for when I need to use a new module for a site. For example, we build a new module for the site. I want the other developers to pull from git and have the new module automatically installed. Adding it to the drush make file will only cause it to be downloaded, and running 'drush si' will cause the site to be reinstalled, wiping out all of the data.

What's the best way to accomplish this?

Edit

I feel I haven't explain this properly. I'm looking for a way to automatically enable modules based on the makefile entries in drush. The idea is the user checks out a project, and then I'll have puppet run 'drush make' and 'drush si' if no settings.php file exists. What I need to figure out is for when the next time the user does a pull and we've added a new module, how to have that automatically enabled through some script. If I need to I'll write something to parse the makefile and run 'drush en' manually, but I'd like to find something that is pre-built to do this.

I worked for a company that had a large dev/stage/prod flow that tried to automate as much as possible.  Everything had to be done in code, scripted either using features or update hooks.

Basically, what you wanting is to have 1 custom module that exists to contain update hooks.  This way, when a developer pulls an update to the code base, they run the db update, and that can perform whatever module enable/disables need to happen.  The update hooks do not affect a new installation, because it is assumed that the module is already up to date when it is installed, and will only execute newer updates.

To summarize:

Continue using your installation profile to perform the necessary installation tasks (enabling modules, etc.).
Use a custom "update" module which uses hook_update_NXXX() to enable/disable new modules and otherwise keep your site's administrative tasks in sync.

Here is a post that talks about a similar approach and gives code examples.


How to add custom submit logic to search_block_form? I want to alter the input typed into the default search block in a way that when users search for "möp" (with a German umlaut) the search should be broadened to "möp OR moep" automatically.

So I simply tried to append a custom form submit to the search_block_form and simply expand the string by a certain logic. But then I found out that the search_block_form seems to be a little bit special. In core/modules/search/src/Form/SearchBlockForm.php I found the following comment.

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // This form submits to the search page, so processing happens there.
  }

My question now is: Where do I actually add the logic exactly if not in the form submit? I don't find any redirect or controller that would help here. Could you please point me in the right direction? Or maybe, you even have a better idea than appending the logic this way?

I removed the D8 tag as I guess the logic behind this is pretty equal amongst all common Drupal versions.

You can do this in hook_search_preprocess():

  Preprocess text for search.

  This hook is called to preprocess both the text added to the search
  index and the keywords users have submitted for searching. The same
  processing needs to be applied to both so that searches will find
  matches.

This is not part of the preprocess in theming. This hook is called directly from the search module. Btw. German umlauts are already replaced by default.


how to set a taxonomy term active? In my block i have different taxonomy term:
term A
-term B
--term c
---term D
when i am on term b it is set to active or bold if i am on term d then it is set to active and bold.
this is already been used
$options = array();
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2) == $t->tid) {
    $options = array('attributes' => array('class' => 'active'));
}

i am new in drupal anyone tell me how it is possible?

The arg() function is taking argument parts from the url.
/taxonomy/term/2 means:
arg(0) = taxonomy
arg(1) = term
arg(2) = 2


Drush suddenly stopped working for one site I have a bunch of sites on my local machine and have been using Drush (v5.4) happily for a long time to administer them.

All of a sudden, with no changes made to one such site, Drush reports these errors:

  Command pm-disable needs a higher bootstrap level to run - you
  will need invoke drush from a more functional Drupal environment
  to run this command.

  The drush command 'dis addthis' could not be executed.

  Drush was not able to start (bootstrap) the Drupal database.
  Hint: This error often occurs when Drush is trying to bootstrap a
  site that has not been installed or does not have a configured
  database.

Needless to say the site in question is running fine on the local machine with no errors (and is completely installed). Drush works fine for every other site on the machine.

What can cause Drush to suddenly misbehave like this for one particular site?

I cannot answer why this happens, but I have a site that periodically does this with drush pm-enable.  I think this site has trouble doing the nightly module update check, and something bad gets cached.  A drush cc all always fixes it.


The PHP version is not correctly detected I'm running Drush on a host that has multiple versions of PHP installed. By default, php --version would give you 5.2.x, but php53 and php54 are also available. So in my .bash_profile I have alias php='php53' (php --version = 5.3.13), which makes Drush work for some commands.

However, I still get "Your command line PHP installation is too old. Drush requires at least PHP 5.3.2" messages for some very useful commands.

A couple of really annoying instances:

drush pm-update will report that it has backed up and then updated all modules and core successfully, then return the PHP version error and restore all backups. In verbose mode, the command that comes before the error is:
php /home/[username]/drush/drush.php  --backend=2 --verbose --root=/home/[username]/webapps/drup --uri=http://[domain name]  pm-updatecode-postupdate 2>&1
drush archive-dump will immediately return the PHP version error

The other commands I have tried so far work fine. I'm not sure why this would be, if Drush is sometimes using the php53 binary, and other times not, or if it just has trouble detecting the version correctly, but some very important features are broken for me.

Drush doesn't use just php directly as a command, but need the full path. With the last version of Drush, you can add the following line in your .bash_profile to set which PHP you want to use.

export DRUSH_PHP=/Applications/MAMP/bin/php/php5.3.14/bin/php

Here is just an example of MAMP, but you can change it as well with your own path.


How do I handle multiple arguments with `hook_drush_command()`? I have to implement a drush command with multiple arguments. How should I handle them  in hook_drush_command()?

In the 'official' make-me-a-sandwich command:

function sandwich_drush_command() {
  $items = array();

  // The 'make-me-a-sandwich' command
  $items['make-me-a-sandwich'] = array(
    'arguments' => array(
      'filling' => 'The type of the sandwich (turkey, cheese, etc.). Defaults to ascii.',
    ),
  );
}

Arguments is clearly an array. Add new keys to it.


Separate grid rows by field value I have a custom content type with fields in which I collect, among others things, country. I'm using Drupal 8. I'd like to create a grid view page (using Views) of the content that is separated by country like shown in the image.

I'd like to avoid creating mupltiple views, one for each country, and then collating them into yet another page.

Any suggestions on how to make it happen?

Use Grouping by a Field

Grouping by Fields is a standard feature in Views.

Create your Content Views with Page Display
Add the Country Field (Probably a Taxonomy term reference, there are ways to import country lists BTW)
Set Format to Grid and set Number of columns
In Format Settings set Grouping field Nr.1 to your Country field

Check in Preview that things look the way you want.
Edit the Country field and set it to Exclude from display because you have it output above each result group, your probably don't want it in each grid cell too
Edit the Country field Style settings if you want more control over how the "group headings" are output, but this works only in certain cases: D7 How to change the HTML wrapped around a grouping output (HTML h3 tag), D8 Allow to configure the h3 element for view style plugins, although you can use Custom text field for more control too.


How to view search API raw sql query can we get the raw SQL query based on the search API views?

Actually, the search result didn't return the result (sorting) in the way I need it to be done.

An example I have a product name "Bicycle 100" and there are other product names such as "Bicycle 100 spare parts", "Bicycle 1100", "Bicycle 1000", "Bicycle 2100".

If user search for "Bicycle 100" and the first result I would like it to display "Bicycle 100", "Bicycle 100 spare parts", then only by the others like "Bicycle 1000", "Bicycle 1100", etc.

I am thinking whether I can write a raw query with union with the search api query.

The latest stable version of Search API module (7.x-1.20) has a known bug when showing the SQL query that is performed. You will have to apply the patch that appears on that issue or upgrade to the latest development version.

Take into account that even when patch is applied, the information that will appear on Views UI will not be the raw SQL query itself. Instead, you will have the properties of a SelectQueryInterface element:

Index: test_search_api_index_node_index
Keys: 'university'
Parsed keys: array (
    '#conjunction' => 'OR',
    0 => 'university',
)
Searched fields: field_test_1, ...
Filters:
status = '1'
Options: array (
    'parse mode' => 'single',
    'conjunction' => 'OR',
    'filter class' => 'SearchApiQueryFilter',
    'search id' => 'search_api_views:test_view_search:test_search_page',
)

In order to get the raw SQL query, you will have to implement a custom module that alters the Search API query and use a debug tool like Devel module.

/**
 * Implements hook_search_api_db_query_alter().
*/
function yourmodule_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  dsm($db_query, 'The SelectQueryInterface element');
  dsm((string) $db_query,'The raw SQL query with tokens');
  // Below I am changing the way Search API performs this search.
  $conditions =& $db_query->conditions();
  if (isset($conditions[0]) && is_string($conditions[0]['field']) && $conditions[0]['field'] == 'word') {
    $conditions[0]['operator'] = 'LIKE';
    $conditions[0]['value'][0] = '%' . $conditions[0]['value'][0] . '%';
  }
}

When printed, you will see the query has some token strings. Those tokens are the same that Views UI has printed above:

The raw SQL query with tokens =>
SELECT t.item_id AS item_id, SUM(score) AS score
FROM {search_api_db_test_search_api_index_node_index_text} t
LEFT OUTER JOIN {search_api_db_test_search_api_index_node_index} t_2 ON t.item_id = t_2.item_id
WHERE  (word LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (field_name IN  (:db_condition_placeholder_1, :db_condition_placeholder_2, ...)) AND(( (t_2.status = :db_condition_placeholder_12) ))
GROUP BY t.item_id

I hope this helps you.


scheduling backup_migrate with elysia cron I am looking at scheduling backup & migrate jobs with the elysia cron module. Can I ask how to call backup & migrate directly from the elysia script? Or should I be calling "drush bam"?

It all depends on your preferences and situation.

Elysia is designed to work in environment when you can trigger Elysia every minute (or every five, or ten minutes, but regularly 24/7). In that environment it would be more convenient to simply schedule Backup and Migrate with Elysia. Just remember to keep what you set in Home > Administration > Configuration > System > Backup and Migrate > Schedules in sync with what you set in Home > Administration > Configuration > System > Cron > Settings.

Benefit of that solution is easily accessible status of a cron task, the fact that you can see with GUI how long it took and when it was last fired, without login to any other tools but your Drupal.

Problem is that if cron system gets delayed, you may lost next sheduled backup - it may be mere 23h 58m since last time Elysia fired BaM task, so BaM may decide it's too soon to take another "everyday" backup. It's common problem with one scheduler calling another. And if you will make Elysia to trigger BaM every 5 minutes, to make sure everyday backup will be triggered consistently, you will waste a lot of CPU power for nothing.

drush bam approach is more direct. Long story short, it's main pros is lack of problems described above, and main cons is lack of benefits described above. And it's slightly faster in execution overall, as one "layer" less is in use.


How can you compute grand totals in an aggregate view I have a aggregate view in D7 that is working great.  The only thing is, I want to add a grand total line to the view.  What is the best way to add a grand total to the view?  Here is a sample of my data.

Dept  Squad    # of Rpts   # Vols   # of Hours  Value of Hours
AK     AK-11        3          6        124.00           2,745.36
FL    FL-893       24         41        664.50          14,712.04

What I would like to do is the above plus a grand total line like:

Dept  Squad    # of Rpts   # Vols   # of Hours  Value of Hours
AK     AK-11        3          6        124.00           2,745.36
FL    FL-893       24         41        664.50          14,712.04

  Grand total      27         47        789.50          17,457.40

Any suggestions?

Thanks for you help.

Dennis

You have to use Views Calc module.
The project page says:

This module adds simple calculations to a views table. Requires the
Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
in theme makes the view look more spreadsheet-like (right justifies
numeric fields, shades calculated columns and rows, and underlines
calculated rows).

For more information go through the module documentation.


Override field template with custom module Instead of adding tpl files (in this case, media-youtube-video.tpl.php) to the theme. How can I override field templates from a custom module? Including when the field is used in a View.

I'm sure there must be an easier way to do this but this is what I typically do:

1.
Register an overriding theme implementation with the Drupal theme registry. So, in mymod_theme(), add a new item. The variables key must match that of the media_youtube_video theme i.e.

/**
 * Implements hook_theme().
 */
function mymod_theme() {
  return array(
    'my_media_youtube_video' => array(
      'variables' => array('uri' => NULL, ...), // see media_youtube_theme() for this
      // bundle the template file with the module itself
      // i.e. theme/my-media-youtube-video.tpl.php
      'template' => 'my-media-youtube-video',
      'path' => drupal_get_path('module', 'mymod') . '/theme
    )
  );
}

2.
Add a preprocess hook for the original theme implementation and suggest your new implementation here.

/*
 * Implements hook_preprocess_media_youtube_video().
 *
 * Or more generally, hook_preprocess_THEME().
 */
function mymod_preprocess_media_youtube_video(&$variables) {
  // If your overriding implementation is not a template but
  // is implemented in a different file,
  // then remember to include the file explicitly at this point..
  $variables['theme_hook_suggestions'][] = 'my_media_youtube_video';
}

Suggestions are evaluated by the theme system in a LIFO fashion. You can read more about this here.

Suppose you are aware that another module is also following the same approach as this one to override the implementation, then you can implement hook_module_implements_alter() and force your hook_preprocess_THEME() (see above) to be called last. You can read about hook_module_implements_alter() here.

This holds good for Views also. In summary, you just need to find out the correct unique name of the original theme implementation you want to override (typically defined in the source module), add a preprocess hook and add your overriding suggestion there.


Feeds Importer and cron not running I have a Drupal 7 setup with a number of different content types, each with a common set of fields.

Each content type has its own feed, which calls a .csv that's produced from a Google Spreadsheet in tab-delimited format. Cron is set to run feeds importers daily, so when we make updates to the Google Sheet they are automatically reflected in the website

This has been working fine until recently, when we noticed the website was not updating. I checked the feeds log and see this:

I checked and the URL to the .csvs are working-- if I past them into the search bar I can download the file.

When I try to run the feeds manually from the "import" page, the screen just goes blank and nothing happens--no error or message. The same thing happens when I try to run cron.

Where is the site running? You mention you can download the file in your browser, but I wonder if the network from the site to google is different than the network from your computer to google.

What's in the error log in general? When the page goes blank like that it usually means some kind of severe error happened and that should show up in the Administer -> Reports -> Recent log entries page for the database log. Or it might show in the php or apache error logs. The location of those logs depends on your system.

How are you running cron? Depending on how you run it you might see different errors. If you have drush maybe try running cron via drush cron.


I am using https://github.com/drupal-composer/drupal-project . How to add more scripts after "create-project"? I want to use https://github.com/drupal-composer/drupal-project to generate several customized projects.

If I want a contrib module to be available for all instances, what is the best way to get them when running "composer create-project"?

I thought to add this logic (to add contrib modules by default) in scripts/composer/ScriptHandler.php but this file doesn't seem to be suitable for customizations.

Is there an easy way to add other scripts to run on project creation?
Or which other way should I chose?

when you use create-project you're creating a new composer project with a  composer.json based on the package type.

The composer.json file is highly customizable. You can set install paths for specific modules/libraries and/or set a list of default modules to install when the project is created. You can also apply patches and run post-install scripts if nessecary. Plenty more options as well. I suggest jumping into the composer docs.

to add a module to composer.json run:

composer require drupal/module_name 8.1.*@dev

Once you have a composer.json the way you like, you can take that composer.json file, place in a different empty project directory and you can simply run composer-install and it will install the drupal project, all the modules in the appropriate directories specified inside the composer.json file, post install commands ect, it will also write a composer.lock file if one doesn't exist. No need to create a brand new project everytime, just manage custom composer.json files thats the beautfy of composer.

https://www.lullabot.com/articles/goodbye-drush-make-hello-composer

https://getcomposer.org/doc/01-basic-usage.md

https://getcomposer.org/doc/


How can i give alphabets only validation in webform? I can give only required and maxlength validation in webform fields , How can i give

alphabets or numbers only validation in webform textfields  ??

UPDATE

I used hook like this :-

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_48') {
        if (!preg_match('/^[A-Za-z]+$/', $form['submitted']['name']['#value'])) {
            // $form['submitted'][$key]['#attributes']['class'] = 'error';
            form_set_error('name', t('Please enter alphabets only for Name.'));
        }
    }
}

this is working . but the order of displaying message is not proper , the first three

message is coming from ajax form validation and fourth one is from the hook , but i need

the fourth message should come first .

If you want to go for a module, Try the Webform Validation module

This module adds an extra tab to each webform node, allowing you to specify validation rules for your webform components. You can create one or more of the predefined validation rules, and select which webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.
The following validation rules are currently included:

Numeric values (optionally specify min and/or max value)
Minimum length
Maximum length
Minimum number of words
Maximum number of words
Equal values on multiple fields
Unique values on multiple fields
Specific value
Require at least one of two fields
Require at least one of several fields
Minimum number of selections required
Maximum number of selections allowed
Exact number of selections required
Plain text (disallow tags)
Regular expression
Must be empty (anti-spam: Hide with CSS)
Words blacklist
Must match a username


Ldap group configuration - Derive from attribute I am using Lightweight Directory Access Protocol (LDAP) and I have a question about how to put Active Directory users in a certain role based on an attribute such as memberOf.

In version 1.0, you could say in drupal authorization under II.B. DERIVE DRUPAL ROLES that you could look for memberOf or ... and when the user that logs in, has the particular role in that attribute, he receives the role that is defined in part IIA.

For example, you can have this in section IIIA - Role Mapping:
CN=Head,OU=Roles,OU=Accounts,DC=Domain,DC=be|beheerder

How can we do the mapping in version 2.0?
My groups that I have, are stored in the active directory in extensionattribute14

Kind Regards

I've handled this by calling a update user account function during validation against the AD.

First fetch the attributes of that account:

$filter = "(sAMAccountName=" . $username . ")";
// This is where you will need to add in extensionattribute14.
$attributes = array('sAMAccountName', 'givenName', 'sn', 'description', 'telephoneNumber', 'userAccountControl', 'distinguishedName', 'memberOf', 'proxyAddresses', 'Mobile', 'facsimileTelephoneNumber', 'mail', 'employeeNumber');
$result = ldap_search($conn, $ldap_base_dn, $filter, $attributes) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($conn, $result);
$entryid = ldap_first_entry($conn, $result);
$attrs = ldap_get_attributes($conn, $entryid);

And then then call the update account function ($attrs from above is passed in as $values):

/**
 * Makes updates to the users account based on values passed from the AD
 * @param  object $account
 * @param  array $values
 */
function update_user_account($account, $values) {

    // ...
    // Code here to update other values from the AD
    // ...

    if(isset($values['memberOf'])) {

        // Loop over groups.
        foreach($values['memberOf'] as $k => $group_dn) {

            switch($group_dn) {
                case 'CN=GRPHO Intranet Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][8] = 'Editor';
                    break;
                case 'CN=GRPHO Intranet User Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][9] = 'User Editor';
                    break;

                // etc. etc.

            }

        }
    }

    // add back in any roles that this user had that are not controlled from the AD
    if(isset($account->roles[3])) $updates['roles'][3] = 'administrator';
    if(isset($account->roles[15])) $updates['roles'][15] = 'site admin';

    user_save($account, $updates);

}


Passing PHP filtered arguments to Panel and View Pane I have been able to pass URL parameters to a Panel and from there to a View Pane inside the Panel.
However, I must pre-proccess the URL data with PHP. I have only been able to use Visibility rules with PHP in the View Pane but cannot manage to insert the PHP code in order to pass the specific PHP-modified values.

By far the best way to do this is to provide your own context.

See What are Ctools plugin (content type, access, etc), and how does one create them? for how ctools plugins work, and adapt one of the examples to a context plugin instead.

That way you can decide what data is passed into Panels, and on to the individual panes in a safe manner.


How can I clone a fieldset? I've been searching for this for a while, but most of the articles I have found are from YEARS ago, so I wanted to jump in here and see if any of you lovely people have an idea... :)
I am creating a webform for a customer that has a fieldset that needs to be applied to different sections within the form, but with all the same fields within that fieldset.
Is there a way to actually duplicate/clone a fieldset within a webform in Drupal 8?
I'm using:

Drupal 8.9.1
Webform Version: 8.x-5.19

Any help would be very much appreciated!
Thank You!
Nicole

Export config, then you'll have the fieldset in the resulting webform's Yaml. Then simply copy the whole fieldset in the Yaml, paste it to somewhere else in the Yaml and rename the elements. Now import the config again and your elements will appear in the form.
Export, paste, rename, import. That's it.


No front Page Content Error While creating a new view and after added the specific content to it.It's not showing the content which I've created instead it's showing

"no front page content has been created "

Go to "admin/config/system/site-information" to set front page.

Bottom section of this page there is a option for set "Default front page".

Give the view link in "Default front page" textbox. You will not able to see that message.


How to take care of .htaccess of all sites in multi-site setup on Linux? I've read this article: http://drupal.org/node/290768 which explains multisite settings on Linux.

But I need separate .htaccess for each site. How do I do it?

You cannot have separate .htaccess files in Drupal's root directory.

You can have different rewrite condition inside your Drupal's root .htaccess file .

You can have separate .htaccess inside your sites/%mysite%/ directory which will control all the files, modules, themes, etc related to that specific site.


Drupal 8 views watchdog issues I found a couple of issues with the Drupal 8 integration of watchdog support for views and don't know where to report them. The views watchdog project page only shows issues for the 7.x version.

With an exposed filter for the message field, you can't get results for words within an em tag (like a module name). In some cases, even plain text can't be searched for. Example: message is "Starting execution of backup_migrate_cron()." I can search for messages with "execution" but no for "backup_migrate_cron()" or "backup".

VBO is not supported for this view type.

Views issues are tracked in the Core issue queue. The VBO issue might make more sense in the VBO module issue queue, since it might need to be accommodated by the module itself.


how Drupal refresh/rebuild its route automatically after route programmaticaly created? I try to understand how Drupal Core rebuild the route automatically after route created programaticaly.

here is one example that i tried: I'm installing External Entities Module.
this module will allow you to create entity and generate its route automatically.

question: how is this possible? what trigger Drupal core to rebuild the route?

i did stack trace on entity form-save action as follow: (to understand what's triggered route rebuild)

KernelDesctructionSubscriber.php line 48 --> public function onKernelTerminate(PostResponseEvent $event)
ContainerAwareEventDispacther.php line 111 --> $definition['callable']($event, $event_name, $this);
HttpKernel.php Line 84 --> $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));
StackedHttpKernel.Php Line 32 --> $kernel->terminate($request, $response);
Drupal Kernel Line 634 --> $this->getHttpKernel()->terminate($request, $response);
index.php Line 22 --> $kernel->terminate($request, $response);

if you see KernelDestructionSubscriber in specific on: onKernelTerminate

public function onKernelTerminate(PostResponseEvent $event) {
    foreach ($this->services as $id) {
      // Check if the service was initialized during this request, destruction
      // is not necessary if the service was not used.
      if ($this->container->initialized($id)) {
        $service = $this->container->get($id);
        $service->destruct();
      }
    }
  }

when the ID equal to drupal.proxy_original_service.router.builder then it goes to: container.php : initialized method below:

  public function initialized($id) {
    if (isset($this->aliases[$id])) {
      $id = $this->aliases[$id];
    }

    return isset($this->services[$id]) || array_key_exists($id, $this->services);
  }

it will return TRUE because $this->services[$id] is set

and then it will trigger: $service->destruct() in onKernelTerminate then rebuild the route.

the question is where in the External Entities code that will make $this->services[$id] is set then trigger rebuild route?

i've been spending quite sometime and still unable to crack this...

Thanks in advance for the help

I can't see anything in the module doing it, but this is done through the router.builder service.

Either rebuild immediately, with \Drupal::service('router.builder')->rebuild(); or tell it to rebuild at the end of the request, which is \Drupal::service('router.builder')->setRebuildNeeded()

Based on what you posted, it looks to me that you went through all the boring, generic stuff and stopped right before if would have gotten interesting, in that services rebuildIfNeeded() method. which checks the rebuildNeeded flag and rebuilds if TRUE.

So, you don't have to do anything to have that method called, that happens automatically if the service got invoked, you just have to make sure that flag is set.


The website encountered an unexpected error. Please try again later (WSOD). Debugging scenario After updating Drupal using drush my website says 'The website encountered an unexpected error. Please try again later'. with white screen(WSOD).

Then when I tried to rebuild-cache using drush there was a drush fatal error originating with rules module. I got it rectified by replacing rules module with 3.x dev version.

I could rebuild the cache and update database using drush. But still the wsod is there

My next move was to enable error reporting. So I added the line

$config['system.logging']['error_level'] = 'verbose';
it did not return any errors on the the screen.
I like to know a debugging scenario for D8 as i faced this same issue for my another D8 installation but that was rectified after rebuilding the cache. I have came across posts by user with similar issues but reasons for their issues were different. So I strongly believe that there should be a debugging scenario that can apply to all.

1- Install Drush if you have not installed it already.

2- Clear cache using drush.

3- Still if you are facing issues start debugging with error logs as following.

Add the following lines to your settings.php

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

While editing settings.php change its default file permission to writable.
And you may also add following to your settings.php

$config['system.logging']['error_level'] = 'verbose';

Additional information is available here!

4- If you see any error related to any custom/contributed module after enabling error reporting service.You may overwrite the particular module folder with its latest release or even try with its dev release

5- You can read the server log messages for additional error informations. These log files may vary as per the server configurations. Some information about the server log file available here!


Custom Drupal breadcrumbs - how to disable the last item I have a D8 custom module providing its own breadcrumbs.
The breadcrumbs are shown perfectly, but the current page (last item) is shown as a link. I want to change Change this but as I see it, the ::build method requires the $links to be returned as an array of Link.

use ...

class BreadcrumbsBuilder implements BreadcrumbBuilderInterface {

  public function __construct() {
    ...
  }

  public function applies(RouteMatchInterface $route_match) {

    $result = // calculate logic
    return $result;
  }

  public function build(RouteMatchInterface $route_match) {
    $crumbs = new Breadcrumb();
    // prepare the data
    $links = $this->buildLinks($prepared_data);

    $crumbs->buildLinks($links);
      return $crumbs;
  }

  private function buildLinks($prepared_data) {
    $links = [
      Link::createFromRoute(t('Home'), '<front>'),
      Link::createFromRoute($title, 'entity.node.canonical', ['node' => $this->node->id()]),
    ];

    foreach($prepared_data as $data) {
      $links[] = Link::fromTextAndUrl($page_title, Url::fromUserInput($dummy_data));
    }
    return $links;
  }

}

The crumbs are shown properly as:

home >> My Title >> page_1 >> page_2

But page_2 is the current page, so it should not show as a link

To answer my own question:
The last link should point to route name '<none>' and that removes the href attribute from the item. So after all super easy.

// untested
foreach($prepared_data as $data) {
  $links[] = $is_last_link($data)
     ? Link::createFromRoute($page_title, '<none>')
     : Link::fromTextAndUrl($page_title, Url::fromUserInput());
  }

Related:
It appears Drupal 8 core does not provide the current page in the breadcrumbs.
The contributed module Easy Breadcrumbs does this for D7. The D8 version is in still in sandbox.
Reference: Blog post.


Drupal fails to send password reset mail Drupal (7 and 8) does not send mail from password reset form and I can not find any bug or failure. More interesting is that it does send mail notification that there is new drupal version.

I have checked following with positive results:

send mail from system
send mail from PHP CLI
send mail from PHP CLI as wwwrun user
send mail from php script in standard php webpage with mail() function.

I have separate /etc/msmtprc config file for apache and only apache can read it.

Apache php.ini contains:

error_log = /var/log/php_errors.log
sendmail_path = "/usr/bin/msmtp -C /etc/msmtprc_apache -t"
mail.log = /var/log/php_mail_errors.log

settings.php contains

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
$conf['error_level'] = 2;

Successful mails are logged in mail log. No failures. Apache error log and php log shows no errors. There are no significant entries in drupal database log.

If I change something in apache msmtprc configuration none of the mails from php are successful. Msmtp correctly relays on gmail with tls.

There is absolutely no indication of error. It seems that everything is OK from the system side but drupal still fails to send the password reset message. (Message is not in the spam nor sent items folder.)

Probably important note is that drupal is migrated to fresh openSUSE installation and that mail worked on old installation for all drupal sites (2x d7 and 1x d8). SELinux and AppArmor are currently not enabled.

Any help is appreciated...

Long answer in short: mod_rewrite was not active in apache :(

Failure drove me crazy so I finally started to think outside of the box :) Misleading point was initial error with msmtp configuration (owner of the config file must be wwwroot (in openSUSE case))...


Submit handler doesn't work after theming the form I have a form:

function payment_system_coeff_form($form, &$form_state) {
  list($_SESSION['payment_systems'], $_SESSION['coefficients']) = payment_system_table();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function payment_system_coeff_form_submit($form, &$form_state) {
  var_dump($form_state['input']);
  exit;
}

It works, when I submit it - I get the text printed.

But when I add the theme for it:

function payment_system_theme($existing, $type, $theme, $path) {
  $path = drupal_get_path('module', 'payment_system');

  return array(
    'payment_system_coeff_form' => array(
      'render element' => 'form',
      'path' => $path,
      'template' => 'table',
    ),
  );
}

table.tpl.php

    <?php
      foreach ($_SESSION['payment_systems'] as $name) {
        print "$name	";
      }
    ?>

  <?php
    $i = 0;
    foreach ($_SESSION['payment_systems'] as $index1 => $name) {
      print '
';
      print "" . $_SESSION['payment_systems'][$index1] . "	";

      $j = 0;
      foreach ($_SESSION['payment_systems'] as $index2 => $name) {
        if ($j < $i) {
          print '	';
        }
        else if ($j === $i) {
          print 'X	';
        }
        else {
          if (isset($_SESSION['coefficients'][$index1][$index2])) {
            $form["coefficients[$index1][$index2]"] = array(
              '#type' => 'textfield',
              '#required' => FALSE,
              '#size' => 10,
              '#attributes' => array(
                'name' => "coefficients[$index1][$index2]",
                'style' => 'text-align: right;'
              ),
              '#value' => $_SESSION['coefficients'][$index1][$index2],
             );

            print "" . render($form["coefficients[$index1][$index2]"]) . "	";
          }
          else {
            print "<input type='text' name='coeffitient[$index1][$index2]' value='' />	";
          }
        }
        ++$j;
      }

      print '
';
      ++$i;
    }
  ?>

<?php print render($form['submit']); ?>

Output of the form looks like this:

It stops working: I don't get any text when submitting the form. How to fix?

I know you've found an answer to your question, but I just want to explain why did you get that problem.

Drupal adds form_build_id, form_token, form_id (hidden fields) for security reasons and it's some purposes, while you're theming the form with template file and render its fields manually usually miss to include those fields, after that you form submission stops working. Recently this problem happened in my Symfony project (I'd found the solution) and after few days in my Drupal project, the solution was the same;

If you render the fields manually and also call drupal_render_children function, you will find that fields can be duplicated, my solution was rendering those fields also, like this:

print render($form['form_build_id']);
print render($form['form_token']);
print render($form['form_id']);

In my case for some reason drupal_render_children duplicated my form fields (I think this is normal, because I manually rendered the fields plus called drupal_render_children), that's why I ended up with this solution.


Listing Inventory items without being purchasable items The company website requires a list of large inventory items - engines, pumps, compressors, etc for the oil & gas industry. I was looking into UberCart but unfortunately it does not need to be an E-Commerce platform. What is the most efficient way of displaying inventory items in Drupal 7?

You can probably do this with just Drupal core and the Views module if you don't need any e-commerce functionality. It would probably go something like this on a basic level:

Add a new vocabulary called 'Categories' and add your terms to it (engines, pumps, etc.).
Add a new content type called 'Inventory Item'.
Add a term reference field to the 'Inventory Item' content type linking to the 'Categories' vocabulary you just created.
Add whatever other custom fields you need to the content type (price, stock, etc).
Create a view that lists all content of the 'Inventory Item' type.
(optional) Create any other views that you may need to filter the content by whatever criteria is applicable.
Start adding content.
(optional) Grab the Taxonomy Menu module so you can easily create menus that break your inventory items down by category.

The order of those steps is somewhat interchangeable.

If you're not familiar with views there's good documentation out there.


How to make 2 Rules work that use the very same Rules Event? On a D7 site I have two rules (using the Rules module) reacting on the same event which is 'After saving a new entityform submission'.

When the actual event occurs only 1 gets fired, even though I've played around with Rule weights. So either I can give precedence to 1 of them or get them to fire at the same time but no luck.

Any help/suggestions would be much appreciated.

2 separate Rules using the same "after update something" event, that's asking for problems.
You should try to rework/redesign those 2 rules somehow. Here are a few ways to do so:

If both rules don't have any Rules Conditions, then move all the Rules Actions of 1 rule to the other rule (and think of the best "order" to execute all Rules Actions).

If Rule 1 has a Rules Condition (say) "Condition1" and Rules Action (say) Action1, and Rule 2 has a Rules Condition (say) "Condition2" and Rules Action (say) Action2, then use the Conditional Rules module to merge both rules together (also), with a Rules Action (not Rules condition!) that looks like so:

Conditional
If Condition 1 then Action 1
Conditional
If Condition 2 then Action 2

Note: if appropriate, first perform anything related to Rule 2, then Rule 1


Drupal migration api: set custom plugin as source in «process» section I migrated nodes including metatags from D7 to D8. As soon as metatags are not field in D7 I do not have it as common source in d7_node plugin. Of course, I can extend this plugin with my own and make join with metatag database table. But this variant seems for me not ideal. As I understand I can't execute any db queries inside process plugins, so I need to feed my custom source plugin result to a metatag field in a process section of my migration config. How can I do it and is it possible?

Yes, it is possible to migrate fields but I don't know Metatags.There is an existing issue in Metatags for creating a migration, it may be of help. https://www.drupal.org/project/metatag/issues/2563649


Search result issue with Search API module I'm working with Drupal-7; where i have installed so many different modules in it. one of them modules is "Search API".

The problem what i'm facing is Result of searched keyword. whenever i use to search for a particular keyword it working for the Exact match with that key word.

For example :  keyword = "Drupal" ;
then result only retrieved if this exact word will match with the content of database. but i would like to get result which are having any of these characters.

For example : keyword = "Dru" ;
then also all the result will retrieved which is having only word "Dru" as well as "Drupal"  & etc..

In short now Query is working with "=" operator but i would like to make it with "LIKE" operator.

What should i do in which page to get resolve this..?

I have tried to many things but not get success.

If you are not using Apache Solr in the back-end, then you will have to use the Fuzzy Search module in conjunction with the Search API module. This module provides drupal sites with a fuzzy search engine to allow for broader keyword matches including partial or misspelled keywords.

*Note: At time of writing this there is some incompatibility with Search API 7.x-1.0-rc1 and Fuzzy Search 7.x-1.x-dev (2011-May-12). To get these two working together, you will need to use the search_api 7.x-1.0-beta10 until the Fuzzy Search maintainer gets the module caught up to the current release of Search API.


How to convert a complex select query to Drupal dynamic query? I read online that db_query is faster than db_select for complex queries.
I wanted to check this for one of the queries I have written.

Following is the code with db_query:

$query = "SELECT og_users_roles.uid
        FROM {og_users_roles} AS og_users_roles
          LEFT JOIN {og_role} AS og_role
            ON og_users_roles.rid = og_role.rid
          LEFT JOIN {users} AS users
            ON og_users_roles.uid = users.uid
        WHERE og_users_roles.gid = :gid
          AND og_role.name =  :role_name
          AND users.uid <> 0
          AND users.status = 1";

$placeholders = array(
  ':gid' => $group_entity->nid,
  ':role_name' => OG_ADMINISTRATOR_ROLE,
);

$results = db_query($query, $placeholders)->fetchAll();

Now, before testing the performance I need to change above to user db_select.

This is what I have done:

$query = db_select('og_users_roles', 'o_u_r')
  ->leftJoin('og_role', 'o_r', 'o_u_r.rid = o_r.rid')
  ->leftJoin('user', 'u', 'o_u_r.uid = u.uid')
  ->fields('o_u_r', array('uid'))
  ->condition('o_u_r.gid', $group_entity->nid)
  ->condition('o_r.name', OG_ADMINISTRATOR_ROLE)
  ->condition('u.uid', 0, '<>')
  ->condition('u.status', 1);

$results = $query->execute()->fetchAll();

However, this seems to fail with a WSOD.
Can someone point the error?

Give a try to Query coder module ( https://www.drupal.org/project/query_coder ): Convert SQL query to Drupal Database abstraction layer code.

Otherwise to debug the error turn on the error reporting, and check the error log which will point you to the suitable path.


Formatting my Link field with multiple values I believe I have a way to do this, but as I'm learning I want to make sure I'm not doing it horribly wrong or reinventing a wheel that already exists (the module search on the Drupal site leaves a lot to be desired).

I've got a Link field with multiple values (just URLs). When this field is being rendered, I would like to sort of preprocess each of the URLs. If it's a youtube or vimeo link, I'd like to change it so that a video embed is rendered instead. If it's a link to an audio file (with certain extensions) then I want to render an html5 audio tag.  Else, I just want to render the link normally.

It looks like I could override mytheme_field__links__mycontenttype() (although I'm not exactly sure how to implement that method just yet, any examples are welcome).

It also looks like I could create a template in my theme named field--links--mycontenttype.tpl.php

Is this the right way to go?

Is one better than the other?

Do you have any links to a good example of how to implement/override these?

Thanks!

The two best ways to do this are the one you suggest by creating a tpl.php like you mention and doing your work in there directly.  Another (and preferred by many, but a bit more complex) is to use template_preprocess_field.

A very good explanation of how to go down the second route is http://www.digett.com/blog/01/18/2012/change-output-single-field-drupal-7-node

That way you don't end up with a whole bunch of field.tpls and you can isolate your changes in that function.


Batch update XML Sitemap for content type using VBO - D7 I am trying to update a portion of my Basic Pages' XML Sitemap setting. By default my Basic Pages are Excluded in the XML Sitemap (what I want), but I want to bulk update only some of them (long story). I can manually go to each of the pages and update them to be Included, but that will be a pain.

I tried to use VBO and I created the filters I want, but there isn't a XML Sitemap update Operation. I can create a Rules Action, but again, I couldn't find integration with the XML Sitemap setting.

Is there a setting for bulk updating the XML Sitemap setting that I'm missing? Or some module that does this already?

Other ideas I have if this functionality doesn't exist:

VBO: Execute arbitrary PHP script & run a Database update
Rules Action: Create a custom action to run a Database update
???

Drupal 7.34, Rules 7.x-2.7, VBO 7.x-3.2, XML Sitemap 7.x-2.2

Thanks.

Looks like there isn't really a rules integration yet.  The best outcome here would be to write that integration and contribute it to the project.

Failing that, a custom action using PHP would do the trick.  Obviously you should take a backup before executing anything like that.


Simple webform with payment module what I need do is not an ecommerce site.

On my drupal website I need a simple web form with a payment (by paypal) and a node reference field prepopulated (by the entity refence and entity reference prepopulate modules).

The scenario is this:

I have a content type called Team.
Only the admin can add nodes for this content type.
This content type has field of type user reference (by entity reference module). This field is empty to default.

Now, when an authenticated user visits one of this nodes, he can click on a link Administer this team!.
If he click on this link, he go on the payment form and it set the referenced node field to the clicked node id. Now with the payment webform he can pay.
The price is always 49 Euro, so he doesn't need set it.

After the payment I would like set an action (by rules module) that fetch the user that pay, the referenced node and set the user on the user reference field on the node.
In this way, trough the nodeaccess_userreference module, the user can start to administrate his team's page...

Hi tried to do this with the payment module beacause this has a good implementation with rules module, but I don't understand how to do a simple webform (at the url www.example.com/pay-your-team) with the reference to the node and without allow to the user change the price.

Can you help me?!

Thanks a lot!

You need to create a custom module for this.  You'll have to learn how to use PayPal's SOAP requests and handle it that way.

This question, as it is now, is FAR too broad in scope to answer in this forum beyond that though.


How to validate webform with JavaScript? I've got a Webform for which I need additional calculations to hidden fields.

I've added a JavaScript file to the page by using drupal_add_js. And let that be the only part that works...

My calculate.js file looks like this:

document.getElementById("webform-client-form-80").onsubmit = function() {
  window.alert("Test!");
  document.getElementsByName("submitted[aantal18plus]")[0].value = 5;
};

Why don't I get an alert? And why doesn't the value of "submitted[aantal18plus]" get altered?
If I change "document.getElementById("webform-client-form-80").onsubmit" to "document.onload", everything works. But unfortunately, there isn't any data yet (tried with windows.alert("");)

A bit more context:
The form is a subcription form for a BBQ. I Have 16 fieldsets (for 16 persons at once) with 4 dropdown menus (for choice of meat). A LOT of fields, and a lot of different prices. I want to calculate things like 'total' and 'number of steaks'. I want to send those in the submission e-mail, so I created 12 hidden fields, and I do need to calculate those values on submit.
I don't (necessary) need JQuery. At submit will do fine, 'cause the fields I'm altering are hidden.

Simply put: onsubmit, how on earth do I get it to work with javascript in drupal??

You can create a custom module for that:

webfv.info
webfv.module
webfv.js

Put all these files into a folder called webfv.

This is the webfv.module file:

<?php
function webfv_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'webform-client-form-80') {
    $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'webfv') . 'webfv.js',
    'type' => 'file',
  );
}
}

And this is the webfv.js file:

    (function($) {
      $(document).ready(function() {
      // Put your code here. //
      });
    }) (jQuery);

And of course, you should have a webfv.info file:

name = webfv
description = JavaScript Webform Validation
core = 7.x
files[] = webfv.module

Note: this is just one way of doing it, there are some other ways.


Only show comments in view where the comment author has a specific role I am trying to make a Drupal View which only shows the comments of users with a certain role. For example I have a node with content_author who has Role Y. The same user (with Role Y) placed a comment, another user with Role X posted a comment too.

I want to have a view which only displays comments from users with Role X. This does not depend on the user who is logged in, so I cannot use a contextual filter I suppose.

Did anyone manage to do something like this?

I figured out how to do it.

Create a view displaying items of type Node.
Create a relationship Comment:User
Create a filter User: Roles and require Relationship with User (which was created in 2.
Specify the roles

You can style the view (and add fields) as you like.


Linux Drush install error: Undefined class constant 'MYSQL_ATTR_SSL_CA' in phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php, line 56 I tried installing Drush with both methods listed in the drush.org documentation. I think they might be conflicting with each other if that's possible.

When I run composer global require drush/drush all the components appear to install correctly. However when I change to a Drupal site (Using XAMPP, /opt/lampp/htdocs/sitefolder) and run drush status I get the following error:

  PHP Fatal error:  Undefined class constant 'MYSQL_ATTR_SSL_CA' in
  phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php on line 56
  Drush command terminated abnormally due to an unrecoverable error.
  [error] Error: Undefined class constant 'MYSQL_ATTR_SSL_CA' in
  phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php, line 56

I do have the following line in my ~/.bashrc:

export PATH="$HOME/.composer/vendor/bin:$PATH"

Unfortunately I don't know how to troubleshoot from here, as there doesn't seem to be an easy way to uninstall Drush via the main method (http://docs.drush.org/en/master/install/), which didn't seem to work for me. composer global remove drush/drush does appear to run successfully.

Thanks in advance.

In my case, not all of the PHP packages made it though the Ubuntu upgrade to 16.04 (which now runs PHP 7 by default).  I needed to add the missing one, and then Drush started working again:

sudo apt install php-mysql

Or for php5 users

sudo apt install php5-mysql

on very recent Ubuntu/Debian distributions.

For PHP 7.1:

sudo apt install php7.1-mysql

For PHP 7.2:

sudo apt install php7.2-mysql

You can search for your version using this:

apt-cache search php-mysql


Can tokens be used to set values of other fields and in modules which use tokens? I am finding the Metatag module rather unwieldy, and I want to create fields in the content type from which Metatag values will be set.

Are there tokens available for the fields of any arbitrary content type, that can be used, or a set formula for creating them?

You try use hook_tokens()

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'key_token' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      $replacements[$original]='Some_value';
      }
    }
  }
  return $replacements;
}

See more document hook_tokens()


Is there a way to cancel a node deletion using rules? I have a node type that represents a phone call.  The user can schedule a call, then record notes about the call.  I want to give the user the ability to deleted these call nodes, but only if the call has not happened yet.  Is there a way to review a call node (using rules) the cancel the delete operation if specific criteria fail?

This could also be used to make an "Are you sure?" option for node deletes.

You should be able to do this via the conditions field in the rules module. Unsure how to create an 'are you sure' option, but you could certainly stop them from doing it with rules.

There might be better solutions, but here's what I'd do if I wanted to achieve what you are doing.

Install Flags and Rules module. Create flag to appear on Content Type 'Phone call' called 'Delete this call'.

In rules create two rules. One called Delete call, the other called 'display message about unable to delete call'.

First rule:

Triggered on action - node is flagged
Conditions - Entity has field call date/time (whatever the field is called)
           - Data comparison - select the date/time field, then is greater than +1 minute.

Then action - unpublish content

For the second rule do the same but change second condition to less than - 1 minute. Then as the action do 'display message on the site' and select message as 'Unable to delete calls that have passed'.

That should work.


How do you programatically create decimal fields in Drupal forms? I simply need to be able to have a text field and validate if input is a decimal number like 100.00, 0.1, 10.6, etc.

I'm using Drupal 7.

Updated question to indicate 'programatic' solution (using Form API).

I can't think of a better solution than to use a standard textfield with the element_validate_number() validator:

$form['element'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#element_validate' => array('element_validate_number'),
);

If you need something more complicated than the is_numeric() that gets run by element_validate_number() you just need to provide your own validation function, or if you want to mess with the widget itself then create your own element type using hook_element_info()


How to alter the title of a views exposed form block with code The title says it all really. My views exposed form block has no title but I want to add one through code. I have been looking through the api for hours and am totally lost. I have tried tons of things but my drupal and php chops are limited.

function hook_block_view_alter(&$data, $block) {
  if ($block->bid == $id) {
    $block->title = $title;
  }
}

Where hook is the name of your module, $id is the numeric ID of the block and $title is the desired title.

You can find the ID with the Devel module by putting dpm($block); inside the hook_block_view_alter() function and then looking at the output for each block to see which one matches. It'll have a delta attribute on the $block object something like -exp-your_view_name-display where your_view_name is obviously the name of the view, and display is the type of display, e.g. page or block. Or you can just pattern-match the delta value instead of selecting by ID, up to you.


What is the proper way to add third party script snippets to head tag? I understand I can hard-code this snippet into html.html.twig but i would prefer a cleaner method. My research is only instructing me how to attach libraries etc, but I can't find any example of injecting code into the header area needed by some third-party services.

I tried the following code, but it doesn't seem to work.

/**
 * Implements hook_page_attachments().
 */
function THEME_page_attachments(&$page) {
  /**
   * Initial JS.
   */
  $javascript_header = "-----js code -----";

  $page['#attached']['html_head'][] = [
    // The data.
    [
      // Add a <script> tag.
      '#tag' => 'script',
      // Add JavaScript to the <script> tag.
      '#value' => \Drupal\Core\Render\Markup::create($javascript_header),
      // Give weight so it appears after meta tags, etc.
      '#weight' => -1,
    ],

    'key'
  ];
}

Your issue seems to be related with hook_page_attachments() not called from mytheme.theme file. If you look to the answer, it's written -

  It appears that this function is only callable from a module, as it is
  listed in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8
  module but not listed as a valid method in Adding stylesheets (CSS)
  and JavaScript (JS) to a Drupal 8 theme.

I verified with the current documentation & that's correct. You can use hook_page_attachments_alter, which has documented in above given document for Adding stylesheets and JS to a Drupal 8 theme.


Programmatically accessing a field group relationship I believe I am using the default Fieldgroup module. I have added a new group using "Add new group", then I have created a couple test fields and nested them under that group.

I see the entry is added in my 'field_group' table in my database.  What I am wondering is how I can programmatically see that relationship.  Please bear with me. After adding content I am using field_info_instance to view each field for that node.  I do not see any field that shows a connection to the group I created.  Is there a function that would let me see this relationship on a field by field basis??

Thank you,

I couldn't find one in the module anywhere but I cobbled this together and it seems to work ok:

function field_get_field_group($field) {
  $group_info = field_group_read_groups(array('entity_type' => $field['entity_type'], 'bundle' => $field['bundle']));
  foreach ($group_info[$field['entity_type']][$field['bundle']]['form'] as $group) {
    if (in_array($field['field_name'], $group->children)) {
      return $group;
    }
  }
  return FALSE;
}

Usage:

$field = field_info_instance('node', 'field_image', 'article');

if ($field_group = field_get_field_group($field)) {
  $group_name = $field_group->group_name;
  // etc...
}

You'll probably want to add some error checking ;)


Page not found on new server in Drupal 7 custom module I have a custom module that uses hook_menu() to create new routes. It works on all my existing Windows development boxes.
I've recently set up an Ubuntu box, and installed Drupal; everything seems to work aside from the custom routes.  I have a menu callback for "test" that gives me a 404 error. I have confirmed that hook_menu() is called in the code. I have clean URLs enabled, and the "Add content" link  goes to "node/add," so it seems that clean URLs/URL rewriting works.

I should add that visiting "?q=node/add" works fine, but "?=test" does not.  It seems like on this machine something weird is happening with the menu system.

Turns out the module requires curl which the server didn't have.  The module didn't bring down the whole site but just didn't work itself.  No way anybody could have diagnosed that!


How to add multiple suffixes for an integer field type? Is there a way to add multiple suffixes for an integer field type? For example, I want to input a value, and I want to be able to specify whether this is in inches or centimeters with a drop down box.

Is there a way to do this using only the field module?

There are 3 options:

Install the Measured Value Field module.
In your custom module implement hook_form_alter and add your dropdown there with markups.
Create actual dropdown and work with just markup.


Add class to section in tpl In my template (Bootstrap), in the following line:

<section<?php print $content_column_class; ?>>

I need to add a custom class AND keep the dynamic column class.
I tried <section class="myclass <?php print $content_column_class; ?>"> but it give me:

Any idea what to do?

Try

<?php print $content_column_class; ?>

and see what is exactly printed

I think you should try something like this instead

<section class="<?php print "myclass ".$content_column_class; ?>">

Hope This helps
Cheers


How to convert query string http://example.com/myview?page=1 to http://example.com/myview/page/1 in views? I have to make url of views seo friendly. I need to convert query string http://example.com/myview?page=1 to http://example.com/myview/page/1.

Can you please suggest, how can i do this.

Try using the module: Query parameter to url(https://www.drupal.org/project/query_parameters_to_url), It will work for you.

Just specify the pattern {^myview} inside /admin/config/search/query-parameters-to-url after installing and activating the module.

Let me know if any helps needed.


Creating new template for new page In drupal 7, I created a content type called page and set the url to /about. If I check the source code I see

<link rel="canonical" href="/website/about">

and

<link rel="shortlink" href="/website/node/7" />

So if I create a new template called page--node--7.tpl.php then it works.
But if I create a new template called page--about.tpl.php it wont get picked up.

What am I doing wrong here?

Thanks!

I think you have issue with hook_suggestions that we need to configure correctly for a template to work.

Its already answered here

drupal 7 template suggestions based on path alias

Hope it will help!


Drupal csv file not readable I have a module which reads in csv file and adds records to the database. It is working properly on localhost. I am able to upload the file and read and then display the result. But, on my server, i am able to upload the file but this piece of code fails, while reading the file.

 $file_handle = fopen($file_url, "r");
 while (!feof($file_handle) ) {
 $line_of_text = fgetcsv($file_handle, 1024);
 print_r($line_of_text);
}

I realized that it might be a permission issue so , i checked that folder has got 0777 permission where as i am not able to give recursive permission to files, files have permission of 0664. and i get access denied when i try to give it different permission, i am on ubuntu server.
After i checked

 $file_handle = fopen($file_url, "r");
 var_dump($file_handle);

On localhost i got: resource(90, stream), whereas on my server i got bool(false).

Node Import, and Feeds are two solutions I've used recently to import content. they may work with while you maintion that your module read from csv and store in DB


Form results sent to different emails I am using a webform module to create a contact us form. The customer has asked for a dropdown list for the visitor to select whom they would like to contact (web administrator/general enquiry). Is there a way to change the TO email depending on the selection? Or is there another way of achieving this?

Here's how I did it in Drupal 7, without the use of any other add-on modules:

Add a select box to the form.
In the select box options field, add your info in this format:

  email-1@address.com|Select Option 1

  email-2@address.com|Select Option 2

  email-3@address.com|Select Option 3

Save your form, then click on the "Emails" sub-tab of the "Webform" primary tab.
Choose "Component Value > The name of the field you created in step 1". Click "Add".
Adjust your settings as needed on the following page, and you're done! The webform will now send an email to the address associated with the choice selected in the select box.


placing a menu block inside a views template I need to place a menu block (the main-menu) inside a views template file - the template for the rows design.

I tried

$block = module_invoke('system','main_menu');
print render($block['content']);

and

$block = module_invoke('menu','main_menu');
print render($block['content']);

but nothing works.

Can anyone please give me a little help?

I used the code which was rendering the main-menu from page.tpl.php file in the theme that I am using in my current project Nexus.

<div id="main-menu">
<?php
 if (module_exists('i18n_menu')) {
   $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
 }
 else {
   $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
}
 print drupal_render($main_menu_tree);
 ?>
</div>

So i used the following extraction:

<?php
$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
print drupal_render($main_menu_tree);
?>

in a views template file for row design. The main menu appeared with content.

Note: The menu which will be rendered might not be themed.


Node Permission base on per Taxonomy Term Is it possible to give view page(or article) permission per Taxonomy term? I know there is a "Taxonomy Access Control" module but this module does not really give the permission, beside hiding the node url. Meaning I still able to see the page if I know the original url. For example, "www.mysite.com/node/100".

I think TAC can provide this functionality.

Here's a screen shot of the TAC config.

http://cl.ly/image/1f1Z433r0y1s


How to use Views 3 API to display custom tables? I have some custom tables in the Drupal Database which are not of any content types. I want to use Views to display the values from the tables on to the website. Is there a way or a module that already provides this functionality? I am using Drupal 7 and Views 3 API.

After lots of research and work, this answer is for people who faced the same problem. The Data module does this for you. This module allows you to adopt a table (created in your Drupal Database and is not a part of any content type, basically a standalone table) and creates a view for that table. The view can be customized. The requirement here is that the table must have a primary key. You can also index this view by creating a content type and using the Views References Module. This will facilitate the indexing of the content in the table and make it show up in search results. Hope this helps.


Drupal 7.10 : views filters error i keep getting the following message on my exposed filters. Any ideas as to what i might have missed out when configuring the filters. I used the cck list (text) widget to compile options in each select list.

ps- i did not select the required option on the views filter options. For each filter i selected the expose filter option, the "is one of" option and the options i want to appear in the filters. I also have the Better formats module selected.

This is a very common and very difficult to debug problem. It happens when there's an inconsistency between the cache version and the submitted version of a form; whatever the reason.

You're best bet would be to upgrade Views and Ctools (and perhaps BEF too) to the latest dev versions.

Also, one important thing to consider is wether or not you have custom code altering the form.


How to enable Administration menu Toolbar style for editor profile? I have created an Editor profile which can create specific content types. However, I would like to give such users the possibility of using the Administration menu Toolbar style (i.e. overlays) rather than the default page display.

Is this possible? If yes, how? Thanks.

You just need to grant a few permissions to the editor role to achieve this. Navigate to http://mysite.com/admin/people/permissions and tick the checkboxes next to the following permissions for the editor role:

Use the administration toolbar
Access the administrative overlay
Use the administration pages and help
View the administration theme

Only the pages that an editor user usually has access to will be shown as links in the toolbar.


How to append currency symbol as prefix to total sum in views calc? I have used Views Calc module to calculate sum of all column fields. How can I append currency symbol as prefix to Views Calc calculated total sum?

You can achieve that in two ways CSS or jQuery

1)CSS (Note: It requires CSS2 capable browsers. )

td.your-views-class-name:before { content: "$"; }

2)jQuery

$('.your-views-class.name').each(function() {
  $(this).before($('<td>').text("$"));
});


How would I make a basic select list? So I am learning the ways of the jedi Drupal, but I have come across a part of a problem in what I am doing.  I am currently trying to make a basic select list with two options.
So far I have something like this.

function form_ee_form($form, &$form_state) {

  $form['select_list'] = array(
    '#type' => 'select',
    '#title' => 'Select One for Data Rundown',
    '#value' => t('Okay'),
  );

This is taken directly from Form API Reference. Familiarize yourself with it.

$form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
         0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );

EDIT

To print the result from the selection, you could consider a few things:

Do not use a form at all. Just use theme_item_list wherein you create hyperlinks to pages with nodes or users.
Use the form, but persist the user's selection (node or user) to the database or SEESION. Then when the form is created you reload the persisted value from the database or SESSION (if not present use default) as the default value so it always reflects the user's last choice, and you create a markup element wherein you show either the nodes or users that were the result of the selection or the default. In the submit you only persist the value to the database or SESSION. In the form creation you look at the persisted or SESSION value (if present, else use default), and display it in the markup element.
Use the form, do not persist anything in the database, and in the submit you inspect the select list value, and depending on the value you redirect (using $form_state) to a page that will show either nodes or users.
Create a jump list: for example ARCHIVE: Example: How to Create a 'Jump Menu' from a List View


Can drupal be installed on a subdomain and used on the main domain? I was thinking about installing Drupal on admin.myexample.com for clients to access an add and edit news posts & products.

Then just using myexample.com as the main site. Calling the database and entries to their pages with PHP/SQL.

Is this practical?

I've been trying to learn my way around Drupal, I know this wouldn't be a way to learn. I'm much more comfortable writing the pages up myself than manipulating Drupal pages (at this point in time.)

Yes, you can have Drupal run in subdomain and have a completely different web site coded on the domain root.

Just make sure that the subdomain is directed at the Drupal root. To be clear, the Drupal root directory is the one that contains the following files:

authorize.php
CHANGELOG.txt
COPYRIGHT.txt
cron.php
.gitignore
.htaccess
includes
index.php
INSTALL.mysql.txt
INSTALL.pgsql.txt
install.php
INSTALL.sqlite.txt
INSTALL.txt
LICENSE.txt
MAINTAINERS.txt
misc
modules
profiles
README.txt
robots.txt
scripts
sites
themes
update.php
UPGRADE.txt
web.config
xmlrpc.php


How can I remove the %20 from a URL evaluted by a contextual filter? I have a contextual filter that is set to evaluate the "Raw value from URL" against my taxonomy term name. The issue is that a few of my taxonomy terms are two or three words long. This results in a URL like:

https://example.com/category/my%20taxonomy%20term

What I want is for my url to be:

https://example.com/category/my-taxonomy-term (but this currently returns no results).

Is there a way to use dashes instead of the %20 in a views contextual filter that uses the "Raw value from URL" setting?

Don't worry, Drupal won't leave you hanging with ugly urls.

1) Open your contextual filter in the admin interface.

2) Expand the "More" section at the bottom.

3) Check "Transform spaces to dashes in URL"

Terms like "my-taxonomy-term" will now be processed as "my taxonomy term"

Bonus: If you need that term to be capitalized for the page title, change "Case" to "Capitalize each word" (also in the "More" section).


Authcache will cache user menu I have used Authcache and memcache to cache pages for authenticated users.

However, I have a user specific menu displayed at top right of every page, and the menu sometimes displayed a wrong users' infomation (avartar, username).

I have checked the Authcache Retrieve menu title using Ajax or ESI option at every menu entry's config page.

I also have tried to generate the menu items in code, but both with no good.

If you serve your menus as blocks then you can use Authcache Block sub module. On the block admin page you will find an Authcache personalization setting.


Config Entity list_builder controller path throws Route Does Not Exist error I have created a custom config entity, which declares a list_builder controller to return a list of the created entities. Before creating a config entity, it renders as expected. Once I create a config entity via its add form, which redirects back to the list_builder controller, the error is thrown. The config entity is saved, but the redirect fails.

Here's the redirect in the config entity form class's ::save() method.

$form_state->setRedirect('my_module.entity.list');

Also, navigating directly to the list_builder controller path throws the same error.

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route
  "entity.config_entity_id.edit_form" does not exist. in
  Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of
  /home/vagrant/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php)

I have no idea where the route entity.config_entity_id.edit_form is coming from. How to resolve the thrown error?

You have somewhere in your code the wrong route.

Probably your route in *.routing.yml is:

entity.my_new_entity.edit_form

But now you are redirecting to

entity.config_entity_id.edit_form

where there is still the placeholder from some example code.


Customize commerce cart form page Task

I have been issued to alter the cart form view Shopping cart form (Commerce Order) on the site.com/cart page of the Drupal 7's commerce module. This includes adding extra choices such as sizes together with simply updating the quantity of each product.

My attempts so far

I've tried overriding commerce_cart_block just realise it was commerce_cart_form that was in charge of the content. Now I've tried a module that's called Commerce Cart View Override and it helps me have a template file called views-view--commerce-cart-form.tpl.php inside my template to display the content.

However I'm not really sure what I'm supposed to do now. In my mind I would override the table that show the items and the form surrounding it. I echo'ed get_defined_vars() in the template just to realise that there are quite many variables passed.

Question

What I desire is an elegant solution that allows me to append more forms to modify existing cart session, all in the /cart page, and also be able to have full control of the current cart table.

What is the ideal way for me to customize the /cart page? Am I on the right path, or there some simplier alternatives that I have missed? Personally I want a coded solution and not a database saved one.

Editing the /cart page in Views

I think this is the expected approach. Note: this assumes you know your way around Views.

Install Commerce Cart View Override, as you've done.
Edit the view named Shopping Cart Form, clone it, change the machine name  to something starting with commerce_cart_form like commerce_cart_form_custom
Select this in the dropdown on the admin page admin/commerce/config/cart-overrides (Administer >> Store >> Configuration >> Cart Overrides), then save.
You can now edit the view that appears on the /cart page by editing this new view. A few non-intuitive tips:

To see a preview in the Views preview, you'll need to enter a shopping cart ID number into the "Preview with contextual filters" box above the preview. You can see some shopping cart ID numbers at /admin/commerce/orders/carts. You just enter the ID number, no other text needed.
To add any views fields from the products, for example product images, you'll need to add a new relationship from Line Items to Products. Under Advanced in the Views UI, under Relationships, click Add, then choose Commerce Line item: Referenced products. Product fields like images and taxonomy tags will then become available under Fields.
A common Commerce Cart configuration confusion: If no "Checkout" button appears for customers who aren't logged in, you need to go to admin/people/permissions and tick the "Anonymous user" box next to "Access checkout"
If you want to change the labels of buttons, for example the "Remove" buttons... that's a whole different story. Form elements are generated in a whole different part of the Drupal ecosystem and put into a View like this pre-rendered, all you can edit in Views is the labels that appear alongside or above the button. To edit the buttons themselves has to be PHP code:

Editing form elements like buttons

In a custom module or your theme's template.php file (remember that if you use a seperate admin theme, your template.php won't have any effect in the views preview, only the customer-facing pages), add something like this (credit):

function yourthemename_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id)  {
  case 'views_form_commerce_cart_form_custom_default':
  //               ^ from here on should match the view machine name from earlier
  //                                         ^ from here, the particular view display, which you can see at the end of the Views UI URL while editting that display
      foreach ($form['edit_delete'] as $row_id => $row) {
        if(isset($form['edit_delete'][$row_id]['#value'])){
            $form['edit_delete'][$row_id]['#value'] = 'New delete button label';
            }
        }

    $form['actions']['checkout']['#value'] = 'New checkout button label';
    $form['actions']['submit']['#value'] = 'New update button label';

  break;
  }
}


Theme function overrides and preprocess functions - for the non-programmer I'm trying to get my head around what these are. I've read a few articles and posts introducing Drupal theming where these are mentioned, but I'm struggling to understand what they are and what they do - each explanation I've seen so far (including on Drupal.org) makes an assumption that I know PHP or have programming experience.

Could someone explain in layman's terms or point to a good, simple-to-understand explanation, please?

Well, the theme layer is PHP, so you will need a minimal understanding of some programming concepts (e.g. what a function is). Especially since you will have to write some basic PHP within them. So the following might not be perfectly suited for a non programmer initally, but I tried to link everything so you can read more about it. Also, add comments if something is not clear.

The theme layer builds upon naming conventions on how to name your functions to have them called automatically. Similar to the so called hooks. At least preprocess functions are a special variant of hooks. I'll come back to that later.

Any module can register theme functions (or templates) by using hook_theme() (You don't need to understand how that works right now). ) For example,  it can basically tell Drupal that it has a theme function called mymodule_fancything. This module is then also responsible for providing the default theme function, which is prefixed with theme_. In the previous example, that module needs to define the function theme_mymodule_fancything.

Later on, that, or any other, module can call that theme function with the function theme() like this: theme('mymodule_fancything', $arg1, $arg2); (D6) or theme('mymodule_fancything, array('arg1' => $arg1, 'arg2' => $arg2));` (D7).

Then, that function will figure out which function to call. First, it will check if there is a theme override for the active theme. That means, a function that is prefixed with themename_ instead of theme_. So in our example, themename_mymodule_fancything. If it finds that function it will call that and if not, it falls back to theme_mymodule_fancything.

As you've seen in the example code, you usually pass a number of arguments to a theme function or a template which contains the data that should be displayed. Sometimes you want to further process/change that information before it's passed to the theme function or the template. Or a module wants to change something of another module. Also because theme functions/templates should not contain any complex PHP processing. Unlike with the mentioned hooks (which can be implemented by all modules and all are called), a theme function can only by overridden once.

That is where preprocess functions come into play. They are invoked by the theme() and receive all arguments passed to that theme function (only in D7) or template. Then they can be altered/extended in any way. There is a large number of rules what preprocess functions are called when but basically, you usually only use one that is specific for a given theme function/template. That looks like this: name_preprocess_hook(&$vars). name can be the name of a module or theme and hook is the name of the template/theme function. There are tons of examples for preprocess functions in core, search for preprocess.

Remember to rebuild theme registry (e.g. with devel.module or by re-saving the theme configuration form).


Theme reply comments differently from node comments (Drupal 7) I am using Drupal 7. I have a question/answer website, I want to theme reply comments differently from node comments. How can I apply a different css theme to differentiate node comments from comment replies? I checked the css class and both node comments and comment replies have the same css class. So how do I add different css class to comment replies and theme them differently?

Clarification: My question is just about theming comment replies differently, like removing borders around them or adding background to all comment replies, while node comments (answers) remain same.

You will have to use the surrounding classes to target the direct comments. Consider a site with the following structure (this is actually based on drupal.org):

...

    ... Node content ...

Comments

      ... Comment content ...

        ... Comment reply ...

...

Node comments can be targeted with the CSS selector .comment-wrapper > .comment. (only target first level childs).

Replies can be targeted with .indented .comment (target all level childs of indented comments).

So have a look at your site's structure and try a similar approach.


How to prepopulate drupal form and still execute a custom submit handler I want to build a custom edit form for a existing node. The edit form should not show all fields and should be populated with the existing field values. Furthermore I want to add a few custom submit buttons. I know I can pre populate the fields with #default_value, but there are quite a lot of fields I have to pre populate like that, so I wanted to pre populate them all at once.

I have made a form function with the following code:

$node = (array)node_load($nid);
$form_state = array();
$form_state['values'] = $node;
$form = node_form($form_state, $node);
drupal_prepare_form('node_form', $form, $form_state);

I have also defined a custom submit button:

   $form['submit_one'] = array(
       '#type' => 'submit',
       '#value' => t('Gereed'),
       '#weight' => 10,
       '#submit' => array('custom_form_submit_one'),
   );

And a submit handler:

 function custom_form_submit_one($form_id, $form_values) {
   watchdog ("Hello","Hello");
 }

When I press the submit button, the submit handler is not called.

When I disable the statement:

$node = (array)node_load($nid);

and I press the submit button, the submit handler is called. However, my form is not pre populated with the values.

Is it possible what I want to do? Can I use a custom form and pre populate the fields (without specifying #default_value for each field)?

Why must you have a separate form? I think a simpler approach would be to modify the existing form on a conditional basis via a form alter hook:

function hook_form_alter(&$form, &$form_state, $form_id) {
  // match our custom content type ('yourContentType_node_form') edit form, and ensure
  // we're editing a specific node
  if ($form_id == 'yourContentType_node_form' && arg(1) == '123') {
    // add new submit buttons
    $form['actions']['submit_one'] = array(
      '#type' => 'submit',
      '#value' => t('Gereed'),
      '#weight' => 10,
      '#submit' => array('custom_form_submit_one'),
    );
  }
}


How do you get dropdown menus with toolbar.module? I'm personally more a fan of the admin_menu style dropdown menus than Drupal 7's toolbar. I was watching a screencast by Randy Fay when I noticed he seems to have the toolbar displaying in a dropdown fashion. Does anyone know how he does that?

Check out the video at 1:50 to see it in action.

Install the admin menu module and activate Administration menu Toolbar style , it's a module in the package of admin menu


Colorbox - Only display some of the images in a gallery I've got colorbox set up and working great, but I'd just like to do one little thing that I can't figure out.  I want to have a colorbox gallery of, for example, a dozen photos, but select three to display on the page.  Once you click one of the three photos on the page, it opens up the colorbox, which allows you to click through all 12 photos.  Is this possible with Colorbox and Drupal 7?

EDIT: I'd like this to be a fix that I can use on a lot of different pages with varying numbers of photos.  Sorry for the ambiguity.

Create a custom template page.
Display the first 3 images - wrap the remaining images in a div that you hide, with css eg:  display: none; or add a hide class to them - attach the gallery_class class to them all so you can call them using

$(".gallery_class").colorbox({rel:'gallery_class'});


how to check files/images which are more than 400 KB Related to QA part of our Drupal site performance, we need to make sure that size of images on the site are not more than 400kb.

I know there will validation and configs we can use while uploading images to site. but for already existing, is there any way to find out images size which are more than specified limit?

A non-code solution would be preferred.

You can try direct SQL query

select fid, filename from file_managed where filemime like 'image/%' and filesize > 400000;


How can I collect data on authenticated versus anonymous traffic? One of the important metrics I miss while planning for performance optimization is the type of traffic my site is receiving. What are the ways for collecting data about the type of traffic? I am mostly interested in anonymous versus authenticated requests.

I think the google analytics module does this out of the box.