How do I pass a variable via drupal_goto()? So I have a function having http://link/to/$id as destination link.

It works when I use Targeted.

But I need to change it to submit form because I need to pass more than one $id. So, I thought it was good to use drupal_goto() rather than the link option.

drupal_goto('mymodule/option/$id');
drupal_goto('mymodule/option/'.$id);
drupal_goto('mymodule/option/', $id);

Those are not working. It always go to http://link/mymodule/option without passing $id variable. How do I do this correctly?

Assume your url is like in this example:

http://example.com/somepage?param1=val1&param2=val2

In that case you can take values of param1 and param2 like so:

$param1 = $_GET['param1'];
$param2 = $_GET['param2'];

You may use this parameter for drupal_goto as

drupal_goto("path_here", array("param1" => $param1, "param2" => $param2));

For Drupal 7:

As YPCrumble says you need to use this code:

drupal_goto("path_here", array("query" => array("param1" => $param1, "param2" => $param2)));

For more details, refer to the API Documentation.


Drush pm-download removing the destination folder I'm creating a system to easily create new Drupal sites, using drush.
When I'm creating a new site, I just point the path where drush should create it and run drush pm-download drupal-7.12 --destination=/var/www --drupal-project-rename=test11 (example) on it.
I saw that drush deletes the folder and then creates it again. Most of the time I still need the files that are in the folder (e.g. 404.html, 403.html etc)

There's any way I could use pm-download without deleting the current files in the folder?

Thanks

-- Info:

Drush version: 5

This sort of request is best made in the issue queue, since what you are requesting is a change in behavior in Drush.  The default behavior for pm-download is to always provide a clean unaltered copy of the module; I for one would be reluctant to alter this behavior, but I could potentially get behind a new option that introduced 'merge' behavior.

A better option, I think, would be for you to download Drupal to a temporary folder, and do the merge yourself in your script as a secondary step.


Capture IP and URL of referrer This code is adapted from /core/modules/statistics/statistics.php. It uses a JavaScript file that sends an uncached POST request to the server (to ensure the code within gets run for every page request).

I want my code within to capture the IP and URL of the referrer. I've tried many things to grab this information and write it to the log, but no luck.

Whatever I do, I get a variation on Error: Call to a member function *something* on null in.... Like, I'm not getting anything. For example, the below throws: Error: Call to a member function getClientIp() on null in main() (line 26 of....

Any ideas?

<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
// use Symfony\Component\HttpFoundation\RequestStack;
// use Symfony\Component\HttpFoundation;

chdir('../..');

$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();

// $container = $kernel->getContainer;

// $request = $kernel->getContainer()->get('request_stack')->getCurrentRequest();
// $request = $kernel->requestStack->getCurrentRequest();

// $url = \Drupal::request()->server->get('HTTP_REFERER');

// $hostname = $request->getClientIP();
// $hostname = \Drupal::request()->getClientIp();

\Drupal::logger('sitelog')->notice(REQUEST_TIME);

Working code:

<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

chdir('../..');

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

$hostname = $request->getClientIP();
$url = $request->server->get('HTTP_REFERER');

\Drupal::logger('sitelog')->notice($hostname . ' - ' . $url);

You are almost there, here is a rewritten version of your code that should work:

<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

$client_ip = $request->getClientIP();
$headers = $request->server->getHeaders();
$referer_url = isset($headers['HTTP_REFERER']) ? $headers['HTTP_REFERER'] : '';

\Drupal::logger('sitelog')->notice($referer_url . '::' . $client_ip);

The main idea of the rewrite is to keep a reference to the HttpFoundation\Request from the very beginning and use if to get access to the parameters you want.

P.S.: Loading Symfony's components as well as booting Drupal's kernel may be an overkill for getting the client's IP and referer url, a simple php script could do that for you and write logs in a file.


Lightbox 2 - Embeded Media Field / Media : Youtube can't play videos on LightBox2 I tried using both 'Embed media field' and 'Media : Youtube' module in D& website to create a content-type field to embed youtube videos and play in on lightbox2. Although images work well with the lightbox, there is some problem with videos.I enabling the videos settings under configuration/User interface/Lightbox2 but is of no use.

All i want is to play youtube videos in the lightbox

You can install Embedded Media Field  module and Video Embed Field module.

Then add a cck field of type "Video Embed" and widget "Video" for a content type.

In that field you can enter the youtube video url. Then display that node in lightbox and it will work fine to play in the lightbox.


Page not found error when using panels I'm trying to add a block to an existing panel. The dialog opens but then I see this error,

  The requested page "/panels/ajax/editor/select-content/panels_page_wizard:landing_page/bottom" could not be found.

and the ajax spinner never stops. The panel module is currently up to date, and google doesn't return any hits for the error.

I can create a brand new panel page, and the same problem occurs.

Turned on logging and saw Rejected-By-UrlScan next to the 404 errors.

Since our site is hosted in IIS, I needed to go into URLScan config, and allow colons, which are used by the Panels ajax func

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

; :   ; Don't allow alternate stream access


Access $display_submitted in page template Is there a way to access a node's $display_submitted Boolean value from within a page.tpl.php?

While normally done in node.tpl.php, if the page is a node view page, the $node variable is also available in page.tpl.php

You can then use something like:

if (isset($node)) {
  // Check if display submitted variable is set for this node type
  if (variable_get('node_submitted_'. $node->type, 0)) {
    // Do stuff
  }
}

An alternative approach would be adding the required logic instead to an implementation of

hook_preprocess_page

Bonus update: You can see the $node variable added to page.tpl.php in core template_preprocess_page

if ($node = menu_get_object()) {
  $variables['node'] = $node;
}


Views field filter handler I have two tables: one that stores field with numeric values and another one that stores field with percentage value.

Is it possible to create view field that would store the multiplication result of these two fields? And is it possible to add such field to the filter criteria?

There are two ways to do this that come to mind:

Use Computed Fields: https://drupal.org/project/computed_field. I haven't personally used this module but I've seen it recommended a number of times. You could create a hidden field on each piece of content which computes the value you desire. Then this can be used in the view as easily as any other field for both display and filtering.
Use views_php field: https://drupal.org/project/views_php. This will show up in the view options as 'Global: PHP' and will allow you to do pretty much anything with your data that you want to. The authors caution it's use because it's pretty easy to mess things up. I've found it to be a quick solution to problems. (As a side note, the most recent release of this functions differently in what variables it allows you to access, so be careful if doing updates. I would suggest using the most recent version.) Your code could be as simple as this in the output box:

<?php
$new_value = $row->value_1 * $row->value_2;
print $new_value;
?>

Then you could create a "Global: PHP" sort by with something like this:

$first = $row1->value_1 * $row1->value_2;
$second = $row2->value_1 * $row2->value_2;

if ($first > $second) {
  return 1;
}elseif ($first < $second){
  return -1;
}else{
  return 0;
}


Make page.tpl.php and page--front.tpl.php share same html Is there a way to make page.tpl.php and page--front.tpl.php share the same template base?

If any of you are familiar with the Twig templating engine, You can define blocks with {% block content %}Node Content{% endblock %} and then do something like:

{% extends 'page.html.twig' %}
{% block content %}Home Page Stuff{% endblock %}

Does PHPTemplate have anything equivalent? I tried using PHP's include() but it doesn't work.

The theme system works by looking for templates that are a precise matches for the current path and then falling back to looking for less and less precise pages.

If you

delete your page--front.tpl.php
clear the cache

Then phptemplate should use page.tpl.php for your front page.


Concatenate two fieds in an EntityQuery condition I'm trying to query some nodes by a given string checking if the string is either in the node title OR if the string is an exact match of concatenating the value of two strings.

I know this should be possible in normal mysql but not sure it can be translated in an entity query. Has anyone stumbled upon this problem before?

Is there some sort of 'free text' condition which is not tied up to fields.

At the moment the below code complains about the fact that CONCAT_WS(...) is not a field which is true.

Maybe there is a simpler solution to this but I'm just not seeing it.

$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'CONTENT_TYPE');

$group = $query->orConditionGroup()
        ->condition('title', $string , 'CONTAINS')
        ->condition("CONCAT_WS('',FIELD_1,FIELD_2)", $string);

$query->condition($group);
$nids = $query->execute();

I don't think it's possible this way.
I would rather split the $string in two parts, and check the two fields with each part.

$query->condition("FIELD_1)", $string_1);
$query->condition("FIELD_2)", $string_2);

You have many ways to separate the string in two.
Is this helping you ?


Drupal services forbbiden error on put but not on post I'm using Drupal Services Module to upload data to my site. It works good on local host, and I can do PUT and POST without problems. But after upload my site to a shared hosting, I can do POST, but PUT always get "Forbidden" errors. For exmple, when I try to update a taxonomy term, it returns "Forbbiden. You don't have permission to access taxonomy_term/2601", where 2601 is a taxonomy term previously created with POST and the same web service's user. And this user has permission to edit this term.
Any suggestion? Thanks.

Assuming it is an apache web server you could try this in your .htaccess file.

<Limit GET POST PUT DELETE>
  Allow from all
</Limit>

Otherwise you may need to contact the hosting support to see if they have restricted PUT requests


How can I make an order generated through Services invoke hooks or checkout complete? I am stuck at integrating a Drupal Commerce store with Services.

I setup a REST server. In several steps I can login, create a user, create user shipping/billing profiles, create an order, add line-items to that order. This works fine, even a correct total gets calculated. I then need a bunch of rules and some hooks to get triggered to make invoicing happen and to send out emails. This fails. I tried to trigger this by changing the order status. Maybe I haven't done it right.

