Mark deletion on custom fields I am using mongodb as the backend for the node_save functionality and I have migrated my custom fields. So for every node save it calls the hook_field_storage_write() . Thus the data is saved in the mysql and then calls the mongodb implementation. This hook inserts the document in mongodb and calls the mongodb_migrate_write_helper. In the function the migrated fields are set with the value of deleted column as 2.

Thus if I have migrated a field 'field_email' from mysql to mongodb the mongodb_migrate_write_helper sets the field_email for the entity as deleted = 2. What does the deleted flag do? Are the rows marked as deleted = 2 deleted in a specific point of time or by some hook calls? . I have seen in many instances in the core modules where deleted is set as 1. Are there any purge scripts that are run at specific points of time for deletion of fields marked as deleted.

function mongodb_migrate_write_helper($entity_type, $entity_id) {
  $migrate_fields = variable_get('mongodb_migrate_fields', array()); // Migrated field names are stored in variable.
  foreach ($migrate_fields as $field_name => $v) {
    $field = field_info_field($field_name);
    db_update(_field_sql_storage_tablename($field))
      ->fields(array('deleted' => 2))
      ->condition('entity_type', $entity_type)
      ->condition('entity_id', $entity_id)
      ->execute();
    }
}

The deleted column in a field table is:

  A boolean indicating whether this data item has been deleted

Therefore the only valid values are 0 and 1. Or, at least, 0 == false, and anything else is equivalent, and == true.

You'd need to ask the module developers for their motivation to be 100% sure why they're bucking the trend there and using '2' instead, but maybe it's some sort of hack to exclude certain records from being queried with WHERE deleted = 1, but still available for WHERE deleted > 0. Not sure though, that's just a guess.

As for what it does: it simply marks a record as deleted, so it won't be included in query results, and can be moved into a deleted data table, from which it's subsequently removed on cron runs.


How to add a "company name" as a user value for permissions and a data variable I am creating a site that allows multiple different company's access to separate resources. Access to resources is dependent on the user's role and the company they are registered to.

Sample User Roles:
Mechanic
Scheduler
Parts Distributor
Driver
Admin

Sample Company's:
Joe's Auto Repair
Car Repair USA
Pro Tire & Oil

Each user has access to only his company's data and the data that is associated with the permissions attached to his role.

How can this be done? Am I going to need to code custom modules?

This article can be helpful for you: https://www.drupal.org/node/200631, and you can try Taxonomy Access Control module to implement it.
Or another way you can try Organic groups - its more powerful.


How to trigger / launch a colorbox programatically? I would like to launch a colorbox right after an user has successfully saved a new node.

The content of the colorbox is a drupal block which would contain instructions asking the user to share that newly created node to their social media.

I am able to set up a link which loads the block into the colorbox when the link is clicked.

I would like, however, to programatically call the "link clicking" event. So, how do I trigger, by JQuery or otherwise, a colorbox from my custom form submit handler?

Install colorbox module. Read its README.txt to find out how to build links for loading inline and iframe content in a colorbox.

Set the id #cbox_trigger_on_page_load for your link and place it somewhere in your page and hide it with CSS.

If you are loading inline content, place the content in a block and hide the block too with CSS.

The mechanics of how to place the hidden colorbox link on the right page is not really what the question is about, is it?

So, lets stick with how to trigger the colorbox.

/**
 * Implements hook_preprocess_html();
 */
function MYMODULE_preprocess_html(&$variables) {
  // The overlay content from the site in an iframe should have cbox_overlay
  // as first path argument.
  // i.e. http:/mywebsite.com/cbox_overlay/content-title.

  // This will prevent a triggering loop.
  $is_cbox_overlay = FALSE;
  if (arg(0) == 'cbox_overlay') {
    $is_cbox_overlay = TRUE;
  }

  $settings = array(
    'is_cbox_overlay' => $is_cbox_overlay,
  );
  drupal_add_js(array('MYMODULE' => $settings), array('type' => 'setting'));

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/colorbox_onpageload.js', array(
    // Making sure our JQuery code runs after colorbox's.
    'scope' => 'footer',
    'weight' => '15'
  ));
}

In the /js/colorbox_onpageload.js file:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      if (!settings.MYMODULE.is_cbox_overlay && $('#cbox_trigger_on_page_load').length) {
        $('#cbox_trigger_on_page_load')[0].click();
      }
    }

};})(jQuery);


Customise Webform Email Submission Data 2 I had read some info from this content: How to use [submission:values] in Email template in Webforms

Submitted on [submission:date:long]
Submitted by user: [submission:user]
Submitted values are:
[submission:values]

The results of this submission may be viewed at:
[submission:url]

Name: [submission:values:name:nolabel]
Address: [submission:values:address:nolabel]

I add last two code in the email setting, but it only print name: and address:

I also try this %email_values %email[name], but it print out as string.

What wrong with my code?

Many Thanks.

Are those fields inside a fieldset? This has tripped me up a few times.

Fields in a fieldset need to be [submission:values:fieldset-name:name:nolabel]


OnSelect datepicker not working I am having a problem with this function, it simply is now working. I have a module with just a basic form and im using the date module to get the datepicker to pop up and that works fine, but when I select a date from the datepicker the alert is not firing.

this is what i have in my theme js file.

//id for nay_date input field
$('#edit-nay-date-datepicker-popup-0').datepicker(function() {
              onSelect: function(selectedDate) {
              alert(selectedDate);
            }
        });

and this is the field i have in my module

$form[['nay_date'] = array(
    '#title' => 'Date',
    '#type' => 'date_popup',
    '#description' => '',
    '#required' => TRUE,
);

I use it without a function as the argument like: jsfiddle

//id for nay_date input field
$('#edit-nay-date-datepicker-popup-0').datepicker({
          onSelect: function(selectedDate) {
          alert(selectedDate);
        }
    });


Question regarding rendering fields in node.tpl.php I'm confused in how the fields can be rendered.
There are 2 variables in node.tpl.php $node and $content, both of which contain fields.
My task was to render all fields separately, to surround them with custom html. First I've tried

print render($content['field_service_summary'])

and got

array(1) { [0]=> array(1) { ["#markup"]=> string(11) "Engineering" } } Engineering

in result.

Trying to get rid of that array, I've taken another approach so the code became:

$field = field_get_items('node', $node, 'field_service_summary');
$output = field_view_value('node', $node, 'field_service_summary', $field[0]);
print render($output);

which actually worked, so, to clear this out I have following questions:

1) Where did that array come from when doing print render(content['field_service_engineering']); and how can I get rid of it(I still like this rendering approach better cause it's just shorter) ?

2) Is the second method I've used totally good, with no drawbacks ?

3) What's the point in keeping fields info both in $content and $node especially regarding that in vanilla node.tpl.php only $content is used for rendering fields ?

4) Just my curiosity: in $content array every field has value #object which seems to contain the node object itself. What is it for ?

That should be print render($content['field_service_summary']); (notice the $ sign prefixing the variable name).
It's technically OK, but unless you've customised the preprocess workflow to a large degree, what you'll find at $content['field_service_summary'] is actually the result of a call to field_view_value() anyway, so you're just duplicating logic. If you find that method to be the way forward for whatever reason, at least move it into a preprocess function so it's not cluttering up the template file.
When nodes are loaded, they get field data attached to them. That data is in a certain format. When a field is viewed (e.g. with field_view_field()) that data is restructured into a render array, suitable to be run through render()/drupal_render(). The arrays might well contain the same data in some places, but they're formatted differently for their various different purposes.
It's a reference to the node object. It might be used by a theme/render function, or it might not. Core puts it there by convention. Remember it's just a reference to the object, it's not a duplicate.


More specific way to override THEME_process_page() function? I'm going to explain my problem through the use of pseudo code.  Right now, i have in template.php the following code

function THEME_process_page(&$variables)
{
    if($variables->view == 'calendar')
    {
        // do something
    }
    else if ($variables->view == 'google_maps')
    {
        // do something
    }
    else if($variables->content_type == 'news')
    {
        // do something
    }
    else if($variables->content_type == 'event')
    {
        // do something
    }
}

Instead of writing a whole bunch of if statements for each view and content_type, can I do something like

function THEME_process_view_calendar()
{
    // do something
}
function THEME_process_view_google_maps()
{
    // do something
}
function THEME_process_content_type_news()
{
    // do something
}
function THEME_process_content_type_event()
{
    // do something
}

If this is possible, what's the correct way of naming functions to do this?

In the case of the content types, Drupal invokes only the preprocess and process functions for the page; it doesn't invoke a different preprocess function basing on the content type of the node being shown. Drupal invokes the following functions (the same order is followed for the process functions):

template_preprocess(&$variables, $hook)
template_preprocess_page(&$variables)
MODULE_preprocess(&$variables, $hook)
MODULE_preprocess_page(&$variables)
ENGINE_engine_preprocess(&$variables, $hook)
ENGINE_engine_preprocess_page(&$variables)
ENGINE_preprocess(&$variables, $hook)
ENGINE_preprocess_page(&$variables)
THEME_preprocess(&$variables, $hook)
THEME_preprocess_page(&$variables)

"MODULE" is the short name of a module, "ENGINE" is the short name of the theme engine used for the currently used theme, and "THEME" is the short name for the currently set theme.

You could say to Drupal to call different preprocess functions, but the hook that would add them doesn't have information about the content type of the node being shown. hook_theme_registry_alter() could be used to add new preprocess functions to a theme function, but all the preprocess function added would be all executed.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['page']) {
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_additional_preprocess_handler';
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_last_preprocess_handler';
  }
}

