Is there an option for radio buttons with Facet API + Search API (database)? I am using several check box facets.  Some of the facets allow me to use check boxes for multiple values.  There is one facet, however, of taxonomy terms for which I want to only allow a single choice; and per the client's spec, it must be a radio button.

I can't seem to figure out how to do that.  I installed the Facet API Select sandbox module, but that just gives me a drop-down box (and what sucks is when I make a selection, I stay locked on that one and don't get the other choices back).  I installed Facet Bonus pack, but the select option from that keeps giving me a PHP error.

I am using Views on top of Search API database.  It may be that I am missing something conceptually, as I am still getting my arms around Facets.

If there isn't an option for radio buttons, then I will contribute a patch to the Facet API Select sandbox module (if it is feasible).  This is for a paid client, so this is happening.

EDIT:  I need to clarify my biz case of what I'm trying to do.  I have 3 facets with check boxes of multiple items to filter down.  On a fourth facet, I provide a list of filters, but need to allow one item to be selected.  So, my choices look like:

Facet 1:  Type of product
   - phone
   - tablet
   - tv

This would filter down the main product category, i.e., single select option the client wants a radio button for.

Facet 2:  Color
   - red
   - blue
   - green
   - black

Facet 3, Facet 4, etc., would be like Facet 2, where the user can select multiple check boxes for the various sub categories.

These facet categories are taxonomy terms, if that matters.

There is a patch for the Facet API Bonus module that adds a radio buttons widget.

The issue with the patch is https://drupal.org/node/2034777

With this patch you also need to use the Facet API module patch mentioned by RajeevK in the comments of your question, which can be found at https://drupal.org/node/1393928

If you try those patches and comment back in those issues with how it worked out for you it will also help progress those issues so that the patches can be committed and you no longer have to use patched modules - a win for all.


How to jump to a specific page in a multipage Webform? I have a multipage Webform, and I'm using Webform Bonus Pack to display a summary at the end before the user finally submits the form.

What I'd like to do is provide "edit" links alongside the various sections of the form data so the user can jump to the page containing those fields.

Does anyone know how I can do this or, failing that, can anyone at least throw me a bone and tell me how Webform decides which page to display after a "next/previous" button is pressed on a multipage form?

I thought I'd be cute and use Javascript to change the value of the hidden "details[page_num]" field to be one greater than the target page, then invoke a click() on the Previous button, but to no avail; it still goes back to the previous (second to last) page. There is a $_POST['details']['page_num'] containing the current page number, but it's apparently not used to determine where the Next and Previous buttons take the form.

I've just published a webform_steps module that provides a navigation bar for multi page webforms. It solves the problem by implementing a submit-handler that simulates the next and previous buttons very similar to how you describe it.

The magic has to happen on the PHP side in the $form_state array.


How create Redirect pattern from old to new URLs? D7: I'm going to update an articles path pattern (/articles/[node:uid] → /post/[new tokens]) but I need redirect users from old path to new one using tokens. And I don't know how to do that.
I tried using the Redirect module, but it allows set only separate URL for each node; no group redirect patterns are allowed. Also the Rules module doesn't allow to set patterns. How can I achieve this?

The problem partially solves by applying "Update url alias" option in admin/content. I do not find out how to show all selected type nodes at one page without pages, because it is terrible slow applying option page by page.
Anyway, by this way, old aliases still exist, work, and don't redirect to new aliases.

You can use the pathauto module to construct your node aliases from tokens (admin/config/search/path/patterns). In addition, there is a setting to tell pathauto to leave the existing alias in place when creating a new one. At admin/config/search/path/settings, you can specify this in the Update action section:


Pass variables to template using hook_block_view_alter() I'm trying the change the homepage path based on the current request. The system_main_block block renders the logo which is linked to the homepage. If the current path starts with /foo/..., I want to change the homepage path to point to /foo instead of the default /.

I want to pass a custom variable to a block using hook_block_view_alter().

The hook gives me the build array and the Block itself as arguments.

How can I add a variable to the build array that I can then access in the view (twig template)?

The build array looks like this:

array
    '#theme' => string 'block'
    '#attributes' =>
        array (size=0)
        empty
    '#contextual_links' =>
        ...
    '#weight' => int -3
    '#configuration' =>
        array (size=4)
            'id' => string 'system_main_block' (length=17)
            'label' => string 'Main page content' (length=17)
            'provider' => string 'system' (length=6)
            'label_display' => string '0' (length=1)
    '#plugin_id' => string 'system_main_block' (length=17)
    '#base_plugin_id' => string 'system_main_block' (length=17)
    '#derivative_plugin_id' => null
    '#id' => string 'my_id' (length=19)
    '#pre_render' =>
        array (size=1)
            0 => string 'Drupal\block\BlockViewBuilder::preRender' (length=40)
    '#block' =>
        object(Drupal\block\Entity\Block)[3592]

I can't see where I can assign an extra variable. Am using the wrong hook?

I think a better option is to override PathProcessorFront::processOutbound():

 public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    // The special path '<front>' links to the default front page.
    if ($path === '/<front>') {
      $path = '/';
    }
    return $path;

Overriding in this case means using a similar outbound pathprocessor with a higher priority and replace '/<front>' or a lower priority and replace '/'.

Edit:

Register the path processor as a service with the tag path_processor_outbound in mymodule.services.yml. This is the core service definition from the example before:

path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']


Intercept 404s for pages in certain path I have a site that regularly adds & removes event nodes based on a third party system. When these nodes are removed, any other articles that link to them get 404 pages. Is there a way I could intercept the 404 results for pages with a certain path and redirect them to the event landing page instead?

I have tried adding the following to template.php but I get a redirect loop

function MYTHEME_preprocess_page(&$vars)
{
    // Redirect expired events
    $status = drupal_get_http_header("status");
    if ($status == "404 Not Found" && preg_match('/\/events\//', request_uri())) {
        drupal_set_message('Sorry, this event is no longer available','error');
        drupal_goto('/events/');
    }
}

Use the Match Redirect module to redirect specific pages that matches urls.

Summary of drupal project page :

This module provides redirecting based on path patterns with wildcards. This functions much like how block page visibility works. You specify a pattern like "old-blog/*" and a target like "new-blog" and all pages under old-blog will be redirected to the page new-blog.

Features
Pattern matching allowing wildcard redirects
Redirect code choice (301, 302, etc)
Filters out existing pages so they won't be redirected (unless overridden)
Loop protection (no chaining redirects allowed)


How can I automatically add a comment to a node with rules Can someone help me with this?

I have created a view that gives me a table of certain fields. Now I would like to add a "bulk operation" that lets users add an automatic comment to that specific node.

I have tried to ad a rule (component) and this was the result.

I have activated PHP-filter mode and tried with a component with "Execute custom PHP code".

The code in the component

<?php
$comment = new stdClass();
$comment->nid = $node->nid; // nid of a node you want to attach a comment to  (er stond 1)
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none
$comment->uid = $user->uid; // user's id, who left the comment
//$comment->mail = 'email@example.com'; // user's email
//$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
//$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
//$comment->hostname = '127.0.01' // OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
//$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject';
$comment->comment_body[$comment->language][0]['value'] = 'Afgehaald'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
//$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = ‘Some value’; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save
comment_submit($comment); // saving a comment
comment_save($comment);
?>

But when I go to the view and execute the operation, he asks for an identifier. But I want him to directly add the comment.

What I mean with the identifier

Can someone help me with this? Or is there another way?

If I'm going right with your requirement that you want an add comment link with every node in view result listing of nodes.

You should add a relation first to that node with comment by using node reference/entity reference by using referece from url widget type.
Your requirement is same like posting answers node on the specific question node.


Migrate old admin's posts to his new user I'm taking over maintenance of a Drupal site but the old admin is staying on as a user.

I need to adjust the ownership of the posts currently under uid 1.

Is this query sufficient or is uid associated with a blog post in other ways?

Is there an admin module for this process?

UPDATE `drupal_node_revisions` r,
`drupal_node` n
SET n.uid = 13392, r.uid = 13392
WHERE
r.uid = 1
AND n.uid = 1
AND n.type = 'blog'
AND r.nid = n.nid

Node data is stored in node table also.. It's a bad practice to change node content directly using sql queries...

You can use Views Bulk Operations (VBO) module to change node authors in bulk...

  This module augments Views by allowing bulk operations to be executed
  on the displayed rows. It does so by showing a checkbox in front of
  each node, and adding a select box containing operations that can be
  applied. Drupal Core or Rules actions can be used.


Real-time preview of node/form in Drupal 7 I'm trying to achieve this in Drupal 7. This is what I need URL for working example (But its not in Drupal).
Requirement - Live Preview with alignment features

From Drupal.Stackexchange I've came across this post 29325 where the user is trying to achieve the similar thing there its mentioned about the Drupal's Live Module but as the description page of the module shows yet its not made up for Drupal 7 and I'm sure this will not fulfill my requirement.
Question:

Rather than Drupal's Live module, is there any other module available?
Can any of the JS/jQuery plugin or library or framework can fulfill my above mentioned requirement?

Note

I've created the left/side panel form using the custom content type hence now, if I can achieve this live preview using some JS plugin/library also then I'm fine with it as I can see that no Drupal module is available for this!

I have started development of a module - Live preview which might be more along the lines of what you're after.

This module provides a more comprehensive, genuine and interactive version of the built-in node preview feature.
The live preview feature requires JavaScript; if JavaScript is disabled it will not apply its triggers, effectively retaining the built-in preview.