Drupal 7 Modules I use:

Services
Commerce Services
Services Entity

How can I make a D7 Drupal Commerce order generated through Services invoke hooks and rules? To make it simpler: How can I invoke the checkout complete process through services?

So, for anyone looking for a solution, here is what I did after asking for help in IRC #drupal-commerce:

Don't use the order status, don't use a checkout-status. Use something (an entity) as a trigger that is necessary for creating the order. I picked the last action provided via .json-file, POSTing a line-item. As soon as this is known by Drupal, all corresponding rules start their work, and some hooks respectively.

Sidenote: I learned something else also and wished to have been pointed to that earlier: Next time I will not use the above mentioned modules again. They're buggy and obsolete in D8 anyway since the concurring RESTws module became part of core.


How to print a table create with views, using a submit button below the view? I created a custom template for my views (table) and I inserted a button below the table.

By clicking on that button I would like the table to be shown in a new page, from which that table can be printed.

Or to say it in another way: I want to embed to new page via such button.

How can I do this?

If I am interpreting this correctly, you want to click on a link and then have a page painted on your screen with JUST the view in it, no other blocks of information, just a clean display of the view information so the user can right click (or what have you) and then print this page and have it printed out without all that extra "stuff" on the page.

If that is correct, what you would need to do is:

Have a link created in your table that links to another page, let's call it print/thisview.
In the Views UI, create a duplicate page display that calls the view in question with print/thisview as the path.
In your theme, create a page-print-thisview.tpl.php template that contains only the content region, none of the other regions.
Clear all caches.

Now, if all is correct in the world, meaning I have oversimplified this a great deal, when you click on that link, it will paint the screen in a clean format that is nice for printing.


Field available only when a value from a Hierarchical Select is chosen I am using the Hierarchical Select module to allow users to first select a continent and then a country. I wish to enable a field only when a user selects North America (first selection) and USA (second selection).
I hope someone could explain how I achieve this.

I created a module that implemented the node_validate function and from the values selected determined if child taxonomies existed when the form was submitted. If they did then obviously the user had not made a selection from the second drop down list.
This is the code I wrote.
function mp_admin_node_validate($node, $form, &$form_state) {
    if ($form["#form_id"]=="jobs_node_form") {
        $loc = taxonomy_get_children( $node->field_tax_regions[und][0][tid]);
        if ((count($loc)>0) && ($loc)) {
            form_set_error("field_tax_regions", t('Location region is required.'));
        }
    }
}


How to change the default navigation "active-trail" class to something different (or add an extra class)? How do I change the default "active-trail" class on the navigation menu <li>-item to something different, or add an extra class to the current active item?

You can use the theme_menu_link function to add or remove classes from menu items. This will target all menu's on the page though.

Probably easiest is to target the menu directly with this function theme_menu_link__main_menu. You have to put display your menu as a block though. For bartik there is already a block available.

Steps

Uncheck Main menu at admin/appearance/settings/bartik
Put main menu block in a region (e.g. header region)
Now you can do:

function bartik_menu_link__main_menu (&$variables) {
  $link = $variables['element'];
   if (isset($link)) {
    if (isset($link['#attributes'])) {
     $link_classes = $link['#attributes']['class'];
     if (in_array('active-trail', $link_classes)) {
      $variables['element']['#attributes']['class'][] = 'myclass';
     }
    }
   }
 return theme_menu_link($variables);
}

If you want to style the main menu when it's not in a block you could use:

function bartik_links__system_main_menu($variables) {
  $links = $variables['links'];
  if ($links) {
    foreach ($links as $link) {
      $link_classes = $link['attributes']['class'];
      if (in_array('active-trail', $link_classes)) {
        // add or remove classes here
      }
    }
  }
  // return themed links
}


Hook for altering secondary local tasks hook_menu_local_tasks() works for the top level tabs, but the secondary tabs don't seem to have an equivalent. Does anyone know how I can modify those?

$primary = menu_local_tasks(0);

$secondary = menu_local_tasks(1);

See: http://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_local_tasks/7

It's actually not a hook, it's just a function that gathers the items while in context.

There is a hook to alter the items: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_local_tasks_alter/7


export search_api settings with features I used features to export search_api settings and in the feature_module.features.inc file was code that started like below:

I am trying to do the same thing again and I can't find the option to export these settings in features any more. Any idea how to do it?