This is only necessary if the preprocess function is not one of the functions that Drupal would invoke.

If you need to use a different template file basing on the content type, then a preprocess function can suggest the template files to use; in Drupal 7, this means to use code similar to the following one:

function mymodule_preprocess_page(&variables) {
  if (!empty($variables['node']) {
    $variables['theme_hook_suggestions'][] = "page__" . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type);
  }
}


How to find in a node template file that node is loaded directly or from 'node_load' function? I want to check, in a node template file (node-node-type.tpl.php), that code is executing because of a direct request from a user visiting a node page or from calling node_load function in somewhere else?

EDIT:

the problem was 'Number of posts on main page' option in 'Post settings'. its value was 30 (I don't remember why I set it to its maximum value but I'm sure there was a reason that wasn't related to it's true functionality I think it triggers something else).

now that we know problem is from 'Number of posts on main page' option how I
can I fix it?
why this option invokes node template file despite the fact that I use a custom page.tpl.php which doesn't call node_view at all?

Edit: I realise after writing the answer that I sound rather negative. Sorry about that, but I can't phrase this in a positive fashion.

Answer: First, and foremost, you are mixing logic, with output. The template should not have logic in it, and should absolutely not care about why it was called.

When a user visits node/1, core will call node_load(1). This is in no way different from calling node_load(1) anywhere else.

A node template does also not execute as a direct result of loading a node. Templates are used when the theme layer renders a node, which is the completely other end of the response.

You can, in theory, call debug_backtrace() to get the call stack, and from there figure out more information about from where node_load was called, but there is almost certainly exactly 0 valid use-cases for this. I guarantee that you do not want to go down that path, and even considering it means that something is seriously wrong.

I have built Drupal-sites professionaly for years now, and have done some really, really ugly hacks during that time. Neither of them would come anywhere near analysing the stacktrace, in the theme layer.


Multiple dates token for auto node title I am using this token to create node title [node:field-date-concert:custom:j-m-Y] and it works fine if there is one value for date in node.

Problem is that if there are 2 or more values i only get first one displayed but would like to get them all.
So instead of just showing 05-05-2016 as node title, i would like to have 05-05-2016, 15-06-2016, 28-07-2016.

You could use the following code snippet in your auto_nodetitle configuration.
Don't forget to select the option "Evaluate PHP in pattern.".
And replace the field_date_multiple with your own field's machine name.

Hope this helps!

<?php

$dates = array();
foreach($node->field_date_multiple[LANGUAGE_NONE] as $date){
  $dates[] = date('j-m-Y', strtotime($date['value']));
}
echo implode(', ', $dates);

?>


Skip Payment Step from Checkout process I have setup a Drupal Commerce website (using Drupal 7) with two shipping options:

Delivery by courier company
Pickup from store

The next step in checkout process is to choose the payment method. BUT...
if the second choice (pickup from store) is chosen, the only available payment method is Pay at store (offline payment). I have managed to show only this option through Rules. So far so good.

My concern is that for better user experience I have to make this step skipped. So after the Shipping step where the user selects the Pickup from store option, the next logical step is the Review pane for a final review by the user before complete the checkout process.

I have read that the Payment selection method (checkout step) is required for the Payment Redirection (I fail to understand it).

I have already tried to use hook_commerce_checkout_router, checking the $order shipping line and use the drupal_goto function redirect to the review page. My custom function is the following:

function <myModule>_commerce_checkout_router($order, $checkout_page) {
  global $user;

  if ($checkout_page['page_id']=='checkout') {
    if (!empty($order->commerce_order_total['und']['0']['data']['components']['2']) && ($order->commerce_order_total['und']['0']['data']['components']['2']['name']=='flat_rate_from_store')) {
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }
}

I get error "The page isn’t redirecting properly". It is the same result as if someone is at the shipping step and manually tried to enter at the url the /review.

Do you think is possible to achieve skipping this step to speed up the checkout process or I have to give up trying ?
At year 2017 it is very important to give a user the best and the most logical way to move around in a website. Useless steps and clicks slow down the process and maybe end in frustration.

The problem is you're redirecting without also updating the order's status. The checkout router determines access to a checkout page by matching the order status to the URL, and it will prevent access to any page the order doesn't appear to have reached yet.

In your case, you should just use the same API function the Payment module uses when it needs to redirect past the off-site payment redirect page because an on-site payment method was used. The function is commerce_payment_redirect_pane_next_page() and you can view the function signature and docs in commerce_payment.module.


How do I programmaticaly get the name/ID of the shipping method for an order? I need to get the name of the shipping method for a given order in my module. I have the id of the order. After I get the shipping info by means of commerce_customer_profile_load($commerce_order->commerce_customer_shipping['und'][0]['profile_id']) i do get the info about the address, but I do wonder how to get the name / id of the shipping method.

I found a good answer at https://drupalcommerce.org/discussions/8274/get-shipment-services-object-flat-rate-order-object

// Be sure there are line_items
if (!empty($order->commerce_line_items["und"])){
  $line_items = array();
  // Gather together the IDs of the line items
  foreach($order->commerce_line_items["und"] AS $line_item){
    $line_items[] = $line_item["line_item_id"];
  }
  // load_multiple allows us to use $conditions so we only load the entity of type "shipping"
  $shipping_line_item = commerce_line_item_load_multiple($line_items, array('type' => "shipping"), FALSE);
}


Delete button not working in Checkout page I created a Rule on event 'After adding to cart' to action 'Page redirect' to redirect straight to Checkout page (at /checkout) so it skips the Cart page.
The cart page by default has the Line Item: Delete button and its title is 'Remove' and it works.
I decided I wanted same in the Checkout page and it is easy to add, just edit the view and add the 'Line Item: Delete button'.
But it does not work. Also for some reason its title is 'Delete', not 'Remove'.
When clicking Delete it refreshes the page giving errors 'There are errors on the page. Please correct them and resubmit the form.' under 'Shopping cart contents' and another error under 'Billing information' which simply says to fill in the form details:

Address field is required.
Postal code field is required.
City field is required.
Full name field is required.

Which makes no sense, I'm just trying to update the cart contents inside the checkout page.

Even better. If I do fill the forms and click to delete the product from cart, it redirects straight to Review page. But I didn't even click the 'Continue to next step' button.

?

Have never done something of that sort but what I assume is, once you move ahead with checkout, a order is created with status IN CHECKOUT or something like that.

So until a product is there in cart, you can remove that & but once you enter into checkout & order id with other details is created...product can't be removed. Maybe someone from Drupal Commerce maintainer can confirm more on this..


Using PrivateTempStore for anonymous users with Internal Dynamic Page Cache & Internal Page Cache modules I'm developing a Drupal 8 project which interacts with an external API. This API handles user authentication, completely bypassing the Drupal user system. This means that logged in API users are treated as anonymous Drupal users.

I have created a module that utilises the PrivateTempStore to store user sessions. This works as expected. However, what I am unclear about, is the best practice as far as utilising the Internal Dynamic Page Cache and Internal Page Cache modules.

At the moment, any user session sensitive blocks or pages that my module outputs are set to have a maximum cache lifetime of zero - to ensure that, for example, the user's account page is not served from the cache.

Is this the correct approach, or would I be best at least disabling the Internal Page Cache module - which specifically targets anonymous users?

The site will be hosted on the Acquia platform, so Varnish will likely be utilised.
For that same reason, is it better to disable one or both of the Drupal caching modules?

Private TempStore always generate Anonymous Session. That means If you are using any Caching Layer for your Application it always break. either in Acquia or other platform.
May be you can use Browser LocalStorage for saving data and sync it when its required. it will help you to cache your pages.
In Acquia, cookie based cache variation Generation possible so you have to create cookie and based on that value you can generate cache tags.


How to render Entity Reference fields in the current language I am trying to render fields from an entity reference in a twig template but they are displaying in the default language instead of the selected one. My twig code:

{% for location in node.field_locations %}

      {{ location.entity.title.value }}
       {{ location.entity.field_sub_title.value }}

 {% endfor %}

You can use the following procedure for translated fields

Add language in your THEMENAME.theme

function dru8_preprocess_node(&$vars) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['lang'] = $language;
}

And in your node.html.twig to get translated fields

{% if node.field_stories.entity.hastranslation(lang) %}

{{ node.field_stories.entity.translation(lang).title.value }}

{% else %}

No translation

{% endif %}

Thus in your case you will need

{% for location in node.field_locations %}

      {{ location.entity.translation(lang).title.value }}
       {{ location.entity.translation(lang).field_sub_title.value }}

 {% endfor %}


How to show tooltips on form labels based on view filter descriptions in a Bootstrap sub-theme? I am trying to find a way to display tooltips when a user hovers the mouse over a filter label of a views search page. Preferably, to reduce hard-coding, I would like to take into advantage the filter description and get the tooltip text from there (and subsequently hide descriptions through css).

Also the best way I found to actually activate the tooltips in Bootstrap is to add the attribute data-toggle="tooltip" to the element that we need to show a tooltip for.

So far I am using the recipe from here adding the data-toggle element

 function mytheme_form_element($variables){
     dpm($variables);
  $original = theme_form_element($variables);
  $return = '
' . $original . '
';
  return $return;
 }

but I don't see the filter description anywhere in the $variables array plus this snippet themes the filter field and not the label but would probably do the trick.