It hasn't yet reached a stable release, but it's worth checking out (-dev version should work just fine).


Convert address to multi value during migration I have a migration that imports data into my address field and it works perfect.

  field_address/locality:
    -
      plugin: get
      source: city
  field_address/postal_code:
    -
      plugin: get
      source: postalcode

The problem I am running into is that some data from my source has multiple values in the city so I need to add some logic that if it has multiple cities, create 2 address field values (multi-value).

I was thinking to make a destination plugin. As a proof of concept I tried to edit Drupal\migrate\Plugin\migrate\destination\Entity::getEntity() with the below options but none of them worked:

$row->setDestinationProperty("field_address/locality", ['Chicago', 'Oakbrook']);

$row->setSourceProperty("field_address/locality", [0 => ['value' => 'Chicago'], 1 => ['value' => 'Oakbrook'], []]);

$row->setDestinationProperty("field_address/0/locality", 'Chicago');
$row->setDestinationProperty("field_address/1/locality", 'Oakbrook');

I was able to accomplish this by creating a custom process plugin for the address field.

  field_address:
    -
      plugin: myaddress
      source:
        locality: city
        administrative_area: state
        postal_code: postalcode

<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Maps values for address.
 *
 * @MigrateProcessPlugin(
 *   id = "myaddress"
 * )
 */
class MyAddress extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $parsed = [];
    // If city name has `and` or `or` it will create multiple address items.
    $cities = preg_split("/ (or|and) /", $value[0]);
    foreach ($cities as $city) {
      $data['country_code'] = 'US';
      $data['locality'] = $city;
      $data['administrative_area'] = $value[1];
      $data['postal_code'] = $value[2];
      $parsed[] = $data;
    }

    return $parsed;
  }

}

My plugin checks to see if there is a string and or or and if there is it converts it multiple values.  Of course, this works out for me because all are US and the cities are for the same state.


Drush installed but all commands could not be found I have drush installed on a remote server and was able to successfully run commands this morning, however I tried executing Drush Self-Update and got a permission error probably because I don't have sudo rights etc and now any drush commands I try run return the error The drush command 'drush_command_here' could not be found.
when I run which drush it returns /usr/bin/drush so I know its installed + other users on the server can run drush commands without issue.
I tried adding the drush alias in my .bashrc file like this alias = '/usr/bin/drush' and also tried using the alias pointing to usr/share/drush but no luck.

Ended up uninstalling and re-installing drush and seems to have fixed my problem. Thanks.


What does "The provided host name is not valid for this server" mean? I am running a Drupal 8 website, and when I browse to any page, I get a plain white page with just the following error message on it.

  The provided host name is not valid for this server.

What does this mean?  How do I fix this?

This error message is coming from a feature that was added to Drupal 8 to protect against HTTP Host header attacks.  The feature is also described in the change record that was generated for the patch.

Essentially, it was possible to spoof the HTTP Host header for nefarious purposes, and trick Drupal into using a different domain name in several subsystems (particularly link generation).  In other words, the HTTP Host header needs to be considered user input, and not trusted.

To combat this, a new setting, $settings['trusted_host_patterns'], was added to Drupal 8 to configure a list of "trusted" hostnames that the site can run from.  The setting needs to be an array of regular expression patterns, without delimiters, representing the hostnames you would like to allow to run from.

For example, if you are running your site from a single hostname "www.example.com", then you should add this to your settings (usually found at ./sites/default/settings.php):

$settings['trusted_host_patterns'] = array(
  '^www\.example\.com$',
);

Note the ^, \., and $.  These are PCRE Syntax.  These just mean that you want to match "www.example.com" precisely, with nothing extra at the beginning and end, and that the dots should be treated as dots and not wildcard characters.

If you are running from "example.com", then just use:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
);

If you need to run a site of multiple domains and/or subdomains, and are not doing canonical URL redirection, then your setting would look something like this:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^.+\.example\.com$',
  '^example\.org',
  '^.+\.example\.org',
);

This allows the site to run off of all variants of example.com and example.org, with all subdomains included.

Once you adjust $settings['trusted_host_patterns'] to the proper value, you should be able to browse to your site again.

You can also check on the status of your trusted host settings from the status report page, which is at admin/reports/status

If you remove the setting altogether, the trusted host mechanism will not be used, and you will see an error on the status report page.  In addition, your site may also be vulnerable HTTP Host header attacks.

If you have this setting configured and are seeing this message, then it probably means you have messed up the regular expression syntax.  In this case, take the first example, and copy/paste into your settings, and then edit it to reflect the hostname your site runs from.


Is there a way for a rules execute PHP action to return a value? I would like to be able to stuff the result of the PHP code into a rules variable. Is this possible?

I think that's not possible. More info here: http://drupal.org/node/1415628


How to generate pdf file from a specific type of content? I have a content type named "employees".

I want that when I add an employee(creating content of type employee) it should also generate a pdf file which will contain the data which I inserted during adding content.

And a link on that node appears stated that "Download the pdf".

You can achieve this functionality with print module. For documentation click here.
This module depends on the libraries you can install any of them.
1. dompdf
2. mPDF
3. TCPDF(Best in performance)
4. wkhtmltopdf


How to remove the home link in menu breadcrumb in drupal I am using menu breadcrumb module in my drupal. I get the breadcrumb like as Home>Content>Aboutus but i need a structure like Content>Aboutus.How can i do this

You can check if your theme bring this option in appearance > Theme settings

Or you'll have to use THEME_breadcrumb hook. Here's the zen function, have a look at the bolded part.

function zen_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $output = '';

  // Determine if we are to display the breadcrumb.
  $show_breadcrumb = theme_get_setting('zen_breadcrumb');
  if ($show_breadcrumb == 'yes' || $show_breadcrumb == 'admin' && arg(0) == 'admin') {

    // Optionally get rid of the homepage link.
    $show_breadcrumb_home = theme_get_setting('zen_breadcrumb_home');
    if (!$show_breadcrumb_home) {
      array_shift($breadcrumb);
    }

    // Return the breadcrumb with separators.
    if (!empty($breadcrumb)) {
      $breadcrumb_separator = theme_get_setting('zen_breadcrumb_separator');
      $trailing_separator = $title = '';
      if (theme_get_setting('zen_breadcrumb_title')) {
        $item = menu_get_item();
        if (!empty($item['tab_parent'])) {
          // If we are on a non-default tab, use the tab's title.
          $breadcrumb[] = check_plain($item['title']);
        }
        else {
          $breadcrumb[] = drupal_get_title();
        }
      }
      elseif (theme_get_setting('zen_breadcrumb_trailing')) {
        $trailing_separator = $breadcrumb_separator;
      }

      // Provide a navigational heading to give context for breadcrumb links to
      // screen-reader users.
      if (empty($variables['title'])) {
        $variables['title'] = t('You are here');
      }
      // Unless overridden by a preprocess function, make the heading invisible.
      if (!isset($variables['title_attributes_array']['class'])) {
        $variables['title_attributes_array']['class'][] = 'element-invisible';
      }

      // Build the breadcrumb trail.
      $output = '';
      $output .= '
' . $variables['title'] . '
';
      $output .= '

' . implode($breadcrumb_separator . '

', $breadcrumb) . $trailing_separator . '

';
      $output .= '';
    }
  }

  return $output;
}

Zen provide an option to disable this feature :

$show_breadcrumb_home = theme_get_setting('zen_breadcrumb_home');
if (!$show_breadcrumb_home) {
  array_shift($breadcrumb);
}


Is there a way to display primary tabs vertical in separate block? In Drupal 7 I want to rearrange standart drupal tabs (eg. 'View' and 'Edit') as vertical and move it to sidebar. Is there a way to do this?

The Tabs rendered in page.tpl.php like this:

<?php if ($tabs): ?>

          <?php print render($tabs); ?>

<?php endif; ?>

in the main content div:
You can override the page.tpl.php in your custom theme and move this part of code to sidebar:

something like :

<?php if ($tabs): ?>

              <?php print render($tabs); ?>

    <?php endif; ?>


Sending private messages between users EDITED
The excellent Privatemsg module provides a wealth of functionality but some sites might not need/want this degree of complexity. Rather than starting with something complex and disabling/removing features, I would like to think about ways to build something relatively simple from basics.
Using the basic infrastructure of D7 what are the ways one could create a simple messaging system that allows user A to message user B, and both of these corresponding users to delete this message individually (i.e. user A deletes message 1, but user B does not; therefore user B can still see message 1)?
How might message threads (i.e. successive related messages) be managed and displayed?
How well would the solution scale (e.g. 1,000,000 messages, 100,000 threads, etc.).
Thank you.

By default, giving a role the permission to delete messages will not delete the message for the other user. I just tested this and it works as you require.

As for only allowing messages between certain users, you can prepopulate the "To" field with /messages/new/[nid]. So on the user page or in views or whatever, you can create this link using tokens or replacements.
Then disable the field with a custom module. Savvy users could change the [nid] in the url or even the html in the page so this depends on how secure it needs to be. They'd need to know another user's nid to be able to do this but they can only know that if they can already view the user.

function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_new') {
    $form['recipient']['#disabled'] = '1';
 }
}


Unable to choose an installation profile on a multi-site installation I installed drupal 8 with the open social installation profile using composer. Now I want to turn this drupal install into a multi-site installation where some of the other sites don't use this installation profile. But when creating a new site (I know how to do this from my D6/7 days) I can't select an installation profile. Instead the Open Social installer is always run and it's installation profile always gets applied.
I figured out it is probably due to the vendor stuff that composer does when installing drupal and open social. It changes some things in the vendor folder that change the drupal 8 installation procedure. But the question that remains is if it is possible to still use this install with the standard drupal installation profiles.

