How can I inject a taxonomy menu as the sub-menu of a standard menu item? I have a main menu, with a top-level structure similar to the following:

Home - Categories - Something Else - ... - Contact

Each of those top-level links goes to an appropriate node page.

I have a vocabulary for Categories (multi-level), and I need to get those taxonomy terms in a sub-menu under the "Categories" item. I'd like to avoid hard-coding the items into the main menu, as the sub-menu should grow/shrink as the vocabulary does.

In the past I've written over-elaborate code to accomplish this, which hooks into taxonomy operations and manages a particular menu's sub-items based on that (very similar to what Taxonomy Menu does, but without having to have a different menu for each vocabulary).

While that method works, it's not ideal and certainly not generic. I can't just lift that code from the old project into the new one, it would require a reasonable amount of customisation.

I can't help feeling there must be a 'standard', module-based solution to this.

I've seen some suggestions out there to use a bunch of different modules in combination (even some suggesting to use Views-based modules, weirdly enough). I'm open to any suggestion, but if it involves installing more than 1 or 2 modules, and a load of hard-coded, context-specific configuration, it's probably not going to help too much in this case.

Option a) Unless I am mistaken, can you not just pick where your Taxonomy Menu will be parented (Menu Location) when you create it? The only problem I think you might get with this is I think it requires you to rebuild the menu every time the taxonomy is updated

Option b) I have done something reasonably similar to this on my site, I used Menu Views module, to allow me to put a view into my primary menu.

If you create a new view which lists all of your taxonomy terms, as a block display, apply any additional filtering/modification in the view if necessary (you may not but in my example I wanted to). Then when you add a new link to your main menu, you can select to use a view rather than a link. From there you pick which view you want to use, select the 'Category' menu item as its parent and save (after saving you then have to enable it in the menu, which appears to be a bug with the module itself)

I can't guarantee that this is the best solution for you, but it worked when I just tested it


open atrium features I installed Open Atrium, and there are no default features showing under the features admin panel. No shoutbox, wiki, blog or calendar. Did I choose a stripped down version of Open Atrium to install by accident?

No, you have to turn those features on if you'd like to use them.

Create a group and then in that group go to Settings -> Customize Features, here you can enable the features you need.


Custom module permission function I am creating a module whose purpose is to display some data. I have a input form that saves data to database; that data is then displayed to the user.

I have created a page where that data can be viewed, edited, and deleted.

My problem is that every user can see this. The best thing I have done is using the global $user variable, and verify that the currently logged-in user is the user who created the data being viewed. Every user could see the Edit and Delete tabs, even when no data was created.

I am trying to figure out how I use the permissions in the same way they are used with the content types, where users can edit any node of a content type, or can edit their own nodes of that content type.

How could I resolve this issue?

You should implement hook_permission.
Then you will be able to add custom permissions to view, edit and delete for your custom form.

Nice tip I'm using myself with Drupal is to open the code of one of Drupal's core/contrib modules that implements the same thing you need and learn how it was implemented there.


How to Use Ajax in form alter in Drupal 7? I have created a content type named "main menu". I have few select lists which depend on one another. I wanted to display a different list when different checkboxes are selected. I figured out that I need to use Ajax to edit the form in order to achieve that but can anyone tell me how to use Ajax with hook_form_alter?

The form id of the form I am supposed to edit is "main_menu_node_form". When I try to access this form using hook_form_alter(), and add the #ajax property of the form fields, it seems that I am not able to do that since the fields are already rendered before the handle is passed to hook_form_alter(). Can anyone please help me solve this?

Note : I have created the content type using hook_install().

function main_menu_content_type_form_main_menu_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  dpm($form_state);

  $form['field_mlnk'] = array(
    '#ajax' => array(
      'callback' => 'main_menu_content_type_form_main_menu_node_form_alter_callback',
      'wrapper' => 'link-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
}

I would be able to give you some detailed information about what you are doing wrong with hook_form_alter if you included some actual code from your custom module. However, since you are not giving any specifics, you can watch the video: How to build beautiful forms in Drupal 7 (note that I entered the URL so that it starts at the moment where the ajax is described). About 5 minutes of watching this will probably give you the answer to your question (since it describes exactly how to use ajax with hook_form_alter), but if you are really impatient, the actual code is shown somewhere around here.

If you want to see a live, well-tested and documented example of a form being altered using ajax, there is one in the Examples module. You can find the actual hook here and the callback function here.

I hope this helps. If it doesn't, give us some more background about your code and we will be able to tell you exactly what you are doing wrong.


menu home item stay's on every page i made a site through artisteer and i wanted to have a different background on each page, i did this with themekey and it worked.
My layout is a header, content and left sidebar with main menu.
The problem is that when i'm on the home page the home menu item is correct and located in the sidebar...when i 'm on the other pages the home menu item is located above the contentblok instead of the left sidebar....what can i do to remove from every page the home item so it only appears in the menul ist in the left sidebar..
Thx in advance
Greetz
fred

Have you tried going to the blocks administration page and checking which blocks/menus are being shown where?  This will allow you to locate the one that you don't want displayed; if it's a menu, you can then go to the menu administration page, find the menu in question, and delete the home page link from it.

Make sure you visit the administration page for the theme that is causing the problem; block placement is configured separately for each theme.


How to modify/add addition variable to service json after successfully register.json? I am able to get the response after register using service register.json

Response:

    {
        "uid": "10",
        "uri": "http://example.com/apps_api/user/10"
    }

Input:

  { "name":"smart", "pass":"smart", "mail":"tushar@smalution.com",
  "status":"1", "roles":[ "3" ] }

I get all the information "uri": "http://example.com/apps_api/user/10" .
I just want to get the "name", "mail", "role" in response.

Do not need to go again "uri": "http://example.com/apps_api/user/10".

Add custom code/module to modify the service response, check hook_services_endpoint_response_alter and all other similar alter hooks services alter hooks

e.g.:

function MODULENAME_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller->callback == '_user_resource_create') {
    if ($result->uid) {
      $user = user_load($result->uid);
      $result->user = $user;
    }
  }
}


How to get list of blocks for region on current page? I have a template of my custom function and I am display certain number of items per row in this template.

For this reason I need to figure out if there are any blocks on the current page in any of the sidebars of my theme(left and right) so I can adjust the number of visible items.

So my question is how to get the list of blocks that are displayed on the current route in certain region and their visibility conditions were already processed?

I do not need to have exact information, ie. if some blocks have #access set to false or if they return empty render arrays are not important.

There's a block.repository service with a getVisibleBlocksPerRegion() method. You can either use that or look at what it's doing.

This will cover access checks as well but not empty blocks.

This is however quite a bit of an overhead as all blocks are loaded and access checked twice. There is an issue to add caching there.

Alternatively, you can use preprocess of the region templates I guess.


How do I build Breadcrumbs for a certain node? In a node preprocess hook I am getting breadcrumbs for the currently viewed node by doing the following:

$vars['breadcrumb'] = Drupal::service('breadcrumb')
    ->build(Drupal::routeMatch())->toRenderable();

This works fine as it uses Drupal::routeMatch() to get the matched route for the current request.

But I also want to get the breadcrumb for each node in a listing of several nodes. In this case I cannot use Drupal::routeMatch() since I want to get the breadcrumb for each node in the listing, not the current page. The problem is I cannot find a way of getting a RouteMatchInterface object (needed by the BreadcrumbBuilder) from a node object. I can get the url containing route information via $node->urlInfo()but there seems to be no way of getting from there to a route match either.

How can this be done?

Edit:

I found a way to get the route match for a certain node. Not sure if it's the ideal way but it gets the job done:

$routeName = $node->urlInfo()->getRouteName();
$routeParameters = $node->urlInfo()->getRouteParameters();
$route = Drupal::service('router.route_provider')->getRouteByName($routeName);
$routeMatch = new RouteMatch($routeName, $route, $routeParameters);

However passing the $routeMatch into PathBasedBredcrumbBuilder::create does not generate bredcrumbs for that route!

On closer inspection it seems that the built-in PathBasedBreadCrumbBuilder class completely ignores the passed in $routeMatch parameter and instead builds the breadcrumbs using the path of the current page, fetched using the injected RequestContext object. I think I would need to swap out this service with my own implementation which uses the passed in parameters somehow. To be continued...

I eventually solved it by creating my own subclass of the PathBasedBredcrumbBuilder from core. This class unlike core's version actually uses the passed in route_match and returns breadcrumbs based on that which makes it possible to get breadcrumbs for a certain node (or any other given route).

I still need to calculate the route match from the current node to pass to the build method (as shown in the question). It feels a bit awkward since the route_match is converted back into a url object in the build method but  it works and it is the cleanest solution i've come up with so far.

Below is the subclass:

namespace Drupal\contextual_breadcrumbs;

use Drupal\system\PathBasedBreadcrumbBuilder;
use Drupal\Core\Routing\RequestContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

class ContextualPathBasedBreadcrumbBuilder extends PathBasedBreadcrumbBuilder {

    /**
    * {@inheritdoc}
    */
    public function build(RouteMatchInterface $route_match) {

      /// Set request context from passed in $route_match
      $url = Url::fromRouteMatch($route_match);
      if ($request = $this->getRequestForPath($url->toString(), [])) {
        $context = new RequestContext();
        $context->fromRequest($request);
        $this->context = $context;
      }

      // Build breadcrumbs using new context ($route_match is unused)
      return parent::build($route_match);
    }

}


How to show data from external api to theme template? I am totally new to Drupal. I have given one assignment to build Drupal site which shows courses from our company site. I am totally stuck in one point. I need to show data from our api into theme template.

Can you please guide me on this? If you have any example, please share with me. I will dig into it and I will try to solve my problem.