You can do it in form alter, here's an example (add additional conditions yourself):

/**
 * Implements hook_form_FORM_ID_alter().
 */
function yourmodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'filter-title';
  $form['title']['#attributes'] = array(
    'data-toggle' => 'tooltip',
    'data-original-title' => $form['#info'][$field_name]['description']
  );
  $form['#info'][$field_name]['description'] = '';
}


How can I delete all field collection revisions? I want to delete all field collection revisions of a specific field.
I found deleteRevision for this job, but I don't know how to use it. (I couldn't find any example of it.)

Anybody know how can I delete all field collection revisions of a specific field?

Since you want to purge revisions on a field in a field collection and not an entire content type, your best bet is going to be doing this directly in phpMyAdmin. I don't know of any modules that enable you to delete revisions for a particular field but not the whole content type.

I would locate the field in question and run DELETE from field_revision_field_yourfieldname.

Of course you should back up things before you run a delete query.

The data for nodes and node revisions are store in two different tables. The data for the node page is stored in field_data_yourfieldname. The data for the revision is stored in field_revision_field_yourfieldname.

To illustrate this concept for you, I set up a fresh install of drupal (7.28) on my local machine and connected it to a new empty database.

I set up a content type called field collection demo and I added two field collections.

Since I'm not sure what your configuration entails, the fields I used may or may not be similar to your fields.

Then I created two sample nodes and edited both of them several times with revision tracking turned on. I mostly used lipsum text but for the last revision I typed meaningful text to help you see what's happening in the database.

Here you see that I have created the two nodes:

Here you can see the lipsum text in the original post.

Here you can see that I've created multiple revisions of the node.

And here you can see the meaningful revised text that is the most recent revision.

The next picture shows you how this data is stored in the database in the field_revision_field_yourfieldname table.

You can manually delete one row from the table using the red "X" in phpMyAdmin. Look, for instance, at the last row in this table.

After I click the red "X" for that row, it is deleted.

You can see that now the revision that began with r2 is gone from the field_revision_field_my_fifth_field table.

This removes the revision from the node's revision page. Notice in this picture, the field labeled "My fifth field" is missing.

But this does not affect the node's public view, because that data is stored in the field_data_my_fifth_field table not in the field_revision_field_my_fifth_field_table.

Therefore, I can safely delete all the revisions from the field_revision_field_my_fifth_field_table with the delete query (as I've done on my demo site) and still view the node with no problems:

All the revisions from the field "My fifth field" are gone on the revisions tab but the view tab remains unchanged.

If you wanted to delete all the revisions for all the fields that comprise a node collection, you would simply run the delete query for each of the field_revision_field_yourfieldname tables in the database.


base_url for both http and https? I have a site that is accessible both through http and https. I see  the security review complains that base_url is not defined in settings.php.

However when I define it as http://example.com, and flush all caches, my template in https is not rendered.

When I comment out the $base_url line in settings.php everything comes back to normal.

How can I resolve this problem?

You probably need to do something like this:

$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$base_url = $protocol . '://mysite.com';

...so that Drupal knows which protocol to use depending on how the site was accessed.


Custom module interfering with CSS on /user page I am having trouble with a custom module. When my site is working properly, the /user page loads 4 CSS files. After rebuilding the cache, only three files load. It's not a 404, Drupal doesn't even try to load the last file.

If I disable the module and load the /user page, the CSS loads properly. I can then re-enable the module and the /user page continues to work. Doing a cache rebuild breaks it again. I'm wondering how that CSS file is generated, and how I can make it load properly when my module is enabled.

Oddly, this issue occurs even if I remove all implementation details from the module: the xyz.services.yml file and the src folder. The only remaining files are README.md and the barebones xyz.info.yml file:

name: XYZ Customizations
description: XYZ-specific additions and modifications.
package: Custom
type: module
version: 1.0
core: 8.x

I'm very confused why this might be happening. Any insight would be appreciated. Thanks!

As it turns out, my custom module folder had the same name as my site's active theme. I believe this was causing the error. Renaming the module appears to have resolved the issue.


DAMP / Aquia Dev (mac) apache fails on import of drupal core 7 I'm attempting to switch from Bitnami to Aquia Dev Desktop for the mac (OS 10.8.2). I'd like to be able to develop a couple sites (using core drupal - not the aquia distro) simultaneously in a reliable environment.

Ran the uninstaller on Bitnami and checked that all files were
deleted.
I successfully installed Aquia Dev Desktop, saw that Apache and
MySQL servers were both running, and got the local Aquia Drupal site
when I clicked "Go to my site" in the control panel. So everything
was working fine.
Downloaded Drupal 7 to a folder on my desktop, decompressed, renamed the drupal
folder to my site name (all lower case and no special characters),
and reset the folder permissions to "Read & Write" and applied to
all enclosed folders.
I attempted to import into Aquia Dev Desktop but got "Error -
Process 'Apache Web Server' failed to start".

I tried using the settings panel in Aquia Dev Desktop to reset port from 8082 to 8080 but apache still won't start.  Tried a few other port numbers and no luck.

Here's the complete Apache error log:

  [Fri Apr 05 15:05:54 2013] [notice] Apache/2.2.23 (Unix) PHP/5.2.17
  configured -- resuming normal operations [Fri Apr 05 15:06:37
  2013] [notice] caught SIGTERM, shutting down [Fri Apr 05 15:06:43
  2013] [notice] Apache/2.2.23 (Unix) PHP/5.3.18 configured -- resuming
  normal operations [Fri Apr 05 15:16:41 2013] [notice] caught
  SIGTERM, shutting down

I have very little experience with server administration or apache configuration.

Can anyone point me in the right direction?

This turned out to be a bug in Dev Desktop.  The good folks at Acquia fixed the bug and posted a new version that works nicely.


How do I use Webform fields in a view? I use the Webform module to get user information, and I want to use some Webform fields in a view; for example, I want to show only some of the fields  (e.g. name and e-mail), and expose a filter for the user's email.

How do I create it?

From Webform vs. CCK (or D7 Field module):

  Webform submissions are not nodes. This means that you can't use Views with submissions, ...


Autocomplete 403s when behind a proxy I've got a virtualbox VM setup as a proxy server between Drupal to try to replicate a CDN causing errors on a client's machine.

My current port is as follows: http://site-name.dd:9999

When I go to the proxy-enabled site, and try to use a given entity reference, I get a 403 error:

An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: http://site-name.dd:8086/index.php?q=entityreference/autocomplete/single/field_guardians/participant/player/NULL
StatusText: Forbidden
ResponseText:
Access denied | Site Here
Skip to main content
Site Title Here
Main menuName
Another Name
A Third Name
Products
Access denied                                        You are not authorized to access this page.

My guess is that this is due to me trying to access via port 9999, and the direct site being on 8086.

I believe a similar (though perhaps not exact issue) is also facing the client. How do I deal with this AJAX error? Has anyone seen anything like this?

This is for a D7 site.

EDIT:

I have also tried changing these settings in settings.php:

$conf['reverse_proxy'] = TRUE;

And alternatively setting one of these two and testing with each, with no success:

$conf['reverse_proxy_addresses'] = array('10.1.0.157');

$conf['reverse_proxy_addresses'] = array($_SERVER['REMOTE_ADDR']);

EDIT 2:

From what I can find, the error is because it is getting the original server port from the autocomplete field input element value. So either I need a way for the 8086 port to recognize the 9999 port as legitimate or I need to switch to the 9999 port as correct.

You should set your Base URL to

$base_url="http://site-name.dd:9999";

From default.settings.php

  If Drupal is generating incorrect URLs on your site, which could
   be in HTML headers (links to CSS and JS files) or visible links on pages
   (such as in menus), uncomment the Base URL statement below (remove the
   leading hash sign) and fill in the absolute URL to your Drupal installation.


Etiquette for module feature requests I am relatively new to Drupal, and I am thinking of posting a feature request on Drupal.org for one of the Drupal modules that I'm using.  Before I do it, I wonder if there is any convention or etiquette that I should know about.

What is the convention for asking a feature request to the module developer? Is it bad to ask for the feature if it's a small thing that I might be able to write myself after some tinkering?

If you have the ability to write the patch, even if it's not "right", it can often encourage the developer to jump in and help. If you're not as comfortable writing the patch, you can also explicitly offer to test it.

Overall, just be polite, and be prepared to be patient. We're almost all volunteers!


How to do social links with icons as a link field in a block? I have a footer that contains a simple contact information and underneath is a social follow set of links.

I created the block type, with the thought that the top part (Connect) is a WYSIWYG.

My second thought was to make the Follow Us just a link field with 5 values, but I want to add a little flexibility and for theming concerns, I need to know what link goes with which service.

Can I either do this with the link field, or can I reference a menu somehow and attach it to this block type? As a menu, I can rig up menu attributes. But if there is a more practical way, I would like to know how to do it.

I do not want to hard code it because they might change URLs or want to reorder the list of services at any time.

I had a similar task, for me was better creating a Custom Block Type, named 'Social networks' with one field of type 'Link'.

In this field you can configure how many links you can handle (remember once you create one block of this type, you'll cannot change this value).

Once this Custom Block Type was created you can configure 'Manage form display' and 'Manage display' if you need.

Now you'll be able to create a Custom Block of type 'Social Networks' that provide a couple of links that you can set/edit, rearrange and use proper template per block, and place where you want.

This was the solution found to not use any piece of code.


Best practice to separate content per city I'm trying to find the best practice to separate user content per country/city in a way that allows the user to select the country or city once so that whenever he adds content it will be automatically assigned to this city/country
and when searching, the results will be related to currently select city too.
so it's more like a global choice across the website.

How is this best achieved usually in drupal,, I used taxonomy to classify content per city.. but this doesn't feel like the solution.
Any guidance is highly appreciated.

You said you already had a taxonomy vocabulary holding the countries and cities. This sounds like a good start. You can add a term reference field to the user profile, so that users can select their locations from the same vocabulary.

One idea (which could work without coding) is that you use Entity Reference for referencing terms from this vocabulary on nodes. Then you can use Entityreference prepopulate to fill out the reference fields automatically based on a value in the URI's query string. As the last step you will need to render the content creation links and make sure the URIs contain the taxonomy term selected on the current user's profile. You can do that e.g. with Page Manager alongside with Panels by adding a New custom content pane, where you can use keywords from the User context which you need to add manually to the page.


How to use  tag in views? I have a site on Drupal 7, where I'm using Views with Multilingual settings.
I have 2 languages, Russian and English.

On the front page, I have created a "Latest News" block with Views.
Each news item has a link to the full article like the following ones:

example.com/en/news/1
example.com/ru/news/1

This block is also shown on some other pages, such "Services - > Service 1"  shown at example.com/en/services/service-1.

The problem is that on my block I use global text to format the output of the latest news; the link is built using the following:

[title]

It works fine on the front page, but when I'm on the Services page, the news link is similar to example.com/en/services/news/1,which is incorrect; Drupal gives me an error about a not existing page.

Is there a way to reference the front page with any tag I can use in the "Global Text" settings?

You can use php filter, or install Token Filter module and then enable tokens in filter which you use (admin/config/content/formats). Token for front page is [site:url] so you should write your link like follow:

[title]


d7: to be inserted ID, is there a cleaner way? I need to know the 'to be inserted ID'

I wrote the following function, it works, however, I'm sure this is not the way to do it.

 function insert_node_style($style) {
  // get latest id
  $id = db_query("SELECT MAX(nid) FROM {node}")->fetchCol('nid');
  $id = array_shift(array_values($id));
  $new_nid = $id + '1';
  // insert nid, vid and style
  db_insert('nodestyle_node') ->fields(array(
    'nid' => $new_nid,
    'vid' => '1',
    'style' => $style,
  ))
  ->execute();
}

Is there are cleaner/drupal way to achieve the same result?

I don't think there's a 100% reliable way to get the ID that will be used next. Even the method you've got won't work completely. Take this example:

Insert a node into the database (it has the new nid of 1 for arguments sake)
Insert another node into the database (it has the new nid of 2)
Then delete that second node
Add a new node to the database again. This time it will have a nid of 3, not 2 (as would be expected from your code).

The problem is that the MySQL AUTO_INCREMENT value exists completely independently of the primary key ids that are currently in the database; so unless you reset the auto increment counter each time there's no way to reliably determine the next id.

Also in a system with multiple simultaneous accessess to the database using code like that introduces potential race conditions.

It would be far simpler to perform this task when the node has been saved, perhaps in hook_node_save().

Oh and one other little thing, the vid you're inserting should not be 1, it'll be determined for you by the system. Using 1 for every node will link every single node to one revision in the node_revision table...probably not what you're looking for.


How can I override the string programmatically in forum topic list? I am using the Forum module in Drupal 7. I want to change "Topic" with "foo", for example, in the General discussion forum page.

Where did I search for this

I did check the template in the forum module file and for this page it is forum-topic-list.tpl.php. There I found that, it is printed by following code,

<?php print $header; ?>

And in the description, the following statement has been provided.

  Available variables:

  $header: The table header. This is pre-generated with click-sorting information. If you need to change this, see template_preprocess_forum_topic_list().

Hence, there is nothing called "Topic" which I can just change as this header coming from the $header.

Now, I did check template_preprocess_forum_topic_list() but it does not have provision to Change "Topic" string.
Lastly, I did check the forum.module where I found the following function starting at line 914.

 function forum_get_topics($tid, $sortby, $forum_per_page) {
   global $user, $forum_topic_list_header;

   $forum_topic_list_header = array(
     NULL,
     array('data' => t('Topic'), 'field' => 'f.title'),
     array('data' => t('Replies'), 'field' => 'f.comment_count'),
     array('data' => t('Last reply'), 'field' => 'f.last_comment_timestamp'),
  );

Now, in the above function you can see t('Topic'). I could simply replace it with t('foo'), but I think this is not the right way.

Any suggestion, how can I override this? Thanks.

You could do it using the String Overrides module.

  Provides a quick and easy way to replace any text on the site.


how can i attach a taxonomy to the users profile? I use drupal 7 and need to attach a certain taxonomy to a user. there is module for drupal 6 but as i see there is no module for that in drupal 7. how can i do that in my module by coding?

why do i have this question: i sell some digital files and now i am developing a module for selling my files. i want to sell them this way: each file has a certain taxonomy. when my user buys that file he or she gets that taxonomy. once he clicks on download link i have to check whether that user has that taxonomy already or not!

Users in Drupal 7 are proper entities and fieldable.

Goto Administration » Configuration » People » Account settings » Manage Fields (admin/config/people/accounts/fields)

Add a new Field.  Choose a label, and choose Term Reference as the field type.  Configure as needed.  This should identical for how you do it for a Content Type (ie, a node).

The click on the Manage Fields tab.  Set up the display for how you need it.

Edit you users, and add in some field data.  It will be in the full loaded $user object, and you can use it in Views over Users.


How to index Drupal Commerce 2 products for the search? The products in Drupal Commerce 2 could not be found through Drupal's default search form.

Modules like Commerce Search are available only for Drupal 7.

How can I index product titles or SKUs and add them to the search in Drupal 8?

Thanks!

The core search will only ever search node's and users. If you want to search other entity types, like products, use Search API.

Just install the module, create a server (you can use the search api db submodule if you just want to use your sql database) and create your index. You will have the option of selecting which entity types get added to the index, you probably want nodes and products. Then add which ever fields that you want to be searchable.

See the official documentation for screenshots and more info on how to take it further (like adding facets).


Remove tasks and index when creating a menu tab from views I am using views to create a menu tab for my views page and it works fine accept it comes with two unexpected tabs: Tasks and Index, which are showed in the photo below. Is there any way to remove them? Thanks.

You can achieve this using hook_menu_local_tasks_alter hook.

  Alter tabs and actions displayed on the page before they are rendered.

function hide_tabs_menu_local_tasks_alter(&$data) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "check your path") {
          unset($data['tabs'][0]['output'][$key]);
        }
    }
}