Or a perfectly acceptable alternative for me would be to make a base install of drupal8 and afterwards add the opensocial installation profile so I can still choose my installation profiles. I guess that would mean ditching composer? Or maybe not? I don't really know because I am not familiar with how composer changes the drupal workflow from the way I used to work with it in d6/7.

In the .info.yml file, do no put distribution statement, ss mentioned in this guide:

# Optional: Declare your installation profile as a distribution
# This will make the installer auto-select this installation profile.
# The distribution_name property is used in the installer and other places as
# a label for the software being installed.
distribution:
  name: Distribution Name


How can I prevent HTML tags getting rendered as plain text? I have my data from SQL with table HTML tags e.g. <tr> and <td>.
When I render it in Views it displaying all the HTML table tags without rendering it.
I put some code in .module file to pass this data using hook_views_post_execute I tried all the solution but nothing seems to work.
My views field is not rendering as table.

You need to unescape HTML. There are two working ways to accomplish this.
First you can mark your field as "raw" and the html would render correctly.
{{ your_field | raw }} should render ok.

As a second resort you can use twig's autoescape functionality:

{% autoescape false %}
{{ your_field }}
{% endautoescape %}

By this way you are telling twig not to escape html markup.


How should I store a static key pairs list? I wish to store around 200 static key value pairs.

A few ways i can think of, are the following:

 - Using `variable_set()`
 - Using a custom table
 - Using a cache
 - Defining a constant in code
 - hard-coding the key pairs

The list will be referenced on every node. I am using the Views module as well.

How should I store the key pairs list in my case?

Regarding Using variable_get and variable_set

I would suggest storing them in variables tables using variable_set in serailized format.. Store your 200 pairs data in an array using variable_get function...

Variables are cached in cache_bootstrap table so that performance will be improved.

Regarding Custom Table

You will lose the cache ability and managing the rows like edit/insert will be a pain since you need to build logic to retrieve and update results.

Regarding Cache Table

It will be a temporary storage. If some one clears all cache you will lose the data.

Regarding Constant in Code

Yes.. You can use constants too..  I am not sure performance impact vs using variables.

Regarding Hardcoded in code

I believe it's same as using constants. But, If you are trying to hardcode everywhere then you will end up with redundant code which will result in update - data consistency problem.

If you think in Drupal way i will say variables is the way to go using variable_get and variable_set..


Using Invisimail within a Contemplate Template I'm in Drupal 7 and using Contemplate and Invisimail, but I can't figure out how to get my emails to be obfuscated.

I think it is because the display of the node is using the contemplate template, which simply says:

<?php print $node->field_email['und'][0]['email'] ?>

I figure I have to wrap that in a call to invisimail_encode_email, as such:

<?php print invisimail_encode_email($node->field_email['und'][0]['email'], 'html_entities') ?>

but that did not work (error message about undefined array index). So, maybe I'm calling that function with the wrong parameters? or maybe I'm calling the wrong function.

Basically, how do I call invisimal from within php?

I'm doing a similar thing, but in a node template. To get the javascript obscured code to return, use the js_entities encoder similar to this:

<?php
$email = render($content['field_email_address']);

// this takes the email address and turns it into a "mailto:" link, otherwise use 'link' => 0
$email_settings = array('link' => 1);

echo "<p>" . invisimail_encoder_js_entities_encode($email, $email_settings) . "</p>";
?>

Also, I use the Quick Javascript Switcher extension in Chrome to quickly toggle js off/on to see if things like this are working:

https://chrome.google.com/webstore/detail/quick-javascript-switcher/geddoclleiomckbhadiaipdggiiccfje


which hook is effective for setting custom breadcrumbs? I have a theme which sets breadcrumbs like this:

function mytheme_process_node(&$variables) {
    (....)
    drupal_set_breadcrumb($my_breadcrumbs_array);
}

This gets overwritten later by something else. I need a specific taxonomy value of the displayed node to set the breadcrumb, that's why I am using this hook. How to do it effectively? Perhaps there is a hook which is performed later and still has access to the node object?

I normally stick that logic in hook_preprocess_page(), it runs late enough in the page build to not be overwritten by anything else.

You can still get access to the node object by using the menu_get_object() function:

function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    // We're on a node page...
    drupal_set_breadcrumb($my_breadcrumbs_array);
  }
}


Create a landing page as the front I have created a content type called 'landing', however when I try and setup this as my homepage

config/system/site-information to the alias 'landing'

It takes on the node--front.tpl.php as the template rather than my node--landing.tpl.php.

If I look at it in /landing the page looks fine.

I also try and hijack the main landing page by setting this in the .htaccess

DirectoryIndex landing

but no luck - any idea how I can set this custom landing pages as my homepage and retain the template style?

node--front.tpl.php is for the front page specifically.

If you don't want a specific template file to apply to the front page only, simply delete node--front.tpl.php and flush the caches. node--landing.tpl.php will then be used instead.


Search system based on two taxonomy vocabulary for Local Business Directory for Drupal 7 I am new in drupal

I am making a Local Business directory. every business entry is a node (content type "Profile") and I make two taxonomy vocabulary name as "Business-city" and "Business-category" . every node is tagged with two taxonomy term.

Now I want to make search system where user can select "Business City" and "Business category".

Please tell me how can I do this.

Thanks in advance

You need to familiarize yourself with Views module. Simply create a view of nodes of your particular content type, add two filters, one for each taxonomy, expose them and you are done.


adding a description to view accordion I am using a view with the format Views Accordion.
So far, I have a View like so:

  award1
     -person1
    -person2
  ...
  award_n
    -person_n
    -person_n+1

Where award is the "header" or "trigger" of the accordion action.
This works just as intended. I'm trying to extend this further to look something like:

  award1
    This is a description of award1. I'm summarizing award1 here.
    -person1
    -person2
  ...
  award_n
    This is a description of award_n. I'm summarizing award_n here.
    -person_n
    -person_n+1

The problem is when i use views accordion with a description like above i get the not so desired result:

  award1
    This is a description of award1. I'm summarizing award1 here.
    -person1
    This is a description of award1. I'm summarizing award1 here.
    -person2

Where the description and the person are overlapping and/or pushing the content out of the accordion effect. I've thought about using Javascript to insert the description after the award div, but i feel like that is a hacky approach to the solution. Is there a better way to do this?

Following up on Volker's comment, I created a new person with the name "award_name description" and assigned the proper award to the person just created.

In Views Accordion settings I checked the box "Add views row classes
Add the default row classes like views-row-1 to the output."

Style the views-row-1 class to make the description pretty.

I have the setting "Add striping (odd/even), first/last row classes", so i had to edit the CSS to swap even and odd so the description has a white background.

Hope this helps someone with a similar problem!


Drupal page other than main It mightbe a lame question but I want to be able to display a custom page let say: "/news".

So, I created a template named: page--news.tpl.php with my content, some rendered views etc.
Now when I got to this address, I can see my requested content however there are two problems:
- title of the page is "Page not found"
- the search form does not work.

Could anyone explain what is going on? I am on Drupal 7.

BTW. My template contain some html and this section to embed another view:

News

                        <?php echo views_embed_view('news_view_block_more', $display_id = 'block'); ?>

Thank you

If you have created a node, for instance a "Page" node, by going to "Content" => "Add Content", AND have the Path or Pathauto module enabled, you can give that node the path "news" when you are editing it.
Alternately, you can create a view that is a page, and has that path.

Specifically, the Drupal menu router has to have an entry for the path "news", and know what to serve up.  Blocks and templates don't create that path entry.

More information on creating content can be found at:
https://www.drupal.org/node/120635


Render videos in CKEditor (WYSIWYG) I am using Media Module 2.x.alpha2 + File Entity Alpha2

Using WYSIWYG (CKEditor)'s Add Media button I can upload videos but there is no proper file formatter to display it in the page, all I see is:

<source type="video/mp4" src="http://path/sites/default/files/myfile.mp4"></source>
<source type="video/ogg" src="http://path/sites/default/files/SSA50002.ogv"></source>

How can I properly rewrite the code to have a proper formatter etc:

<div id="video_lightbox_myvideo" class="lightbox" style="display: none;">
<embed name="player_1" id="player"
          type="application/x-shockwave-flash"
          pluginspage="http://www.macromedia.com/go/getflashplayer"
          width="800" height="600"
          src="http://path/wel/players/jwflvplayer/player.swf"
          allowfullscreen="true"
          allowscriptaccess="always"
          flashvars="file=' . $video_path . '&fullscreen=true&image=' . $video_preview . '&skin=http://path/wel/players/jwflvplayer/skins/mainley.swf">
          </embed>
 </div>

Instead you can use Wysiwyg Media Embed module to embed videos.

  This is an integration of the CKEditor MediaEmbed plugin for the
  Wysiwyg module.


Add Fields to the Link Module Image here:

I made this with Photoshop. The "URL" field is supposed to be a Link field (the Link module). But it seems that it only provides an optional title field but no way to add fields like this. Or should I create a new node type and add "Quality" and "Provider" fields then reference (the Entity Reference module) that node with this? Seems that adding those two fields are more ideal. Please advise. Thanks.

There is a module just for this, where you can add and group fields together, as well as add multiple field groups: Field Collection