>   /**  * Implements hook_default_search_api_index().  */ function
> vimn_search_default_search_api_index() {   $items = array();
> $items['node_search'] = entity_import('search_api_index', '{
>     "name" : "Node search",
>     "machine_name" : "node_search",
>     "description" : null,
>     "server" : "solr",
>     "item_type" : "node",
>     "options" : {
>       "index_directly" : 0,
>       "cron_limit" : "50",
>       "fields" : {
>         "nid" : { "type" : "integer" },
>         "title" : { "type" : "text" },
>         "created" : { "type" : "date" },
>         "changed" : { "type" : "date" },

I was having this problem today too.  Features would not display my search_api index for export.  It also wasn't displaying my Page Manager pages, Page Manager handlers, or Views.

I realized the problem was that I had moved all of those configurations into a custom module.  Features wouldn't try to export anything that is module-provided, even if those items had been created through that site's UI in the first place.

I disabled the module (without un-installing) and Features was happy to let me export my index configuration after that.


How can I render a token within a token via rules mail action? I want to send a node via rules. I can send it using the [node:body] token. However, I want to be able to use tokens in the actual node body as well. (Note: These are not global tokens)

Think of it like a newsletter and in the body field I am using

Dear [field_ef_first_name], ...

I can get the token to render if I put it directly in the rules action mail message body, but if it is in the node body field itself, it doesn't render.

The name field is coming form a views rule loop.

Rule exported:

{ "rules_send_newsletter_when_published" : {
"LABEL" : "Send newsletter when published",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--blog" : { "bundle" : "blog" } },
"DO" : [
  { "VIEW LOOP" : {
      "VIEW" : "entityforms",
      "DISPLAY" : "views_rules_1",
      "ROW VARIABLES" : {
        "field_ef_email" : { "email" : "Email" },
        "field_ef_first_name" : { "first_name" : "First Name" }
      },
      "DO" : [
        { "mail" : {
            "to" : "[email:value]",
            "subject" : "[node:title]",
            "message" : "[node:body]",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]

}
}

Using tokens within the body of a node, combined with using [node:body] in a Rules Action, will only result in the token being included as is (without rendering). However, based on what you're trying to do, you may want to have a look at an entirely different approach to achieve your goal ...

Enable the Forena module (disclosure: I'm a co-maintainer), and have a look at Active Users Email (using FRX syntax), which is one of the samples included in the module (which can be used to eMail a template message body to all registered users).

These are the parts in this FRX file that are relevant to the question here:

The datablock drupal/active_users, which is (just) an SQL statement that looks like so:

--ACCESS=access administration pages

SELECT uid, name, mail, login, status

FROM {users}

WHERE status=1 order by name
The frx:foreach="*", which will cause an iteration for each row included in the results of the data block, for everything inside that div (related to the datablock).
The div with class="email-body", which starts with Dear {name}, and which includes a replacement token indicated with {name}.
The line with <frx:doc type="email" />, to enable document format "Send eMail".

After you enabled the module, and visit the relative path at /reports/drupaladmin.sample_active_users_letter, this is what will happen:

Run the SQL query (as contained in the datablock).
Iterate over each of the results returned by the datablock (SQL statement).
For each iteration resolve all the tokens (i.e. as within that Dear {name}).
Display how the eMail will actually look like (for each iteration).
Add link (upper right) titled "eMail". If you actually click that "eMail" link, a confirmation screen will be shown with these details:

number of eMails that will be eMailed (= number of rows in the datablock).
radio button to either send an eMail, or actually send all eMails.

With the above in mind, this is what you'd need to get it to work for your case:

Clone the delivered sample, and tune it as detailed below.
Adapt the datablock to retrieve the desired data (columns), similar to what your view is doing. Or create a new one that fits your needs and use that one instead. Make sure to include the data related to your field_ef_email and field_ef_first_name.
Adapt the From, To and Subject to fit your needs.
Use whatever tokens you need, anywhere in the Body of your eMail. E.g. to replace that Dear {name}. If you need more, or other, data, just add an appropriate name to your datablock (as an extra column). As a sample, here is part of an FRX file I created to transform webform submissions into some kind of followup-eMail to each of those who submitted the form:

Hello,

thank you for using our form (with node id = {node}) to submit your feedback (with submission id = {submission}). You're now confirmed via the eMail Id you entered (= {fieldvalue}) to receive eMails from us.

We'll get back to you shortly for an additional followup eMail.


Is it possible to load a webform that is using a specific custom handler? I have a custom handler for one of our webforms, it may be re-used for other webforms. It integrates with a 3rd party API and sends the response back to Drupal.
I have to save the submissions to handle the response.
I`m wondering if its possible to load all webforms which are using this custom handler?
My goal is delete submissions of those webforms when they are older than a certain time.

You can use the next code:
$webforms = \Drupal::entityTypeManager()->getStorage('webform')->loadMultiple();
  foreach ($webforms as $webform) {
    foreach ($webform->getHandlers() as $handler) {
      if ($handler->getPluginId() == 'your_custom_handler') {
        // do your logic.
        break;
      }
    }
  }


Rendering addressfield In my Drupal 7 commerce website, I have my checkout page which will add my billing and shipping profiles. I need to just display my shipping address and billing address, instead of input fields. (Data fed from an ERP backend.)

So I've hidden al the input fields. Now I want to render the addresfield value and add it to my form just for display. But I seem to be unable to do so.

I  have the following code in my form alter:

  $handlers = array('address' => 'address');
  $context = array('mode' => 'render');
  $address_render_array = addressfield_generate($form['customer_profile_shipping']['customer_profile']['#value']->commerce_customer_address,
                            $handlers, $context);
  dpm($address_render_array, 'render arr');
  dpm(drupal_render($address_render_array), 'rendered');

However drupal_render() returns an empty string and I do not understand why. I've tried to X-debug, and I saw strangely enough that #access vars where FALSE, but I'm not finding out why.

After which I want to display it in my form

Something like

$form['my-address'] = array('#markup' => $renderedaddress);

I used

  $output = field_view_field('commerce_customer_profile', $form['customer_profile_shipping']['customer_profile']['#value'], 'commerce_customer_address');
  $form['customer_profile_shipping']['rendered_address'] = array(
    '#prefix' => '
',
    '#markup' => render($output),
    '#suffix' => '
'
  );


SQL query to display a particular content type? I want to create a view which displays a list of a particular content type. I only have access to the database and I need to figure out the list of content type through view; therefore, I am thinking to write SQL for it. Is it possible to do?

I am using Drupal 6.

List all content types

To build a list of all your content types in a Drupal 6 site, use an SQL query like so:

SELECT * FROM `node_type`

The values in the type column in the results you get, corresponds to the machine name for each of the content types you have in your site.

List all nodes of a particular content type

Here is an SQL query to display a list of nodes of content type story in a Drupal 6 site:

SELECT *  FROM `node` WHERE `type` = 'story'

Change story to the machine name of your particular content type (= any of the values in the type column from the first SQL above).


Upgrading multiple modules at once crashes the process Just upgraded from 7.18 to 7.23 and selected to upgrade all modules and all I got is neverending 'Preparing to update your site' on Installing updates page on /authorize.php?batch=1&op=start&id=40

So what if I refresh page or something will the site crash or something?

UPDATE: It just crashed after like 20 minutes of nothing and I got this error:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /authorize.php?batch=1&id=40&op=do StatusText: Service unavailable (with message) ResponseText: PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {queue} WHERE (item_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 8656 ) in SystemQueue->deleteItem() (line 273 of /modules/system/system.queue.inc).Uncaught exception thrown in shutdown function.PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {batch} SET batch=:db_update_placeholder_0 WHERE (bid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] =&gt; a:12:{s:4:&quot;sets&quot;;a:1:{i:0;a:15:{s:7:&quot;sandbox&quot;;a:0:{}s:7:&quot;results&quot;;a:2:{s:3:&quot;log&quot;;a:1:{s:5:&quot;views&quot;;a:1:{i:0;a:2:{s:7:&quot;message&quot;;s:57:&quot;Installed &lt;em class=&quot;placeholder&quot;&gt;views&lt;/em&gt; successfully&quot;;s:7:&quot;success&quot;;b:1;}}}s:5:&quot;tasks&quot;;a:0:{}}s:7:&quot;success&quot;;b:0;s:5:&quot;start&quot;;d:1377856599.71076107025146484375;s:7:&quot;elapsed&quot;;i:0;s:5:&quot;title&quot;;s:18:&quot;Installing updates&quot;;s:12:&quot;init_message&quot;;s:40:&quot;Preparing to update your site&lt;br/&gt;&amp;nbsp;&quot;;s:8:&quot;finished&quot;;s:38:&quot;update_authorize_update_batch_finished&quot;;s:4:&quot;file&quot;;s:35:&quot;modules/update/update.authorize.inc&quot;;s:16:&quot;progress_message&quot;;s:29:&quot;Completed @current of @total.&quot;;s:13:&quot;error_message&quot;;s:22:&quot;An error has occurred.&quot;;s:3:&quot;css&quot;;a:0:{}s:5:&quot;total&quot;;i:12;s:5:&quot;count&quot;;i:12;s:5:&quot;queue&quot;;a:2:{s:4:&quot;name&quot;;s:17:&quot;drupal_batch:40:0&quot;;s:5:&quot;class&quot;;s:10:&quot;BatchQueue&quot;;}}}s:16:&quot;has_form_submits&quot;;b:0;s:11:&quot;current_set&quot;;i:0;s:11:&quot;progressive&quot;;b:1;s:3:&quot;url&quot;;s:36:&quot;/authorize.php?batch=1&quot;;s:11:&quot;url_options&quot;;a:0:{}s:10:&quot;source_url&quot;;s:0:&quot;&quot;;s:8:&quot;redirect&quot;;s:28:&quot;/authorize.php&quot;;s:5:&quot;theme&quot;;s:5:&quot;seven&quot;;s:17:&quot;redirect_callback&quot;;s:11:&quot;drupal_goto&quot;;s:2:&quot;id&quot;;s:2:&quot;40&quot;;s:13:&quot;error_message&quot;;s:110:&quot;Please continue to &lt;a href=&quot;/authorize.php?batch=1&amp;amp;id=40&amp;amp;op=finished&quot;&gt;the error page&lt;/a&gt;&quot;;} [:db_condition_placeholder_0] =&gt; 40 ) in _batch_shutdown() (line 537 of /includes/batch.inc).

If you have drush try running drush updatedb.

Errors you are getting you should restore backup of your site and update modules one by one.

You can also login phpmyadmin and try to optimize and cleanup mysql if you don't have a copy as it seems your db is crashing and it could be pending database updates. If you don't have drush try going to yoursite.com/update.php to run db updates.

If at all possible use drush for managing your site gives you option to update as well as rollback any updates.


How to deploy translations in code? As the title states, I want to export the translations in code and deploy it with a version control system like GIT.

We have a multi-language Drupal system (English and German) and we have Localization Update module installed.

While some modules doesn't even have a German translations, some are insufficient and some translations are not how we like to have them.

So I add/edit the translations using the UI under admin/config/regional/translate/translate and I can export them into a de.po file under admin/config/regional/translate/export.

I don't know really where to put this file and commit/push so that I can update the languages on other development and production environments.

We have a 3 stage development environment. Local - Dev - Pro. I do all things in local and push to Dev.

But with translations I couldn't get this workflow. Everytime I update a string's translation, I do it on every environment manually and this is not a perfect way. There must be something I'm missing.

You could use Features Translations:

  Features Translations adds a new Features component called
  Translations that allows to import/export sets of translated strings.
  String sets can be chosen per language and per text group.


How to configure trusted patterns for localhost:8082/d8multisite.com? I have my drupal site running on localhost:8012. My url looks something like this : localhost:8012/d8multisite.com/ . I tried the following for enabling trusted_host_patterns.
$settings['trusted_host_patterns'] = array(
  '^d8multisite/.com$',
  '^localhost:8012//d8multisite/.com$',
  '^localhost/:8012//d8multisite/.com$',
  '^localhost/:8012//d8multisite/.com//$',
);

I don't have much knowledge of regular expressions. I have been following the official Drupal 8 documentation for reference. Please guide me as to where am I going wrong. Any help would be much appreciated.
Thanks.

The trusted_host_patterns settings is only for the domain name used to access the site. The regular expression you use must not include neither the port used to access the site, nor any path. If you access the site using as localhost, then the setting you should use is the following one.
$settings['trusted_host_patterns'] = array(
  '^localhost$',
);

If the site is accessible either as localhost or d8multisite.com, and you want to be able to access the site using both of them, then you should use the following setting.
$settings['trusted_host_patterns'] = array(
  '^localhost$',
  '^d8multisite\.com$',
);

Since the dot has a special meaning in a regular expression (it matches any single character), you need to escape it, so it is considered a normal character. To do so, you need to use . not /..


How to remove title 'Navigation' from Navigation menu in Drupal 7? How to remove title 'Navigation' from Navigation menu in the left column?

You can click "edit block" or go to the Blocks administration page and enter '<none>' for block title for the Navigation block.


Hide the number of products on the shopping cart when it is empty I copy the file "commerce-cart-block.html.twig" in my sub-theme. Currently it displays my shopping cart with the number of products inside.

I want that when there is no product in it, the shopping cart remains displayed and the number disappears.

How to do this ?

      {{ count }}

  {% if content %}

        {{ content }}

        {{ links }}

  {% endif %}

Could you not add an if around the  tag containing the {{ count }}?

since you are using Drupal 8, you can use Twig filters. One way could be like below.

{% if count > 0 %}
    {{ count }}
{% endif %}


How to trigger a Rules action based on which content pane of a panel is used? I have a page with a path like www.example.com/newsroom. On this page nodes are displayed with help of 2 different views:

View 1 : contains voted nodes by user.
View 2 : contains not voted nodes by user.

The 2 views are content panes and www.example.com/newsroom is a panel page. So there is no difference in the path of both views, and the user can see both views together.

I am using the Rules module to perform some action when vote is cast on any of node. And using Rules one can check the path from where a user performs an action on a node, simply by using the token [site:current-page:url]. But  in my case that is www.example.com/newsroom (no matter where the vote is related to).

Is there any way that I can differentiate if a node on that page is voted from via View 1 or View 2? As [site:current-page:url] returns path www.example.com/newsroom ... Based on which view it is, I want Rules to perform different actions. So how to check in Rules if the node being voted on is from View 1 or View 2?

I do have different classes of both views, but I'm not sure how to check those with Rules.

Any suggestions?

Have a look at the Rules panes module. Some details about it (from its project page):

Rules Panes allow embedding Rules components as content panes in Panels (or so).
By default any parameters for the component are entered manually by the end user, but they can also be pre-populated with CTools contexts on the page (which will also hide the form input).

So if you can find a way to transform your "... rules to perform some action ..." in a Rules component, you should be good to go.
Some pointers to some more docu/demos about it (also mentioned on its project page):

Videos introducing this module.
Presentation from DrupalCamp Stockholm 2013.
Video about Rules panes.


Duplicating content blocks Is there a way to clone or make copies of blocks?

For example, we have some blocks that are quite bespoke. We need to make multiple copies of them so we can display certain content within them on different pages.

You can use the entity_clone module, which allows you to clone entities.

You can also clone blocks


Get all commerce product types I am creating a module that needs to add a number of fields to all commerce product types.
In Drupal 7, I used the function commerce_product_types() to get all the types and than used that, but I can't seem to find the equialent in Drupal 8. So, I have commerce product type 'default', but I also have 'radios', and 'computers'. I don't know how many types there will be on the website, so it needs to automatically detect all types.

Use this:

/**
* Get all product types
* @return array
*/
public function getProductTypes() {
   $product_types = \Drupal\commerce_product\Entity\ProductType::loadMultiple();
   return array_keys($product_types);
}


Display region's blocks into user-profile.tpl.php I created a view listing content type called stories. Then I created a block with this view.

In mytheme.info file I have this code :

regions[header] = Header
regions[story] = Story
regions[content] = Content

So I put the view into the Story region

I want to display the region into user-profile.tpl.php so I add this code :

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

If everything work, it should display all the stories via the view.

I don't know why it does not work.

Thanks for your help !

If you would like to show blocks only on the profile page and not on the user/register or user/login or or user/*/edit, you can use the code for blocks visibility.

<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && is_numeric(arg(1)) && (arg(2) == NULL) )
{
  return TRUE;
}

else {
  return FALSE;
}
?>


Create user programatically after e-mail verification I am programatically creating user with this code:

    $new_user = array(
        'name' => $state['unique_name'],
        'mail' => $state['values']['email'],
        'pass' => $state['values']['password'],
        'status' => 1,
        'init' => $state['values']['email'],
        'roles' => array($role->rid => $role->name),
    );

    $account = user_save(NULL, $new_user);
    _user_mail_notify('register_pending_approval', $account);

This code is creating user and should send verification email, after which user should be able to log in. Problem is that users are able to log in immediately.

  Please note that I work on localhost and cannot send email from
  localhost. I will have very little time to test site on real server,
  so I would like to know the solution in advance.

The solution could be this approach:

  The only way I was able to accomplish this was by setting the users' status to 0, then sending a custom email with a link to a custom verification page. The link contains the ID of the user and a hash of a private key concatenated with the user's email. On the verification page, I pull the user's email from the database based on the ID in the URL, concatenate the private key to the email and hash it, if the hash matches the hash in the URL, I set the user's status to 1, enabling the user to login.

But the next question is how to generate that "private key" from user database datas and from email link. I can't see any private key of user in drupal database.

you don't get private keys from the database because Drupal doesn't store them.

try looking up in settings.php for the $drupal_hash_salt variable. that's the one used to encode/decode strings.

hope this helps.

cheers


How to escape strings before insert query? I've used mysql_real_escape_string() to make strings safe before using Drupal.

Must I escape string before inserting it to database? If the answer is yes, then how must I do it?

I use something like this to insert into database:

\Drupal\Core\Database\Database::setActiveConnection('mydb');
$connection = \Drupal\Core\Database\Database::getConnection();
db_insert($table_name)->fields(array(
'myfield1' => 'My String',
))->execute();
\Drupal\Core\Database\Database::setActiveConnection();

No need to worry about escaping. The Drupal database abstraction layer is taking care of query parameter escaping by turning them into placeholders and escaping the data.


I'm having a problem getting Context to work properly I'm having a kind of weird problem with the Context module in my Drupal 7 environment.  I have the module installed and enabled, however, when I go to Structure --> Context --> Add, the Add Context Admin UI appears and under "Conditions" whenever I select one of the choices, the box to the right of it does not activate like it should, so I cannot put in a path or whatever.  Nothing at all happens.  It's the exact same for the "Reactions" as well.

It works fine in my development environment and the environment with the problem was migrated from the development environment, so I don't understand why it won't work.

I have tried completely uninstalling the module (including deleting the 'Context' folder from the server) and re-downloading and re-installing, flushing the caches, etc.  Everything I can think of and I still get the problem.

Is this a problem anyone else has seen and how do I fix it?

Thanks

I had the same problem with the "blocks" section.

In the blocks section, you need to select the block(s) you want to add in a template region from the right panel where there is a list of all the blocks. Then click the + sign of the corresponding region.

As for the condition problem, that is weird have you tried in different browser?


Where can I find my edit profile file I'll try to make this as simple as possible.

I use Drupal Commons and want to add this code:

if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
}

to my profile user's profile page.

Does anyone know where I can find that?

What I want to do: https://www.drupal.org/node/942014

I've not used this particular distro, or module... there's not a block that already contains the user badges? There are several places you could add the code, there might be more:

Add a user_profile.tpl.php template to your theme, add the code in there.
Create a simple custom block with the code. You might have to get a reference to the User. I think your module would have to provide that (I don't think it is in the variables available to blocks)
Using a preprocess function for the profile in your theme. Might best work in combination with the tpl.
(not recommended) uses php filter, and put the php directly in a block.


How to make XML sitemap to work after transfer from localhost? My XML sitemap module was installed and enabled long time ago when I just started to make my website on WAMP/ localhost.....

Now the site is live and on real host and domain; but sitemap is still on:

http://localhost/zen/sitemap.xml with 1050 links....

Error loading stylesheet: An unknown error has occurred (805303f4)http://localhost/zen/sitemap.xsl

And I don't see any option to change it's path....

What should I do?

Can I somehow correct it's path or I have to reinstall?

If I reinstall, what happens with all settings?

Did you define base_url in settings.php file? Try to set your current website address for base_url, then clear cache and run cron to generate sitemap. If this doesn't work, backup your database and run SQL query as:

UPDATE variable SET value='s:99:"http://example.com";' WHERE name='xmlsitemap_base_url';

Where the 99 is the length of your domain (including the http and all) and example.com is your domain.


How to implement User roles for specific taxonomies? Some info about what I'm working on:

I have a taxonomy on my site called 'countries'.
I have three 'countries' terms: "UK", "USA", "AUS"
I have created a new user role in Drupal 7 called 'countries_admin'.

What I am trying to achieve:

I want to be able to add three countries_admins and assign each one a country (and be able to easily add more users when I add more terms).
The user should only be able to create/view/edit/delete nodes which are in this term.

My question:

Any suggestions about how to do this?

Note: I have tried Taxonomy Access Control but it seems that I'd have to create a new user role for each country, which isn't really what I wanted.

It appears to me that there are 2 ways to answer your question. Read on for more details ...

Option 1: The Organic Groups module

Organic Groups is a possible answer to your question. It is probably the module that most users are familiar with.

If you're not familiar (enough/yet) with Organic Groups, then reviewing the amazing set of (free) videos to Learn Organic Groups might help.

Option 2: The Group module

Maybe you want to give it a try to use the Group module, which is like an alternative for Organic Groups. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Resources:

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Comparing both modules

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".


How to change new theme for a content type Requirements: Create content type based theme.

I have a requirement to create content based theme, I mean if the content type is article then node view call theme-1 and if type is basic page then node view call theme-2

ThemeKey module can do this:

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
...


Get a module version for a list of modules Context

Drush version 8.x
Drupal 7 site

Problem

Mr. HtraenuRekaos has a text file with a list of Drupal contrib modules.
He wants to get the recommended-install version of all the modules in the list.
This list is not associated with any pre-existing site, and none of the modules are currently installed.

Non-solutions

Mr. H has already looked at this SO post: Using wget to get the latest module version, but he does not want to use wget, he wants to use drush
Mr. H does not want to actually download or install the relevant modules, he only wants to get a list with the latest recommended D7.x version.

Question(s)

Is there a drush command that will turn before into after?

Before

MODULE_NAME_HERE    ;; RECCO_VERSION_HERE
contrib_module_001   ;;   __blank__
foobar_module        ;;   __blank__
htraenurekaos        ;;   __blank__

After

MODULE_NAME_HERE    ;; RECCO_VERSION_HERE
contrib_module_001   ;;   7.x-1.6
foobar_module        ;;   7.x-2.2
htraenurekaos        ;;   7.x-3.6

Mr. H does not want to actually download or install the relevant modules, he only wants to get a list with the latest recommended D7.x version.

Well, at the very least, you can do:

drush @site.env up module_name --select for individual modules, you can also do:

drush @site.env pm-releases which has a load of options for output.

https://drushcommands.com/drush-8x/pm/pm-releases/

It has format options.


setErrorByName not working properly if field is in #details In a form, some fields are defined in '#details':

$form['person2'] = [
  '#type' => 'details',
  '#title' => t('Person2'),
];
$form['person2']['lastname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Last Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('lastname2') ? $this->store->get('lastname2') : '',
];
$form['person2']['firstname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('First Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('firstname2') ? $this->store->get('firstname2') : '',
];
$form['person2']['email2'] = [
  '#type' => 'email',
  '#title' => $this->t('Email'),
  '#size' => 64,
  '#default_value' => $this->store->get('email2') ? $this->store->get('email2') : '',
  '#weight' => $weight,
];

In validateForm() I have some controls: if one of the fields has a value, the others should have one too.
I use setErrorByName but I can't have the faulty field highlighted in red, though the control fires as expected...
Here is the code:

  if (!$form_state->getValue('firstname2')) {
    $form_state->setErrorByName('lastname2', $this->t('This field is required.'));
  }

Answer provided by Clive in comment is the correct one.

$form_state->setErrorByName('person2][lastname2', $this->t('This field is required.'));

Though if you just want to make the field required it would be better to do:

$form['person2']['lastname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Last Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('lastname2') ? $this->store->get('lastname2') : '',
  '#required' => true,
];


Implement a Facebook login without breaking the privacy Like everybody knows Facebook ignores the privacy compleatly.

So I would like to allow users to login via Facebook without breaking their privacy or non Facebook users. Curriently I'm using the modules Fbconnect, OpenID Selector, OpenID Selector for Drupal login and OpenID Selector for Facebook Connect.

I want to allow the users to log in like in stack exchange. This works almost so like expected except the Facebook stuff. The plugin adds to everypage a stupid link to Facebook. So Facebook can spy my users. How can I avoid that?

Is it possible that I download the http://connect.facebook.net/xx_XX/all.js script and put it on my space? Or maybe to proxy the access and cache the file. Does anyone know if some of my ideas are forbidden by Facebook?

I can suggest you a module called Janrain engage drupal.org/project/rpx , this does not add links, it helps you during the registration to collect the user data as well. Have a look to it.


After Update to 8.5.6, "Add" Links Missing From Page but still are in router I recently manually updated Drupal to the 8.5.6 version.  I did this by moveing over the files (using command line) according to Drupal.org instructions and running update.php.

I have two issues that I'm guessing are related:

My themes no longer toggle from the front end and I can't force them to change by clearing cache, running cron, rebuilding menu or anything else that I can think of.
All "add" links are missing ** - "Node/add" is present in the routing file and still works.  However, it is missing from the content page. It also seems that ALL "add" links are missing from the site. To get there, I need to manually type in the path.

I am running out of obvious ideas on how to fix.  Can anyone point me in the right direction?

I followed the instructions below:

Drupal Page on Running Installation Manually

Below, you can see the commands Drupal tells you to follow:

cd /path/to/your/drupal/directory
rm -rf core vendor
rm -f *.* .[a-z]*
wget https://www.drupal.org/files/projects/drupal-x.y.z.tar.gz
tar -zxvf drupal-x.y.z.tar.gz
cd drupal-x.y.z
cp -R core vendor /path/to/your/drupal/directory
cp *.* .[a-z]* /path/to/your/drupal/directory

Thank you everyone for your feedback.

We ended up wiping the whole server and starting over.  I had done various updates manually by dragging and dropping. We re-installed Drupal and this time around used composer and drush.  That solved the issue. I was not able to ever FINALLY diagnose what happened.


Set default value of Search form block to be searched terms So I have the Search form block in my template, but after performing a search it doesn't show the query in the form field.

How do I set the default value on search results to be the query?

i.e if I search "cats"..on the search results box, I want "cats" to remain in the search box.

Just like it does on Drupal Answers :)

For the regular search block, the preprocessing function template_preprocess_search_block_form() runs (you can find it in the search.module file of the core search module), which assigns the search terms you've entered to the $key variable which is used by the function building the search form.

You should include your own preprocessing function (named appropriately to run before your own template file) which performs a similar task to initialize any variables you need/use (you can even grab the code from the one cited above).  Since it sounds like you want to have the keywords printed, make sure the $key variable is actually set...  If you have a custom theme, you can just include the preprocessing function in your theme's template.php file.

Does that help?  Let us know if that works!

=========== ANSWER ADDITION ====================

OK, so here's what I've just tested that does work.  I've added a search preprocessor to my custom theme in the template.php file.  If you just copy this (with your own theme's name prefixed), it should work after you clear your cache.

I actually had to bang my head against the wall for a little bit.  At first I just copied the preprocessing function exactly from the search module, with the exception of setting the field's value to the search term in that first line (since it doesn't do that be default)... But nothing rendered.  Then I realized I had to add that second line I've commented on to set the '#printed' property to false, so that drupal_render() will render them again.  Soooo... I don't know if this is a good solution or not.  There may be a better way, but this is all I can think of and it works...

Again, in short, this is my copying the search module's preprocessing function and making the two line edits I've commented on by saying 'ADDED THIS LINE' to get the extra functionality.  Hope that makes sense.

function YOUR_THEME_preprocess_search_block_form(&$variables) {
// ADDED THIS LINE -- get the search term from the URL, so you can use that as the value of the search box text field
  $variables['form']['search_block_form']['#value'] = arg(2);

  $variables['search'] = array();
  $hidden = array();
  // Provide variables named after form keys so themers can print each element independently.
  foreach (element_children($variables['form']) as $key) {
    $type = $variables['form'][$key]['#type'];
// ADDED THIS LINE -- these fields have already been rendered by the search module's preprocessing function, so they won't render again here unless you do this...
    $variables['form'][$key]['#printed'] = FALSE;
    if ($type == 'hidden' || $type == 'token') {
      $hidden[] = drupal_render($variables['form'][$key]);
    }
    else {
      $variables['search'][$key] = drupal_render($variables['form'][$key]);
    }
  }
  // Hidden form elements have no value to themers. No need for separation.
  $variables['search']['hidden'] = implode($hidden);
  // Collect all form elements to make it easier to print the whole form.
  $variables['search_form'] = implode($variables['search']);
}

p.s. The above would obviously make the change for all search block forms on your site...


Dynamically remove library based on user role, cache context not working I want to remove all libraries of modules & themes, except those from modules/themes that are defined by me.
This should only be done for anonymous users. All libraries should be served to authenticated users.

I'm adding the user.roles cache context in the html preprocess hook and remove all library definitions that are not desired:

/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(array &$variables) {
  $variables['page']['#cache']['contexts'][] = 'user.roles';
}

/**
 * Implements hook_library_info_alter().
 */
function mytheme_library_info_alter(array &$libraries, $module) {
  /* Remove all libraries that are not needed.
  Only remove them for anonymous users, since a lot of libraries are required for the admin interface to work. */
  $allowed_modules_with_libraries = [
    'mytheme',
    'google_tag',
    'my_custom_module',
  ];

  if (!in_array($module, $allowed_modules_with_libraries) && !Drupal::currentUser()->isAuthenticated()) {
    $libraries = [];
  }
}

My problem is, that the attached libraries are not completely separated by user role cache context:

My test workflow:

Clear all caches
Requesting page as authenticated user
Contrib assets in browser sources panel:

This is as expected.

Requesting same page as anonymous user
Contrib assets in browser sources panel:

This is not as expected, nothing should be present here.

The other way around:

Clear all caches

Requesting page as anonymous user
No contrib assets are displayed browser sources panel.

This is as expected.

Requesting same page as authenticated user
Assets in browser sources panel:

This is not as expected, paragraphs and webform assets are missing.

The x-drupal-cache-contexts HTTP response header content: languages:language_content languages:language_interface languages:language_url route session theme timezone url.path url.query_args user

The user cache context is there, shouldn't the response be cached by user (including the role) then?

I tried doing this by using hook_page_attachments_alter, but not all libraries that are attached to the response are listed there.
I'm not sure if changing the library definitions with hook_library_info_alter is the right approach. Since I don't want to change the libraries. I just want to detach them from the response.

The page_cache and dynamic_page_cache modules are enabled.

hook_library_info_alter() is not the right approach. You get the role of the user who installs a module or clears the cache, not of the user who requests the page. Info alter hooks in general are about changing information provided by other extensions and usually are only recalculated if an extension is added or removed and for a better dev experience on a cache clear.

And indeed, hook_page_attachments_alter() lists only libraries added by other hook_page_attachments(_alter) hooks. See invokePageAttachmentHooks(), which starts with an empty attachments array:

  public function invokePageAttachmentHooks(array &$page) {
    // Modules can add attachments.
    $attachments = [];
    ...

So we can rule out both hooks you've mentioned. Attached libraries are collected from many different places (YAML, render arrays, hooks) and they are merged (bubbled up) through the entire page building and rendering process. So it might be a good idea to attach the override in form of a custom library the same  way and let Drupal calculate the assets when rendering the page. See https://www.drupal.org/node/2216195#override-extend


How do I get the username of the logged-in user? I am working on a site where on a page I am querying some data related to my project.

Here I have many clients and I have given all of them access to project search page. On search page I run a query according to the fields selected by the user and display the result as a table on the page itself. But my query is as such that it is not user dependent.

I just want to ensure that each user has a specific set of output for itself (i.e not all the table would be displayed to all users).

How do I get the username or user ID of the logged-in user?

You can use the global $user object:

An object representing the user currently visiting the site.
Contains preferences and other account information for logged-in users. When a user is not logged-in, the $user->uid property is set to 0.

e.g.
global $user;
$name = $user->name;
$id = $user->uid;

// or
$name = $GLOBALS['user']->name;
$id = $GLOBALS['user']->uid;


Getting a custom view of Twitter and Facebook posts I would like to display my client's twitter and facebook posts in a most-recent format in a custom view or block that will be implemented on their site. I was thinking of using the Feeds module, but was told by someone on twitter that cURL was the way to go. Giving these elements custom styling and keeping them listed by timestamp (not type of aggregate) is very important to me, and I was wondering about how to get this done.

I have clients who require exactly the same feature, and the best method I have found so far is using Feeds and Feeds XPath Parser.

I create two Feeds importers that import from the RSS feeds of the client's Twitter and Facebook profiles. I set Feeds to create a node for each update (content type 'Social update') and use Feeds XPath Parser to populate the correct fields (title, body, timestamp, etc). I also set Feeds to automatically purge imported nodes after two weeks, and set it to schedule import on cron every hour.

Now I have each new post in a node, and I can display them however I like using Views.

This works ok, BUT I'm not convinced it's an optimal solution. I've looked at modules that interface with the Twitter and Facebook APIs for a better solution (e.g. Twitter Pull, Facebook Pull, Feeds Facebook Parser, Twitter) but they don't seem to provide a method for pulling Tweets and Facebook posts together in a single view or block. I'd love to get some more ideas on this.


Problems to add a form in a block I have a very small experience with Drupal but I have to add a little form in a block (for a newsletter) in a custom module.

I write this code for the moment :

function block_contact_default() {
  $content = array();
  $content[] = '
My.Site
';
  $items[] = array('class' => 'mail', 'data' => l(t("By mail"), 'node/'.variable_get('webform_contact_default_nid', FALSE)));
  $chat = variable_get('default_chat', "");
  if(!empty($chat)){
    $items[] = array('class' => 'chat', 'data' => l(t("By chat"), variable_get('ot_default_chat', "")));
  }
  $facebook = variable_get('default_facebook', "");
  if(!empty($facebook)) {
      $items[] = array('class' => 'facebook', 'data' => l("Facebook", $facebook));
    }
    $twitter = variable_get('default_twitter', "");
  if(!empty($twitter)) {
    $items[] = array('class' => 'twitter', 'data' => l("Twitter", 'http://twitter.com/'. $twitter));
  }

    $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), $language->language);
    if(strstr($path_newsletter, 'node/') !== FALSE){
        $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), 'fr');
    }

    $form['#method'] = 'post';
    $form['newsletter_form'] = array(
      '#type' => 'fieldset',
      '#title' => t('Suscribe to Newsletter !'),
      '#tree' => TRUE
    );
    $form['newsletter_form']['newsletter_mail'] = array(
      '#type' => 'textfield',
      '#title' => t('E-mail'),
      '#default_value' => t('E-mail')
    );
    $form['submit'] = array('#type' => 'submit', '#value' => t('OK'));
    $items[] = array('class' => 'newsletter_form', 'data' => $form);

    $content[] = theme('item_list', $items);
    $content[] = $form;

    return array(
      'subject' => t("Contacts"),
      'content' => implode('', $content),
      'classes' => array('block-contact')
    );
}

I'm using Drupal 6.25
But when I go on my page I get only a string "Array", not really what I wanted... I'm sure I don't do this properly. Could you help me ? Thank you with advance.

More information would be more helpful to answering this question. I have no idea what file/function you have put this code into, if you have in your module any of the other hooks necessary to display a block or what your actual end-goal is here (are you printing a form in a block created by another module?). However, this code doesn't seem to correlate to any of the hooks necessary for creating a block within a module in Drupal 6.

You should take a look at the Examples for Developers module and its examples of a module that creates a block and a module that creates a form. By following those examples, you should be able to easily build a module that will create a form and a custom block that outputs that form.


How do I increase the memory assigned to PHP? I have a script that saving the hundreds or thousands of nodes at one time and It is nearly impossible to manage it with Batch API. When I am running my script it saying :

  Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 16 bytes) in /home/staging-uls/www/sites/all/modules/token/token.module on line 461.

I set the memory using ini_set('memory_limit','256M'). My script is still so long that showing the error. Is there any other way to do so?

What my script is doing exactly:

It fetches a data from other site using cUrl. The data are articles, journals and some other user's data.
After getting the data in XML format, it adds each content.

I increased the max_execution_time to unlimited and I used output buffering for keep my script in progress. Change the memory limit to 1024M. I got it from This URL.


Using Ubercart with https protocol I just installed rapidssl certificate and I want to serve my cart pages using https protocol.
I put all files inside apache2/ssl folder, edited default-ssl inside apache2/sites-available. The certificate is installed, but after visiting https://www.mysite.com or any link using https protocol, the browser gives me either the "It works page" or a not found page. It is probably due to path pointing to default directory.

I am assuming that I if put the correct path in the default-ssl file it should work. However, I read that having both http and https pages serving the same content is not good for SEO.

What would be the correct way of enabling cart* pages to automatically use https protocol?

If you care for SEO, consider using Metatag module:

  Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.

For Drupal 6 there is Nodewords module, that was inspiration for Metatag as far as I know.

To force https where you need it, use Secure Pages. You can check "Switch back to http pages when there are no matches" to make sure pages not required to use SSL will never actually use it - that way you save both server's CPU load (as encoding isn't free) and problems with duplicated content. It's pretty convenient, and a good first step, but it should not stop you from setting canonical, of course.


creating custom content comprising both static and dynamic data I need to create certain pages in my site, some of them relatively simple layout with mostly static content like Contact Us and About Us which I've created as Content Type Page (node). Similarly other content types have a relatively complex layout and content composed of both static and dynamic data. For example a page with some fancy header images a couple of paragraphs (static) and a list of URLs for contents belonging to a specific category (dynamic). Some of the pages have their own flyout menu (which i use Nice menus) and I create a new menu element and add the block for that specific page which I feel is definitely not the best method to go about this. My site is content heavy and there are many such pages and so its not possible for me to code the URLs in the content body in static manner.

I'm relatively inexperienced with contributed modules like Views and Panels but tried to get some ideas watching webcasts. But it seems that they are very vast topics and I couldn't find what I required from them. Hence request any of the members who've faced similar circumstances to share their experience and provide the methods/implementations or even modules they tried for this.

Panels and Views is the way to go.  However, this question is way too broad; in fact, a book could answer it.  That book is Drupal's Building Blocks: Quickly Building Web Sites with CCK, Views, and Panels by Earl and Lynette Miles.

Also see the Views tag wiki on this site, which links to Node One's excellent screencast.


Filter the users name in the list of admin / people of organic groups Drupal 7 I have a lot of users in several organic groups, I need filter the users by username to acept or deny join to group.

Generic url group page: group/node/[nid]/admin/people

I appreciate any guidance to filter users (contributed module, hook_form_alter...) or disable pagination in this page.

Thanks :)

You can see admin/structure/views/view/og_members_admin/edit/default

In og 7.x-2.0-rc1 exists this functionality


How do I install sandbox module 'Filedepot multiupload'? I am new to Drupal and I am unable to install the sandbox module called Multiupload, it is an add-on module for Filedepot but there are no installation instructions that I can see. I am unsure where to put the files.

Steps I have taken so far:

Installed filedepot and it is working.
Installed plupload.
Overwritten filedepot-mainpage.tpl.php with the multiupload version.

The link you provided for the sandbox module 'Filedepot Multiupload' is actually an issue (request) for Drupal.org Project Applications.
The actual sandbox project is located at https://www.drupal.org/sandbox/e.ruiter/2290395 . On that page, wihin resources, there isn't any link mentioned (yet) with title "Read documentation", which typically points to either available "Community documentation", or to the "Readme.txt" that comes with the module.
The module's Readme.txt appears to be the best documentation currently available. To review/browse it, you have 2 options:

Browse the module's source code that you downloaded, which should contain that readme.txt.

Follow the "Browse code repository" on the project page of the sandbox project. Next visit the "Tree" tab and click on the Readme.txt link there.

Here is the content of that readme.txt:

Introduction: This module extends the filedepot module with multiple upload support. Files can be uploaded with the plupload module which supports drag and drop.

Installation: Just install the module by copying the module to site/all/modules directory or install with drush. If you get some errors about files missing and plupload is not loading, you are probably missing the plupload library. Find the README file of the plupload module and follow the instructions.

Note: while you're reviewing the Readme.txt and experimenting / testing that module, consider either (or both) of these approaches:

enhance the readme.txt with anything you learn/discover about it, and then contribute an updated version of readme.txt back to this sandbox project. E.g. by creating a documentation issue, and attaching a copy of the updated readme.txt.

create a community page containing such documentation, and then create a documentation issue for this sandbox project, requesting the module owner to update the project page to point to this new community documentation.


8 - form #states greater than x How do I use #states to show an field if the value of another field is greater than one of my variables?

The code below is for =$chkval

$chkval = 4;
// This would be set by a database query

'#states' => array(
    'visible'=> array(
        ':input[name = 'actual_reps'] => array('value' => $chkval)
    )
)

Unfortunately, Drupal does support that.

The following states may be applied to an element:

enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed

The following states may be used in remote conditions:

empty
filled
checked
unchecked
expanded
collapsed
value

The following states exist for both elements and remote conditions,
but are not fully implemented and may not change anything on the
element:

relevant
irrelevant
valid
invalid
touched
untouched
readwrite
readonly

When referencing select lists and radio buttons in remote conditions,
a 'value' condition must be used:
@code
'#states' => array(
// Show the settings if 'bar' has been selected for 'foo'.
'visible' => array(
':input[name="foo"]' => array('value' => 'bar'),

),
),
@endcode

You can see state support value, but value is array, so can't use condition of value.
See the process states documentation page for more information


How can I override the empty search message? What do I have to do to override the message

  Your search yielded no results

from core search module inside core/modules/search/src/Controller/SearchController.php?

You can implement template_preprocess_item_list (or hook_preprocess_HOOK to be precise) in your theme or module to override that.

/**
 * Implements template_preprocess_item_list().
 */
function MYTHEME/MYMODULE_preprocess_item_list__search_results(&$variables) {

  $variables['empty']['#markup'] = '<h3>' . t('Foobar') . '</h3>';
}


Node Reference retrieve Field I'm using Views RSS to generate custom RSS feed which includes georss

I have to content types Shops and Events I can get the location fine from Shops because it has dedicated location field, but Events uses Node Reference to generate drop down menu of all Shops and has no location field.

How can I access the location of the referenced Shop from the View? I understand I have to create a relationship, but I'm not really sure where to start.

I'd appreciate any advice.

View of nodes where content type = Event.

Add a relationship to nodes referenced via the Shops field.

Add a field for Location using the Shops relationship.


Upload and get images in custom module with custom block form I need some help
I need create slider on the front page with custom block.
I create custom module, create custom block and form.
How i can get images after upload in form for use in twig-template??

For example i create some block with input[type]=textfield, and use this values in twig-template. How can i use images??

its my code for 'textfield'

<?php

namespace Drupal\dot\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'SocialLinksBlock' block.
 *
 * @Block(
 *   id = "social_links_block",
 *   admin_label = @Translation("Social Links Block"),
 * )
 */

class SocialLinksBlock extends BlockBase implements BlockPluginInterface {
    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state) {
        $form = parent::blockForm($form, $form_state);
        // Retrieve existing configuration for this block.
        $config = $this->getConfiguration();
        // Add a form field to the existing block configuration form.
        $form['youtube'] = array(
            '#type' => 'textfield',
            '#title' => t('Youtube link:'),
        );
        $form['google'] = array(
            '#type' => 'textfield',
            '#title' => t('Google link:'),
        );
        $form['twitter'] = array(
            '#type' => 'textfield',
            '#title'=> t('Twitter link:'),
        );
        $form['facebook'] = array(
            '#type' => 'textfield',
            '#title'=> t('Facebook link:'),
        );
        return $form;
    }

    public function blockSubmit($form, FormStateInterface $form_state) {
        // Save our custom settings when the form is submitted.
        $this->setConfigurationValue('youtube', $form_state->getValue('youtube'));
        $this->setConfigurationValue('google', $form_state->getValue('google'));
        $this->setConfigurationValue('twitter', $form_state->getValue('twitter'));
        $this->setConfigurationValue('facebook', $form_state->getValue('facebook'));
    }
    /**
     * {@inheritdoc}
     */
    public function build() {
        $config = $this->getConfiguration();
        $youtube = isset($config['youtube']) ? $config['youtube'] : '';
        $google = isset($config['google']) ? $config['google'] : '';
        $twitter = isset($config['twitter']) ? $config['twitter'] : '';
        $facebook = isset($config['facebook']) ? $config['facebook'] : '';

        return array(
            '#theme' => 'block--sociallinksblock',
            '#youtube' => $youtube,
            '#google' => $google,
            '#twitter' => $twitter,
            '#facebook' => $facebook,
        );
    }
}

In Drupal there is not much help available to store images in configuration. You would need to do most things yourself, like build the form fields, submit and store the images and take care how they should be rendered.

But Drupal has a great infrastructure to store images in content. So the better approach is probably not to use a block plugin, but to create a custom block type, which is content like a node. Here you can add the image fields  and configure how they should be rendered in ui.


Remove js file by template or add condition in info file I work on drupal 7, I added all js by info file, work well in whole site. But we want to remove or not load of a specific js in a specific content type page.

I try by template.php of following code

function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type) && !empty($vars['node']->type) && ($vars['node']->type == 'my_content_type')) {
    $js_path = drupal_get_path('theme', 'mytheme') . "/js/xyz.js";
      unset($vars[$js_path]);
  }
}

but load  xyz.js. How to remove of this js file.

You can use hook_js_alter()

Perform necessary alterations to the JavaScript before it is presented on the page.
Parameters
$javascript: An array of all JavaScript being presented on the page.

Then you should be able to use menu_get_object() to load the node type and unset the js file in the $javascript array.
function MYTHEME_js_alter($javascript) {
  $node = menu_get_object();
  if ($node->type == 'node_type) {
    unset($javascript['path/to/script.js']);
  }
}

Note: I haven't tested this or checked syntax, let me know if it doesn't work and I will test.


How to make values of fields of newly created node available in Rules I have a rule which is triggered upon Event: 'After saving new content'.

My Action involves executing custom php code. Please how can i make the values of the fields of my new node available in my php code.

Thanks.

You can use fields of node currently being added in two ways

Check down the PHP code text field you will find text saying

  "The following variables are available and may be used by your PHP
  code:". Inside this you will get some site variables as $site and node variables as $node.

As per requirement you need fields of current added node so $node is the reference for current added node and also contains the fields you need.
Find the screen shot to see how it can be used,as in the example I am using drupal_set_message to show the title of current added node or with first code of line it is simple dpm($node), which will show you complete insight of node once this rule is saved and devel module is installed.

Other way is to use tokens replacement options.

Under replacement patterns you will see "Replacement patterns for saved content". This list provides current node fields as toke replacement.
Check the screen shot.

For example usage,if you want to show node title using tokens in rules simply add this code

`drupal_set_message(token_replace('[node:title]', array('node' => $node)));` in the php code.

here in the following screen-shot is a code comparison for the above two ways, you can use any.I usually prefer using $node.


Using container element in form widget I want to build a widget for a own field type. In the function formElement() of my widget I want the elements wrapped in a div. For this purpose exists the container element. So I build my form:
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['myitem'] = [
      '#type' => 'container',
      '#attributes' => [
          'class' => ['my-item'],
      ],
      '#attached' => [
        'library' => [
          'mymodule/mylibrary',
        ],
      ],
    ];
   $element['myitem']['label'] = [
    '#type' => 'select',
    '#title' => t('Label'),
    '#default_value' => isset($items[$delta]->label) ? $items[$delta]->label : NULL,
    '#options' => $options_for_label,
  ];
  //… more elements

  return $element;
}

The rendering of the form looks like I wanted.  But the form entries will not be saved. There are no errors and none of the elements were attached to the entity and persisted in the database.
If I don't use the container element and place my elements direct in $element like this:
 $element['label'] = [
  '#type' => 'select',
  '#title' => t('Label'),
  '#default_value' => isset($items[$delta]->label) ? $items[$delta]->label : NULL,
  '#options' => $options_for_label,
];
//… more elements

then all will be saved.
How can I get my widget-form elements be wrapped within a div for styling?
(A similar question using container element within form widget, here with focus at form state was asked 3 years ago, but without answer :-( )

From WidgetBase::form:
// Most widgets need their internal structure preserved in submitted values.
$elements += ['#tree' => TRUE];

When customizing the structure you also need to make sure the values get submitted correctly. For example by adding WidgetInterface::massageFormValues to your widget.
A much easier way though is to keep the standard structure, which is using property names as form keys, and add the container by #prefix/#suffix:
$element['label'] = [
  '#type' => 'select',
  '#title' => t('Label'),
  '#default_value' => isset($items[$delta]->label) ? $items[$delta]->label : NULL,
  '#options' => $options_for_label,
  '#prefix' => '
',
  '#suffix' => '
',
];


How can i add our own field in Ubercart billing address? I have used Ubercart in my project.
I would like to add my own one field in Ubercart Address field.

How can I?

Does any one had same experience?

Entire order is an object, so having some extra fields for order object from checkout level will solve this.

Extra Fields Checkout Pane module will help to add additional fields.


Twig name for field of view I have an view that uses the Unformatted list format and Show: fields.

I've added the fields to it and the view has _Content type: my_content_type_ filter.

I want to write a template file for the fields in that view, with the following code.

{% if field_name == 'field_photo' %}
    ...
{% elseif field_name == 'field_something_else' %}
<div class="something">
    {% for item in items %}
        {{ item.content }}
    {% endfor %}
</div><!-- .something -->

I don't know which name to use for the template file.

I've tried the following names, but they don't work. MY_CUSTOM_TYPE stays for the content type I have set in filter for that view.

field--MY_CUSTOM_TYPE.html.twig
field--node--MY_CUSTOM_TYPE.html.twig

What is the correct filename for the template file I am trying to use?

You could use:

views-view-fields--[view-name]--[machine-name].html.twig

Use the machine name if you only want to affect a specific view Display. (IE: when you click + Add button, that other view/display does not get affected). If you wan't all displays to be affected, then don't include the machine name.

views-view-fields--[view-name].html.twig

{% if fields.field_photo.content|striptags == 'some value' %}
    ...
{% elseif fields.field_something_else.content|striptags == 'some value' %}

        {{ fields.field_something_else.content }}

{% endif %}

If you just want to add a div class regardless of the value of the field and not depending on some condition, then simply

{{ fields.field_machine_name.content }}

OR you can do this through the Views UI:

Now, if you need something more global, IE: You want to affect all Views that contain your field and future views that will contain your field, then you need to use:

views-view-field--[field-name].html.twig

{{ output -}}


Is it possible to individually update each module using update.php? I am trying to update the reCAPTCHA module (which is installed on sites/all/modules) in Drupal 7. I could see other 3 modules which have pending updates. Is it possible to individually update each module using update.php?

You can't update single module using "update.php".
You can update single module if you installed drush.

List all available modules (except core) with below command.

  drush pm-list --type=module --no-core --status=enabled

Update specified module only.

  drush up 'module-name'

or

  drush pm-update --no-core "module_name"


Ctools: stay always within modal window When I load some pages using Ctools modal window, those pages have many another links, submit buttons etc, so when I follow those links, I loose the window. Drupal Overlay has no problems with it.

Is it possible to emulate Drupal Overlay using Ctools?

You may can use this module
Overlay Paths

This is a simple module that enables administrators to use the built-in Overlay for non-admin pages.

This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.

This module is designed to be used by module developers comfortable with writing code to define which pages should appear in the overlay.


Add class in sub menu I am trying to convert html to Drupal 7 theme.

function theme_menu_tree($variables){
  return '
' . $variables['tree'] . '
';
}

simply returns the entire menu how to make it like following

Item

Link1

Link2

Use theme_item_list function for it, see the below code

$title = 'Title';
$type = 'ol';
$items = array(
  'one',
  'two',
  'three',
  'four',
  'five',
);
$items[] = array(
  'data' => 'something',
  'class' => array('dummy'=>'category'),
  'children' => array('1.1','1.2',array('data'=>'1.3','class' => array('dummy'=>'category'),'children'=>array('1.3.1','1.3.2')))
);
$attributes = array('class' => array('test-class', 'demo-class'));

print theme_item_list(array(
  'items' => $items,
  'title' => $title,
  'type' => $type,
  'attributes' => $attributes
));

This will give you following HTML output:

Title

one

two

three

four

five

something

1.1

1.2

1.3

1.3.1

1.3.2


field collections and blocks I have a number of content Types (Basic Pages) and a region (right sidebar)

What I'm looking to do, is display a particular fields content in this block depending on what page I'm on.

I know I could do this for a block for each page, but I have over 200 pages, and doing this for all of them would be time consuming.

I have created a field collection named 'rightcol' which is a text field.

So ideally, what i need is when I'm on a particular page, in the right-hand region, that pages 'rightcol' content will display.

Am I correct in thinking I'd need to create a view for this?

I think you are correct. You should be able to create a view block, set the field to be "rightcol" and then use contextual filters (under advanced features) to filter what is in the view depending on URL.


How to add a JS confirmation popup when clicking an #ajax button I have a basic FAPI button input that is #ajax enabled and that's working fine, but I want to add a JS "Are you sure?" confirmation popup when clicking the button before the code actually runs, and I'm not sure how to do that because FAPI's JS seems to be eating the click before I can get to it no matter what I do.

I've tried adding an inline onclick handler, like so:

$form['search_filters']['channels']['channel_delete_' . $channel->nid] = array(
  '#type' => 'button',
  '#name' => 'channel_delete_' . $channel->nid,
  '#value' => 'Delete',
  '#attributes' => array(
    'class' => array('confirm'),
    'onclick' => "return confirm('Are you sure you want to delete that?')"
  ),
  '#button_type' => 'no-submit',
  '#ajax' => array(
    'callback' => 'delete_channel_callback',
    'wrapper' => 'channel_container_' . $channel->nid
  ),
);

...which doesn't help, and I've also tried adding:

$('.confirm').click(function(e) {
  e.preventDefault();
  alert('Is this recognized')? // never runs
});

in my module's JS which is also ignored.

Any other ideas? Is there a way to add a submit handler to the top of the stack which Drupal #ajax will recognize?

Drupal is a PHP framework, and it's amazing how much fancy AJAX stuff you can get using that and the FAPI. But it has it limits and for a use case like this, I would suggest that you use custom JavaScript. Also instead of using the usually JavaScript dialog, you could use jQuery UI to create a themable dialog instead.

Anyways the problem that you're facing is probably caused because you use AJAX on the submit button. Since you are using AJAX for the actual delete call, preventDefault and the like won't work.

What you would have to do is something like this. (This is not widely tested but should work.)

Drupal.behaviors.module = {
  attach: function() {

    var events = $('.confirm').data('events'); // Get the jQuery events.
    $('.confirm').unbind('click'); // Remove the click events.
    $('.confirm').click(function () {
      if (confirm('Are you sure you want to delete that?')) {
        $.each(events.click, function() {
          this.handler(); // Invoke the click handlers that was removed.
        });
      }
      // Prevent default action.
      return false;
    });
  }
}


Enabling HTML in MENU_LOCAL_TASK titles (primary tabs) I would like to place a <br /> tag in my MENU_LOCAL_TASK titles so that I can reduce the width of the primary tabs.

It seems that in theme_menu_local_task the link title is run through check_plain, but when I remark this line out only the link title of the active tab responds. All the inactive tab link title are still being sanitized.

Basically, I want to have HTML in my MENU_LOCAL_TASK titles - without using any contrib modules.

Any ideas? Thanks.

The key is this if construct: if (!empty($variables['element']['#active'])) with regard to getting the titles of the inactive tabs to respond. My solution was to customize: theme_menu_local_task. Perhaps there is a better solution?

/**
 * Alter theme_menu_local_task.
 */
function my_theme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      if (arg(0) != 'my-page') { // ** ADDED **
        $link['title'] = check_plain($link['title']);
      } // ** ADDED **
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  if (arg(0) == 'my-page') { // ** ADDED **
    $link['localized_options']['html'] = TRUE; // ** ADDED **
  } // ** ADDED **

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";
}


Add unique class to each link outputted by views I'm using views to output a list of links (fields). I can type in an url and a text and the text becomes the link text that goes to the url. Now I want to be able to add a unique class to the link when I add it from the backend. Or have a unique class/ID added to it by default, that is also fine.

How can I do this?

Go to Theme information link in your view, create a new

 views-view-fields.tpl.php

http://api.drupal.org/api/views/theme!views-view-fields.tpl.php/7

there you could assign a dynamic value from your query result to $field->class or add another custom wrapper to each field or use
http://api.drupal.org/api/views/theme!views-view-field.tpl.php/7

for this field only


What does a basic module look like that includes a content type, a couple of fields and a view? I am looking at turning my Features into proper modules. There is nothing fancy to them other than a content type, a couple of textfields attached and a view. It looks like the features module pretty much exports these into a module anyways but it looks like it relies on some helper functions in the features module to get this going. How can I convert my feature so that it doe not require the features module to be installed?

I don't know of an example module that has all of those pieces together, but I think you'll find that field_example and node_example from the Examples for Developers project useful.
As well, this page of the Features documentation mentions something interesting:

Technically, an exported Feature is a Drupal module – it has a .info file and a .module file (along with some .inc files matching the components of the feature).
If you're a developer and find a feature bundle a good starting point for a module, you could just extend the feature by editing its .module file (and if need be also the .info file) to include hooks and what have you.

So you may wish to export your Feature, then develop on it from there based on the samples in field_example and node_example.


How to display content type field values in tab panel format? I have created custom content type. I want to display it's data (field values) in tab panel format. is there any way to change it through CSS?

im using the Quick Tabs module for creating tabs. Here is a quote about it (from the module's project page):

... allows you to create blocks of tabbed content, specifically views, blocks, nodes* and other quicktabs*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:

if you choose ajax mode for your Quick Tabs block (and this is chosen on an individual QT basis), only the content of the active tab will be loaded on page load and the content of the other tabs will be loaded via ajax on tab click (this is good for performance if you are loading, for example, several large views)
in non-ajax mode the tab content is just hidden / shown on tab-click. This latter method is an ideal way to do something like the Most Popular / Most Emailed stories tabs you see on many news websites, where it is used more as a space-saving device in your sidebar. If however, you want a QT block as the main content of your entire page, then the chances are that ajax mode will be more appropriate.

Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks. Multiple Quick Tabs blocks can be placed on a single page.
For theming of the tabs, several styles have been provided for you to choose from (in the 7.x-3.x branch this functionality comes in a separate submodule, Quicktabs Tabstyles), along with the default option of no style, if you prefer to add your own theming instead.


When using Rules, does a page refresh happen immediately if the event is set to 'Drupal is initializing' I have several views pages set up on my site that filter the content that is shown to normal visitors.  In general, these views will show users content that they have created.  However, when an admin user visits one of these pages, I want them to see all of the content (created by everyone.)  Currently, I have a rule set up which will redirect all admin users to a different url which has a different view (with access restricted to admin users and no filters)  Functionally, this does want I want (all users click on the same menu link, but eventually reach different pages.)

I am wondering, does the rules redirect event happen before the first view is loaded?  I want for the redirect to happen as soon as possible to save server resources and load time.  So, If the redirect happens after the page is created, it would be better for me to change my navigation strategy.

You have not specified the exact condition you are using. If you are using 'When content is viewed by an authenticated user' condition, then yes, views are being loaded in node load hooks, and they are already there by that time. The good news is that if these are cached, it will lighten things up, and the amount of admins is always limited, so a non-issue performance-wise.

But, if you really wanted to make one view show to one user and another to another, this is what you can do:

Create a separate block for each view display.
Put these blocks on the page.
Apply conditions for blocks that will show them for specific roles. Advanced to admins, and usual for non-admins, or all else.

And voila - you will have a solution without redirects and overhead.


Infinite redirects with drupal_goto I am writing my own 403 page, and would like to redirect the user to the login page if the user is not logged in. I use this code in a page callback, but when I am viewing an unauthorized page (say /user/1) as anonymous user, I got infinite redirect to /user/1.

function MODULE_membercheck() {
    global $user;
    if (!$user->uid) {
        //drupal_goto('user/login', array('query' => array('destination' => 'member/check')));
        drupal_goto('user/login'); //these two lines won't work
        return;
    }
    // other stuff.
}

update

It is quite easy to reproduce the problem. Just create a module and add a menu (member/check), and redirect anonymous user to login page in the page callback function. Then set the default 403 page to this menu entry, and try to open an unauthorized page.

Where is MODULE_membercheck() getting called from? It would seem that it's getting called on user/login page requests which makes these pages redirect to themselves, hence the infinite loop.

You can either modify the calling of the function to ensure it doesn't get called on the login page or add a check in your function to make sure the current path is NOT user/login before doing the redirect, something like this:

function MODULE_membercheck(){
  global $user;
  if (!$user->uid && current_path() != '/user/login') {
    drupal_goto('user/login', array('query' => array('destination' => 'member/check')));
  }
  // other stuff.
}