You can also take a look on Tab Tamer module.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully
  when javascript is disabled.

  Tab Tamer utilizes Drupal's cache system to help conserve server
  resources.


Possibility to reinstal module without deleting old configuration for module permissions by term I tried to upgrade my site from Drupal 8 to Drupal 9. In this process I upgrade the module Permissions by Term to Version 3.0. The upgrade failed due to problems with extension of CiviCRM that were not covered by update report. So I turned back to D8. Afterwards I got the messages that the module Permissions by Term 3.0 was not compatible to D8 and thus disabled. So I downgraded that module by Composer successfully to version 2.31. After trying to reinstall it I got the error message that it couldn't be installed because of existing configuration. In the web I found several ways to delete old configurations, but of course I would like to keep it since I'm afraid I would have to review every page to set permissions again. Thus my questions: Is there any way to reinstall the module without deleting my old configurations (or was my fear wrong)?

Module configuration files are stored in the module's config/install directory. When you enable the module, Drupal tries to install those configurations. If Drupal complains that the configurations already exist, then you can take the following steps:

Identify which configuration files Drupal is complaining about.

Move those configuration files out the module's config/install directory. It doesn't really matter where you move them to, but you're going to want to restore the files after everything is fixed so I suggest just moving them up one level into the config directory.

Try to install the module. Drupal won't find the module's default configuration files that you moved so it shouldn't complain any more.

If Drupal still complains, that means you missed a configuration, so repeat the above steps.

Restore the original configuration files - move them back into config/install.

Note that this is a workaround - not a solution. The module should be examined to ensure it properly removes its own configuration (if appropriate) when uninstalled, and that it declares the proper dependencies in its configuration, and that configurations which are not removed are defined as optional. Please file a bug report in the issue queue for that module so that this can be fixed for other users.


How to lock distros so they can only be used on 1 URL? I plan on making distributions for dating sites and stuff like that.

Maybe sell them as functional themes.

How do I lock the distribution and theme so the client can only use it on 1 URL?

I have seen this done with many website and templates, how can I do this with Drupal?

I see 2 possible approaches (there might be others):

Include "something" that requires an API key, whereas 1 such key can be used on 1 URL only.
Offer a "hosted" version only, which uses your distribution. That way you don't have to ... "distribute" the distribution.

PS: Drupal is GPL, so before creating something that is based on Drupal, make sure you do understand the legal aspects of GPL ...


Display node field into cart how can I display node info(not only title but all fields) into cart?
Example:
My site has a lot of stores and each store can buy some books.
How can I display stores info into user cart?
Thanks in advice

The Drupal cart is a views display of commerce line items. Depending on your setup you'll have to alter the existing cart view and add one or two views relationships (in the advanced section).

The first relationship is from commerce line-item to commerce product. It is called something like Commerce line-item: Product. This exposes all product properties to the view.
If you use a product display with custom properties, you can also add Commerce Product: Referencing Node (depending on the fields you need this one is optional).