How do I pass the UID in URL to embedded View? Probably a stupid question, but I'm stumped... I have a simple View which lists all terms from a Taxonomy. Within this is a Global Field Type of "View" which is trying to list any content related to the Term, and authored by the UID present in the URL. However I am unable to pass the parameter from the URL to the View using standard Replacement Patterns. I can pass the Term using [!name] but not a parameter from the URL.

So parent view URL is /report

This is called with the UID appeded, e.g.: /report/34

How do I get 34 passed to the embedded view as contextual filter?

Many thanks for any help on this seemingly simple use case!

****** ANSWERED ********

Check Alfred's answer below, but also make sure the order of your Contextual Filters is correct. In this case, I was passing a blank value, rather than NULL value, as the first parameter from the parent view.

Swapping the order of the Contextual Filters over mean't I could pass a NULL value from the parent view (i.e. just the first one). Hope this makes sense.

In an embedded view you typically use the "When the filter value is not available" option for the contextual filter to achieve this.

Select "provide default value" then choose "raw value from URL" and set the path component to be 1.

You should also set validation criteria and select what should happen when the value is missing or incorrect.


Consistent style of user-entered tables Soon I will face a problem of ensuring constant look of tables entered by user throughout the site. I will probably install one of available WYSIWYG editors and allow tables therein.

I would probably want to prepare a set of table templates (with row headers, column headers, row&column headers, with column headers and subheaders, etc...) and would want the user to select appropriate template, determine row&col count, and then just fill in the data.

My task would be ensuring that the tables get appropriate classes upon submit and process them accordingly.

Would you do that with jQuery or with some WYSIWYG editor setup/plugin?

I am facing a similar problem and am developing a custom module to act when the specific content type is generated (hook_node_presave).  My concern is that the more they are required to do to generate the format, the more things will go wrong. All the user has to do is enter the cell contents as delimited rows and the module determines the size of the table and generates all the HTML and class content to match up with the css I have developed for its display.


How do you go about using contexts and a menu page callback? Currently we have a page that is generated by a hook menu page callback. The path is structured like menu/%location_name/menu/%parent_category/%child_category. The function requires at least one of the category wildcards to properly work.

In the page callback we then set up our context's condition which is to determine which of the categories we're in. See code below:

  if(empty($term_parent) == FALSE || empty($term_parent) == FALSE) {
    if ($plugin = context_get_plugin('condition', 'ss_menu_core_condition_default')) {
      if(empty($term_parent) == FALSE && empty($term_child) == TRUE) {
        $context_term = $term_parent->tid;
      } elseif(empty($term_parent) == FALSE && empty($term_child) == FALSE) {
        $context_term = $term_child->tid;
      }
      $plugin->execute($context_term);
    }
  }

Everything up until this point makes a bit of sense to me. And currently it validates fine and I can actually see the context when using context_active_contexts(). Although the gotcha that I must be missing is how do i go about allowing the metatags context module's reaction to use this term for token replacement?

At first the tokens avaliable were pretty generic default site wide things such as current page, current user, date, etc... It wasn't until i found a patch that taxonomy terms ended up showing up as token replacements. But none of them seemed to work as it seemed the context didn't know of what term to use.

This leaves me at a point where I felt like the only solution was to do something hackish and just set my values in the active context as follows:

  $context = context_active_contexts();
  $context['ss_menu_core_menu_sections']->reactions['metatag_context_reaction']['metatags']['und']['description']['value'] = $context_term->description;

This still doesn't feel right at this point since we can't actually use the metatags reaction form to populate the values. If anyone has any ideas that would be amazing.

Thanks.

Take a cue from metatag_context_entity_prepare_view() in that patch.  You need to stuff your desired term entities into the metatag_context_entities static variable in your page callback like so:

drupal_static('metatag_context_entities', array('taxonomy_term', $terms));


how can i create new region in theme? I just want to create a new region in my theme on the top right side of page.
with height = 50 px and width=200 px

i'm using drupal version 7

First you need to define region in your_theme.info https://drupal.org/node/171205#regions

for example

regions[search_bar]         = Top Search bar

then you probably want to output that region in your page.tpl.php:

<?php print render($page['search_bar']); ?>

to make it height = 50 px and width=200 px you need to write some css. You can also add some wrapping div with id:

<?php if ($page['search_bar']): ?>
<div id="search-bar">
    <?php print render($page['search_bar']); ?>
</div>
<?php endif; ?>


How to apply flags retrospectively for group subscriptions using Organic Groups? We've a large site running Drupal 7 with OG, Flag, Rules, etc.

OG uses a subscription model where you have to confirm you want to join a group (or leave a group) so we've decided to move to a Flag system that then uses rules to add (or remove) that user from the group.

All works great, except the site is already live and we have a lot of members in groups already, which obviously Flag doesn't recognise.

Is there a way to force Flag to check if a group subscription exists already?

I seem to understand from your question, that you're looking for a way to flag the existing members of an OG group.

If that's what you want, then a possible approach to make this work, is to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users (of an OG group) that you want to be processed.
add a loop to perform a Rules Action, whereas you just flag each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

PS: if this is NOT what you want, by using this approach (anyway) I believe your question about "Is there a way to force Flag to check if a group subscription exists already?" became obsolete ...


Why does using '#type' => 'text_format' change the position of the field's description? I have a form with a text field which looks like this:

$form['myTextField'] = array(
    '#title' => 'Write here',
    '#type' => 'text_format',
    '#format' => 'filtered_html',
    '#description' => "Description goes here")
);

Now I would like the description to appear bewteen the title and the field, so I tried the technique described here. It works for all the other fields, but not for this one. I can make it work by changing the above code to this:

$form['myTextField'] = array(
    '#title' => 'Write here',
    '#type' => 'textarea',
    '#description' => "Description goes here")
);

The downside of this approach is that I end up with a plain old textarea instead of a text_format, which is what I need.

Any ideas as to why the description appears below the field rather than above it when I use '#type' => 'text_format' as opposed to '#type' => 'textarea'?

text_format is not a single form element that is rendered like textarea, textfield checkbox etc. Instead, it is several form elements (you get two form elements, one to select the filter, and a textarea to enter the actual text).

What you need to do is use the #after_build property to define a function that will enable you to alter the element after it has been built (the two form elements has been created). You can define custom theme function here and move data around in order to output the description and other data exactly how you want to.

Look at the FAPI documentation for more info.

Update

The #after_build on text_formats works a bit differently than expected, as it gets called twice. What you could is:

$form['text_format'] = array(
  '#type' => 'text_format',
  '#title' => t('Body'),
  '#my_description' => t('The text you enter here appears on the page.'),
  '#after_build' => array('after_build'),
);

And then

function after_build($element) {
  if ($element['#type'] == 'textarea') {
    $element['#description'] = $element['#my_description'];
  }
  return $element;
}

The idea is that you create a value for the fake description and convert it to the real description on the text area. What will happen with the normal description value is that is will be added to the filter form element only which is why your theme overrides doesn't work.


How to render a ctools content type programmatically? I have a ctools plugin aka. content-type aka. panel pane. How does one render it programmatically ?

ctools_content_render() is the solution.


Remove comma from unlimited items body in content type i have a content type with multiple body fields. It's works but there is a single comma between the body fields on the rendered page. I can't for the life of me figure out how to remove that god forsaken comma. Pls help!!!

Edit, here is an image to hopefully clarify the output issue I am having:

So, the body is an array:

I need to figure where the array is being rendered so that I can remove the comma that is being used to separate the array.

for anyone else using the progressive theme:
template.php, line 458:
from
  $output .= drupal_render($variables['items'][$i]) . (($i == count($variables['items']) - 1) ? '' : ', ');

to
  $output .= drupal_render($variables['items'][$i]) . (($i == count($variables['items']) - 1) ? '' : '');


Is there a site as good as Smashing Magazine geared towards drupal rather than wordpress? As the title says, I'd like to find a site that is similar to the Smashing Magazine site that caters more to drupal users.

I love this site. I have yet to find a Drupal centered one that keeps me checking the feed so often for quality content.

I'll try any suggestion.

Well I have been trying to make such a website www.techiestuffs.com, but since I haven't found authors to write drupal based content I have scattered the site with categories I am comfortable with. If I find authors I will work with them.


How i can add a new line in my code here? HI guys go to THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE and help how to separate that text in 2 lines

 $form['kkkkkk'] = array(
          '#type'          => 'textfield',
          '#title'         => t('blablabla'),
          '#default_value' => variable_get('kkkkkkkk', ''),
          '#description'   => t('sdakgbflabfgdsbf "THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE" fdghhtrjgvfnbhsgf.'),
          '#required'      => TRUE,
          '#size'          => 10,
          '#required'      => TRUE,
        );

There are two options (simplified code example):