There are a few answers to that question, and it depends on the design (appearence and behaviors), but the Drupal foundation is usually the same.
1st step
Create a custom block and place it in a page (node of a generic type is a good option or a programmatically created page.
OR
Create a custom page (see ´hook_menu´)
2nd step
Create a custom theme function using ´hook_theme´ (template file is usually easier to maintain)
3rd step (connect to the API)
Due to performance considerations (async vs. sync request) I prefer to use JavaScript to get the data and present it on the page / block we created. (AngularJS is my friend..)
If JS is not an option, then you can make the request in ´hook_block_view´ in case you used custom block, ´hook_page_build´ or in your ´hook_menu´'s callback in case you chose a page in step 1.


Install custom module into modules/custom folder I've just made a facebook module, it's working nicely, the only thing is that it doesn't install into the modules/custom folder. The module installs into the modules folder (the custom folder is located inside this modules folder).

How can I make sure the module installs into modules/custom?

This is my .install file.

/**
 * @file
 * Install, update and uninstall functions for the facebooklikebox module.
 */

/**
 * Implements hook_uninstall().
 */
function facebooklikebox_uninstall() {
  db_query("DELETE FROM {variable} WHERE name LIKE '%facebooklikebox%'");
  cache_clear_all('variables', 'cache');
}

function facebooklikebox_update_6101() {
  // Get the default settings
  drupal_load('module', 'facebooklikebox');
  $defaults = _facebooklikebox_get_settings(TRUE);

  // Define a settings array based on the variables already set (or their defaults)
  $settings = array(
    'facebooklikebox_pageurl' => variable_get('facebooklikebox_pageurl', 0),
    'facebooklikebox_height' => variable_get('facebooklikebox_height', 0),
    'facebooklikebox_width' => variable_get('facebooklikebox_width', 0),
    'facebooklikebox_bordercolor' => variable_get('facebooklikebox_bordercolor', 0),
    'facebooklikebox_showfaces' => variable_get('facebooklikebox_showfaces', 0),
    'facebooklikebox_showstream' => variable_get('facebooklikebox_showstream', 0),
    'facebooklikebox_showheader' => variable_get('facebooklikebox_showheader', 0),

  );

  // If a setting matches the default value, unset it (we wont need to store it)
  foreach ($settings as $key => $value) {
    // We used to use -1 for disabled, convert this to 0 for the new diabled
    if ($value == -1) {
      $settings[$key] = 0;
    }
    // Now compare the value to the defaults. Only store if an "override".
    if ($value == $defaults[$key]) {
      unset($settings[$key]);
    }
  }

  // Save the settings in a single array rather than individual keys
  if (!empty($settings)) {
    variable_set('facebooklikebox_settings', $settings);
  }

  // Remove all the old settings
  variable_del('facebooklikebox_pageurl');
  variable_del('facebooklikebox_height');
  variable_del('facebooklikebox_width');
  variable_del('facebooklikebox_bordercolor');
  variable_del('facebooklikebox_showfaces');
  variable_del('facebooklikebox_showstream');
  variable_del('facebooklikebox_showheader');
}

As I know Drupal web interface will always install modules to sites/all/modules.
Placing modules in subfolders like sites/all/modules/contrib, sites/all/modules/custom, or sites/all/modules/dev is a task for Drush and Drush Make; you can manually place the module in the right folder.

You can move your module folder with the PHP rename() function, or implement your own Updater instead of core ModuleUpdater. In your case, these solutions look improper.


field template for a specific content type I've read from http://drupal.org/node/1089656 that I can create a template for a field in specific content type as field--field-name--content-type.tpl.php.

I have a custom content type "festivals_events" and a cck field "field_description".
So, I created a template "field--field_description--festivals_events.tpl.php".  But it is not working.

I tried to replace _ in field name with - as suggested in Template Suggestion, http://drupal.org/node/1089656, to become my template name file name as "field--field-description--festivals_events.tpl.php"
This too is not working.

I think it is definitely can be used as it is mentioned in Template Suggestion.
What is wrong with me?

Thanks in advance.

Try "-" in the contact type name like field--field-description--festivals-events.tpl.php

[Edit]
You may also need a template suggestion in your theme.

function mytheme_preprocess_field(&$variables) {
    if($variables['type'] == 'festivals-events'){
        if($variables['element']['#field_name'] == 'field_description') {
            $variables['theme_hook_suggestions'][] = 'field__field_description__festivals_events';
        }
    }
}


context - url wirh parameter I'm using Drupal 6 and context. It seems that context does not react on path like this mypath?123 Is there any way to check such path with context?

If you're wanting a module-based solution the Context Query Parameters module adds Query String condition that lets you check for multiple query values.

  This module introduces a Context condition that allows you to trigger
  a Context based on query parameters on a given page request.


How often does hook_cron happen? How often does hook_cron happen? what is the periodic time for executing the codes inside this hook?

As often as you like :)

By default you can configure it on: /admin/config/system/cron (This will be executed on someone's page load, so it is importan to know that if nobody visits your site this will not be executed). This is known as poormanscron (Drupal 6).
Calling with a internal/external cron script (wget for example) to yoursite.com/cron.php

This is a heavy process so normally you want to limit cron functions like check updates. elysia cron is very useful in this case.

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.


Mollom captch disappear after using hook form alter for validation I have altered Request new password form  field label

function useredit_form_user_pass_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title']='Username';
  $form['#validate'] = array('useredit_user_pass_validation');
}

function useredit_user_pass_validation($form, &$form_state) {

  $name = trim($form_state['values']['name']);
  if(preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",$name))
  {
     form_set_error('parent_field_email', t('Please enter valid username.'));
  }
  # try to load by name.
  $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
  $account = reset($users);

  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }else{
    form_set_error('name', t('Sorry, %name is not recognized as a user name.', array('%name' => $name)));
  }
  }

form get's altered and validation works but captch image gets disappear. How to resolve this ?

I have done below changed above code:

$form['#validate'] = array('useredit_user_pass_validation');

by

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

And it's works !


Having each child record inherit (display) data elements from a parent record I'm new to Drupal and have been watching lots of videos on entity relationships but am a bit lost still....trying to wrap my head around the differences between nodes, entities, etc. and how to define relationships.

What I would like to do is have 2 pieces of content - Company and Program.

The company information will be filled in by an administrator of the site (company name, address, phone, website, etc)  -- these values are only editable by the administrator but can be read by any authenticated user.

Then any authenticated user can create a Program which will have its own set of fields (program name, date, program director, etc.)

Each Program is considered a child of Company and so the Program would also have read only fields that present the company info.

Can someone please point me in the right direction of how to link the Company directly to the Program.  I have seen ways of adding a select list field that would allow the user to select a Company from a list of companies...but I want this to default to the same company each time.

Thank you for any ideas/help.

E

There are several modules to use in conjunction.

Firstly, you need Entity Reference and its dependency, Entity API
https://www.drupal.org/project/entity
https://www.drupal.org/project/entityreference

Install those two modules the normal way.

Others have written add on modules for entity reference such as Entity Reference Prepopulate:
http://drupal.org/project/entityreference_prepopulate
That module can be helpful for prepopulating values for the entity reference fields you create.

So after you've installed the modules you can go to the Manage Fields page for you Program content type, and add a new Entity Reference field.

Might call this field "Company"

Click Save

On the field settings page, Select the Target type (entity type) as "Node"
For the Target bundles (content types in the case of node) select your Program content type
Optionally you can chose to sort the options for the entity reference field by a property of the node such as title.

Click Save

On the next screen you can set the default Company for the Reference field, or you can configure add modules such as Entity Reference Prepopulate to configure defaults based on context.

Click Save

Now you can edit or create Program nodes and reference a company node from them.

For this example I had created a Company node called "A Company"


Embed RichFilemanager I want to embed RichFilemaneger (https://github.com/servocoder/RichFilemanager) in a Drupal-8 site. RichFilemanager has its own index.html and a php-conncetor for implementation in other sites.

But it's not clear to me which approach to follow.

Should i keep RichFilemanager in it's own directory in the Drupal-root and connect to it via the php-connector? In that case it seems to me that Drupal can't take care of the security...
or should i copy the content of the index.html to a twig template? But that would make it hard to keep up with updates of RichFilemanager.

Can anyone point me in the right direction?
Are there similar tools implemented which i could use as an example?

You should include it with composer to your Drupal project. That is step one. You don't need to consider package management - composer will do this for you.

How you wire it up from there is basically up to you and your use case. I assume first you start with a basic controller and go from there in a custom module.


Appropriate way to include a PHP file in a theme tpl I guess this is more of a "Drupal way" question than a technical question. I have a multi-site install with a base-theme shared by all of the sites.  The base theme has two 'page' theme files (one is specifically for the homepage).  As you can imagine, there are shared elements to the layout (let's say a header and footer for conciseness). I'd like to keep the 'header' and 'footer' in separate PHP files so that I have one place to edit them versus going into 2 separate files and editing four blocks of code if something changes.

What is the appropriate way to create php files for 'header' and 'footer' and include them in the page.tpl and page--homepage.tpl templates?

Should they be in a folder called includes with a .inc extension, should this not be done at all, etc..?

I think the "Drupal Way" would be to create a variable in your template.php file, and then just call the variable in your page theme.

http://drupalize.me/videos/overview-templatephp


Views Exposed Filters: how to get functionality shown in this image? I'm wondering how hard it would be to get the functionality shown in the image, and at the associated webpage, with Views Exposed Filters. How would you go about it? Thanks in advance!

I notice 3 main things:

Entering text in the autocomplete search box causes the select list options to filter. (The matching letters are also underlined, which is fancy but not necessary.)
Selecting an option causes it to fill the search box.
A number after each select list option tells the user how many pieces of content are available.

The actual search box can be seen on this webpage: https://properties.aplaceinthesun.com/AP1724897/Beautifully-Maintained-Four-Bedroom-Villa-For-Sale

You would need to configure the Select2 or Chosen JQuery component to do this.

Create the list of object with count and apply the one of the above library.

For Drupal use Select2 module


How to redirect certain requests to use https://www.example.com in pantheon? In my Drupal install I would like to direct most URL requests to use https://www.example.com and only a few pages to use http://www.example.com Since my site is hosted on pantheon i cannot use .htaccess and i need to rely on my settings.php file. I tried the following but it doesn't really seem to work.

$redirect_domain = 'www.example.com';
if (isset($_SERVER['PANTHEON_ENVIRONMENT']) && $_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
  $redirect_location = '';
  // Do not require HTTPS for specific pages.
  if (in_array($_SERVER['REQUEST_URI'], array('/node/524','/some/unsecure/iframe'))) {
    // Check if HTTPS is enabled.
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
      $redirect_location = 'http://' . $redirect_domain . $_SERVER['REQUEST_URI'];
    }
  }
  // Require HTTPS for everything else.
  else if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
    if($_SERVER['HTTP_HOST'] != 'www.example.com'){
      $redirect_location = 'https://www.example.com' . $_SERVER['REQUEST_URI'];
    }
    else{
      $redirect_location = 'https://' . $redirect_domain . $_SERVER['REQUEST_URI'];
    }
  }
  // Perform redirect.
  if ($redirect_location) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: ' . $redirect_location);
    exit;
  }
}