Now you have all field of your product (and product display) available to views and you can add them in the Fields section.


Add custom text to certain pages To add custom text to a node I have a code like this:

function mymodule_node_view($node, $view_mode, $langcode) {
  $var=....;
  if (.....) ){
      $node->content['new'] = array(
       '#markup' => $var,
     );
  }
}

It works perfectly, but now I need to add this text to pages that don't load any node. So I can't use this hook.

I mean something like the drupal_set_message function, showing custom text at the top of certain pages.

maybe you can add this to your if condition:

if($view_mode == 'full' && node_is_page($node)){
   //your code here
 }


How to add a menu item to main menu: hook_menu() or menu_link_save()? I just want to programmatically add some menu items to the main menu, but none of the answers I found worked. Some answers suggest using hook_menu(), others suggest using menu_link_save(). I followed what reported in Can I add a custom link to "Main Menu" via hook_menu? but it just doesn't work. There's no new item added, neither in the UI nor in the database.

function mymodule_menu() {
  $items['my/path'] = array(
    'title' => 'Title',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

Also I found How and where do I programmatically add a menu to the Navigation menu?. Answer #2 says that using menu_link_save() is the way to go, but I could not get it to work. Do I have to place the code in a certain location or a special hook?

$item = array(
  'link_path' => 'my_path',
  'link_title' => 'Title',
  'menu_name' => 'main-menu',
  'weight' => 0,
  'language' => 'en',
  'plid' => 0,
  'module' => 'menu',
);
menu_link_save($item);

Since both answers didn't work out, it seems that I am missing a crucial point. Could anyone say what's going on here?

After a hard time I figured out what hampered the execution of the above code: clearing caches isn't enough to see the results. I had to use devels menu reset (/devel/menu/reset). Using drush's drush eval 'menu_rebuild();' as mentioned at How do I call the menu_rebuild function in Drupal 7? somehow does not work. I do not know why.


Wysiwyg Comments is not turning off I'm new at Drupal and I am having trouble with comments in some content types.
I create a new content type and check that it'll hava comments, but I don't want the Wysiwyg editor, so I disable it, but it's still there, how can I disable it for a content type speciffic?
NOTE: I Turn off the Wysiwyg comments in this content Type.

For Drupal 6, I normally add the following to a custom module:

function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}

To be honest, I can't recall why I am using $form['#id'] instead of $form_id for the conditional.


How to mock a node field value for phpunit? I'm working on a project where we need to have code coverage using phpunit.

I have a method that includes this code:

  $node = \Drupal::entityTypeManager()->getStorage('node')->load($node_id);

  $form['data-title']['#value'] = $node->label();

  $form['data-description']['#value'] = $node->field_description->value;

So I need to mock out the node object.

I can get the node label to work, but not the field_description->value

Here's my set up function in my test class:

/**
   * {@inheritdoc}
   */
  protected function setUp() {
    $container = new Container();
    $container->set('string_translation', $this->getStringTranslationStub());

    $renderer = $this->getMockBuilder(Renderer::class)
      ->disableOriginalConstructor()
      ->getMock();
    $renderer
      ->method('render')
      ->willReturn('Hello world');

    $container->set('renderer', $renderer);

    // Mock entity type manager.
    $this->entityTypeManager = $this->getMockBuilder(EntityTypeManagerInterface::class)
      ->disableOriginalConstructor()
      ->getMock();

    // Mock a node and add the label to it.
    $node = $this->getMockBuilder(Node::class)
      ->disableOriginalConstructor()
      ->getMock();
    $node->expects($this->any())
      ->method('label')
      ->willReturn('shaken not stirred');

    $node->expects($this->any())
      ->method('access')
      ->willReturn(TRUE);

    $node->expects($this->any())
      ->method('id')
      ->willReturn(1);

    // @todo figure out how to add a field to a mock node.
    /*$field_description = new \stdClass();

    $field_description->value = 'This is a description';

    $node->set('field_description', $field_description);*/

    $node_storage = $this->getMockBuilder(EntityStorageInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $node_storage->expects($this->any())
      ->method('load')
      ->willReturn($node);
    $this->entityTypeManager->expects($this->any())
      ->method('getStorage')
      ->willReturn($node_storage);

    $this->uuid = $this->getMockBuilder(UuidInterface::class)
      ->disableOriginalConstructor()
      ->getMock();

    $container->set('entity_type.manager', $this->entityTypeManager);

    $entity_repository = $this->getMockBuilder(EntityRepository::class)
      ->disableOriginalConstructor()
      ->getMock();
    $entity_repository->expects($this->any())
      ->method('getTranslationFromContext')
      ->willReturn($node);

    $container->set('entity.repository', $entity_repository);

    \Drupal::setContainer($container);
    $this->form = MyForm::create($container);

  }

The following should work using PHPUnit Mock Objects as in your example.

First mock FieldItemListInterface __get magic method.

$fieldDescMock = $this->getMockBuilder('\Drupal\Core\Field\FieldItemListInterface')
  ->disableOriginalConstructor()
  ->getMock();
$fieldDescMock->expects($this->any())
  ->method('__get')
  ->with('value')
  ->willReturn('blah');

Then mock the Node/ContentEntityBase __get magic method.

$node->expects($this->any())
  ->method('__get')
  ->with('field_description')
  ->willReturn($fieldDescMock);


Available tokens in the Filter Section of Views Are any tokens(as nid) available in the FILTER CRITERIA of Views (see pic bellow). For example I can sort out all nodes with greater than the current NID...

I don't see any way in the Views UI to do this, but you certainly can with a hook:

function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && ($node=menu_get_object())) {

    $filters = $view->display_handler->get_option('filters');

    $filters['nid']['value']['value'] = $node->nid;

    $view->display_handler->override_option('filters', $filters);

  }

}

which would set the value in the node nid filter to that of the node nid the View is displayed on.


Rewrite query string for exposed taxonomy filter I have this page: https://www.meubelentheo.be/catalogus

On the top of this page, just below the title you will see links such as Babykamer, Bureau, Decoratie etc.

These are taxonomy terms in an exposed filter. I use the Views module together with Better exposed filter.

If you click on the first term Babykamer, you will see the URL changes to https://www.meubelentheo.be/catalogus?field_portfolio_tags_tid=34

What I want to achieve: rewrite the part after the ? to something like ?term=babykamer or even better, rewrite the whole querystring to catalogus/babykamer

I tried the Query paramters to URL module and this indeed rewrites the URL to but this is not what I want. I want the taxonomy term name to be shown in the URL.

Any ideas?

You can accomplish this look by using Contextual Filters instead of an exposed filter in Views. But this approach will involve several changes. In a nutshell you would need to:

The list of tags on top would need to be a different (taxonomy) Views, embedded in the Header area of your catalogus View using Global: View area. In the taxonomy view, you will need to rewrite the output of the Taxonomy field (use "Rewrite results" in the taxonomy field) to a link that points to /catalogus/[field_portfolio_tags]
Add a Contextual Filter to your catalogus View. Be sure to add the taxonomy field Portfolio tags to the list of fields in this View (you can hide it if you don't want it to display for every single product). Choose the taxonomy Content: Portfolio tags. Choose Display all results in When filter value is not in URL. In WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED  choose Specify validation criteria. Validator: taxonomy term. Filter value type: term name converted to Term Id.

When you click on a taxonomy term in the embedded header View you will be redirected to /catalogus/name_of_tag. The Contextual Filter will assure that only products with that tag will be shown.

This should be it!


Node Update not showing to anonymous user even after clear cache I have a live site , when i update any node, it is not reflected for anonymous user.Even I clear the cache.This domain has SSL certification but we use it only for few pages.But if we use https for the updated content for anonymous user, It show the updated content.
  We have used cache for bloack and anonymous user and minimum cache lifetime and cache expiration is 1 hour.

You have set the value of Expiration of cached pages to 1 hour

Expiration of cached pages tells the External Caches for how long they can server the old version of a page.

In your case browser is the External Cache and it assumes that it can show old content for an hour. So it doesn't even make a call to you website when you request the page.

You can see the changes after an hour or clear all your browser caches to see the new changes.

More Explanation


What is the difference between limit(1) and range(0, 1)? In a query I tried using limit(1); I got a WSOD, but when I use range(0,1) I don't get any WSOD.

What is the basic difference between limit(1) and range(0, 1)?

Base difference is that range is a method of SelectQuery class, and limit isn't.

Some APIs can extend SelectQuery and add limit. For example  $query->extendQuery('PagerDefault') will return object of PagerDefault class that has limit method defined.

It may result in a syntax looking like limit() is invoked on SelectQuery, when in fact it isn't:

$query = db_select('node', 'n')
      ->fields('n')
      ->condition('type','problem','=')
      ->extend('PagerDefault')
      ->limit(20);


How do you set a default input text format per content type? I want to be able to set a different default input text format per content type and per content field.

For example, the format type choices might be "Plain text" and "Rich text editor" and in some cases I want the format to default to "Rich text editor" but keep "Plain text" as a choice in the dropdown. I know that I can change the order of the text formats to make "Rich text editor" the first choice, but this method changes all of them, that's not what I want to do.

In the absence of a stable release of Better Formats module, you can create a custom module to do this for specific content types or fields.

Create a module (modulename.info and modulename.module, inside a folder 'modulename'). Example:
default_text_format.module:

<?php
/**
* Implements hook_element_info_alter().
*
* Sets the text format processor to a custom callback function.
* This code is taken from the Better Formats module.
*/
function default_text_format_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'default_text_format_filter_process_format';
      }
    }
  }
}