$description = t('Foo.
Bar.'); (recommended)
$description = t('Foo.') . '
' . t('Bar.');

The
 tag causes a line break in HTML. Both options give the same result technically. The difference is in what translators can do with it.

Option 1 treats the sentence as a unity and gives translators more flexibility. For instance, if the French translation needs to change the word order ('Barre.
Fou.'), that's possible. However the French translator would also have the possibility to leave out the line break completely.

Option 2 is more rigid. A translator could never control which part comes before the line break and which part comes after. The translator may not even know that the sentences "Foo." and "Bar." will be combined into a single page element, because they show up as separate strings in the translation interface.


In Drupal 7 Commerce 1.x - is there a way to include the price into the dropdown product select box? Currently the price is outside of the select box on product display's. Is there a way to include the price in the select box itself?

Example:

$5 - Basic Repair - Scratched Disc Recovery

instead of whats below.

Include the price in the product title itself in same way which you want to show in select box.

There are other way, in that you will have fetch the product id of the product reference field in template.php & load full product to get price. Then prepare title again at theme lavel..

For better understanding of what I am talking about, you can see my answer for a question here, where I have explained how to prepare title of node again which include taxonomy. You also have to do something similar like that..

But I will suggest you to follow the first solution of mine means - Include price with title of the product.


How to show a views count for nodes that ar not available to anonymous users I made a view which displays a count for nodes in a nodetype. But anonymous users don't have access to nodes in that type. Those users should be able to view the count. Is there a way to achieve this?

Go to edit screen of your view. In right column, Advanced section, click Query settings.
Check Disable Query Rewritting. Now Drupal permissions will not affect views results.


What's the best way to create variables that are available to every single URL on my site, based on node id or taxonomy id? On Drupal site A we have a bunch of links to non-Drupal site B. For marketing and tracking purposes all these links have a different URL variable appended to them, so that when a user registers on site B we can determine where on site A they came from.

At the moment I use page.tpl.php to create the variable ($forceCode) but it now transpires I need this variable to be available to node.tpl.php too, and I feel like there must be a less hacky and more universal way of doing this, probably using a preprocess function in template.php that right now seems beyond my comprehension level.

PLAIN LANGUAGE EXPLANATION

$specialPages is an array of node IDs that need a special code.
$specialFolders is an array of taxonomy IDs that need a special code.

If the current node ID matches any in the nid array, I set the variable accordingly.
If not then I get the category (taxonomy) of the current node, or if the current page is a taxonomy term itself then use its own tid.

Then using this taxonomy ID I get all other tids that are parents of that tid.
Then I look for matches of any of these taxonomy IDs in my array of special tids in order to set the variable.

If the current page has not matched any of my special nodes or taxonomies, the variable remains its default value.

ACTUAL CODE

// we later restrict our parent taxonomy search to certain types but it's not strictly necessary
$contentTypes = array("article","advpoll","event");

$specialFolders = array(
    276 => "events",
    292 => "free-dating",
    498 => "date-explorer"
);
$specialPages = array(
    22 => "reviews",
    86 => "texting"
);

$forceCode = "default";

// check for specific page first
if (@array_key_exists($node->nid,$specialPages)){
    $forceCode = $specialPages[$node->nid];
} else {
    // there was no entry for this nid, let's check parent terms
    $parentTerms = array();
    $hasParents = false;
    if (arg(0) == "taxonomy") $hasParents = arg(2);
    if (@in_array($node->type,$contentTypes)) {
        $category = field_view_field('node', node_load($node->nid), 'field_category');
        $hasParents = $category['#items'][0]['tid'];
    }
    if ($hasParents !== false) {
        $parents = taxonomy_get_parents_all($hasParents);
        foreach ($parents as $term){
            $parentTerms[] = $term->tid;
        }
    }

    foreach ($parentTerms as $tid){
        if (array_key_exists($tid,$specialFolders)){
            $forceCode = $specialFolders[$tid];
            continue;
        }
    }
}

I've found a very satisfactory solution using function matchtheme_preprocess(&$variables, $hook) which will always supply variables to page and node templates.

The more complicated bit was finding an appropriate way to get this function to collect the data I need (nid or tid) properly regardless of whether it was the page or node template making the call.

Essentially (this is the cut down version) I just did this:

if ($hook == "page"){
    // supplies variables to page.tpl.php
    // the page template can cover anything, including a node and taxonomy
    if (arg(0) == "node"){
        $nidToCheck = arg(1);
    } else if (arg(0) == "taxonomy"){
        // already a taxonomy page, the term id is the category
        $hasParents = arg(2);
    }
} else if ($hook == "node"){
    // supplies variables to node.tpl.php
    $nidToCheck = $variables['elements']['#node']->nid;
}

From there if ($nidToCheck) allows me to use the nid to generate $hasParents for nodes, and then I can move on handling all nodes and taxonomy terms to do what I want (all this bit is essentially the same as in my question).

Finally I feed back to the template an array of variables in much the same way as they were set before.

So glad to have this sorted as it caused quite a headache. Would love to hear whether or not this is an efficient or clever way of dealing with it. The most obvious issue to me is that the array of variables (and of course the whole function) will get run twice on node pages - once for the page template and once for the node template - which is a touch inefficent. I guess I could contain the whole thing in an if (!isset...


How to validate node title field Drupal 7 I want to add validation to the node title field. When the user enters the character X and submits the form they should get a message saying "you are not allowed to enter special character X".

You can setup field/property validations with the module Field validation.

Here's the documentation on how to add validation to properties (with the Field validation module), as the title isn't a field in Drupal 7.


Making rules refresh page when message after one has time to read the message? Issue:
I added a message that should be displayed upon user login using rules. It worked fine only that
 1. The page stuck (showing the message) and you had to refresh and click okay to discarding information upon reload.
 2. The page did refresh but did so immediately so that one did not have more than a split-second to view the message.

Question:
How do you make rules display the system for, say, 5 seconds and then refresh the page? A mixture between the two possible scenarios described above.

You might want to consider

Absolute Messages

  Displays system messages in fully themeable colored horizontal bars on
  top of the page.
  ...
  * messages could be dismissed automatically after a specific time - configurable in module settings for each message type separately,


Contextual Filters and URL Paths I have a taxonomy of region names, and a content type of products. Each product is referenced to a region. I am attempting to create a single view that would show the products for a given region based on the url. For example, http://www.mysite.com/[region-name1]/products and http://www.mysite.com/[region-name2]/products should display products referenced to those specific region. Right now I have the view path set to /%/products, and a contextual filter set, but when I attempt to view the products, I get page not found. (It does work when I am previewing the view).

It works when I set the view path to [region-name]/products for a specific region and don't use a contextual filter, but I am trying to avoid having to create a view for each region if there is a way that I can do it once for all regions.

Arguments don't seem to work in the first position. So /%/product won't work, but /content/%/product will. Just move the argument to at least the second position and all should be fine.


jQuery doesn't work on new hosting I'm using small jQuery script to change src argument on img tag. It works without any problems on my hosting but after migrating website on client's hosting this script doesn't work at all.

I have checked with Firebug and the script is there. I also tried to access to [website]/misc/ui/jquery.ui.core.min.js in browser and jQuery is shown. I tried to install jquery_update module and change versions of jQuery (with and without CDN). None of this helped.

I noticed on 'Status report' page warning because of PHP mbstring extension.

Is this could be the possible reason for not working?

In Firebug my script shows like:

<script><![CDATA[
]]><!--//--><![CDATA[// ><!--

jQuery(document).ready(function() {
    var img;
        img = '/sites/all/themes/ave/img/logo2.png';
        jQuery('.logo-img a img').attr("src", img);
    });

//--><!]]><![CDATA[
]]></script>

Do you have some ideas or maybe similar experience?

Your issue is in this line

img = '/sites/all/themes/ave/img/logo2.png';

It should be something like this:

img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';

and if that does not work just inspect the src param of the image and adjust accordingly.

And perhaps replace the whole script with this:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            var img = location.protocol + "//" + location.host + '/sites/all/themes/ave/img/logo2.png';
            $('.logo-img a img').attr("src", img);

        }
    };

})(jQuery, Drupal, this, this.document);


Drupal Content Type Data Become Label for Field on Another Content Type I'm using Drupal 7, and on my Drupal website I've created a content type. This content type has 2 fields: field name, and code. I need to create another content type, and (on this content type) fields based on the data of the "Name" field of the previous content type.

For example:

Content type ABC: content

Name  | Code
AAAAA | A
ABABA | B
ACACA | C

Content type DEF: fields

AAAAA (widget: textfield)
ABABA (widget: textfield)
ACACA (widget: textfield)

How can I achieve this?

A better way is to use Entity reference

  Provides a field type that can reference arbitrary entities:


How to get all parent menu items' titles of the current node? I know I can load the node's menu item like so:

$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

But to use a menu structure in a breadcrumb I need to load all parent menu items. I feel like the menu service provides such a function but I dont get anything out of the documentation. This here seems pretty mighty but it really lacks documentation.

Edit: I've already came this far:

$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

if (is_array($menu_link) && count($menu_link)) {
  $menu_link = reset($menu_link);
  if ($menu_link->getParent()) {
    $parents = $menu_link_manager->getParentIds($menu_link->getParent());
    dpm($parents);
  }
}

and it gives me:

Array
(
  [menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e] => menu_link_content:2fd24ddd-19e2-4e8f-9764-839b3f51139e
  [menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4] => menu_link_content:e30b827f-bc67-4892-b23f-28b23188ffd4
)

Is there an easy way to get those titles?

Even shorter using the MenuActiveTrailInterface.

$node_id = $node->id();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$currentPluginId = $menu_link->getPluginId();
$trailIds = $this->menuActiveTrail->getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key => $value) {
  if ($value && $value !== $currentPluginId) {
    $breadcrumb->addLink(
      new Link(
        $menu_link_manager->createInstance($value)->getTitle(),
        $menu_link_manager->createInstance($value)->getUrlObject()
      )
    );
  }
}