typing in example.com does correctly redirect to https://www.example.com but typing in https://example.com doesn't perform any redirect.

That's because the $redirect_location doesn't get updated for https://example.com. See updated code below.

$domain = 'www.example.com';
if(isset($_SERVER['PANTHEON_ENVIRONMENT']) && $_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
  $location = '';

  if(in_array($_SERVER['REQUEST_URI'], array('/node/524'))) {
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
      $location = 'http://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }
  else {
    if($_SERVER['HTTP_HOST'] != 'www.example.com') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }

  // Redirect
  if ($location) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
  }
}


How do I print line breaks and HTML in a watchdog message? I am trying to log emails to watchdog for testing in my local dev environment.

function MYMODULE_mail_alter(&$message) {
  // First: Prevent the mail from being sent.
  $message['send'] = FALSE;

  // Next: Log the mail so it can be debugged if necessary
  ksm($message);
  $logemail = $message['subject'] .'\nThe following email was not sent: \n
Subject:
' . $message['subject'] . '
Body:
'  . $message['body'][0] . '
';
  watchdog('MYMODULE', '@logemail', array('@logemail' => $logemail), WATCHDOG_ALERT);
}

However, this gives me a value for Message that doesn't have any line breaks and ignores my HTML
 and \n:

Patrick K, new members for the week of April 23\nThe following email was not sent: \n
Subject:
Patrick K, new members for the week of April 23
Body:

Dear Patrick K,

We haven't seen you in awhile. Hundreds of people have joined since you last logged in.

Log in now and say hello to our newest members!

How can I get the line breaks and HTML to be rendered in the watchdog message?

However, this gives me a value for Message that doesn't have any line breaks and ignores my HTML
 and \n

As well it should :)

You've wrapped the HTML message in a
 tag, whose job is simply to preserve everything within as literal text, so that the browser won't interpret it as HTML. To fix, just remove the
 tags. If there's a possibility the email content could have been user-submitted, run it through filter_xss() first with an appropriate list of permitted tags, to avoid pain when you view the log message.

At the same time, \n isn't an escape char in HTML, so that's treated literally and rendered as text. It's an escape char in PHP, but it won't affect the outcome here as browsers collapse multiple whitespace chars into a single space anyway.

You could use PHP's nl2br to convert \n to
 automatically if the message content was dynamic, but since you're using a literal string, you might as well just be explicit and use
 instead of \n when you want a line break.

This is a basic working example:

$message = [
  'subject' => 'test subject',
  'body' => ['
some content
On a new line
'],
];

$allowed_tags = array('div', 'a', 'table', 'br', 'etc...');
$output = '!subject
The following email was not sent:
Subject:
!subject
Body:
!body';
$args = array('!subject' => filter_xss($message['subject'], $allowed_tags), '!body' => filter_xss($message['body'][0], $allowed_tags));
watchdog('MYMODULE', $output, $args, WATCHDOG_ALERT);

It's worth noting that the list view of the watchdog messages strips out HTML, so without the spaces after the first !subject and not sent:, some of the message will run together and make it harder to read at a glance.


How to disable the Superfish Accordion? Is it possible to disable the superfish accordion 'main menu' link at the smaller responsive sizes? Instead of clicking on 'main menu' to see the navigation, I would like the navigation to already be expanded without having to click on a link. The navigation should go from the horizontal menu directly to the vertical menu.

In my superfish navigation block, under superfish settings, set the style of the superfish menu to none and under superfish plugins, disabled sf-Touchscreen.

In my main stylesheet I defined the menu style I wanted at the smaller size.


Redirect anonymous users to the register page Is it possible to redirect anonymous user to user/register page?
How can I do that?

You should take a look at the Rules module and setup a rules that redirects anonumoys users to the user/register page.


Keep Summary field deployed I'm using the node's Summary field for article teasers. Although not mandatory, this field is being constatly populated by content editors for article content types. I'm trying to make it visible instead of Drupal's default collapsed state, but I've hit a wall on identifying the related JS function and how to modify it without hacking core files.

Any idea on achieving the desired UI modification?

EDIT: OK, seems like the /modules/text/text.js is the file in charge of adding the link that shows/hides the Summary field.

Since I don't want to simply comment out or edit core files, I think I'll have to make a custom module to unset this js file and not allow it to be loaded. I'm no JS expert but by looking into the code it seems to me that this file impacts only the text summary. Hence my updated question would be:  are there any side effects to unset this file?

For the default value for the field (under Field Settings), in the "Summary" field, you can put a blank " ". This will force the summary field to show up. If you want to do it the correct way, then you will have to check the Javascript that shows/hides the field.


Registration full name I would like to edit the registration fields, but I can't find where to do it.
I want to replace the username field on the registration form with two fields for first name and last name, which are then used to create the username as <first name> <last name>.

There is Auto Username for Drupal 6, and there is a Drupal 7 port of the module sitting in the issue queue.
Perhaps you could test the zip that is attached to that ticket, and help fixing any bugs. ;)

Alternatively, perhaps you could make this happen using the Rules module.


Avoiding content-type overkill: 5 slightly different pages = 5 different content types? My drupal 7 site mainly consists of a main menu with 5 entries, each linking to a more or less simple page. These 5 pages have a lot of common fields, simply some fields are slightly different. Normally, i would have to create a content type and an actual node to accomplish this — but since there is only one actual node for each of the content types, it feels like an overkill to me.
One alternative is to handle all fields in one singe node, separating the 5 areas in the edit-form by fieldgroup-tabs, and generate the pages with views …
Downside of this approach: instead of using display suite to do the theming, i would have to theme using views-fields, which is a pain.

The node field module, which allows you to add custom extra fields to single drupal nodes doesn’t work for me, since i am using entity-reference fields, which aren’t supported.

So what’s your best practice?

(Annotation: The content isn't very often updated and the content of the fields hasn't to be used in tokens, but i have to use a more or less "rigid" field structure in order to make editing content an easy no-brainer for the content maintainers. using „wide open“ WYSIWYG textareas isn’t a way to go, because maintainers will alternate often and will have only little knowledge about the project.)

Answer is it depends.

How often is the content in these nodes being updated? Does the content in the different fields need to be used in tokens, views, etc?

If it's never updated OR if you can use wysiwyg to edit the body to position things where they need to go and make it easily editable then use one node type.

If the info needs to be put into fields so views/tokens can pull bits out of the nodes then creating fields for those values is important.


Get current currency symbol in drupal commerce How can I get current currency symbol of site in my custom module?
as example if set to USD show $.

I know there is some api provide this job, but I don't found them, anybody know how can I get current currency symbol ?

With Drupal 7, if you want to get the default (current) currency you can use  the following code.
$cur = commerce_currency_load();
$sym = $cur['symbol'];


How to have a drupal module respond on node creation I am trying to convert some of my rules to a custom module for more flexibility and better configuration.

However, I am stuck; I want my module to read some fields on node creation (or update). In rules there is the event property where I can choose 'on creation of node'.

I suppose I have to use a hook of some sort, but hooks like hook_node_insert() (and some others) that respond on a node being created (or saved) are depending on a node parameter; hook_node_insert($node).

So how do I get this node property?

All credits to Clive, but here is the answer.

You need to write a custom module: Simply write a MYMODULE_node_insert($node) function containing the code you want to execute. Drupal will call that function every time a node is created (when the module is enabled).

If you are changing the code of a module that is already enabled, you should clear Drupal caches, as otherwise Drupal will not notice the module contains a new hook implementation. This can be achieved by disabling the module before editing it, and re-enabling it after the code has been changed.


user_presave and user status I have written this hook in my custom module, just to track the status changes of the users.
/**
 * Implements @see hook_user_presave
 */
function mycustommodule_user_presave(&$edit, $account, $category) {
$account_user_id_=$account->uid ;
 $new_status=  $edit['status'];
 $previous_status= $account->status;
watchdog('attention',
     'User  %ui changed status to: %newstat, previous status was %previousstat',
     array('%ui' => $account_user_id_, '%newstat' => $new_status, '%previousstat' => $previous_status, WATCHDOG_NOTICE));
}

I noticed for example that when a user activates his newly created account by clicking on the link sent by email, the status moves to 1 which is good .
But I also noticed other message that I couldn't know its cause:
"user 34 changed status to: , previous status was 1" . What makes the status of a user moves from 1 to  null ?