/**
* Callback for MODULENAME_element_info_alter().
*/
function default_text_format_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change input format to "Filtered HTML" for body fields of article nodes
  if ($element['#bundle'] == 'article' && $element['#field_name'] == 'body') {
    $element['format']['format']['#default_value'] = 'filtered_html';
  }
  return $element;
}

And default_text_format.info:

name = Default text format
description = Adapt the module code to set a default format for a content type.
package = Custom modules
core = "7.x"

Put these files in a folder 'default_text_format' in sites/all/modules/custom.

Change bundle name as appropriate for your content type. And you can substitute 'body' with your own 'field_contenttype_fieldname'. (After this comment / better_formats code.)


get taxonomy terms of specified language I know I can get list of of taxonomy of a vocabulary with

 $terms =  \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('course_category');

 kint($terms);

but it returned all that vocabulary terms, I am working on multi language site,I want retrieve terms of specified language.

my Drupal version is 8.1.3

I had some difficulties with printing tags in the current language in code too. This is what worked to get ONLY the translated terms of a vocabulary:

$vocabulary = 'MY_VOCABULARY_NAME';
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();

foreach($terms as $term) {
    if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $termList[$tid] = $translated_term->getName();
    }
}

// To print a list of translated terms.
foreach($termList as $tid => $name) {
     print $name;
}

To link the tags, see https://drupal.stackexchange.com/a/243160/71941


How to use the gallery formatter settings in a display suite code field? I am using the gallery formatter module to format photo galleries.

To satisfy a requirement I need to create a Display Suite code field that displays the list of pictures attached to a related node (attached through the Entity reference module).

The get the field_gallery containing images of the related page I use the following in the code field:

<?php
    $relatedNode = node_load($entity->field_related_page['und']['0']['target_id']);
    $field = field_view_field('node', $relatedNode, 'field_gallery', array( 'label'=>'hidden'));
    echo drupal_render($field) ;
?>

However this only displays a raw list of images. I need this list of images to be fomatted by the gallery formatter.

The formatter should be passed to field_view_field() as an array (instead of array( 'label'=>'hidden')) but how can I get the list of key->values that fill the array?

May I suggest field slideshow if you havent tried that already.  Field Slideshow

  Provides a Slideshow formatter for Image fields, using JQuery Cycle
  plugin.

  Compared to Views slideshows, building the slideshow from multiple
  nodes, this module builds it from a single node, with a multi-valued
  Image/Media/Field Collection field.


Apply Imagecache style to raw image url I have a site I'm working on where images are inserted into the body of blog nodes and I'm wanting to return these images in a view. I'm using computed field to successfully return the url of the images in the view, but I would like to apply an imagecache style to this before displaying it using

<img src = "[computed_field]">

Does anyone know the best way to do this? I've been searching around and have not been able to successfully do this yet. Thanks!

It sounds like you should handle this in your computed field's PHP since you're already parsing out the image there.

//Assuming $entity is the parsed node in question
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $entity->body[LANGUAGE_NONE][0]['value'], $matches);

//If an image match has been found, build a URI relative to public file base
//Assume image URLs are something like:
// "/sites/default/my_files/some_dir/whatever.jpg"
if(isset($matches[1][0])) {
  $public_dir = variable_get('file_public_path','sites/default/files');
  $uri = file_build_uri(str_replace("/$public_dir/","",urldecode($matches[1][0])));
  $entity_field[0]['value'] = image_style_url('thumbnail',$uri);
}


Results in view page with search api having multiple duplicate result I am in a dilly of a pickle.
I have a view that returns indexed content types.
The problem is that the view is returning multiple instances of the same content.
All of these are indexed nodes.

I read about someone else having the same problem here:
Results in view page having multiple duplicate result
They say you can use
hook_views_pre_render() in your template.php file
to filter the extra content types out of your view.

Specifically the article said to

function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}

This did not work for me. There was no $row->nid property. I think this is because they are using regular nodes and I am using indexed nodes.

Here is an example of my "$row printed out. (from $row above)

object(stdClass)[489]
      public 'entity' => int 4
      public '_entity_properties' =>
        array (size=2)
          'search_api_relevance' => string '1' (length=1)
          'search_api_excerpt' => string '' (length=0)

I altered this to try and filter by the property on "$row" called entity, which holds the id of the indexed item.

function BootstrapBlocks_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'search_the_mangroves') {
    $count = 0;
    foreach ($view->result as $row) {

        if (!in_array($row->entity, $used_nids)) {

          $new_view_result[$count] = $row;

          $used_nids[$count] = $row->entity;
          $count++;
        }
    }

    $view->result = $new_view_result;
  }
}

Indeed this does filter out the extra content.  I know this because in template.php I printed it out to be sure, but when I set the view to use the new content
ie:  $view->result = $new_view_result;
I get no content type back from the view.
Any idea what might be the issue?

Please help me.

Sincerely,

David Pugh

PS: if you need any more info, let me know.

I solved my issue.
Turns out the filter TEMPLATE_views_pre_render function I programmed in was working, the problem was in the template it's self. I had tried to solve this problem on the template before trying this issue.
Before I was trying to only allow $row 1 to return, which didn't solve my problem.
I then tried the _views_pre_render function, and saw that it was filtering but my view was not showing any data.
That is because only one row was being returned due to the _views_pre_render function, but the only row being returned was row #0, and in the template below I was specifying to only show row 1.

So, in conclusion, if you have views with search api and find that

        <?php $lastItem = 0;?>
            <?php foreach ($rows as $row_number => $columns): ?>
                <?php if($row_number == 1):?>
                <?php $array = array();?>
                <?php foreach ($columns as $column_number => $item): ?>

                    <?php if($item != null && $item != "" && strlen($item) != $lastItem):?>

                                <?php print $item?>

                        <?php $lastItem = strlen($item) ?>
                    <?php endif ?>

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

So, in conclusion, if you have views with search api and find that the solution listed here,
Does not work for you, then your data returned to the _views_pre_render function is probably different due to your search api, and you should follow my BootstrapBlocks_views_pre_render function above, and you should be filtering out the duplicates.


Picture field in user table I can see the picture field in the user table, and it seems the field accepts a picture address.
I want to allow users to upload their picture to the site.

Is there any module or code to use this field?

Check the user account settings in page admin/user/settings, the option for changing user picture is "Picture support."


MSAccess to SQLite install and setup custom content types? I'm looking for information on how I could use or import a MSAccess database into a SQLite install of Drupal 7. Is this possible or will I have to export the MSAccess tables to CSV or something and then add them to the SQLite db slowly?

** Full Disclosure I've Not Tried This Using the Requested Setup!! **

I've migrated Joomla -> Drupal and CSV to drupal ... so I have some experience with this. But having not tested your exact request I'm not 100% this will work.

You can install PDO and PDO support for ODBC drivers. I assume your PHP environment is Windows so you can also install MSAccess, which supports an ODBC driver connection. Here is a blog example of how to install/use MsAccess ODBC for a plain PHP webapplication.

You can then configure your settings.php file to include a custom database connection using PDO to use an ODBC driver to talk to your MSAccess database. This could look something like:

   $databases['remote_msaccess_db']['default'] = array(
     'driver' => 'odbc:DRIVER={Microsoft Access Driver (*.mdb)}',
     'DbQ' => 'C:\some\path\to\your\db.mdb',
     'uid' => '',
     'pwd' => '',
     'host' => 'localhost',
     'prefix' => '',
   );

That's actually the hard part :). Which may not work. Assure you have the same 32bit or 64bit ODBC drivers for PHP as whatever version OS MSAccess is running.

After that you can use a tool like Migrate to move the data from MSAccess into Drupal content types, Entities or even a plain old table based migration which Migrate supports (and I've used).


Custom validator for checking if fields match I have two fields, value and copy that I'm trying to do some custom validation on to make sure they roughly match each other.

So far in my module I have this:

function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if(!empty($fields['field_value']) && !empty($fields['field_copy']))
    {
        $fields['field_copy']->addConstraint('CopyMatchesValue');
        $fields['field_value']->addConstraint('CopyMatchesValue');
    }
}

A constraint

<?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that value matches copy
 *
 * @Constraint(
 *   id = "CopyMatchesValue",
 *   label = @Translation("Copy Matches Value", context = "Validation"),
 * )
 */
class CopyMatchesValue extends Constraint
{
    // The message that will be shown if the format is incorrect.
    public $copyValueMismatch = 'The value does not look like it matches the copy.';
}

And a validator

<?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the CopyMatchesValue constraint.
 */
class CopyMatchesValueValidator extends ConstraintValidator
{
  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint)
  {

      foreach ($items as $key => $item) {
          var_dump($item->value);
      }
      exit;

      // do some processing to make sure they match

      $this->context->addViolation();
    }
  }
}

I was expecting $items to have both fields I added the constraint to, but that doesn't seem to be the case.

How can I pass two fields to one validator so that I can validate them against each other?

I'm not sure if constraints is the best way to go when you need access to two fields. In your form alter, could you add a custom validation method? That way you would have access to array &$form, FormStateInterface $form_state giving you access to all fields.

$form['#validate'][] = 'my_test_validate';

And then your validation function...

/**
 * {@inheritdoc}
 */
function my_test_validate(array &$form, FormStateInterface $form_state) {
  // Do what you need to do here...
}