How to structure theme folder to make it more manageable? So far, I've been able to put page, node, field and block templates in their own separate folders. My idea is that Drupal needs to find the main original tpl file (ie page.tpl.php) in a folder and will then look for the overriding files in that directory. If so, how do I structure a similar thing for my Views templates? Do I create a few folders and put the original files (view-fields.tpl.php etc) in each respective folder?

I'll try my own suggestion and will post back if it works, so that others can benefit from it.

I typically put all TPL's in a templates folder, further subdivided by categories such as views, node, page, etc.

Here's an example folder structure from one of my recent projects:

themename
- fonts
- images
- scripts
- styles
- templates
-- node
-- page
-- user
-- views

Basically, the only thing that goes into the root folder is the .info file, and the template.php file. Everything else is subdivided by category.


How do I set Views Bulk Operations Fieldset Collapsed by default? Using VBO, I am trying to set the Operations Fieldset to collapsed by default. Is there a setting to do this? or a theme override that I can use per view?

Use hook_views_bulk_operations_form_alter()

<?php
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {

 if($form['#form_id'] =='views_form_block_id'){

  $form['operations_fieldset']['#collapsed'] = TRUE;

 }

}
?>


How can I generate a list of the numbers of users with Roles B, C, and D that have Role A? My site has a large number of user roles.  To generate a list that shows the number of users with each role, I created a view of users and set a Contextual Filter to User: Roles and then Display as Summary.  This gives me a list like this:

Role A (23)
Role B (10)
Role C (15)
Role D (7)
Role E (4)

What I would like to do now is to create a new view that shows how many users that have Role A have Role B, C, or D like this:

Role B (4)
Role C (6)
Role D (3)

However, I don't know how to get Display a summary to work in this way.  If I add Filter Criteria such as User: Role, then only the count for that role will be shown.  However, I want to show the count of users for all roles given that the user has Role A.

Use case: On my site, users get roles based on their interests.  They also get roles based on how involved they are on the site (like here on SE).  I want to generate statistics on the role choices of my most active users.

To do this, I ended up having to make several views, each with a filter of Role = A, etc., as suggested by Praveen S's comment.


Is there a way to send password to the user through 'Welcome (awaiting approval)' email? I am working on a Drupal site where, i want to send an email to the user providing him with the password. Is it possible.....?

Dig into these modules and you'll find something worth (quotes included are from their project pages):

Subscriptions:

  ...enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

Notifications:

  ... This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.


Exposed filter in views to filter users by age I have the Birthday module installed that displays the age of users. I am trying to create an exposed filter in a view that will allow users to select from $age1 to $age2. Of course this requires two filters (one min age and one max age) so the view will display all users who fall into that bracket. The Birthday module computes age "on the fly."
Any guidance on how to proceed with this will be greatly appreciated.
Thanks.
:)

You can use the contextual range filter module. to create a filter range for your age field.

  Views Contextual Range Filter is a simple plugin for Views that adds
  the option to contextually filter, not just by a single value, but
  also by range.

  Numeric, alphabetical (string) and list ranges are all supported. Node
  ids, user ids and even taxonomy term ids are all special cases of
  numbers so will work also. Range-filtering on the "created" (posted)
  and "updated" (last modified) node properties is also supported,
  provided you use the correct format as dictated by Views. So, YYYYMMDD
  for full dates or one of the shorter year+month, year-only,
  month-only, week-only and day-only formats.


How to programmatically access the allowed HTML tags in Filtered HTML A bit of an oddball question. In Drupal 7, I have a comment form page that is required to show the allowed HTML tags available to users. The default list has been added to over time so now I have about 40 different tags.

I want to display it programmatically as part of the form, but I cannot give users the option to change the text format (I want them to use the default Filtered HTML) so I've hidden the Text Format portion of the comment form using the Simplify module.

So my question is how can I output the revised list of allowed HTML?

I've rummaged through the filter module, and tried to print the results of filter_filter_info() like so:

$filter = filter_filter_info();
print_r($filter);

but all it returns is the default list of tags that comes with vanilla Drupal, maybe 10 tags or so. It doesn't show my revised list of tags at all.

I've searched for quite some time but can't find any info on how to do this, so any help would be appreciated!

$filters = filter_list_format('filtered_html'); // put your filter name here
$tags = isset($filters['filter_html']) ? $filters['filter_html']->settings['allowed_html'] : FALSE;


Content subscriptions/notifications from multiple terms? I have a clothing site where multiple taxonomy vocabularies are used for content. For example, there are "Boys" and "Girls" terms, and clothing size terms such as "2" "4" "6" etc., as well as "Seasons" and "Sport" vocabularies.

A user only wants to be alerted when "Boys" "4" "Basketball" new content is posted.

I am aware that modules such as Notifications, Subscriptions, Simplenews, etc. exist -- but these only allow for new content notifications based on a single taxonomy term.

Could this be done with Rules (e.g. content type that contains each users' subscribed terms)? Or some other way, perhaps using Flag?

I have a similar use case for my site.  What I do is utilize views loops.  I create a view rule that accepts multiple taxonomy terms (I use AND rather than OR.  I think you would too).  Any user who has all the items in their profile is then sent a PM when on Create New Content.  It's not terribly elegant but it works.  I think it may be a bit too restrictive.  But Them's the breaks.


How do I safely get the internal path to the current site in a multisite setup? I'm working with a multisite Drupal 7 install with many sites. The site accepts both "www." and without via Apache. I'm developing a themes in /sites/all/themes which is used by many of these sites and I want something like this:

$apple_icon =  array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => '/' . path_to_site() . '/apple-touch-icon.png',
      'rel' => 'apple-touch-icon',
    ),
  );
  drupal_add_html_head($apple_icon, 'apple-touch-icon');

where path_to_site gives like /www/drupal7/sites/blah.com etc. depending on the site being used. I need this since each site will need a different icon.

I guess something like '/sites/' . $_SERVER['HTTP_HOST'] and then I can use symlink aliases for the "www." variant.

How can I do this properly?

You can use conf_path to get the path root to the current site - then append the rest of your path to that.

  Returns the configuration path based on the site's hostname, port, and
  pathname.

e.g:

$apple_icon =  array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => base_path() . conf_path() . '/apple-touch-icon.png',
    'rel' => 'apple-touch-icon',
  ),
);
drupal_add_html_head($apple_icon, 'apple-touch-icon');


What could cause a View template to ouput wrong row index? Context
I have a weird issue on my live environment that I have never seen on my local environment. Cache bins are disabled on my local environment and enabled on live server.
When clearing all caches on live server, the problem disappears for some time, then reappears. When disabling cache bins on live server the problem doesn't seem to happen anymore.
Issue
In my custom theme, I use a simple "Single field" template to override a given view field.
/**
 * @file
 * Theme override for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 */

In the output HTML of this field, I need a simple incremental id from 0 to n where n would be the total number of rows in the view results. Something like below for a View with 5 results:

...

...

...

...

...

So in my field template, I use:

...

This works fine, except on some occasions, only on my live server with caching enabled where the output will be for example:

...

...

...

...

...

Important notes:

I sometimes get indices such as 19 when there are only 10 or 15 results in the view so that number seems to come out of the blue.
This happens when the view is filtered using a single taxonomy term.

Question
Am I wrong assuming that row.index should give me an incremental sequence of integers for every view, with or without caching? If I am wrong, then what should I be using? And if not, what could cause this behavior?

To solve it using views-view-field.html.twig
First in view settings, add field "View Result Counter" and hide from display.
Now in your twig you can do

...


How can I debug an email function? I'm using flag_friend module and want to customize the email that is sent after a friend request is made.

What's the best way developing code for email functions like this where you can't just reload the page to see your changes?

I would have to go back, remove the friend request and create a new request to trigger the next email, then wait for the email to arrive.

You could write an automated test with SimpleTest.

Takes quite a bit of initial effort but once you have it, it is a matter of a few seconds to re-run your test.

Simpletest also automatically intercepts sent mails and you can then get them directly in the test with $this->drupalGetMails().

See for example How do I write automated tests for a Drupal site?


Which hook to use to give a user a role after purchasing something in Commerce 2? I made a site that sells services in Commerce 2.  I want to hide access to the "Orders" and "Payment info" pages until a user purchases the first product.

To do this, I created a role, Paid, for users who have purchased something.  This role has permission to view orders and so forth.

Which hook should I use to give the user the Paid role after making a purchase?

In Drupal 8 Commerce is using Event dispatcher instead of hooks.

In this case, you should subscribe into the event named commerce_order.order.assign, the hook invoked then a order is assigned to a user. In this moment you can code to grant the role to the user. You can see an example of how commerce_log submodule from commerce used this event here.

If you need, you have this tutorial which tells you how to subscribe to a event from event dispatcher.


How to edit files without changing the last modified date? One of my sites recently got hacked with the dreaded pharma-hack. The hacker inserted base64_decode'd code into includes/bootstrap.inc

Initially I thought the FTP password was discovered since the password was quite weak.

However, the Hosting providers indicate that there has been no FTP access from other than my I.P. address. And also the file bootstrap.inc's "Last Modified" date has not been changed.

I let the client know to change his FTP password, and he's only done it a day after. However during that time, they changed another file includes/cache.inc (must've realised the code has been removed from bootstrap.inc), but the cache.inc's Last Modified date didn't change either. So now he's (client) changed his FTP password, but I'm worried that this hacker is gaining access not by through FTP, but by some other means.

I've thoroughly went through the site, and haven't noticed any abnormal, or out of place *.php files uploaded into the directories. Maybe I haven't looked hard enough? What other means are there to change a file's contents without using FTP? And how to change a file without changing the modified date?