You get NULL for $edit['status'] because the status hasn't been changed. The functions that calls user_save(), which invokes hook_user_presave() contain the following code.
// user_profile_form_submit()

$account_unchanged = clone $account;
entity_form_submit_build_entity('user', $account, $form, $form_state);

// Populate $edit with the properties of $account, which have been edited on
// this form by taking over all values, which appear in the form values too.
$edit = array_intersect_key((array) $account, $form_state['values']);
user_save($account_unchanged, $edit, $category);

// user_register_submit()

$account = $form['#user'];
entity_form_submit_build_entity('user', $account, $form, $form_state);

// Populate $edit with the properties of $account, which have been edited on
// this form by taking over all values, which appear in the form values too.
$edit = array_intersect_key((array) $account, $form_state['values']);
$account = user_save($account, $edit);

As the comment says, $edit contains only the account properties that have been changed, not every property. If you want to obtain the status value, you should use the following code.
$new_status = isset($edit['status']) ? $edit['status'] : $account->status;


Is there any way of adding the exact same login options of StackExchange websites in a Drupal 7 site? I think that the title is pretty descriptive but I would like to be as detailed as possible so let me list all the login options that I would like my drupal site to have available:

Open ID
Stack Exchange
Facebook
Yahoo
Gmail
Wordpress
Blogger
AOL
Google Profile
Verisign (optional)
LiveJournal (optional)
Clickpass (optional)
ClaimID (optional)

So, is there any solution to implement this in a Drupal 7 website?

StackExchange uses the JavaScript OpenID Selector. Drupal can use the JavaScript OpenID Selector by means of the OpenID Selector module.


HttpFoundation Request POST parameters From VueJS, I am sending a POST HTTP request to my Drupal 8 controller.

Here is my Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class ExampleController extends ControllerBase {

  public function doSomething( Request $request) {

    \Drupal::logger('mymodule')->notice($request->getContent());
    \Drupal::logger('mymodule')->notice($request->request->get('message'));

    return [];
  }
}

The first log entry outputs:

@"params":{"message":"hello world","headers":@"Content-Type":"application/json; charset=UTF-8","Access-Control-Allow-Origin":"http://localhost:8080"}

The second log entry fails (it is empty).

What am I doing wrong and how am I supposed to retrieve this message POST parameter?

For completeness, here is the JS POST request:

this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}).then(response => {
  // response
}, response => {
  // error callback
});

mymodule.routing.yml file:

mymodule.api_example:
  path: 'simple_path'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ExampleController::doSomething'
  methods: [POST]
  requirements:
    _access: 'TRUE'

Apparently with Vue Resource, I need to add emulateJSON:

  emulateJSON boolean Send request body as application/x-www-form-urlencoded content type.

this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}, {
  emulateJSON: true
}).then(response => {

  console.log(response);

}, response => {
  // error callback
});

Now in my D8 backend:

$params = $request->request->get('params');
$message = $params['message'];

And now it works as expected.


SearchAPI Autocomplete - Pass in contextual filter to alter query I'm trying to modify the Autocomplete module query with hook_search_api_alter_query. I would like to pass in the contextual filter of the page I embed the search in into the module so I can add it to the query. In a hook_search_api_alter_query function I wrote, I just used arg(1), which works for the actual search, however when the autocomplete module runs, var_dump(arg(1)) returns Response Type: string(33) followed by the autocomplete results and their html tags.

Is it possible to pass in the contextual filter into the autocomplete module so that I can use it , since the contextual filter has been changed to /search_api_autocomplete/search_api_views_[view name]/-?

My current query alter hook:

    function hook_search_api_query_alter(SearchApiQueryInterface $query) {
      var_dump(arg(1));
        $prod_code = arg(1);
        $tid = taxonomy_get_term_by_name($prod_code);
        if (!empty($tid)) {
            $base_filter = $query->createFilter('AND');
            $or_filter = $query->createFilter('OR');
            while (!empty($tid)) {
                $or_filter->condition('field_prod_code', array_shift($tid)->tid);
            }
            $base_filter->filter($or_filter);
            $query->filter($base_filter);
        }
    }

My problem is that arg(1) within the autocomplete module isn't the taxonomy term, therefore the function doesn't go through the if statement. I need a way to get the contextual filter for the autocomplete function so that it can alter my query like it does when searching.

I ran into the same issue.
You could save your data in a session in hook_init or hook_boot.

/**
 * Implements hook_init().
 */
function hook_init() {
  $arg = arg();
  if (isset($arg[2]) && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2]) ) {
    $_SESSION['last_term'] = $arg[2];
  }
}


Adding a custom URL to the top of a view based on status of another field Okay... so I have this crazy problem. Not really, but I can't figure out how to do it.

I have a view, that lists out a content type "request". When you click on the title, it links to that node (also displayed using a view).

So what I'm trying to do is this:
When on a node whose content type is "request", I need to dynamically create a link that uses the title.

For example, if the Node is http://www.example.com/request/this%20is%20the%20title

Then I'd like a link to appear of this form:
http://www.example.com/survey?request=this%20is%20the%20title

BUT ONLY if that node has a field_type_status of "closed"

Summary:
Dynamically create a link using node's title using a view based on a field's status.

Your question is actually several questions. I'd suggest that you break you problem down into smaller, more manageable questions otherwise the number of responses might be low.

For starters, a break down:

"I need to dynamically create a link that uses the title" ->
Pathauto module.
"I'd like a link to appear of this form": The
format that the URLs appear in can be set in the Pathauto
configuration settings for the node type.
"BUT ONLY if that node has a field_type_status of "closed" -> Hmmm,
this might require some custom code. It's kind of a weird spec as
it's considered good SEO to use Pathauto on all site content. Good
luck with this one, perhaps someone else will help you with this one.


Getting current tid on taxomony/term/{id} without using arg() From a page based on a url of taxonomy/term/##, how do I properly get the tid (the numeric value in the URL) without using args()? Is using args() a decent way of doing this?

From where this page is coming, from core taxonomy or views?.

By default the taxonomy module provide the taxonomy/term/## callback and views module also provide a default view with the path taxonomy/term/##.

If you haven't enabled the Taxonomy term view then this page will be the default taxonomy core page, in that case you can use menu_get_object('taxonomy_term', 2) to get the loaded term.

For arg(), the document says

  Avoid use of this function where possible, as resulting code is hard to read. In menu callback functions, attempt to use named arguments. See the explanation in menu.inc for how to construct callbacks that take arguments. When attempting to use this function to load an element from the current path, e.g. loading the node on a node page, use menu_get_object() instead.


Feed import many fields into single content type I have a content type that I want to import some sitenames and siteurls from a csv file. So basically create a node type with option to import csv file to fill up field types sitenames and siteurls under one project with feeds or any other solution need help

Setup: Drupal 7, Views 2, Feeds

You are in the correct path, the Feeds module will allow you to import into the a content type data from a CSV file. You should install the feeds module first, create the content type after and last map the columns of data on your CSV file to the content type fields.

If you want to manipulate the data first before creating the node the Feeds Tamper module will help you do that.

Note: On the feed module page that are a couple of links to help you with the setup. Also Mustard Seed Media released a new podcast about the feed module as well.


How can I send emails with drupal_mail() and hook_mail()? I have this code for send a simple notification email.
function mymodule_commerce_checkout_complete($order){
  $buyer = user_load($order->uid);
  if(in_array('wholesale', $buyer->roles)){
    $params['buyer'] = $buyer;
    $params['order'] = $order;
    drupal_mail('commerce_mayoreo_workflow', 'new_order_mayoreo', 'myemail@gmail.com', user_preferred_language($buyer), $params);
  }
}

This is the hook_mail() implementation.
function mymodule_mail($key, &$message, $params){
  switch ($key) {
    case 'new_order_mayoreo':
      $langcode = $message['language']->language;
      $message['subject'] = t('New Quote request', array('langcode' => $langcode));
      $message['body'][] = t("New Quote request has been created\n\nYou can download the CSV format of the request here:\n\nhttp://bbheperfumes.com/download-order-csv/@order_id",array('@order_id' => $params['order']->order_id), array('langcode' => $langcode));
      break;
  }

}

It's not sending the email, and Im checking in recent log entries and there is not anything about a failed delivery, anything about system tried to send a mail.
I could not figure out why it's not sending the email, so I want to ask if mimemail has something to do with this issue?
I just have the MimeMailSystem in the 2 first select lists that are displayed in the configs of mail system.
By the way, I am using a fresh install of Commerce Kickstart.

Debugging such kind of eMail issues can sometimes be challenging.

Consider the 3 Modules to Help you Debug Emails in Drupal 7. Here is a quote from it:

  Problems can exist in multiple areas; like Drupal itself or your mail server. So when an email issue arises you first need to check and see if Drupal is generating emails and then make sure your mail server is sending the emails. Luckily in Drupal there are a few modules that can lessen the pain of debugging emails.

These are the 3 modules/steps mentioned on that link:

Intercept Emails Using Devel.
Log Emails Using Mail Logger.
Re-route All Emails Using Reroute Email.

PS: Debugging Drupal emails contains another checklist with 8 possible reasons about what may be the problem.


Taxonomy list in views -Term 1
   --Term 1 Sub 1
   --Term 1 Sub 2
     -- Term 1 Sub 2 Sub 1
     -- Term 1 Sub 2 Sub 2
 -Term 2
 --------------------
 -------------

This is my Taxonomy structure. I need to build a taxonomy list in views.

http://mydom.com/gallery/term-1  // this will list the next level of taxonomy.
http://mydom.com/gallery/term-1/term-1-sub-1 // this will list the next sub level

etc like that. Can you please suggest one good way for doing this

Install and activate the Views Tree module.

Add a new 'Taxonomy Terms' view. (Choose the vocabulary or 'All').