custom MailSystemInterface implementation I need to create a custom implementation of MailSystemInterface.

I created a file called my_module.mail.inc but I don't know how to load it and how to tell Drupal to use it by default.

I installed the mailsystem and autoload modules but don't know what to do next.

Any help would be greatly appreciated. Thanks

for mailsystem to work, you need to implement MailSystemInterface class and enable your new mailsystem class as default, for example in module hook_install():

    variable_set('mail_system', array_merge(
       variable_get('mail_system', array('default-system' => 'DefaultMailSystem')), // Previously set mail_system variable
       array('login' => 'MyCustomMailClass')   // My new key(s) which ADD to the previous keys
    );

Note: array('login' => 'MyCustomMailClass') "login" is a module name, which will be used to identify your new mailinterface.

Next you should call your new mailsystem from hook_mail(), like:

drupal_mail('login', 'registration', $form_state['values']['register_email'], language_default(), $params, 'mail@exmaple.com', true);

And class implementation could look someting like:

class MyCustomMailClass implements MailSystemInterface {

/**
 * Concatenate and wrap the e-mail body for plain-text mails.
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 *
 * @return
 *   The formatted $message.
 */
public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);

    if ($message['module'] == 'login') {
        $body =  $message['body'];
        $message['body'] = array();

        // Convert any HTML to plain-text.
        $message['body']['plain'] = drupal_html_to_text($body);
        $message['body']['plain'] = drupal_wrap_mail($message['body']['plain']);

        // Wrap the mail body for sending.
        $message['body']['html'] = drupal_wrap_mail($body);
    } else {
        $message['body'] = drupal_wrap_mail($message['body']);
    }

    return $message;
}

/**
 * Send an e-mail message, using Drupal variables and default settings.
 *
 * @see <a href="http://php.net/manual/en/function.mail.php
  " title="http://php.net/manual/en/function.mail.php
  " rel="nofollow">http://php.net/manual/en/function.mail.php
  </a>   * @see drupal_mail()
 *
 * @param $message
 *   A message array, as described in hook_mail_alter().
 * @return
 *   TRUE if the mail was successfully accepted, otherwise FALSE.
 */
public function mail(array $message) {
    $mimeheaders = array();

    if ($message['module'] == 'login') {
        $separator = md5(time());
        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // main header
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = "multipart/alternative; boundary=\"".$separator."\"";

        // message
        $body = "--".$separator.$eol;
        $body .= "Content-Type: text/plain; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['plain'].$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"UTF-8\"; format=\"flowed\"; delsp=\"yes\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message['body']['html'].$eol;
        $body .= "--".$separator."--";

        foreach ($message['headers'] as $name => $value) {
          $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          preg_replace('@\r?\n@', $line_endings, $body),
          join("\n", $mimeheaders)
        );

        return $sendM;
    } else {
        $message['headers']['From'] = $message['from'];
        $message['headers']['Sender'] = $message['from'];
        $message['headers']['Return-Path'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Reply-to'] = $message['from'];
        $message['headers']['Errors-To'] = ASK_US_REPLY_TO_HEADER_MAIL;
        $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

        if(isset($message['customMode']) && $message['customMode'] == 1) {
            $message['headers']['Content-Type'] = 'text/plain; charset=UTF-8; format=flowed; delsp=yes';
        }

        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }

        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        $heads = join("\n", $mimeheaders);

        $sendM = mail(
          $message['to'], mime_header_encode($message['subject']),
          // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
          // on Unix and CRLF on Windows. Drupal automatically guesses the
          // line-ending format appropriate for your system. If you need to
          // override this, adjust $conf['mail_line_endings'] in settings.php.
          preg_replace('@\r?\n@', $line_endings, $message['body']),
          // For headers, PHP's API suggests that we use CRLF normally,
          // but some MTAs incorrectly replace LF with CRLF. See #234403.
          $heads
        );

       return $sendM;
    }
}}


Give restricted editors access to unpublished nodes Using Drupal 6.22.

I want to have editors create nodes (in a unpublished state) and be able to edit them. If they navigate away from the node their editing, they can't find it unless they have the full URL to it.

Is there a way to give them access without granting privileges to the admin pages and administering nodes?

I think creating a view of unpublished content and having it only show for editors is one possibility.

I think you'll find the Workbench module (Drupal 7 only) will fit your needs nicely.  There's a good screencast explaining the module on the project page.


Is there a reliable way to show Drupal messages from JavaScript? I need to show status messages (the kind typically shown by drupal_set_message()) in my module's JavaScript code. How can I do this reliably, such that the theme and placement of the messages remains consistent with the way drupal_set_message() does it?

I'm looking for a solution that accounts for the presence or absence of prior messages on the page, and that works for any theme.

Pointing to existing modules that perform this would be great!

I'm using Nice messages module to replace every message with a popup in the corner of the screen.

https://drupal.org/project/nicemessages

It lets you choose if you want the messages of a status to stay visible until closed, or auto close after x seconds.
And add a handy "close all" if there are more than one.

If anything, check out how it works. It's a good starting point i guess.


Can we use a hook_update_N for a module without hook_install? I am working on a custom module which does not have an install file but nevertheless uses a lot of tables. The one who worked on it previously, created the database tables manually. Now I want to add more tables to it. I could run the query manually to get the job done but I wanted to use the 'Drupal' way to do that. So I was wondering if we could use a hook_update_N for a module without hook_install?

No module needs to implement every hook. You can use hook_update_n() and not have a hook_install() function just fine.

You'll probably at 1 point want to define hook_schema() for these tables. An easy tool to get the "drupal" schema for any mysql table (already defined) in your mysql database is the Schema module.

  Schema documentation: hyperlinked display of the schema's embedded
  documentation explaining what each table and field is for.
  Schema
  structure generation: the module examines the live database and
  creates Schema API data structures for all tables that match the live
  database.
  Schema comparison: the module compares the live database
  structure with the schema structure declared by all enabled modules,
  reporting on any missing or incorrect tables.

  Note for MySQL users:
  The Schema module requires MySQL 5. Prior versions of MySQL do not
  support the INFORMATION_SCHEMA database that the Schema module uses to
  inspect the database.


Allow users to select among various default images while creating their profile if none is uploaded I'm using ImageCache, ImageField and Content Profile to create my user profiles and I'd like to offer different default images if the user doesn't upload one.

Currently, ImageField offers a default image if none is uploaded but how can you show your user a lists of profile images in order to let them select one or upload their own ?

I'm looking to get something like this:

Of course if the user upload one it will be used on their profile.

Any module you can recommend me or custom code to achieve this ? Does the Gravatar module allow this ?

Thanks a lot.

Use this module - Avatar Selection.

Does exactly what you're looking for.


Language select: how to set up In the current set up for every English page, there's a Spanish equivalent.  Each page has its own unique URL.

Previously we had it set up so that you could click "Spanish" within the English page and it would call the Spanish URL and visa-versa.

We've been asked to make it global -a button at the top of the site.

Is there a clean way to detect what the Spanish equivalent is of the current page with PHP and make the switch?

Locale module by default provides you a block, Language Switcher, that switches language of the site. It's a list of installed language.

If you like a fancy switcher, you can install this module:
Language Switcher Dropdown

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.

  The module also integrates well with Language Icons module if
  installed.

Here's an example


What file generated output I was debugging by adding a print_r() to my code to check array values along the way. The problem is I forgot where (which module and which file) I had added the print_r() statement since it has been some time I had worked on it. Now some of my pages are outputting an unwanted array print out. Is there a way to find out which module and which file specifically generated the array print out?

If you are running on Gnu/Linux or Unix, you should be able to position yourself above the directory holding your code and use the following shell command:

grep -r print_r .

This will recursively search through the current directory and all the directories below it for the string "print_r" and print out all lines containing that string, prefixed with its file name.

For future debugging, I suggest you install the Devel module for debugging.  At least one of its debug printout functions (dpm()) will print where the debug statement is placed by name of file and line number if the object is complex enough to produce a Krumo accordion display of the object/array.

For simpler objects, use the second argument to dpm() to remind yourself where you placed it. E.g.:

dpm($uid, 'mymodule, line 42, $uid');


Permission to submit webform only for the author of the node I'm using webform 8.x for a personal project and I'd like to know if it possible to enable only the author of the node to submit the form.

In my project each node is an aquarium, and I am using webform to collect the all the daily data for that specific node ( aquarium ), like temperature, pH, KH ecc.
I was able to create a view related to the node (aquarium) where you can see the data submitted daily for that specific aquarium, but the problem is that everyone can submit the form, while I need only the author of the node to be able to submit the webform.

Can you please give me some ideas? I'm stuck..

You haven't said if this is Drupal 7 or Drupal 8 but this should work for D8

It sounds like each author already has a user account on your website, so you can go to "Settings" on your webform and then click the "Access" tab (.e.g /admin/structure/webform/manage/FORM_MACHINE_NAME/access)

And in there you can restrict the ability to create submissions to a specific user(s) only


How can I select which tags should be stripped from the footer? In Drupal 6, the footer message is stripped of some HTML tags. In my case I want to place <img> with a <map> tag so the image would link to different sections. Drupal strips off the <map> tag, even if I add it to the accepted HTML tags in "Filtered HTML" data type.

Is there a way to enable the <map> tag in the footer?

I assume you are talking about a custom block that you add in the footer region of the site. In that case, you need to include all the HTML tags used to create a map image, which are <area>, , and <map>.