Drupal 6.

Thanks.

Update: Most likely an FTP breach, as the affected site had a very weak FTP password (8 char only, all lowercase, only alphabets). This was probably done through brute force guessing the password, and then uploading a file that's sort of like a file manager. I seen this file cleverly (well not so I guess) disguised as LICESNE.php (hacker can't spell :) ) and ironically I managed to hack this file and gain access to the administration screen.

From this page you can create new files, modify existing files and run scripts on the server, delete files, manage databases etc. It was a 1 page hacker administration page!

The sites have not had a breach now as I've done the security updates and changed the passwords to secure ones.

Again thanks for all the answers and comments. Much appreciated.

Consider this PHP code:

touch('/path/to/file', strtotime('-1 month'));

That will change a file's modified date to one month ago.

It's pretty easy to mess with the modified date of a file if you've got access to the server, which your hackers obviously have (at least to some degree).


How to set one content type to only one language in a multilingual site? I have a multi language website, it's for both English and Arabic, the site's default language is English, but for specific content type which is blog section of the website. I need to set it's default language to Arabic and to never translate it's content. Is it possible?

Install the Entity Translation module then go to edit your content type and under Publishing options in Multilingual support check the option  Enabled, with field translation

Go to: YOUR_SITE/admin/config/regional/entity_translation and configure your content type like this:

Obviously I select French but in your case you must select Arabic.


How to add onclick event to a link? I need to create a link, which when clicked should be able to set a session variable.

I have used l() function to create the link and tried this but this is not working.

'name' => l(t($n['name']),'edit_details',array('attributes' => array('onclick' =>$_SESSION['id']=$n['id'] ))),

Links do not allow any callback action, you can not set a variable on click event.

Instead you can either make it a custom form, where submit button is themed to look like a link instead of link and on form submission set the value in session.

Or other way would be, if its not secured information, you can pass it as query parameter in URL.


cache : "drush cr" versus admin toolbar "flush all caches" What the drush cr would do that the flush all caches would not?
Particularely regarding block caching?

I got mad trying to set a custom block twig template for eventually figuring out that nothing was wrong with my code but flush all caches was not enough and drush cr would do the job.

https://www.drupal.org/node/2640110

EDIT: could there be a bias of my local dev settings ?

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Drush's cache-rebuild command does the following:

Clears the APC cache
Bootstraps Drupal
Calls drupal_rebuild()
Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

Source: https://drupalize.me/tutorial/clear-drupals-cache?p=2512.

In drupal 8 it is recommended to use cache-rebuild instead of cache-clear.
Your dev settings shouldn't matter for this.

in drupal 8 the drush cc all is deprecated and yo should always use drush cr.


Is it possible to change the value of the field based on the the browser's language? On my Drupal 8 website I have a content type "Video" which has an "Embed Code" field. Later the user is able to watch the video inside the platform. The value for this field usually looks like this:

<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/some_link" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Is there a way to change the source link based on the language of the browser? So for example when the user browser's language is set to "FR", then I would like to append to the emded link the french captions, so that the link looks following ?

https://www.youtube-nocookie.com/embed/some_link?cc_load_policy=1&cc_lang_pref=fr

This is the plugin what also core using for browser language negotiation. You can have a closer look what the plugin exactly does: \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser

The code

$language_negotiation_method_manager = $this->container->get('plugin.manager.language_negotiation_method');
$plugin_id = LanguageNegotiationBrowser::METHOD_ID;
/** @var \Drupal\language\LanguageNegotiationMethodInterface $language_negotiation_method */
$language_negotiation_method = $language_negotiation_method_manager->createInstance($plugin_id);
$request = $this->container->get('request_stack')->getCurrentRequest();
$browser_langcode = $language_negotiation_method->getLangcode($request);

This will either give you back a valid language code or FALSE if the negotiation was unsuccessful.

Regarding the dependencies

$container is only used as an example to show which services are being used.
Request is always present as an argument when you are in a controller.


Change the wording of the registration page I want to change the wording of the default registration page.  I found some posts about completely customizing/re-theming the page but they seemed like total overkill for what I had in mind.  Specifically, this is designed to be a website for only students that go to my school, so I have already set it up so that you can only register with @myschool.edu email address.  But I can't figure out how to let people know that on the registration page.  I am surprised you can't edit the registration page through the configuration module at all.

If you just want to add a few directions at the top/bottom, try creating a custom
 block.  Create a custom block with the instructions you want to add.  On the block configuration page, you can set the path to display only on certain pages.  Set that to user/register.  Then all you have to do is make sure the block is appearing in the appropriate region in your theme.


Bootstrap simple carousel: how to display it on front-end? I've installed Bootstrap simple carousel module and I know how to add/edit slides. But I didn't find anywhere instructions on how to display them on the front-end. Module didn't create any new block, view or something?!?

How to display slide show on the front-end?

If you look at https://git.drupalcode.org/project/bootstrap_simple_carousel/blob/8.x-1.x/src/Plugin/Block/CarouselBlock.php

/**
 * Provides a 'Bootstrap simple carousel' Block.
 *
 * @Block(
 *   id = "bootstrap_simple_carousel_block",
 *   admin_label = @Translation("Bootstrap simple carousel block")
 * )
 */

There is a block for it, called, "Bootstrap simple carousel block". You just have to place it in a region over at /admin/structure/block


Superfish - File not found: sites/all/libraries/superfish/sfsmallscreen.js I just downloaded and enabled the latest (dev) version of superfish module, as well as the library... I am getting the following error:

  File not found: sites/all/libraries/superfish/sfsmallscreen.js

Should I remove this line from the libraries path:

sites/all/libraries/superfish/sftouchscreen.js

Or just download a previous (recommended) version of superfish?

Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js)


drupal site crash and went to maintenance mode While creating a huge volume of pages in drupal website, our live site went down after 5 hours. We investigated logs on Apache, PHP and MySQL thoroughly but couldn't identify any specific cause or error for the site crash.

It's quite possible that your server crashed (ran out of memory).  You can start by restarting MySQL, otherwise just restart the entire server to get things going again.


Adding multiple menus entries to a view We have a view with a page attached to it. By default the settings screen pictured below lets you add only a single menu entry for the view.

Is it possible to have this featured in two or more menus as menu links?

Yes, you can add as many menu items as you like in the menu administration section of the website.

Go to admin/structure/menu
Click the "add link" link for the menu you want to add an item to
Add the menu item to the path you are using for you view.


Removing Baground Link From Slideshow Hello i Am Using Drupal 7 and created  a slideshow using views and views slideshow so in slideshow when a user is clicking the image url is opening you can also check my slideshow at Windowhelpdesk.com When Anyone Clicks on image a url is opening i want to remove that url plz anyone help me to do this

When you add the image field to views, make sure to set it to 'Link image to: Nothing'


Need advice on remote storage for load balanced drupal site Not quite sure if this is the correct thread to be posting this in, so please feel free to move it if its not.

Background:

Our developers have nearly finished developing our Drupal 7 based web application and as with any start up, I am assuming the role of the sys admin, financial controller and everything else under the sun! My experience with Linux is limited to what i've been able to learn through the internet i.e - install and configure apache, mysql, php, memcache, varnish etc.

Current set up:

After having spent the best part of 4 weeks stress / load testing various cloud service providers we ended up with Google Cloud.

2x web servers (8 cores + 7.5gb ram each) running:
- Ubuntu 14.04 LTS
- Apache 2.4 (mpm_event + PHP_FPM)
- Memcache 3.0

1x database server (4 cores + 26GB ram) running:
- MySQL 5.6

1x Load balancer for the two web servers

Problem:

I'm now at the part where I need to decide how / where to run the filesystem for our load balanced Drupal application. As you all know, Drupal stores assets by default on the local disk /sites/default/files. Now, obviously this isn't going to work with a load balanced solution since files that are written to server 1 will not be available to be served from server2.

Potential solutions?

These are the following potential solutions I have thought of:

1) Use the Amazon S3 module for Drupal which allows the application to both write and read from an S3 bucket. This seems to be the easiest solution, but i'm a bit reluctant after having spent a lot of time configuring my servers for speed and performance. That extra bit of time its going to take Drupal to write to S3 is what worries me and the fact that I have less control over the situation.

2) This is where my inexperience in terms of implementation lacks, but the second option would be to spin up another instance, mount it to the servers (is it possible to mount another server to both web servers??). Then change Drupal so that it writes to that mounted filesystem. (This seems more performant, but not sure whether possible and certainly a more complex task).

3) Use rsync between the two web servers. Again, my experience with rsync is very limited and i'm not sure whether it would be able to read / write fast enough.

So, that is my current dilemma. And any input whatsoever would be greatly appreciated.

Thank you!

Upon further research, I decided to boot up another VM instance and mount my two web servers to it then installed NFS server and client respectively. This seems to work very well.


Submit data into database I have read a great deal and trying to learn how to get data into a table in the db. I have the below code to test entering just the first name of someone and I am getting an error. I have tried to follow the examples.module but I am missing something. I would appreciate a nudge in the right direction...

function ghost_form_form_submit($form, &$form_state) {
$entity_id = db_insert('field_data_field_first_name') // database table name
  ->fields(array(
    'field_first_name_value' => $form_state['values']['field_first_name_value'],
  ))
  ->execute();

drupal_set_message(t('Your form entry has been added'));
}

Here is the complete form code...
https://gist.github.com/anonymous/f6d8dc19a3eed0f56d59