Add a relationship to Taxonomy Term:Parent Term. Do NOT set this relationship as required.

Add two fields for Taxonomy Term:Term ID.
The first label as Main Term ID, and exclude from display. This one does not use the relationship.
The second label as Pareent Term ID and exclude from display. This one Does use the relationship.

Add any other fields you wish to include (Name, Description etc) and style as you wish.

Change the view format from Unformatted List to Tree (Adjacency model), and under settings, set the Main field to Main Term ID and the Parent field to Parent Term ID.

Create a page display, give it a path, and save the view. Go to the path and look at your taxonomy tree. (The tree styling sometimes does not display in the live preview, particularly if you use Seven as an admin theme.)


Renaming a Content Type Machine Name I have a really annoying typo right through my Drupal install (db table names, modules...you name it it's right through). Ideally I would like to fix the typo and not recreate the content type/modules etc.

The process I have gone through so far:

Find/replace all instances of the typo in the Database using this Script https://gist.github.com/leewoodman/9544808

I then renamed all the tables where the typo occurred using this:

RENAME TABLE field_data_field_accomodation_ref TO field_data_field_accommodation_ref,  field_data_field_offer_accomodation TO field_data_field_offer_accommodation, field_revision_field_accomodation_ref TO field_revision_field_accommodation_ref, field_revision_field_offer_accomodation TO field_revision_field_offer_accommodation;

Then I ran this ruby script to replace all instances of the typo in my files/file/folder structure: https://gist.github.com/dvdsgl/4600317

Then I deleted all caches manually in the DB using:

SELECT
  CONCAT('TRUNCATE TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') AS table_name
FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = 'my-db-name'
    AND TABLE_NAME LIKE 'cache_%'
    AND TABLE_TYPE = 'BASE TABLE'

I am pretty confident I fixed all the typos but I then get an entityreference error.

Am I missing another step here somewhere?

It is impossible to tell whether you've missed something without having complete access to your schema.  The fact that you get an entityreference error after clearing all caches is not a good sign.

A safer approach to renaming a content type machine name is to recreate the bundle with the correct machine name, and then use Node convert to convert it from the old machine name to the new one.

  Node Convert ... gives the ability of converting the node from its current node type to another node type. Also it gives the ability of transfering all the custom CCK field values of the current node type to the destination CCK fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accessed in Administer → Content → Convert Nodes.

It allows both single node a and multiple node conversion. Here is a link to the documentation.

I've used the module for a similar use case as yours, with success.


Alter views with hook_views_query_alter() i'm trying to hook all my site views with hook_views_query_alter()

I can't find how to add a relationship and condition in the query.

Here is my (not working) code

/**
 * Implementation of hook_views_api().
 */
function taxonomy_location_views_api() { // your module name into hook_views_api
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'taxonomy_location'),
  );
}

/**
 * Implementation of hook_views_query_alter().
 */
function taxonomy_location_views_query_alter(&$view, &$query) {
  // get taxonomy term ID
  $tid = subdomain_get_sid(subdomain_get_current_subdomain());
  if($tid) {
    $join = new views_join;
    $join->construct('term_node', 'node', 'nid', 'nid', array(), 'INNER');
    $query->add_relationship('term_node', $join, 'node');
    $query->add_where('term_node', 'term_node.tid', $tid);
  }
}

Any ideas?

I found a slightly different solution that works.

Instead of adding programatically the relation, I instead added a clause in $query->where

function taxonomy_location_views_query_alter(&$view, &$query) {
  $tid = subdomain_get_sid(subdomain_get_current_subdomain());
  if($tid) {
    $query->where[0]['clauses'][] = "(node.vid IN (SELECT tn.vid FROM term_node tn WHERE tn.tid = %d))";
    $query->where[0]['args'][] = $tid;
  }
}


How to translate products with Drupal commerce module? I'm using Drupal commerce module. I don't see the Multilingual tab in the product type: product at admin/commerce/products/types/product/edit.

How do I make the product translatable? If that is not posible (hard to believe...) how can I just translate the product title?

Entity translation allows to to translate products. To be able to translate the title, you will need to replace it with a field and use that instead. There is the Title project to help with that, but I haven't yet tried if it is compatible with Commerce products.


Drupal module to hide part of body field initially I'm having trouble finding results for this because there are so many conflicting search terms.

I have a content type in which I want to hide most of the Body to start, but add a Read More type of link which would just use javascript to reveal the rest of the body.

Here is an example of what I'm talking about (I'm converting this site to drupal):

http://www.inadaydevelopment.com/app-10biiFinancialCalculator-iOS.php

I'm having trouble searching for something because "Read More" returns a ton of results about the standard Read More link.

Do you know of a module that will let me do this easily?

You can do this using a jQuery plugin. See this drupal/stackoverflow response.

The jquery project page for readmore. Other jquery modules can do this as well such as Expander. Expander looks newer and more supported (off hand).

You could just add this file to your site's theme folder and theme info file. You probably want to not use Teasers anywhere and just rely on the JS readmore links for a CSS selector targeting your node body content. Your theme may have a more specific selector.


Content type with multiple users - create a view of all users that relate to content of that type Suppose you have a content type called political party. Political parties can have members that are users. A user can be a member of multiple political parties.

I am trying to create a view where I list every user that is a member of a political party, and list them each only once. I don't need to see what party they are in, and this should just be a newest user sorted list of users that are listed in at least one political party's member field.

So these are the content types that need to be related:

party
   |-members (user reference list)
user

How would you construct a view for this using the views module? I am a little lost on how to tackle this.

(note: I am using political parties, but actual content type name is different. It just is easier to explain this way)

I'm not entirely positive this is the type of relationship you want for this data.  If you use a node_reference field on the user rather than a user_reference on the node it would be pretty straightforward to create a view of Users who party.

Query all users and then add a Relationship to the field_party node reference.  Require the relationship with a Delta of 1.