I have tried with a block contained the following HTML.

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
</map>

Once I enable those HTML tags for the Filtered HTML input format, the HTML added to the page for that block is the following.

<map name="planetmap">

  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun" />

  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury" />

  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus" />

</map>

Keep in mind that, since the function Drupal used to filter out HTML tags is filter_xss(), the HTML you pass to the Filtered HTML input format is altered to:

Remove characters and constructs that can trick browsers
Make sure all HTML entities are well-formed
Make sure all HTML tags and attributes are well-formed
Make sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Then, also _filter_xss_attributes() is called; that means also tag attributes are filtered.


Views Link to Teaser I'm using JCarousel with Views. I've been able to get my content working fine and linked properly to their nodes in a modal window using colorbox-load. I'd like to be able to open up only the teaser content in the window. How can I do this?

If the link in your View is something like that node/XXXX I think it not possible, or at least you should modify the node.tpl.php and add a condition inside to show only teaser or full content according the context (from jCarousel or not).

Another solution it's to create another view, that will display only the Tease and point your links (from the view jCarousel) to that view. This view need to show node (tease) and accept an argument (nid).


How to change default language for configuration entities? I made a mistake during the development of my Drupal 8 site. Some time ago I changed the default language (to german) - but I continued to create the configuration entities (like fields and so on) in English.
Now I found out that this was not really smart - and I want to change the default language of all existing configuration entities.
First of all, I just tried to delete the german language - so Drupal 8 switches back to English as default. Now every new configuration entity (new field) is defined in English. That's fine. But every existing configuration entity shows "Unknown (de) (original)" as the default language. And when I open it to save it again nothing changes.
I took a look into the database considering to change it directly there - but unfortunately, the configuration is stored binary.
Is there any other way to solve this problem?

I changed the configuration directly in the MySQL table "config" (In my case table names has a prefix ("something_config") so change the example below if necessary).

The configuration values are in the column "data".

First I cast the content to a string.

Then I replace the definition of the wrong langcode. In my case I replace 's:8:"langcode";s:2:"de"' with 's:8:"langcode";s:2:"en"'.

In the end I cast the result of this replace operation back to binary and save it in "data".

These three steps can be managed in one single SQL statement:

UPDATE `config` SET data = cast(
 replace(
    cast( data AS char ) , 's:8:"langcode";s:2:"de"', 's:8:"langcode";s:2:"en"'
 )
 AS BINARY )

Then clear the cache and you are done.


The best way to render field content without any  wrapper I have a content type with filefield "ttf" wich I want to render as Url to the file .
with this url to file I want to create an link :

<a href="<?php print render($content["field_ttf"]); ?>">Download

But this output a wrapper around the url

I know that there is a function field_view_field() that do the Job but I'm looking for a better solution

Look in the core modules/field/theme/ folder, copy the field.tpl.php file to your theme then rename it to whatever the system name for the field is. i.e field--body.tpl.php

Edit the file to remove the surrounding divs and anything else you don't want. All you actually need is the foreach and the render($item);

Don't forget to clear the cache so it will pick up the new file, hope that helps.


How to set permission for exposed filter in Views block I have a View with several blocks or displays. In one of these displays I have added the filter "Published" and made it exposed, so that user can switch between published and unpublished content.

Now I only want users with the administrator role to be able to see this filter, but I cannot figure out how to do this.
Can anyone give me a hint?

Thanks in advance

If you expose the filter as a block from within the view (Advanced - exposed form in block) then you could set the permissions on the exposed form block in the block system to Admin role users. Alternatively I can only think that you might need to use hook_form_alter to amend the permissions on that form if you want everyone others to see the view but not the exposed form.


How to add variables to $conf array? To modify some default settings for the Feeds module, I need to set a variable in the $conf array. What is the right way to achieve this?

I've tried adding it in the settings.php file (currently on local), but it doesn't appear in the variable table (even after restarting the server). "Clear all caches" didn't change anything, either. What am I missing?

What I am actually trying to do is to set $conf['feeds_process_limit'] = 15; exactly in the same way as described on http://drupal.org/node/1363094 and http://drupal.org/node/1393450; after adding it to the settings.php file, the result is the same: The amount of imported items isn't being limited.

How can I ensure the variable was set as in the settings file, and not to the default value?

Your variables will not show up in the variables table; variables are loaded from the database first and are then overwritten by settings.php. You might need to add a global $conf to access the variables in your settings.php.


Views exposed filter to take multiple values I'm running a D7 system and have a requirement where I want user to be able to pass multiple values in one of the exposed filters.

I've got hundreds of nodes called 'group' and I want user to be able to pass multiple 'group' names in order to filter results.

is this possible?

You can use Better Exposed Filters module for this type of requirement you have.

Using this module you can add multi-select option for group names, so you will filter your results on multiple values.


Views show list of nodes that have referenced node on another content type I have research and people content types.
In people content type I have nodes that are authors for researches.
I referenced author name field on research content type to people content type.
Now I want to show all people type nodes that referenced in research content type nodes.
In another word I want to show list of all my authors from my people content type.
Thank you very mach.

I found the solution:

Add view from people content type.
and add relationship referencing entity with the author_name field and check Require this relationship.
To remove repeated rows use Views Distinct module.


Display taxonomy term description when mouse hovers I created a taxonomy and added vocabulary with terms(each term has a description). Included the vocabulary to an auto-complete field. It all works good.

In the auto-complete field, terms appear in a drop-down menu as a list without any description.

Here, I want to add a feature for the field in such a way that when the user hovers through the terms in the drop-down menu it should display its corresponding description.

And, Also have an idea of implementing the stackexchange Tags drop-down feature. I like the SE approach of displaying the tags (as buttons) and its corresponding description (below the button). I'm loving it.

Either way is ok, displaying the description when mouse hovers and SE drop-down feature.

You could try using beautytips and views. There is an old Drupal 6 video explaining how to do it for feeds, showing a part of the body when hovering the title in a list: http://www.veoh.com/watch/v200239557fzYsENz.
It is still pretty much accurate on the conception of it.


hook_form_alter isn't working I've been trying to insert a placeholder for my search-bar, so in my page.preprocess.inc I call hook_form_search_block_form_alter(), then specify the form's array, and create the placeholder array, but it doesn't work. I've tried multiple things but none of them seem to affect the form in any way. I use devel themer, as both the devel page array and <?php dpm() ?> don't seem to work on my frontpage. My alternative would be to use jquery but I'd rather have this work then having to resort to the longer method.

Here's what I'm working with:

theme name - hitech_wolf

EDIT: I'm using omega4

PAGE.PREPROCESS.INC

    <?php
        // Can Ignore, left in here just in case it influences the alter statement
        /**
         * Implements hook_preprocess_page().
         */
        function hitech_wolf_preprocess_page(&$variables) {
            $path = drupal_get_path('theme','hitech_wolf');
            drupal_add_js($path . '/js/iframe_colorbox_support.js');
        }

        /**
         * Implements hook_form_alter().
         */
    // Separate Attempts - present for example
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#placeholder'] = array(
        t('Search...'),
      );
    }
    function hitech_wolf_form_search_block_form_alter(&$form, &$form_state) {
      $form['search_block_form']['#attributes'] = array(
        'placeholder' => t('Search...'),
      );
    }
    function hitech_wolf_form_alter(&$form, &$form_state) {
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes']['#placeholder'] = t('Request your username');
      }
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#attributes'] = array('placeholder' => t('Request your username')
    );
  }
}
        // Check if anything works at all - doesn't
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          hide($form);
        }
        function hitech_wolf_form_alter(&$form, &$form_state, $form_id) {
          unset($form);
        }

PICTURES - form id/location

hook_form_alter() belongs to template.php, or in a module, as only there it can be recognized; it doesn't work the same as preprocess functions. See also this Reddit.


Products not display in other languages I am using multi-language internationalize module for category and products translate. When product created assigning only English language category only but not assign other languages, How to assign to other languages.

There is any solution for this with module or else any other solution.

check the (http://drupal.org/project/entity_translation) module   and also read this  https://drupalcommerce.org/discussions/820/how-do-i-setup-multilingual-products

https://www.drupal.org/documentation/modules/translation


How to include "children" content types on a content type page? Let's say I override the way a content type page looks. My content type is Parent. So I create a page named: node--parent.tpl.php

But how about when you want to use nested content types?

Let's say:

Content Type Parent
Content Type Child

I use node--parent.tpl.php, but how do I display the children that belong to the parent? (linked using Contextual Filters).

For example in node--parent.tpl.php have a way to display:

Parent Name: Joe

Children: Sue, Phil, Mary and Jim

Contextual filters are part of Views, they can't be used to link content types together. If you're simulating a relationship between the two types using a contextual filter, it will only exist in the very narrow context of that View.

The standard way to link content types together is with the Entity Reference module. Something similar to the following should get you what you're looking for:

Add a multiple cardinality entity reference field to the Parent content type, referencing the Child type.
Optionally install Inline Entity Form, if creating the Child content while inside the Parent edit form makes sense for your use case. It provides a widget for the entity reference field type. I won't go into details, if you choose that widget and visit the edit form for a Parent node, you'll see what it does.
Use either the autocomplete or inline entity widget to relate the Child nodes to the relevant Parent nodes.
Visit the display options for the Parent content type, choose "Rendered Entity" for the display format of your entity reference field, and in the settings choose an appropriate view mode.

That will render the Child nodes inside the Parent node without the need to alter the template file at all.