The only error I get in watchdog is the $entity_id. However I am not sure what I am missing.
Thanks

This message is probably because you missed some database fields in your insert query (we do not know the field type and what exactly you are trying to achieve). Other than that, it is very odd that you attempt to insert a record directly in a Drupal field's table as this not how it is meant to be used. As per Clive's comment, this can lead to data inconsistencies, cache issues etc.

So I would strongly recommend you to take a good look at Drupal examples on how to define a custom table using Schema API, or even better take a look at this guide on using the Entity API, which you allow you to properly utilize Drupal Fields with your own custom module. Third option is to use the API of an existing module such as nodes, users etc. so that you properly save the field's value.


How to make links to private directory always use ssl? I am trying to connect all links to files in a private directory to use SSL.

This is what I have done so far;

if (preg_match('!^system/files/webform/([^/]+)(/.*)?!', $path, $matches)) {

    if($_SERVER['SERVER_PORT'] != '443') {
       header('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
       exit();
    }

}

This forces private directory file links to use https but it has some issues for users who are not logged into the site.

Depending on where you've placed the above code (e.g. a hook_init invocation), it might not trigger for an anonymous user if caching is involved on your site.

An alternative to this approach is to do it at the web server level so that any request that matches a URL pattern will always switch over to HTTPS. For example, with Apache RewriteRule you could do the following:

  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^system/files/webform/(.*)$ https://www.example.com/system/files/webform/$1 [R=301,L]


custom template for entity as referenced entity I have a node type for which I have a custom tpl. OK.

But this node type I also have as a referenced entity in another nodetype. And in this case I need another custom tpl.

Is it possible to have another tpl and if yes: how do I name this file?

What you can do is to add a custom view mode for your node type, and then use the new view mode for your entity reference field. You have a couple of options, depending on whether you want to code a custom module, or stick with available contrib modules.

The entity view modes module will allow you to add your new view mode, or you can use hook_entity_info to programatically add a new view mode in a module you write yourself. This article provides an example of adding a view mode with hook_entity_info:

function acme_view_modes_entity_info_alter(&$entity_info) {
  // Define the view modes
  $entity_info['node']['view modes'] += array(
    'featured_story' => array(
      'label' => t('Featured Story'),
      'custom settings' => TRUE,
    ),
    'secondary_story' => array(
      'label' => t('Secondary Story'),
      'custom settings' => TRUE,
    ),
    // Define more in this array as needed, e.g. tertiary_story
  );
}

That same article also provides an overview of adding theme hook suggestions so you can supply the name you want to use for your template (the entity view modes module will handle this step for you).

For selecting the new view mode to use for the display of your entity reference, which you do on the "manage display" tab of your content type that includes the entity reference field, choose "Rendered Entity" as the Format for the field's display, then a settings-gear button will appear to the right of it. Click that button and among the available settings will be a select element to choose the view mode.


Adding translation to a custom module I cannot make the module translation strings to be considered, unistalling and installing the module again.

Is the indicated .po relative path correct?

in my module blockForm function i have :

  $form['retrieval_method'] = array(
    '#type' => 'fieldset',
    '#title' => $this->t('Retrieval Method'),
  );

my .info.yml

name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: 'amu_hal'
interface translation project: amu_hal
interface translation server pattern: modules/amu_hal/translations/%language.po

and in

  /sites/mysite/modules/amu_hal/translations/fr.po :

msgid "Retrieval Method"

msgstr "Méthode d'extraction"

i have activated the core interface traduction module and the

  /fr/admin/reports/translations

tells me Missing translations for 11 projects:

amu hal (8.x-3.0). File not found at modules/amu_hal/translations/fr.po

Thanks to comments and doc , i have moved the whole module in modules/custom/ and for info file:

name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: amu_hal
'interface translation project': amu_hal
'interface translation server pattern': modules/custom/amu_hal/translations/amu_hal-%language.po

Placing the po file at

  modules/custom/mymodule/translations/mymodule-fr.po

now i could update the translation at

  /fr/admin/reports/translations

and make string translations

Note that the same po file is not found if the module is placed in sites/mysite/module


How do I overwrite the page? I used the CCK module to create a content type that has three fields (title, description, and body). I want to overwrite two pages: one is where there is a "create content" navigation located on the left page; the other one is where I click  on "Create page" and which displays the form page.

To alter a node edit from, you need to create a custom module that implements hook_form_alter(), using code similar to the following one:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    $node = $form['#node'];
    // ...
    // @todo Add the code you need.
    // ...
  }
}

For examples of actual implementations of hook_form_alter() that alter the node edit form, see book_form_alter(), locale_form_alter() (which alters also other forms), menu_form_alter(), path_form_alter(), and taxonomy_form_alter().


Locked out of my local site after transfer I put an old site on my new machine and got it up and running, except for clean URLs. The login creds in my notes didn't work so (after a few attempts) I used mysql via drush to change the password, no dice. I also checked to be sure I had the correct user1 name and it is. Though all this, the account got blocked because of all the login attempts, which I also tried to remedy via drush, however it alert still says the account is blocked and I still can't login. I don't know where to go from here.... please help.

well you can first

drush upwd --password="yourNewPassword" UserName

to reset your password.

then you would need to remove the attempts so you can try to login again, you need to truncate the table flood.

TRUNCATE TABLE flood


How to change value of a node field after a webform is submitted? I have a content type "items" with a Select list field with the options 0|Free and 1|Reserved.

I am trying to change the fields value from 0 (default) to 1 when a certain webform is submitted (the webform gets the Nid from the url).

For this I have made (and enabled) a custom module (by following a tutorial I found) with the code below:

function reservable_item_change_status_webform_submission_insert($node,$submission) {
  if($node->nid == 5){ //my webform has an id of 5
    $nodeID = $submission->data[3]['value']['0'];
    $reservableItem = node_load($nodeID);
    if($reservableItem ->type == 'items'){
      $reservableItem->field_item_status['und'][0]['value'] = 1;
      node_save($reservableItem);
    }
  }
}

My problem is that nothing is happening. No errors, but the field status is not being changed to reserved.

I am using Webform version 3.2 because the tutorial stated it was meant for Webform 3.x. I will test with 4.x after I get this working.

Any help would be greatly appreciated.

If typo:

if($reservableItem ->type == 'items'){

change into:

if($reservableItem->type == 'items'){

In my implementation I get the submission values like:

$submission->data[3][0]

So try to change it accordingly


How to display 01, 02... instead of Jan, Feb... on Select List with Date I use Drupal7.
I have a profile2's field, named "Birthday".
I set the FIELD TYPE as Date. And, I set Custom input format as "Y-m-d" under "More settings and values" on field edit page. This is because, simply, I want the select list displayed like "2015 07 20(year month day)".
But, on user registration page, it is displayed as "2015 Jul 20". As I wrote, I want to display 01, 02... instead of Jan, Feb... on Select List.
Did I do anything wrong? I apologize if this is an obvious question to you. But, I've been searching the solution for hours and don't find yet. Any tips will be appreciated.Thank you in advance.

I have noticed that same issue that the data entry is not actually showing the data entry points that you want it to when entering items in your form. The data is stored in the data base the way you would like but this is more of a theme item I believe. So since you are using the Data API (I think, if not just turn on the Date API and this should work) you can fix this at the theme level and show the data entry the way you would like. The date API offers a hook that you can use called hook_date_select_process_alter() and you should be able to show the data the way you would like in the front end using this hook.

I would not use string overrides module for this b/c as you state you will change the months everywhere, that is not a good thing.

The code to do this (Would be placed in your theme's template.php file Make sure to clear your site cache after adding this):

/**
 * Implements hook_date_select_process_alter().
 */
function THEMENAME_date_select_process_alter(&$element, &$form_state, $context) {
  // dpm($element); // Uncomment to see before render array.
  // Loop through months and change options to numerical options.
  foreach (date_month_names_untranslated() as $key => $month) {
    // Change #options array, key is built with data API function (The same way that the Date API does this).
    // The sprintf() function is used to make things like 1 into 01 since this is technically a string.
    $element['month']['#options'][$key] = sprintf('%02s', $key);
  }
  // dpm($element); // Uncomment to see after render array.
}

You can use the $context variable above to limit this to certain forms like the node edit form ($context['form']['#node_edit_form'] is TRUE on the node edit form) or the form id ($context['form']['#form_id']) would equal your form id. I think that this is almost the way that the Date API intends you to change these items since they offer these hooks.


Transfer money between users? Is there a way with Drupal to transfer money between users? Im making a skill sharing website, so users can buy and sell their skills. Thanks

I think the Ubercart funds module that is the best answer for your question; the module still has a development snapshot only, though.

This will make you able to transfer funds through your drupal sites to different users.

  Ubercart Funds implements a Site Funds Management System using Ubercart, It integrates features like Deposit Funds, Withdraw Funds, Transfer Funds..etc, which makes implementing most features of a Money site like Paypal or Skrill possible and easy using Drupal.


Workflow and Organic Groups. How can you email the next state changer when content is posted? I would like to notify someone with editor permissions that a user has posted content in the workflow.  I found a token for the current state updating user ([workflow-current-state-updating-user-mail]]), but nothing for the next user in line.

I've seen reference to using rules to send email to all users of a particular role, but I need something more like 'send email to users of a role who belong to the current group'.

Is this possible?

Solved this by writing a module to create a custom token from a field added to the group_node_form.  I followed this tutorial, making adaptations for organic groups:  http://rbayliss.net/story/creating-tokens-drupal-6