This type of reference would seem to make more sense for your use case as well, since this would enable any user to administer their own party affiliations rather than the party manage the list (but then this is an analogy and I don't know the particulars).

Either way you are hitting up against the boundaries of what is possible using references.  I'd encourage you to take a look at the Relation Module which is designed to handle these kinds of bi-directional relationships, e.g. Display the members of the Party, Display the parties an individual is a member.


Rendered markup different than template markup I am using drupal 7, and the bootstrap base theme to make a simple theme for a website I am working on. I am having issues with Drupal forcefully changing my html5 hierarchy and it's causing the site to break.

Is there anyone that would know what would cause the issue?

I have attached the code snippet in particular that is causing issues, as well as a screenshot from Chrome's inspector showing the misplacement. I have confirmed it's doing it on at least 4 browsers, so I do believe it's a drupal issue.

    <section class="<?php print $column_width; ?>">
      <?php if (!empty($tabs)): ?>
        <?php print render($tabs); ?>
      <?php endif; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>

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

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

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

As you can see from the image, the  is being placed outside of the root
 instead of inside of it (and underneath the other
), like the template is telling it to do.

EDIT: The 5 console errors are from image files not being found because I haven't uploaded them yet.

The comments in this question were helpful, but I can't credit both people so I will post the answer.

My default views-view-unformatted.tpl.php had an extra closing tag inside of it somehow. Not sure how since it's a default views display. Removing the tag fixed the issue.


What is the difference between template_preprocess_search_result() and template_preprocess_search_results()? I am seeing 2 functions like template_preprocess_search_result() and template_preprocess_search_results() in Drupal 7. I just got confused on which function I should use when modifying my search results.

Can anyone tell me what the basic difference between these 2 functions is?

template_preprocess_search_result is to process variables for search-result.tpl.php which will render output for each of the search result independently.

template_preprocess_search_results is to process variables for search-results.tpl.php which will render output after each of the search result is already rendered through search-result.tpl.php

For example, if there are 4 search results. for each of the results search-result.tpl.php will be used. and at the end search-results.tpl.php will be used. Ending up using search-result.tpl.php for 4 times for each of the results and search-results.tpl.php only once at the end.

Hope that is clear.


Change Search API Facet title for boolean values I have my shop set up in Drupal Commerce. I have added search API and configured facets for things like taxonomy terms, which are perfect.

However on my product display nodes, there are a set of values that are boolean on/off checkbox fields for different attributes. These are...

Vegan friendly
Vegetarian
Contains sugar
Won a taste award
Contains gluten
Contains Alcohol

But they are showing their 1 or 0 key values for the boolean. Is there anyway to name these facet values?

I want to hide the 0, hide the block titles, rename the "1" to the block title, and then group them all together with CSS. The only thing im stuck on is renaming the 1 value.

I appreciate any help!

I downloaded Facet API Bonus module, and used the exclusion option to hide fields that were "false" or "0".

I then went into the content type and changed the "1" value to what I wanted it to say.

Along with a little CSS around the field to neaten it up, I now have exactly what I was after.


How to display only the first value in Views, by overriding TPL.PHP? I am trying to override the output of one field in Views, and I need it to print only the first value of the field.

Like:

Unfortunately my knowledge of PHP and Drupal-API are very low, so I hope to get some help here.

You can do this on the View edit page using the UI without editing the template.

Go to admin/structure/views
Edit the view in question
Under Fields, select the field in question
Expand the section 'Multiple field settings'
Set as: 'Display 1 value(s) starting from 0 (first item is 0)
Save your view and that's it.


Issues migrating site config at various points in project lifecycle Issues migrating site config at various points in project lifecycle

Hi

My team and I have begun a new project for our company using the very latest version of Drupal 8 (version 8.5.6)

We wanted to use config migration in order to carry config changes from one developer across to another seamlessly and across to staging and production environments.

We are in the middle of testing the migration workflow and have run into a problem.

I started off the project by doing a standard Drupal 8 installation. I then did a migrations export (drupal ce), committed this to the repository.

My colleague proceeded to install Drupal also, also a standard install, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:

[ERROR] An error occurred while trying to write the config file: "Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing."

Prior to this we had an additional issue where Drupal complained about mismatched UUID’s. We got around this by updating his UUID as follows:

Error received:

[ERROR] An error occurred while trying to write the config file: "Site UUID in source storage does not match the target storage.

Fixed with:

drush config-set "system.site" uuid "42e3c541-5ebc-4ec9-a8f0-e8c6ad1ccfb7

The above UUID was gained from my installation.

So now we are left with the first error explained above.

We tried deleting the shortcuts manually, as suggested in several places on the internet, but this caused his system to completely break.

I also thought possibly that instead of him doing a clean, standard install at the start of the work that he should have used a snapshot of my initial installation, and when we move the app to staging and/or development it will follow suit that we use backups for the initial setup to ensure the DB is in sync with regard to UUIDs, but I am not convinced this is the correct way to do it.

So, we are a little lost on exactly what is the recommended workflow for migrations, with the view that we will be using the workflow going into production also, e.g. after launch we will want to use config migration export/imports to apply changes made locally.

My colleague proceeded to install Drupal also, also a standard install, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:

Don't do that. Config import/export is meant to be used for the same site. That's exactly why the site UUID check exists, that's to tell you that what you are trying to do doesn't work.

Either you need to sync the database or you need to use something like https://www.drupal.org/project/config_installer to install based on an existing set of configuration.

Usually the process is that content and configuration flow in opposite direction. You have your production site where new content is created, from time to time you want to sync the full DB down to your staging/development and then you have configuration changes that you are creating locally and then deploying to dev/staging/production.

See also presentations like https://events.drupal.org/vienna2017/sessions/advanced-configuration-management-config-split-et-al for example.


Contextual filter on Views Block file not found I am trying to use a views block with a contextual filter for taxonomy terms to create an index that can filtered based on terms in the URL.

This works fine with a views page: so if the URL is /my-index then I see all the sub pages. And if the URL is /my-index/apples I see all the sub pages tagged with apples.

Now I when I make a block the same as the page view described, I understand that the block does not have a source for the contextual filter, so I have to provide a filter value. I have tried all the settings, but the problem seems to be that when using a views block and the URL is /my-index/apples I get a file not found error. With /my-index I get the full list as expected.

The filter works in preview mode, and if say I set the Default Value to Fixed Value=apples, is works at URL /my-index (filtered for apples as expected), but when URL is /my-index/apples then again I get file not found error. Then if I change the filter value to 'Display all results for specified field' I get the same result i.e. /my-index shows all and /my-index/apples gets file not found.

It seems to me that when the URL is /my-index/my-term it is not getting to the /my-index page to run the views script in the block. So I cannot connect the page URL to the block because I am not getting to the page at all when I add my-term to the URL.

I have set up a new alias for the page and tried new terms in case there is some sort of clash somewhere but to no avail.

The answers provided at Contextual filter with a block view did not seem to help. I tried every setting in every combination several times.

I think you are just a bit confused about the structure of the page drupal creates so hopefully this might help to clarify it all.

When you create a page display in Views with a contextual filter, you basically are creating a menu item / path on your website. In this case, it's probably something along the lines of my-index/%, with the % being the contextual filter.

You then define that filter to be a tax term.  So, you can then type in  www.yourhost.com/my-index/foo and www.yourhost.com/my-index/bar and www.yourhost.com/my-index/baz and get the $content of those pages filled with the fields of the view you created filtered by foo, bar, or baz.

Or any other term a user puts in in place of the %.

This way you aren't creating umpteen individual views, eg, you don't have to create my-index/foo, my-index/bar, my-index/baz, etc etc page displays for each and every possible tax term.

Plus if you say show me everything if the contextual filter is missing, then you can also go to www.yourhost.com/my-index and get a list of everything.

Now to blocks.  These aren't the main $content of your page, but rather little boxes of additional information off to the side.  They can be placed pretty much on any page you want through the block admin pages, you just go in there and tell it what region you want and pages and off you go.

So, in this case, let's say you created a page display called my-index/% like the above.  In this example, let's also say that this view lists the content on your system sorted by Title.  So, in the main content area of this page you'd have that listing of your content tagged with that tax term sorted by title.

But let's say you wanted a block off to the side listing the very latest content tagged with that same tax term.

Here, you would create a block display of content sorted by creation date in descending order and limited to 1 item.  Here you would also add a contextual filter, but in the supply the default argument, you would tell it to take it from the url and specify where it is, in this case the 2nd argument.

Then you'd save everything and go to the block admin page and down in the list of blocks available you'd see this View Block.  Assign it to a region in your theme and then in the pages, restrict it to my-index/* and then it will show up on that page along with your main content.


Enter object with dsm i am actualy trying to read a field value in my panelized node.

I want to recieve the data in the red marked field, as u can see in my screenshot.

I tried to following:

<?php print_r($display->context['panelizer']['data']['field_centerpage_layout'][0]['value']); ?>

But I recieve this Error:

Fatal error: Cannot use object of type ctools_context as array in C:\seu\xampp\htdocs\iptp\sites\all\themes\mytheme\plugins\layouts\he_two_70_30\he-two-70-30.tpl.php on line 29

I would be thankful for any kind of help :-)

As you can see from your Krumo output (plus the very descriptive error message), data is an object, not an array. I'd imagine $display->context['panelizer'] is also an object but it's hard to say as you haven't mentioned in your question how that's populated. You should use either

$display->context['panelizer']['data']->field_centerpage_layout[0]['value']

or

$display->context['panelizer']->data->field_centerpage_layout[0]['value']

Probably the second one.


Can i populate the empty sites/default/files/ with files from a local installation? There are no JavaScript and CSS files in the following folders:

/home/vhost/WWW/mysite.com/sites/default/files/js
/home/vhost/WWW/mysite.com/sites/default/files/css

All the folders are empty. Can i populate the folders with aggregated css and js files from another drupal installation that is the same?

Update: thx to googletorps and sheenas ideas and hints regarding the special constitution of the aggregated css and js-files i just have had a closer look at them - which are based on my local (!!!) installation of the exacly same installation - a drupal commons: for the sake of a better understanding the aggregation of the hashed files i add the output of the shell here:

we see the files how the should (!!!) look like:

here we see the css-files

linux-vi17:/srv/www/htdocs/com624/sites/default/files/css # ls -l
insgesamt 872
-rw-rw-r-- 1 wwwrun www 158526 22. Jan 12:10 css_2c40e29bada7df2a0872e3284d5906c0.css
-rw-rw-r-- 1 wwwrun www 164051 22. Jan 12:04 css_509f375f4dd1349c65961ef65612b39f.css
-rwxrwxrwx 1 root   www  62359 20. Jan 23:35 css_715c2ea6e483943b9fb7a7870eb8d3af.css
-rwxrwxrwx 1 root   www 163905 20. Jan 23:35 css_7d8ae0563cfe8042f1ae8c8b997decaf.css
-rw-rw-r-- 1 wwwrun www 158378 22. Jan 12:08 css_ad58026023b58c62611ee2690b7767ed.css
-rwxrwxrwx 1 root   www 164051 20. Jan 23:52 css_dc93777fb44b0e70ce92cdbc3fb098e9.css
-rwxrwxrwx 1 root   www    869 20. Jan 23:35 css_dfe74e375bbbe435aaa2c17f83c4843a.css
linux-vi17:/srv/www/htdocs/com624/sites/default/files/css #

and here the javascript-files

linux-vi17:/srv/www/htdocs/com624/sites/default/files/js # ls -l
insgesamt 2004
-rw-rw-r-- 1 wwwrun www 252042 22. Jan 12:09 js_49eafedecb47a7ddbcbaca1afe9934bd.js
-rwxrwxrwx 1 root   www 116020 20. Jan 23:35 js_5b2fd4858d6549bf716717a2aeff7ec8.js
-rwxrwxrwx 1 root   www   2619 20. Jan 23:35 js_5e4cf1f9d580681533f28941e5369206.js
-rw-rw-r-- 1 wwwrun www 291843 22. Jan 12:04 js_7308bd15ff335fb80932a983f43a674e.js
-rw-rw-r-- 1 wwwrun www 244292 22. Jan 12:08 js_7fccee0ff92c41edc64dbe9af3cc42d5.js
-rwxrwxrwx 1 root   www 291843 20. Jan 23:52 js_b03baa42e9679d7c9bfa96bf43b644de.js
-rwxrwxrwx 1 root   www 291460 20. Jan 23:35 js_b6a467b980c752283820195189e6e5e0.js
-rw-rw-r-- 1 wwwrun www 289758 22. Jan 12:10 js_c97e31b30c535ae5779711f7966b6096.js
-rw-rw-r-- 1 wwwrun www 252637 22. Jan 13:49 js_e4cc5b6ab05a295dab73ce5aac20ac1d.js
linux-vi17:/srv/www/htdocs/com624/sites/default/files/js #

Note: and what we can see here in a good way - the files are generated at different times. (note this is not!!! the mentioned site with the broken style - this is a site that is runned locally on the local lampp)

Well what makes me wondering is the following fact we have very differnet owners of the files - see that we have sometimes have

root   www
wwwrun www

question: why is this so!? i do not understand this! OR wait - the owernship corresponds with the permission (chomod..) what do you think? in othe words: is there a relationship between the permission which is in one case pretty much/ high ]

-rwxrwxrwx 1 root   www   2619 20. Jan 23:35 js_5e4cf1f9d580681533f28941e5369206.js

and in the other case pretty low / weak and this correspondents/results in the wwwrun-user:

-rw-rw-r-- 1 wwwrun www 291843 22. Jan 12:04 js_7308bd15ff335fb80932a983f43a674e.js

latest Update: after adding the files i have the following results: http://campus-24.com/?q=home

If your two Drupal installs are exactly the same, it is possible. Your biggest problem will be figuring out the name of the files, since they will have some hash value generated by Drupal. I don't know exactly how this is generated, but yes it is possible.

Now while this is possible, it's not a long term solution. If you had a live site, and something was failing to generate the aggregated css and js files, it could be a quick short term solution until the real problem was found and fixed.

I believe that you have asked about this already and received answers about file permissions etc, some of this which doesn't belong here, since it's about setting up a server and not Drupal itself. I would advise against pursuing this path, and instead try to resolve the real issue. If you want to upload files, use image cache and a lot of other modules and features you need to resolve this anyways. Making a hacky unstable solution will do you no good.


Using Entity Metadata Wrapper to set/get value from custom field added via Field API to custom entity type My question is related to: Using entity metadata wrapper with custom entity type

I know that I should inform EMW how to work with entity properties via hook_entity_property_info_alter

but what about custom fields added via Field API to custom entity. I'm trying to set value of that kind of field via EMW but after entity save, field (db table) is always empty.

I've forgotten to set fieldable => true in hook_entity_info. Now EMW works


Authenticated REST requests becoming anonymous user I'm new to the services and rest_server modules (and RESTful APIs altogether.) As I understand it though, the steps are basically this:

Send a post request to /api/user/login with the username and password set in data
Store the token you get in the response
On subsequent post requests, add the token to the header with the key X-CSRF-TOKEN

When I use the Postman Chrome extension to do that, it works great. When I do it in code, it does api/user/login fine, I get the token, but when I try to access /api/other/endpoint, I get 403 Access denied for user anonymous error.

The first request (/user/login) looks like this:

POST /api/user/login HTTP/1.0
Content-Type: application/json
Accept: application/json
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 41

{"username":"NAME","password":"PASSWORD"}

And the second request (/other/endpoint) looks like this:

POST /api/other/endpoint HTTP/1.0
Content-Type: application/json
Accept: application/json
X-CSRF-TOKEN: vGJm5GNDGumf-SoHnLsBU6d46EkrOZkvUY0CSa08GA0
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 0

If I make requests to /user/token after authenticating, I get new tokens each time. If I try to logout immediately after logging in (and send along that token), I get a "406  Not Acceptable : User is not logged in." error. it tells me user is not logged in.

If I check the site though, it shows the user as successfully having logged in, and still being logged in after the fact.

Do I have to save/send anything regarding the session name/id or cookie? Everything I've been looking at suggests only the session token is necessary.

(Answering my own question, and trying to sound like a third-party so it makes better sense when read...)

It looks like it definitely has something to do with the session/cookie/etc., as subsequent calls seem to be coming from a different client (from the REST server's perspective.) I'm guessing bare PHP has no way of maintaining that cookie, like how a browser would. After looking here, it looks like the cookie needs to be formatted as such in the header of the request:

Cookie: session_name=sessid

(The cookie could also be retrieved from the response's headers->set_cookie variable. The latter will include all the expiration/link info in the string as well. While either method seems to work, I'm not sure if there are any ill-effects from one or the other. I just used the first method because it was the first solution I came across.)

Both session_name and sessid can be taken from the data area of the response after a user/login request. So the  request would ultimately look something like this for a user/logout

POST /api/user/logout HTTP/1.0
Content-Type: application/json
Accept: application/json
X-CSRF-Token: igHUQD11Y8LYdyzHi8m5t33U_tCVZNHE6BbptE4mrwQ
Cookie: SESSd3a1acd26f95229c67cd0a9a1e455bd4=rv-Kbyb8znaGlYBBU5Dn7M2GzkYdWnun5aXcVYLVfvY
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 0


Submission handler for the user registration form doesn't work I'm working on a Drupal 7 portal. I added a custom field to the registration form and I would like to get hold of custom field value when the registration form is submitted and before it is stored in the database.

I'm trying to use the submission handler for the registration form and print the content of $form and $form_state, but those values never get printed as message. I installed the Devel module as well.

function user_register_form_submit($form, &$form_state) {
    drupal_set_message('
'. print_r($form, 1) .'
');
    drupal_set_message('
'. print_r($form_state, 1) .'
');
    drupal_set_message(t('An info message from user_register_form_submit'), 'error');
}

I appreciate any input on what the issue could be.

In hook_form_alter use foloowing code

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'user_register_form'){
    $form['#submit'][] = 'module_custom_form_submit';
   }
}

after that use

function module_custom_form_submit($form, &$form_state) {
    // Do whatever you want.
}


How do I get the count of all messages in the inbox? How can I get the count of all the inbox messages, with the Private message module?

Below the inbox messages, I need to display the count of total messages, such as:

  10 of 55

_privatemsg_get_new_messages() is the function to get new messages in Drupal 5.

Is there any function to get the count of all messages in Drupal 6?

There is a privatemsg_unread_count() function in Drupal 7. If that doesn't work in Drupal 6, check the module file for the name of the function.


Where do I include css file? As a total newbie in Drupal I asked myself where do I include a css file? (Using Drupal 6)

I wrote a web application with javascript, php and mysql and now I'm trying my first steps in migrating this application to Drupal. I already found out on Stackoverflow How to include css and javascript files.
Since i know now which function to use to include my css file, I don't know where.
Do I have to simply create a new module (named "mymodule" like in the example from stackoverflow)?
Or is the css file only applied to the module "mymodule"? If so, how can I apply it to a page filled with plain HTML?

To include your custom css say demo_global.css in your theme write following line in theme_name.info file of your theme folder-

      stylesheets[all][] = css/demo_global.css

Note: You must clear the cache to see the changes.
For more information please refer https://drupal.org/node/171209


how to customize my views-view-table.tpl.php? i have a view table for property list and i want to customize the view source code to make it print specific label that i add from inside of view in the administration

the view source code :

<thead>
  <tr>
    <?php foreach ($header as $field => $label): ?>
      <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?> scope="col">
        <?php print $label; ?>
      </th>
    <?php endforeach; ?>
  </tr>
</thead>

but this code print all fields labels even its empty!

output :

the output that i need like this :

any suggestion to update the code ?

The best way is to use field_info_instance($entity_type, $field_name, $bundle_name)to get information about specific instance of a field. The label of the field is contained in the array returned from that function.

The general code :

<?php
 $info = field_info_instance($entity_type, $field_name, $bundle_name);
 print $info['label'];
    ?> :

in my situation :

<?php
 $info = field_info_instance('node','property_photo','property');
 print $info['label'];
    ?> :

OR

by Using this Code :

<?php print $header['$field_name']; ?> :

in my situation :

    <?php print $header['property_photo']; ?> :

that's it .


Drupal Views for 2 Title Styles Mock:
Site: http://www.mastersfunds.com.php5-23.dfw1-2.websitetestlink.com/funds-and-performance/equity-fund

Brief: The mock has the title with 2 font styles. The first part is in blue text and the fund/ticker is in a smaller, light gray font.

Is there a way to use VIEWS to display the TICKER font/html directly after the Title as displayed in the mockup? What VIEWS settings would I use?

I think as a relatively new Drupal developer, you could benefit tremendously from getting to know CCK. This will allow you to have flexibility with how fields are laid out and ensure that page layouts remain consistent.

The way you've approached the task, I can think of two ways to get that ticker to show: using jQuery and using a theme function. If you know about template.php and theme overrides, I'd recommend that route. Otherwise, this should be doable with jQuery:

Using jQuery:

Place this in a js file:

$(function() {
    $('#block-quicktabs-fundsperformancetabs h2').append('
MSILX, ETC
');
});

And in your stylesheet

.ticker {
    text-transform: uppercase;
    color: #CCC;
    font-size: 11px;
}

Be sure to include your js file in your theme's info file.

scripts[] = js/custom.js

This has the downside of being 'in the code' instead of editable by the client, but that's where CCK would come in.


How to redirect anonymous users to login page using Rules module? I'm using rules module with drupal 7 in order to redirect anonymous users to the login page, so I created a rule with react on event "Drupal is initializing", condition "User has role" with anonymous user and "Not site login url", then added an action "Page redirect" to site login url. When I tried to test the rule; drupal kept redirecting to the login page over over and over until apache server stopped working. Any recommendations.

The way I solved it as follow:

Events: Drupal is initializing
Conditions:

User has role(s) - Parameter: User: [site:current-user], Roles: anonymous user
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login

Actions: Page redirect - Parameter: URL: user/login

Export rule as follow:

{ "rules_login" : {
    "LABEL" : "login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "login" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/login" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/login" } } ]
  }
}


How can I use tokens in my content I want to use tokens in my content but it seems like it doesn't let me. I've found an article about using the Token Filter module but I have not been able to configure it so that it would print. In the README.TXT it says,

  Go to /admin/settings/filters and enable the token_filter for any of
  your existing filter type    or if you wish, create a new one.

but my problem is, when I go to http://127.0.0.1/drupal-7.34/#overlay=%3Fq%3Dadmin%252Fsettings%252Ffilters (on my installation, I just get to see  and I'm not sure how I can "enable the token_filter for any of your existing filter type" - may anyone help me?

Thank you!

Actually in order for this to work you need the token filter module:

https://www.drupal.org/project/token_filter

Otherwise there is no option in text format config.


How to associate an entity view mode with a path? (Commerce product entity) I created a view mode for a Commerce product entity with http://drupal.org/project/entity_view_mode , now I would like to associate this with a path like myproduct/[entity_id] , so I can attach meta tags and everything else to it.

How would I go about this? Essentially, I am trying to avoid using a product display node for a product entity.

You can add your own entity view path with

hook_menu

e.g, something like

/**
 * Implements hook_menu
 */
function mymodule_menu(){
  $items = array()
  $items['myproduct/%myproduct'] = array(
    'title callback' => 'myproduct_page_title',
    'title arguments' => array(1),
    'page callback' => 'myproduct_page_view',
    'page arguments' => array(1),
    'access callback' => 'myproduct_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * My Product page view callback
 */
function myproduct_page_view($myproduct){
  drupal_set_title($myproduct->title);
  $uri = entity_uri('myproduct', $myproduct);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Some example to get entity display
  $view_mode = 'full';
  return myproduct_entity_view($myproduct, $view_mode);
}

See node_menu node/%node for example node view implementation.

Nevertheless, I'd recommend using standard product display nodes for product display.


How can webform performance be improved on low internet connection? I built a site with Drupal 9 and webform.
The form consists of three pages and contains a few computed fields.
On the first page are mandatory fields.
The form is used by logged-in users only.
When on a machine with a normal/fast internet connection, everything is fine.
When on a machine (smartphone) with a slow internet connection (or on Low-end mobile in Chromium's developer tools), I can enter all information on the first page, press next, it loads the second page and jumps back to the first one, claiming that the mandatory fields were empty.
Is there something that should be cached and that I missed so far? Do I have to manipulate some timeouts (where are they, I didn't find them)?

To enable all caching:

Navigate to "Extend" and enable the following modules:

Internal page cache
Internal dynamic page cache

Navigate to "Configuration > Development > Performance" and enable cache for a period of time (E.g. 6 hours) and check both the options for "Aggregrate CSS/JS"

Hopefully that may help with your issue.


Pathauto pattern for a content type depending on a reference field? This question is already asked here, but the answer selected does not work for Drupal8.
Description: There is a content-type, which has field, referencing taxonomy term. The term is in "Content class" dictionary. This term is used in views to filter the right content for the view. When a link in the view is clicked, it opens the node. This is OK.
So, it is needed pathauto to generate /Content class term/Content_title_name when this node is opened.
What did not work:  [node:field_content_class:value]/[node:title]. This is not accepted, produces error: Path pattern is using the following invalid tokens: [node:field_content_class:value]
The accepted (by Drupal) pattern:  [node:field_content_class]/[node:title] generates alias, containing only the [node:title] part. The first component is empty.
This is made to not create separate content-types for nodes with the same fields.
EDIT: The accepted answer works on a fresh copy of Drupal with language translation enabled. I continue to investigate the case with my production site.

A taxonomy field is referencing entities, it has no value property. See how to print value of a taxonomy field to headline with node.html.twig?
Converting this to a token pattern:
[node:field_content_class:entity:name]/[node:title]


remove link tags in head I am working on a project involving migrating a site with many static pages to Drupal 8. Since a number of the pages are old blog posts, there's often broken links, broken images, etc.

For quality assurance, we are using the httrack command line tool to traverse the new Drupal 8 site and report broken links and images.

It turns out that Drupal 8 is putting some extra <link> tags in the page head (the <head> section of the html, not the header region or anything like that).

First, when there is a page with a taxonomy term in it, there are links to the term's admin pages in the head, like so:

<link rel="devel-definition" href="/devel/taxonomy_term/226/definition" />
<link rel="clone-form" href="/entity_clone/taxonomy_term/226" />
<link rel="token-devel" href="/taxonomy/term/226/devel/token" />
<link rel="display" href="/taxonomy/term/226/manage-display" />

These links are on the page even for anonymous users.

Second, we have media images in our pages, and they are getting weird head link tags, also. For instance, if we have the image inside-a-classroom.jpg, we'll have this: <link rel="image_src" href="Inside A Classroom" />.

The problem is, httrack is finding these links in head, trying to download them, and returning a 404. And of course it would, because when it spiders, it's not logged on and can't access admin menus. In the case of images, they're not even proper links to the image.

Is there any way we can turn these off? They are false negatives in our scraping, and make it difficult to quality check our work.

Links like this are handled as attachments to the page.  They are inserted where the Drupal placeholder tags (like head-placeholder) are in the twig file.

To modify these, you need to use hook_page_attachments_alter().  Here's example code that fixes a problem with canonical URLs containing query string not getting generated properly by core (converts & to &amp;).

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  if ( isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {
      if (in_array("canonical_url", $item)) {
        $href = $item[0]['#attributes']['href'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          // Formatted to include a newline in page source.
          '#template' => "{{ href|raw }}
",
          '#context' => [
            'href' => '<link rel="canonical" href="' . $href . '"/>',
          ]
        ];
      }
    }
  }
}

In the case of these entity links, these are in the 'html_head_link' area of the attachments.

FYI - This is also related to this core issue.


Create a new node by program and fill the specific field automatically the goal of my program is to create a content of the specific content type

The specific content type (called A content type),have three fields:title,body,select option

when the user press a button, and the program will lead the user to the edit content page.

But the select option field will select the option i want and the AUTHENTICATED user can't

change this field.

How can i do?

the method i think is create a new node and fill the select field by programming. After

that, lead the user to the edit page of  the node  i just created.

but i still can't disable the select field

Does anybody have the suggestion? thx a lot !

i am not good at english. i hope you understand what i ask ?

The field permission module lets you define detailed permission on field level. If you have different types of users you may be want to define a new role for your users.


Display Node Title field in Field group I can't find the solution to print (display) Drupal's Node Title in a field group? I want my Node Title in the field group (see image).

In this project I can't use Display Suite. I also can't find a template suggestion for a field group?

How do I manage to do this?

A solution would be to install the Display Suite module.

Once both Display Suite and Display Suite UI modules are enabled you must go to the presentation, choose a layout at the bottom and save, then you will have a lot of fields that weren't available before. One of those fields is the node title.


Update from 8.1.3 to 8.1.7 gives me a fatal error on most pages After attempting to update to version 8.1.5 I received the

"The website encountered an unexpected error. Please try again later."

error on many pages. I also get the following error in Recent Log Messages;

"Drupal\Component\Plugin\Exception\PluginNotFoundException: The "2" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of   /home/username/public_html/domain/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Any ideas what could be causing this or how to fix it?

Update 2016/07/20

I just tried once again to update from 8.1.3 to 8.1.7 and am getting the same errors. My 8.1.3 site was stable with no errors.

Specifically, the site has the following issues after updating and after running update.php several times.

non-admin users can't log in; they receive the white screen of death upon login attempt, and can't even navigate to a different page than the default user page. The can only successfully logout using /user/logout to get back to the working frontpage and other working content pages.
when logged in as admin, eveything seems to work except for the "extend" and "people" admin tabs, which result in a wsod.

The reports details show the following information after an unsuccessful attempt to access;

Type php

Date Wednesday, July 20, 2016 - 08:09

User admin

Location http://www.domain.com/admin/people

Referrer http://www.domain.com/admin/config/people/accounts

Message Drupal\Component\Plugin\Exception\PluginNotFoundException: The "2" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /home/username/public_html/domainfolder/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Severity Error

Hostname @@@.@@.@@@.@@@

Operations

Type
page not found

Date
Wednesday, July 20, 2016 - 11:34

User
admin

Location
http://domain.com/quickedit/metadata

Referrer
http://domain.com/node/preview/aabc334a-08fb-4d6a-8672-281dbe7a56e6/default

Message
/quickedit/metadata

Severity
Warning

Hostname
113.37.159.155

Operations

Type
php

Date
Wednesday, July 20, 2016 - 11:25

User
admin

Location
http://domain.com/node/add/lesson

Referrer
http://domain.com/speakraku

Message
Warning: mkdir(): File exists in Drupal\Component\PhpStorage\FileStorage->createDirectory() (line 165 of /home/username/public_html/domain/core/lib/Drupal/Component/PhpStorage/FileStorage.php).

Severity
Warning

Hostname
113.37.159.155

Operations

Fixed - tracked the problem down to the dev version of field permissions I was using. Updated to the latest dev version and all related issues were resolved.


Use a Token in Minimum Field I am new to rather new to Drupal (coming from Django/Python), and was wondering if there was anyway I could use a token in the minimum field of my registration.

What I basically have is a registration from, which is then a field in one of my content types. In this content type I also have a field called minimum deposit. So I wondering if I could somehow link the value in the minimum deposit field to the minimum in my registration? Like for the minimum value have: [node:minimum_deposit].

In a nutshell, there is no way that I know to do this with a token. You need to create a custom module that implements hook_form_alter() to set the default value of your minimum deposit field before the form is rendered. You'll set this default value using the value of the field in the pre-existing node (you'll need to load the node programmatically within the hook function and get the value of the field).

I could give you more details if you let me know what type of form you are using: are you creating a form programmatically with Form API? Using Entityform module to create the form? Using Webform module? Using the "Add to Cart" form provided by the module Drupal Commerce? Post a comment below and I'll edit this answer.


Is it allowed to call t($variable)? In Drupal 7 t() this warning was present:

  You should never use t() to translate variables

In Drupal 8, well, it's Drupal 8, who knows where to even look?

I tried

StringTranslationTrait::t
t()
LocaleTranslation::getStringTranslation()

and haven't found a similar warning. But absence of evidence is not evidence of absence. Is it OK now to use a variable?

The advice is the same, it's just moved. The docs for t() say:

  See \Drupal\Core\StringTranslation\TranslatableMarkup::__construct()for important security information and usage guidelines.

On that page you'll find familiar advice:

  Translating Variables
  $string should always be an English literal string.

  $string should never contain a variable, such as:

  new TranslatableMarkup($text);

  ...

So generally speaking no, it's not OK to pass a variable as the first argument to t() in Drupal 8. Always use a literal string.

If you need to use variables for t(), pass a literal string containing placeholders, and a second argument containing their replacements. For example:

new TranslatableMarkup("@name's blog", [
  '@name' => $account
    ->getDisplayName(),
]);