How do I determine the values to use in the payload for the add to cart method in the Commerce API The documentation for the Commerce API gives the example payload below for adding items to a cart. How do I find the type and ID values for the product variants in my store configuration?
{
  "data": [
    {
      "type": "product-variations--default",
      "id": "e8daecd7-6444-4d9a-9bd1-84dc5466dba7",
      "meta": {
        "quantity": 1
      }
    }
  ]
}

I eventually located these using the path https://mydomain.com/jsonapi/product-variations/default.
A call to https://mydomain.com/jsonapi exposes the end-points you can use, based on your product configuration. Mine looked like this:
        "product--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/products\/default"
        },
        "product-attribute": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attributes"
        },
        "product-attribute-value--rate": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-attribute-values\/rate"
        },
        "product-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-types"
        },
        "product-variation--default": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variations\/default"
        },
        "product-variation-type": {
            "href": "http:\/\/mydomain.com\/jsonapi\/product-variation-types"
        }


Is it possible not to use utf8mb4 as encoding? Due to an old version of libmysqlclient, we are stuck and can't deploy a completed site to our server.  The client does not support utf8mb4.  We have the datacenter who manages the server looking into the issue, but is there a way to make Drupal use the regular utf8 character set without hacking core?

MySQL (and libmysqlclient) have a minimum version requirement of 5.5.3 for Drupal 8 (see https://www.drupal.org/node/2558615, https://www.drupal.org/node/2473301, etc).

It's not often that requirements are applied arbitrarily, so there will almost certainly be something in MySQL >=5.5.3 that core/vendor code requires.

As such, I would have to assume that no, it's not possible to change this without hacking core. Maybe not even with hacking core, as vendor supplied code may rely on it.


Delete a file uploaded via field? Is it possible to delete a file not in usage outside of the context of a field widget in Drupal 8?

I tried to find a route like admin/file/{file}/delete but don't really see anything in the file module to do this operation.

I found this issue, which I assume is related. So the question remains: How can you delete files? I've set "delete orphaned files after" to Never in the admin so that files are not mistakenly deleted, which has happened to me a few months ago.

There is no functionality for this in core in the UI. You could do a entity load + delete with drush ev/core-cli or console, but that's basically your only option.

File entity does offer a UI for this, but you possibly don't want to use it anymore.

That said, setting that setting to Never is IMHO the wrong solution, as it also doesn't delete files that were only uploaded but then for example removed again or never really submitted. See https://www.drupal.org/node/2801777 for more information and another solution for that.

That said, when using media_entity, it should be save to configure Drupal to delete unused files as the media entity itself will always count as a usage of the file, so it will only ever get deleted if you manually delete a media entity.


Webform and TypeForm How would I add an image to a Drupal Webform?

The trick to including anything in a Webform is to use the "Advanced HTML/Text" element, which allows you to utilize Drupal's Text Format functionality to embed any media, including videos.


Error: Class 'Drupal' not found in bootstrap.inc Please tell me what I'm doing wrong. I'm unable to run drush, see error below:

[~/public_html/d8]# drush -d status
Bootstrap to phase 0. [0.01 sec, 1.86 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 1.98 MB] [bootstrap]
Cache HIT cid:                                                       [debug]
6.0-rc4-commandfiles-0-6046c80192c5b97fbcd88f24c7e529ed [0.02 sec, 1.99 MB]
Bootstrap to phase 0. [0.09 sec, 5.27 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.14 sec, 5.28 MB] [bootstrap]
Initialized Drupal  root directory at /home3/public_html/d8    [notice] [0.15 sec, 5.39 MB]
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Class 'Drupal' not found in /home3/public_html/d8/core/includes/bootstrap.inc, line 164  [0.15 sec, 5.4 MB]

I'm using:

Drush Version   :  6.0-rc4
drupal 8.0.0-beta7
PHP 5.4.38
MySQL 5.5.42-37.1

Drush 6.x only works with Drupal 6 or 7, upgrade to Drush 7.x.

Source


Block Node Access After A Certain Amount of Views I've come across a client requirement in Drupal that is very new to me.

The website is subscriber based, so users pay to subscribe at which point they are granted a subscriber role. They then have access to particular content types that they did not previously have access to. This is all easy enough.

The challenge though is that they require each node to only be accessible 5 times by each user.

The website is running Drupal 7 and presently has both Content Access and NodeAccess modules installed along with Rules and Flag.

So far I've worked out how to block access to an entire content type using Rules and roles. I've also been experimenting with Rules and Flags to block a node. For example:

If a node is flagged 5 times by the same user, it should be blocked.

But it still seems to come back to requiring a role that is not able to access it. It's impractical to have a role for every piece of content that cannot be accessed though. Content Access and NodeAccess also revolve around roles.

It seems like every possibility I come across requires a role in order to prevent access, which just doesn't work for this situation as every user is going to potentially have a number of different nodes they cannot access and they are all going to be different. This severely limits the ability of roles to work as far as I can see.

Does anyone have any ideas that might be able to point me in the right direction to achieve this?

Thanks in advance for your help!

You can control it using hook_node_access($node, $operation, $account) for Drupal 7. For Drupal 6 one can use hook_nodeapi() for similar result.

When $operation is view, first update usage index for that $account (you need a database table with nid and uid as keys, and number of uses field) and then test if he still can see it, or no. Return appropriate NODE_ACCESS_* constant. Done.

Of course you will need to write your own module, but I guess it'll take less time to wrap simple function in a module than to hack 3 or 4 modules to work together in a way they was never designed to.


Populate second node reference field based on what first node reference field is selected I have 2 content types. "ABC" content type and "DEF" content type.  In "DEF" content type i give reference to "ABC" node reference.

I am building another content type called "XYZ" where i give node reference to "ABC" and along with it i give node reference to "DEF" content type.

My problem is that i need to filter out the "DEF"(node reference to "DEF") drop down based on what "ABC" is selected from previous "ABC" drop down.

How to achieve this.

Any help is appreciated.

You can use custom coding to achieve this, here the idea

Add a script to call a ajax call back on change your first node reference select list.
Define the menu callback in your custom module.
On change of first select list, get the selected node id and pass to above defined function
Write the query to get depended node ids
Output it as

$options .= "nid." ".$selected." >".$data->node_title."";
     echo $options;
In your jquery ajax success part, add it eg:
success: function(data) {
f(data){$('#your-second-noderefernced-field').html(data);}

Hope this idea help you to proceed on


How to remove the default  tags generated by modifying manage display? We are using a mix of Display Suite using the manage display and Paragraph Module on the content types to help control some of the output of the nodes.

One problem we are trying to resolve is how to remove the extra div tags that are generated for the fields.

The options we have tried are:

use custom module to call hook_preprocess_entity and hook_preprocess_field hooks so that we can add the div classes as needed

PRO

We can rewrite the output to include any classes or values we want
Because we are using a module is that the module code can be cached

CON

We cannot completely control what is outputted as shown below.

Write a paragraphs-items-pr_body_title.tpl.php file so that we can rewrite the output

PRO

We can control the exact output and remove the div tags outlined below

CON

I am learning that template files are not cacheable

Example (issue):

 /* field value */

 /* field value */

Desired Scenario:

     /* title value */

     /* body value */

What is the recommended way to resolve the issue?

It seems you are missing the  Display Suite Extras submodule (ds_extras)?
You can change the default field templates easily there.
From DS Extras doc:

Default Field Template

Default: will output the field as defined in Drupal Core.
Reset: will strip all HTML.
Minimal: adds a simple wrapper around the field.
Expert Field Template: gives full control over the
HTML, but can only be set per field.

You can override this setting per field on the "Manage display"
screens or when creating fields on the instance level.

admin/structure/ds/list/extras:

Once the Extras submodule activated you will have control by fields. visit the CT "manage display" page and the main CT page (edit). Mode "Minimal" or "Expert" seems what you need.


Search engine question I have a site that has over 18,000 data items in a catalog. I am using Drupal 7 and the latest Views module to display the data. The data items contain an auto make, model, year, cv axle. My search query needs to be able to search this catalog in the following matter: If the EU click in an input box for "make," they can put in the search term (e.g. Ford) and all Ford models pull up. In addition, there is another search field next to the "Make" field for "Model" and another one for "Year." I want Drupal to add all the search terms together to alter the view. Right now, If the user types in one term and searches, it works; however, if the EU types in another term in the "Model" field say, the view that outputs will only include the last term searched.
For example, I type in "Ford," and all Fords come up; if I add a term to the "Year" field (e.g. 1999), all 1999 autos come up, not just the Ford models of that year.

How do I create a search engine that spans terms across multiple fields (Make+Model+Year: OR however many search term the EU wishes to include) to filter what is output through Views?

Any help would be greatly appreciated!!

www.sutrack.biz=> cv axle catalog link

You might considder using the search api module. It allows you to do full text search on the index you setup, it has support for facets integrates with Solr and a lot of other nice things. I can recommend it for some easy and powerful search. It also integrates with Views allowing you to easily customize search results.


Any way to bulk delete menu items? I just deleted 25 menu items and it took me some time to do it.

Just wondering if is there any way (module) to bulk delete menu items.

Try Menu Editor module

  Menu Editor enhances the menu editing form with inline text fields for
  title, path and description, and provides placeholders for new items.


How to add a button that jumps to an external link in the content type? I would like to add a purchase button in the content type, the button is an internal link, for example:www.example.com/go/nodeid. And then add an external purchase link to the text field, for example:https://item.jd.com/2385876.html. Click the buy button (internal link) JS jump to the external links, because I do not want to search engine crawling the external link address.
For example,
 open the page（http://www.chong4.com.cn/read.php?18818）, showing the link（http://www.chong4.com.cn/cydb/go.php?18818_127334_22s）, click will jump to（https://detail.tmall.com/item.htm?id=536478627694&ali_trackid=2:mm_13376157_4604749_42838263,22s18818:1479362916_3k2_69258376）

nofollow: Links to an unendorsed document, like a paid link. ("nofollow" is used by Google, to specify that the Google search
  spider should not follow that link)

  source: HTML  rel Attribute

All you have to do is write your link like this:

Buy Now


How to direct add content in drupal? Trying to look an answer for this but couldn't.

Default workflow of Drupal adding content is: "Add Content" > Choose Content Type. Can I just make my website to do direct adding content without need to choose the content type in advance?

You can add custom links that aim directly to your content type in the admin tool bar.

Take a look on this link: https://drupal.org/node/1664828


Application of patches after core/module updates What is the recommended way to automate application of patches after updating core or contrib modules? For now, I'm doing this manually but it gets tedious for sites with a large number of modules that need to be patched.
There seems to be a myriad of methods one can do this but I was wondering if there is a particular method which is the "industry-standard"?

If you find yourself doing this often then it might be beneficial to use a make file for the project. Then you can have your make file contain all the patches and just rebuild the codebase instead of updating in place.

Also, be sure to mark patches that you are using in production as "Reviewed and tested by community" this will make them more likely to be committed to the next release which will stop you from having to include that patch in the future.


access callback admin permission is not working This is a follow up to  drupal.stackexchange.com/q/228722/9921

I have an api that I creates that I would like to restrict access to users with administrator role. But for some reason the 'administrator permission'  is not working. And the api returns an error when I add this restriction.
To clearify the use of language here:

    User : admin
    Role : Administrator
if you go to people permissions, Administrator has a permission of type administer permissions

I am 100% certain the user is an administrator

function mymodule_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_api_userslist',
    //'access callback' => array('administer permissions'), // tried both and they don't work
    'access arguments' => array('administer permissions'),
    'delivery callback' => 'mymodule_json',
  );
  return $items;
}

function mymodule_api_userslist() {
  // code not included since I know it works if the permission are just all permisions
  $data = Do an entityfieldquery to fetch users and return them
  return $data;
}

function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

The above code is being called via

  $users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

Any ideas?

____EDIT

<?php

/**
 * Implements hook_menu().
 *
 * */
function data_export_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'data_export_api_userslist',
    'access arguments' => TRUE,
    'delivery callback' => 'data_export_json',
  );
  return $items;
}

function data_export_api_userslist() {

  $data = data_export_process_users();
  // Do an entityfieldquery (or some other query) to fetch users and return them
  // as an array, not HTML or json. Json encoding will happen in the delivery callback.
  return $data;
}

/**
 * Delivers JSON. Used as a deliver callback for api menu items.
 *
 * @param array $data
 *   An array to be encoded as json.
 */
function data_export_json($data) {
  if (is_int($data)) { //https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_deliver_html_page/7.x
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

function data_export_process_users () {

  $results = array();

  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');

  $results = $query->execute();

  $users_node_list = entity_load('user', array_keys($results['user']));

  $return_results = array();

  foreach ($users_node_list as $key => $value) {
    $output = array();
    $output['name'] = $value->name;
    $output['email'] = $value->mail;
    $output['init'] = $value->init;
    $output['role'] = array_slice($value->roles, 1, 1)[0];
    $output['status'] = ($value->status) ? 'active' : 'blocked';
    $output['last_access'] = format_date($value->access,'small');
    $return_results[] = $output;
  }

  return $return_results;
}

function data_export_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', ['administrator', 'contributor', 'publisher'], 'IN');
  $query->condition('users.init', '', '<>');
}

Your latest edit clears up where the problem is likely to be:

  The above code is being called via

$users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

You're probably under the impression that the active user session from the calling site will somehow be passed through to and become valid for the API site? That won't happen, even if it's the same site - you're making a completely new request which doesn't share anything with the request you're making it from.

If you're building a secured API, you need to provide an authentication method that integrates with Drupal's login system, while still handling tokens etc for the API communication itself. That can be a fair amount of work, so people tend to use existing solutions like the Services module.

That module has an authentication layer for the core Drupal user login built in, and provides hooks for you to register your own resources. It will probably take less time to build your API using Services than building and testing your own authentication, so it's worth a look.


Multilingual websites - Hiding site till ready I am having basic workflow problem in creating translated website in Drupal 7. A site was handed to me which was already live(lets say www.mywebsite.com). It is having two languages already (English-www.mywebsite.com and Finnish-www.mywebsite.fi).

Now I need to add new language translation(Swedish). www.mywebsite.se already point to old D6 site (www.oldmywebsite.se). Also in language interface(admin/config/regional/language) Swedish domain entered is old one(i.e. www.oldmywebsite.se) to help visitor still access old site.

Question:
So how can I create new Swedish dev site, something like se.www.mywebsite.com which will be hidden from public but I can still work on translations and it will later replace old Swedish site. Which modules to use or what I need to do at Drupal and domain level?

I have not worked on any translation setup before so I am feeling completely lost.
Any help will be appreciated.

Summary :

www.mywebsite.com      :   new English
www.mywebsite.fi       :   new Finnish
www.oldmywebsite.se    :   old Swedish site

se.www.mywebsite.com   :   Want to create dev Swedish site which will later replace old swedish site

As long as you do not add se.www.mywebsite.com to the DNS nobody will find it.
You locally can add se.www.mywebsite.com to your hosts file and point it to a IP (maybe your localhost). When ready to be launched you can add a pointer from se.www.mywebsite.com to the IP of the production server.


How can I add custom classes to each view's generated row? Is it possible by using the theme preprocessor add some classes to views generated rows?

For example: based on Drupal site about default theme implementation to display a view of unformatted rows.views-view-unformatted.html.twig:

  Available variables:
  - title: The title of this group of rows. May be empty.
  - rows: A list of the view's row items.
  - attributes: The row's HTML attributes.
  - content: The row's content.
  - view: The view object.
  - default_row_class: A flag indicating whether default classes
     should be used on rows.

I know that it's possible and we can add our desired classes to each row inside the views-view-unformatted.html.twig:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

But I want to understand is it possible to do the same thing for custom views like front-page by use of:function template_preprocess_views_view_unformatted__frontpage in particularor in other template_preprocess_views_view generally?

If you look at /core/modules/views/views.theme.inc at template_preprocess_views_view_unformatted you'll see this code:

function template_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
  $style = $view->style_plugin;
  $options = $style->options;

  $variables['default_row_class'] = !empty($options['default_row_class']);
  foreach ($rows as $id => $row) {
    $variables['rows'][$id] = [];
    $variables['rows'][$id]['content'] = $row;
    $variables['rows'][$id]['attributes'] = new Attribute();
    if ($row_class = $view->style_plugin->getRowClass($id)) {
      $variables['rows'][$id]['attributes']->addClass($row_class);
    }
  }
}

This is how if you have set a row class in the view, it gets added.

And the resulting output:

You can copy this function to your custom module and customize it as you like.  For example, this will add the "views-row-" plus the name of your view cleaned up using the pathauto cleanstring utility:

function mymodule_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];

  foreach ($rows as $id => $row) {
    // Add custom class to each row that encorporates the view id.
    $custom_row_class = \Drupal::service('pathauto.alias_cleaner')
      ->cleanString($view->id());
    $custom_row_class = 'views-row-' . $custom_row_class;
    $variables['rows'][$id]['attributes']->addClass($custom_row_class);
  }
}

If you would like to add classes to a views rows from hook_preprocess_views_view, you can do it this way:

function mitsloan_global_preprocess_views_view(&$variables) {
  $view = $variables['view'];

  if ($view->id() == 'testview') {

    $row_style_plugin = &$variables['rows'][0]['#view']->style_plugin;

    $custom_row_class = 'views-row-' . \Drupal::service('pathauto.alias_cleaner')
        ->cleanString($view->id());

    $row_style_plugin->options['row_class'] = $custom_row_class;
  }

}


How to stop all the processes except by entering Linux via SSH? I have been deleting some Feeds through the Feeds GUI, but somehow Drupal 7 has been stuck. The site is in maintenance mode. I have no Drush access, and I cannot enter with Admin 0 user.

How can I stop all the processes except by entering Linux via SSH?

If you can log into your hosting account control panel, you may have access to PHPMyAdmin to change the password. Also you might be able to reboot your server from there.


"Organic groups: Group node" equivalent? I have several Drupal 6 views that use the "Organic groups: Group node" relationship.  Does anyone know what the equivalent relationship in Drupal 7 is?  Trying to set this up in Drupal 7 and the wording is confusing as I don't know what.

The one I was looking for (after much trial and error) is "OG membership: Group Node from OG membership"

That relationship seems to be the same as "Organic groups: Group node" in Drupal 6


Apache Solr Search, add taxonomy field in search results I'm really bumping my head on this.

I simply need to add tids from a term reference field on nodes returned by a solr search result.

It's a unique term reference.

I looked for the field in solr console and it's 'im_field_arbo'.

I followed this and that and came to this :

1.

    function MYMODULE_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
      if(isset($entity->field_arbo)) {
        $document->addField('im_field_arbo', $entity->field_arbo['und'][0]['tid']);
      }
    }

This doesn't throw back any errors.

2.

Then, to retrieve it, I tried either hook_apachesolr_query_alter, hook_apachesolr_query_prepare with :

    $query->addParam('im', 'im_field_arbo');

and hook_apachesolr_modify_query with :

    $params['im'] .= ',im_field_arbo';

Still, no trace of my field in my search results.

Any help ? Thx very much.

Update

I think my field is well indexed : _apachesolr_index_document_build_node works like a charm.

Now the question is : "How do I get them back in search results ?"

To show the field you have added to your Solr index you first need to add it to the search result. Add this to template.php

function template_preprocess_search_result(&$variables) {
  $variables['im_field_arbo'] = $variables['result']['fields']['im_field_arbo'];
}

Then in your search-result.tpl.php you can access the field like this:

<?php if ($im_field_arbo): ?>
  <?php print $im_field_arbo; ?>
<?php endif; ?>


Looking for a SEO plugin for Drupal For my internship I could use some help with the optimization for search engines.

Are there any plugins that will help me increase the SEO performance of the website im trying to optimize? So far I only found a checklist but thats not what im looking for. Wordpress has a Yoast plugin that checks every move I make to optimize it for search engines. Does Drupal have a similar plugin?

I thought the following was a bit like Yoast . SEO Compliance Checker - https://www.drupal.org/project/seo_checker

Once downloaded install and enable.

SEO Checklist

Basic SEO Modules

Keyword Rules

Then go to configuration .

Once those modules have been enabled you’ll then have a nice set of Sliders to use in the ‘Thresholds for the SEO Rules’ box.
Set up your sliders depending on what the recommended levels are at the time.
From here you’ll then need to visit the Article that you want to optimise .

  Click on PREVIEW

The Keywords are taken from 'tags' .


Need help configuring new user signup email notification I am new to Drupal and use Drupal 6 now. I have a site all built up and I want to just send a new member email template when he sign-ups. I don't want any other email templates for now.

I installed postFix on the server. I also use FB for Drupal module.

My Question is this: How do I send welcome email?

Please let me know steps, modules I need (if basic modules are not enough) etc.

The workflow for registering users can be configured at index.php?q=admin/user/settings. If this does not suit your needs, let us know how your workflow differs from what can be configured on that page.

I suspect you want to check the option Visitors can create accounts and no administrator approval is required. and uncheck the option Require e-mail verification when a visitor creates an account. The e-mail that are sent can be configured in the fieldset User e-mail settings and for some e-mails, you can configure whether to send them at all.


Running a function before a View executes I have a carousel built using Views (7.x-3.x) that displays 10 items. In this carousel I would like to place 1 item (inclusive of the 10) that displays Twitter content.

What I would like to do is run the function that uses the Twitter API before the View is built/executed. If it succeeds then the View should display 9 items from it's own query (10 items total.) If it fails, then the View would display 10 items from it's own query.

I have successfully implemented the View and the Twitter function running on the theme layer though in order to have a 'fall back' by altering the number of items displayed I would need to do this before the View is built/executed.

Can anyone point me in the right direction for this?

I believe I am looking at the right function "hook_views_query_alter" but I'm not sure how to set "items_per_page"

Thanks

You might be interested in a similiar kind of question I answered here:

How do you customize the title of an RSS feed created by Views RSS?

I would just set the view size to 10 always. And then use array_unshift() as I did in that reply to "prepend" the new item Object to the front of the view results array, if your Twitter call return its 1 item of content. Or else you just let the original 10 come from Views.


How to specify translation for strings in twig template & php files I've found a lot of examples and modules where such expressions are used .

In php files

 t('Submit this form'),

In twig files

 {{ 'Send'|trans }}

So as I know this is used for the translation purpose, and I've also used these functions in my theme & modules.

But the question is where I can specify translation for these words & phrases ?

I think you could do that with the User interface translation, "/admin/config/regional/translate" (which is part of the multilingual core package).
By the way you can also use:

{% trans %} Your english text {% endtrans %}


How to debug hook_form_BASE_FORM_ID_alter not working? I am at wits' end. I have a clean install of Drupal 7.28 and a custom module with the following two hooks:

/**
 * Implements hook_form_alter().
 * /
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'form_alter');
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 * /
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state, 'BASE_FORM_ID_alter');
}

And that is all there currently is in the custom module.

I have verified that the the base_form_id for the Article node form is node_form, by printing it out (using dpm($form_state).  This is what is printed:

base_form_id (String, 9 characters ) node_form

And yes, I have cleared the cache (I've even restarted apache and rebooted the server).

I believe my code is identical to what is shown in numerous tutorials about how to use hook_form_BASE_FORM_ID_alter().

Still, when I open the form to create an article, the first hook (hook_form_alter()) fires, and the second (hook_form_BASE_FORM_ID_alter()) does not.

This hook is in 54 functions in the core, so it is very unlikely that it just does not work.

As I said, I am at wits' end.

Has anyone a suggestion for what to try next?

Not sure if relevant but I while copying your code I did received a warning. Warning: Unterminated comment, but perhaps that sneaked in while placing the code in the question.


Dependency inject a class with values from a config object? Is it possible to DI dependencies in Drupal 8 but initialize it with values from a config object?

For example, SoapClient requires specifying the WSDL when called. I have different WSDL URLs depending on what environment I am using (test/prod etc).

I know you can do this from the services yaml file, but I have not read of a way where you can reference a value or value(s) from a config object.

My ultimate goal is to create a decorator or factory for SoapClient, but I'm not sure which.

edit: updated with code.

An interface:

<?php

namespace Drupal\iana_netforum_auth\Factory;

use SoapClient;

interface SoapClientFactoryInterface {

  /**
   * Create a SoapClient.
   *
   * This method should prepopulate the SoapClient with values from our
   * module configuration so it is ready to use.
   *
   * @return SoapClient
   */
  public function create() : SoapClient;

}

The factory:

<?php

namespace Drupal\iana_netforum_auth\Factory;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\iana_netforum_auth\Exception\NetforumException;
use SoapClient;

class SoapClientFactory implements SoapClientFactoryInterface {

  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  public function create() : SoapClient {
    $config = $this->configFactory->get('iana_netforum_auth.settings');
    $arguments = [];

    try {
      if ($config->get('mode') == 'live') {
        $endpoint = $config->get('live_endpoint');
      }
      else {
        $endpoint = $config->get('dev_endpoint');
        $arguments = [
          'trace' => $config->get('enable_trace'),
          'exceptions' => $config->get('enable_exceptions')
        ];
      }

      return new SoapClient($endpoint, $arguments);
    }
    catch (SoapFault $error) {
      throw new NetforumException('Invalid WSDL endpoint specified.');
    }
  }

}

The class:

class NetforumClient implements NetforumClientInterface {

  protected $username;
  protected $password;
  protected $token;
  protected $authorizationHeaders;

  /**
   * Drupal\Core\Config\ConfigFactoryInterface definition.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface definition.
   *
   * @var \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface
   */
  protected $soapClient;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   An instance of ConfigFactoryInterface.
   * @param \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface $soap_client_factory
   *   An instance of SoapClientFactoryInterface.
   */
  public function __construct(ConfigFactoryInterface $config_factory, SoapClientFactoryInterface $soap_client_factory) {
    $this->configFactory = $config_factory;
    $this->soapClient = $soap_client_factory->create();
  }

Not sure which part exactly is unclear. There are lots of examples in core.services.yaml that inject the config.factory service to read a configuration object, for example this:

diff.formatter:
  class: Drupal\Core\Diff\DiffFormatter
  arguments: ['@config.factory']

The constructor for that then looks like this:

/**
 * Creates a DiffFormatter to render diffs in a table.
 *
 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
 *   The config factory.
 */
public function __construct(ConfigFactoryInterface $config_factory) {
  $config = $config_factory->get('system.diff');
  $this->leading_context_lines = $config->get('context.lines_leading');
  $this->trailing_context_lines = $config->get('context.lines_trailing');
}

Once you have the config object, you get the configuration you want and pass it along to the SoapClient constructor.


Get parent entity in media preprocess hook I am having a paragraph with a media entity ref field   "field_paragraph_image_ref".
I would need to modiy the media twig template depending on a field value of the parent, which is a paragraph entity.
How can i get the field value from the parent entity in the media preprocess
  function hook_preprocess_media__picture__image_without_link(array &$variables) {
      $media = $variables['elements']['#media'];
      //A method to get the parent entity, that i cannot find in var_dump(get_class_methods($media));
      // and finally get a field value from the parent paragraph entity
}

i have ended up doing:
function hook_preprocess_media__picture__image_without_link(array &$variables) {
   $media = $variables['elements']['#media'];
   $parent = Drupal::entityTypeManager()->getStorage('paragraph')->loadByProperties([
    'field_paragraph_image_ref' => $media->id()
  ]);
   $parent = reset($parent);
   var_dump($parent->get("field_paragraph_image_link_page")->getValue();
}


Adding a CDN asset to drupal theme via info file Just as the title suggests...I tried using an absolute path:

stylesheets[all][] = 'http://fonts.googleapis.com/css?family=Lato:300,400,700,900'

This doesn't work...how do I add this to a theme?

You can add it in the theme template.php file.

function YOURTHEME_preprocess_html(&$vars) {

      // Load font
      drupal_add_css('//fonts.googleapis.com/css?family=Lato:300,400,700,900', array(
        'type' => 'external'
      ));

}

Tip: Dont set a protocol to load external resources from Google


How can I automatically assign users to a node based on a taxonomy? I've Googled this but might just not be using the right search phrases. I'm building an RFP repository for my company. Each RFP question will have a Category assigned to it. Within Drupal, I'd like to:

Automatically assign one or more users as the SME (subject matter expert) based on the Category that was assigned to the question, e.g. if Category = Analytics, then automatically assign user 'John Smith' as the SME upon node creation. The users assigned to the question should be viewable on the node.
To do this, I'd need to have a mapping of Category => SME(s) table I'd assume.
The end goal, would be to use something like the Flag module to be able to notify those users via email if an RFP question that they are the SME for needs updating.
Ideally, there would be a way to automatically update existing nodes with the most current mapping of Category => SME (people leave, new people come onboard, etc.)

I would do something like this:

RFP question is a custom content type.
RFP question includes a term reference/entity reference to a taxonomy vocabulary called Category.
Category has an entity reference field (to users) called SME.  This way, each term can be assigned to a user.  If you do it this way, you also don't need to worry about updating existing nodes when the SME changes; you can simply update the term entry in the vocabulary Category once, and all relevant nodes will be changed.
With this config, the SME won't be visible on the node, just the category.  You can fix this by creating a block in Views and adding it to the node page.
You can use Flag with Rules to automatically notify by email the user marked as SME when a node is flagged for updating.


Using Git with a Drupal site May we use git with a Drupal Site ?

Because I'm trying to use Git with a Drupal site and it seems that not all the information that are pushed !!!

Thank you

Git is a source code management (SCM) system.  There are many different source code management systems out there and Git fall into the category of a distributed version control system (DVCS).  It takes a "peer-to-peer" approach to version control as opposed to a "Client-Server" approach like version control systems like Subversion (SVN).

Yes we can use GIT with drupal.

To setup a GIT repository in drupal project please visit below link.

Git Setup


How to create a new Solr server URL I am using Drupal 7 and apache solr for one of my sites. I am using tomcat with apache solr to search the contents in my site. For testing purpose i use http://localhost:8080/solr to connect to the solr server. But i would like to change this to http://development.site:8080/solr. I have no big exposure to apache solr. It would be helpfull if some one can guide me.

Thanks.

you can configure your Solr Server under the following URL:

http://my.drupal-domain.com/admin/config/search/search_api/server/apache_solr/edit


Add FILTER CRITERIA in Views Programmatically I want to add/modify a filter criteria programmatically.

For example, for a view, I added an "Email Address" filter whose value is needed to change dynamically, it is needed to set to the current logged in user's email id.

How to achieve that? Please see attached image for more details. Please help.

Use the Devel module and dpm($view) and dpm($query) after you put like "test@email.com" into the "value" field found in your pic. See the object/array structure of the view and query from the devel output.

Then use the function hook_views_query_alter(&$view, &$query) in your module to target the WHERE condition filter condition and set it to the value you want.

Something like:

function MYMODULE_views_query_alter(&$view, &$query) {
  global $user;
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // This will only work as-is if you always have something in the filter by
    // default, I guess. This hook runs always so you could just put
    // 'test@test.com' as the email to filter by in views and this
    // will always override it. I'm sure there is a cleaner way to put
    // the filter dynamically at runtime. But i think thats more complex
    // php that customizes a view.
    //
    // The index 2 below is the index of the condition for the email filter.
    // Your $query structure may be different in your dpm() of the View $query.
    $query->where[1]['conditions'][2]['field']['value'] = $user->email;
  }
}


Transform textinput into select-field I'm trying to transform my textinput into a select-field but I keep stumbling upon An illegal choice has been detected-error.

What I try in my hook_form_alteris this:

$form['distance']['search_distance']['#type'] = 'select';
$form['distance']['search_distance']['#options'] = drupal_map_assoc(array(100 => '100 km', 200 => '200 km'));

It looks like he's doesn't like strings to be in the select list, although, the value of the input is an integer...

How can I make this input field accept my modifications?

I don't know if this is causing the error, but you're using drupal_map_assoc() wrong...

The point of that function is to take a linear array and convert it to an associative array with the values of the given array as associated keys. e.g.

$form['distance']['search_distance']['#options'] = drupal_map_assoc(array(100, 200, 300));

I kind of suspect what you're meaning to do is this:

$form['distance']['search_distance']['#options'] = array(100 => '100 km', 200 => '200 km');

Your array is already associative, no need to try making it associative all over again :)


How to send user created articles to approval queue? I have an approval queue set up on a member's portal. The approval queues contain five content types that I created, one of them being 'Articles' and it is receiving daily RSS feeds. I'd like to also allow any user created articles to go there too.

The problem I have is that there is an Articles Adhoc page that was created in the views that is taking all of the user created articles.

I have disabled this page but the new articles still aren't going to the approval queues.

I checked around the Redaction module but I am unable to find anything on how to get this done.

I'm not sure this is what you need but maybe you can achieve this using Rules. I've created a rule for nodes of type 'forum topic' and this is an example:

Event: Before saving content of type your type
Conditions: Data comparison -- Parameter: Data to compare: [node:is-new], Data value: true
Actions:

Conditional

If: User has role(s): Parameter: User: [node:author], Roles: new, Match roles: any

Set a data value: Parameter: Data: [node:status], Value: Unpublished
Show a message on the site: Parameter: Message: your message, Message type: Warning, Repeat message: false

The exported rule:

{ "rules_forum_needs_approval" : {
    "LABEL" : "Forum needs approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "rules_i18n" ],
    "ON" : { "node_presave--forum" : { "bundle" : "forum" } },
    "IF" : [ { "data_is" : { "data" : [ "node:is-new" ], "value" : 1 } } ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "user_has_role" : {
                "account" : [ "node:author" ],
                "roles" : { "value" : { "14" : "14" } },
                "operation" : "OR"
              }
            },
            "DO" : [
              { "data_set" : { "data" : [ "node:status" ], "value" : "0" } },
              { "drupal_message" : {
                  "message" : "[node:title] needs approval.",
                  "type" : "warning",
                  "repeat" : 0
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Twig - accessing node properties How can I access node property which name starts with # in twig template?

I have content type with field Category and I need to access value of that field inside of twig template?

Using dump(content.field_category[0]) I get this

array (size=5)
  '#type' => string 'link' (length=4)
  '#title' => string 'Example' (length=5)

How to access #title ?

Thank you.

You can add this line, {{ content.field_category[0]['#title'] }} to get  value of title inside twig.


Auto URL Aliasing for Custom Menu Paths with Term Id Here is my problem.

I have created a view with path as groups/% where % is a term id.
Now, i would like to create auto aliases for all groups/% with % as a term name.

Ideally i would like to add this alias path on creation of a term related to particular vocabulary. Is there any module that will do this out of the box ?

PATH AUTO MODULE: As far as i know it allows to set patterns only for taxonomy term paths and node paths for different content types.

But, how to set patterns for custom menu paths ?

I am not sure whether we should take this way or not but I found this:

We can save new path alias using path_save() function.

Here is how I managed it:

I called the function after submission of node or group node.

Then I called a custom function and fetch the real URL of the node i.e in your case it will be group/tid.

Now I retrived term name from term id and created new alias with term name.

Called path_save() function with necessary information.


Remove `/node` from front page when using a template file (page--front.tpl.php) As it stands I have no content going to the front page, i am simply using a template file for the front. When I sign out and sign in as any role of user on my site my front page url turns into:
www.mysite.com/node

I do not want this behavior, and have tried several methods but nothing seems to work.

I have tried adding this snippet to setting.php:

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  if ($path == 'node') {
    $result = '';
  }
}

I have tried creating a custom module and have tried every suggestion from https://www.drupal.org/node/500296 nothing works.

I have encountered this behavior before, and to solve the issue i added the
Node Page Disable module and deselected the Retain /node as an active url? checkbox which removed the /node from the home page URL.

Now when I implement the module and deselect the checkbox and save the form, the checkbox goes back to being selected after the form is submitted. I cannot figure out what is going on, I have cleared every cache known to man-kind, used different machines and operating systems so obviously something is conflicting. I just don't know where to look.

I cannot post a bug/issue to the module page because drupal site is currently broken for creating new users... This is a nightmare. If anyone could give me some insight on possible conflicts or have any crazy ideas how I could get around removing this useless /node from the home page after a user signs in; it would mean the world to me. Thanks regardless.

I used Global Redirect and it seems to do the trick. I'll still accept someone else's answer if anyone can give any insight on what might of been the solution to my original issue.


in drupal 7, how to add user pic and name to the user menu when logged in? In drupal 7, there are default blocks such as user menu block and login block, the user menu block are especially working for the logged in user while login block are working for non logged in user.

the user menu block contains the static user menu with account, profile, logout menu item, however what I want to do is when the user logged in, the user menu can have additional menu item showing the user pic and name.

I know this could be done by making a new block with php code, but I just want to know if I want to use the existing user menu block, what and how I should change it?

In Drupal 7, you can implement hook_block_view_alter() to alter the content of a block defined from another module. For example, menu_block_view_alter() is an implementation of that hook done by the Menu module.

function menu_block_view_alter(&$data, $block) {
  // Add contextual links for system menu blocks.
  if ($block->module == 'system' && !empty($data['content'])) {
    $system_menus = menu_list_system_menus();
    if (isset($system_menus[$block->delta])) {
      $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($block->delta));
    }
  }
}

$data is the array defined from the implementation of hook_block_view(), and it contains two array indexes:

"subject": the default localized title of the block
"content": the content of the block's body

In Drupal 7, $data['content'] could be either a string containing HTML code, or an array as accepted from drupal_render().

$block is an object containing all the data about the block loaded from the database. You can at least count on two elements:

"module": the name of the module implementing the block
"delta": the identifier for the block used from the module implementing it

If you just need to alter one single block, you can consider implementing hook_block_view_MODULE_DELTA_alter(), which is the equivalent of hook_form_FORM_ID_alter() of hook_form_alter(). Replace MODULE with the module name, and DELTA with the identifier for the block.
The hook gets the same parameters as hook_block_view_alter().


Advanced Forum - how do I delete a forum? I'm using Advanced Forum - how can I remove the default forum created (General Discussion)?

Structure > Forums > You should see General Discussion listed, hit the Edit Forum link > Scroll down and hit the delete button


Change domain name for a multi site I currently have a Drupal 7 Multi-Site. In my sites folder, the domains are like this:

winatlife.guide
journal.winatlife.guide
store.winatlife.guide

I need to change the domains to this:

blog.blessingsjournal.com
journal.blessingsjournal.com
store.blessingsjournal.com

In addition, my root drupal folder is changing from win-at-life to blessingsjournal.

I have made all these changes. When I visit any of domains, I get the following error message:

Forbidden

You don't have permission to access / on this server.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

What could be chasing this? I haven't changed any of the permissions on the Drupal install.

Steps I have tried

1) Database Update

This StackOverflower answer says that the domain is hardcoded in the database and it provides a query to fix it. I have run the query, but it does't seem to have done anything.
It was written in 2010, so maybe it's for Drupal 6?

2) Make a sites.php file

According to this Drupal Groups thread, in Drupal 7 multisites, you need to put a file called sites.php in the root sites directory. (In that directory there is an example.sites.php which can be used as a template).

I made a sites.php file and used the new domains but it had no effect. (Nb I did not need to use such a file before the domain change)

3) Checking .htaccess

My .htaccess is set as follows:

  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

I was having problems because I was making a copy of the original site and then updating the code in the copy. For some reason the code was not copying properly. The databases were also not exporting properly from PHPmyadmin.

This is how I fixed it:

My site was in hosting that had Cpanel. So using Cpanel I made an archive of the site. I then downloaded the archive, renamed it and then uploaded to create a new copy of the site. This copy was a perfect replica of the original, so it had no problems.
For the databases, I used this command to export them via mysql in the command line:

mysqldump -u DATABASEUSER -p'PASSWORD' DATABASENAME > dump.sql

In this command, you mustn't have a space after -p. So your command might look like this:

mysqldump -u host_mary -p'pass123' marywebsite > dump.sql

I then created new databases.
Finally, I imported the code into the new databases using this command

mysql -u DATABASEUSER -p'PASSWORD' DATABASENAME < dump.sql


Different groups of radio buttons with the same name I need to create several groups of radio buttons, grouped by a concept (collapsible) but the radio buttons must have the same name so that the form only sends one selected option among all the groups

Group 1
() Radio 1
() Radio 2
() Radio 3
Group 2
() Radio 4
() Radio 5
Group 3
() Radio 6
() Radio 7

I am developing a shipping method of commerce_shipping
This form is for choose a shipping service details, therefore I only generate a part of the form of the checkout page in the function that defines the details of the service, using the commerce_shipping API.
I test to set the #name property for all radio buttons but I lose the form tree, and I need to keep it so that another function can receive the data. Being inside commerce_shipping I do not have absolute control either.

The question is: What Form API elements should I use?

I tested

$form['group_1']  = array (
  '#type' => 'fieldset',
  '#title' => t('Group 1:'),
  '#container' => TRUE,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);
$form['group_1']['radios'][] = array (
  '#title' =>  'Radio 1',
  '#type'=>'radio',
  '#return_value' => '1',
);

But ther resulting radio button name is group_1][radios][0] and the next is group_1][radios][1], as the name is different then they are not part of the same selection

Every group is a fieldset

  $form['pickup_group']['term_'.$tid] = array (
    '#type' => 'fieldset',
    '#title' => $pickupWrapper->field_taxonomy->name->value(),
    '#container' => TRUE,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

Every radio

  $form['pickup_group']['term_'.$tid]['shipping_pickup_point'][] = array (
    '#title' =>  drupal_render($renderable_node),
    '#type'=>'radio',
    '#return_value' => $pickupWrapper->getIdentifier(),
    '#parents' => array('commerce_shipping','service_details','shipping_pickup_point'),
  );

I solved adding the array of parents and itself in #parents on every radio, I don't like so much because I don't have control about this parents. My code doesn't generate this parents it comes from the commerce_shipping API. But works...


Views Exposed Filters AND result for multi select field I'm working with a view with exposed filters for a directory style page.

One of the filters is a multi-select check list, however, we want the results to return AND results only. It is currently returning OR.

For example: Activity open to:
- Men
- Women
- Older People
- Children

So I only want to see results that have both selected.

All the testing I've done returns OR options, so they can have Men OR Women. I want Men AND Women returned.

Views' filters default to an OR between all the options selected. If you pick the "Is all of" option, it will change to an AND operator.


How can we do open a popup for login facebook and after complete it will close? I want a popup that will open when anybody wants to sign-in using facebook or any social site login. The box pops up and will close after successful login or cancel

This is code I am using for this and I know something missing please give me some hint---

<a href="https://www.facebook.com/dialog/oauth?client_id=MYCLIENTID&amp;redirect_uri=http%3A//www.MYWEBSITE.COM/fboauth/connect&amp;scope=email" class="facebook-action-connect" onclick="window.open(this.href,'popupwindow','width=700,height=500,scrollbar,resizable'); return false;"  target="_self" style="color: White; font-weight: bolder; cursor: hand; text-decoration: none">

You should try ulogin...
I hope this will solve your whole problem.
:)

Description:-
uLogin service allows your users to login using their accounts at:

Facebook,
Twitter,
Google,
Windows Live ID,
LinkedIn and various open id.


How do I add elements to a node view? In Drupal 8 routes like entity.node.webform.user.submissions (path such as /node/2/submissions), entity.node.webform_submission.canonical (path such as /node/2/submission/118) etc etc display entity view in the main content block. My question how would I append/pre-append/insert html elements (such as link tag,submit button, textfield etc etc) in the entity view.For example if the view shows a table listing submissions how to pre-append a link button at the top right corner of the table.
I have tried:

function my_module_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display){
    kint($build);
    kint($entity);
    }

In kint($build) and kint($entity) I can't see any part where to add HTML markup. How and where should I add it?

The Webform module for Drupal 8 does not fully support display modes.  To alter a submission's HTML or text you will need to use hook_preprocess_webform_submission_html() and hook_preprocess_webform_submission_text().

I created a ticket on D.O. to look into this issue.


Use GET instead of POST for AJAX call I was wondering if anyone had any tips for use a GET call with ajax forms instead of POST?

One of our ajax calls is returning some JSON that we want to be cached in the browser.  If we can switch the call to GET then that caching will happen for us.

It is easy to use GET instead of POST, but Drupal sends a lot of information about dom-elements and loaded css/js, so that it is often too long for a GET request..

var ax = new Drupal.ajax("element-name", this, element_settings);
ax.options.type = "GET";

If you do not use these, you can strip them:

//Override parameters for Get Requests
var backup = Drupal.ajax.prototype.beforeSerialize;
Drupal.ajax.prototype.beforeSerialize = function(element, options) {
  if(options.type != "GET") backup.call(this, element, options);
}


Listing top level terms in views including those without children My vocabulary looks like this

Level 1a

Child a
Child b
Child c

Level 1b

Child a
Child b
Child c

Level 1c

Level 1d

Child a
Child b
Child c

Level 1e

I have managed to display parents and children terms using Taxonomy term: Parent term and filter on (Parent) Taxonomy term: Parent term (not empty). But terms without children on the same level with "parent" are not displayed.

To get the children I used filter “(Parent) Taxonomy term: Parent term (not empty)”. If I set the same filter to “is empty”, I get all level 1 terms including those terms without children just like I want it. So right now it seems like an either-or situation. I can only get the top terms or the children terms but not both.

How do I get the top level terms including those without children and corresponding child terms for those with children?

If you add a filter to parent term = "empty (NULL)" it will display all terms that have no parent above them.

For more detailed steps, try this blog post I wrote: http://fdiv.net/2012/08/11/taxonomy-views-browser-arbitrary-depth


Migrate users from a custom application DB into Drupal Is there a way (kind of best practice or tool) to import Users from a custom CMS into Drupal (with of course the all fields already set)?
I think a JSON object with my all Users' data is the only way.
Passwords are actually strings encrypted in md5 so all passwords should be regenerated by the Users (that's not a big problem).
Someone suggested JSONdata.com but the URL is not reachable.

Thanks in advance for all welcome suggestions/remarks.

Yes. The Migrate module does exactly just that.

You just need to write a migration script, which is comprised of the source (there's a lot of plugins out of the box like MySQL, CSV, JSON), the destination (there's already a User class you can extend from), and the mapping (the mapping of source fields to destination fields).

Drupal will probably have a different hashing mechanism that your CMS, so the passwords probably cannot be reused. The values can be copied as is, and just force your users to reset their passwords. There's also the Force Password Change module for that.


How to add a css class to the nodes in the front page according to taxonomy of each node in drupal 7? in the front page, I have displayed multiple nodes (article) in the teaser view, each article has taxonomy.

I want to theme each node teaser according to the taxonomy it has, I think it can be done in the theme_preprocess_html(&$variables, $hook), for example

function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {

    // something here, but I don't know what to do
  }
}

the first step is how to find all the nodes in the frontpage, the second is to get the taxonomy of each node, the third is to add the specific css class to each node according to the taxonomy of each node

Does any have suggestions?

Supposing that "field_tags" is the taxonomy field for which you want to use the taxonomy term values, you could use the following code.

function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {
    $terms = array();

    foreach ($variables['page']['content']['system_main']['nodes'] as $nid => $array) {
      $items = field_get_items('node', $array['#node'], 'field_tags');
      foreach ($items as $tid) {
        if (!isset($terms[$tid]) && ($term = taxonomy_term_load($tid))) {
          $terms[$tid] = drupal_html_class($term->name);
        }
      }
    }

    if (!empty($terms)) {
      foreach ($terms as $class_name) {
        $variables['classes_array'][] = $class_name;
      }
    }
  }
}


Can I have multiple favicons in D7 This favicon generator (recommended here) generates multiple favicon png files and code for the <head> section of your HTML pages. This is said to be better than a single favicon file which might not display correctly in some devices.

But I think "Path to custom icon" in D7's /admin/appearance/settings only accepts a single favicon file.

If so is there a way to use multiple favicon png files?

If I can only use a single image what is the best practice for the format of the file?

You're looking for the Head Module:

  This module provides a range of metatags that can be added to the
  document head of each available theme.

  In an attempt to keep themes clear of anything that could be
  considered optional, i have aggregated all the frontend related
  metatags you could ever need into one advanced theme settings page
  which can be found at admin/appearance/advanced


QR Barcode automatic creation from Nodes new or previously created I wish to create automatically created barcodes from newly create Node content and also Node content already created in the Drupal V7.3x system. Further to my previous posting Barcode Creation I can allow a user to create a QR barcode from a text field entered on a Node Form which successfully shows the QR on the Node display page; but this is no longer what I want, I require the QR code to create on the fly to create the QR code which will ultimately be the URL of that Node which is being shown so that the user then can scan it and save for later ie on a mobile device.
I have tried with Rules, but to date cannot get the Rule to write, save or show any QR code.

If it is a PHP script code, then what would it be to create onto the Node page the user would see.

I want to do it via Rules is possible but the barcode field wasn't showing in Rules. Any advice on a correct procedure or a Rules structure is most welcome.

PS:

I have found this type of PHP on https://www.drupal.org/node/1364118, and I wonder if this is the direction I need to go? to solve it:

    <?php
if (!isset($commerce_product->field_barcode['und'][0]['value'])) {
$commerce_product->field_barcode['und'] = array(0 => array ('value' => $commerce_product->sku));
}
else {
if ($commerce_product->field_barcode['und'][0]['value'] == '') {
$commerce_product->field_barcode['und'][0]['value'] = $commerce_product->sku;
}
}
commerce_product_save($commerce_product);
?>

Since my original posting, a new module appeared. So I ultimately chose this module: drupal.org/project/page_url_qr_code_block does the job spot on and creates Node QR Codes on the fly via a Block. There maybe other ways, but for now, this is it.
Thanks all.


Two different front pages? I have a website at mydomain.com. I am creating a clone of it on mydomain2.com. The only difference is that I want the landing pages to be different. Both domains are running the same codebase.

How do I make the landing page differ, depending on what domain you are on?

(Note: Without using i18n)

You can do this by using the Domain Access module which is meant for creating a site (with one code base and one database) where certain content is accessible by DomainA and other content is accessible by DomainB. In your case you can set all content to be accessible to both domains and just change the site settings for the front page based on current domain. In D8 there is the Domain Site Settings module which makes this easier, but in D7 you should use Domain Variable to change site_front based on the current domain.

This method will allow you (for example) to create two view pages or nodes or whatever (one for each domain) and display completely different content (or content in a different order) depending upon the domain.


How do I add an AJAX action on a select element in a ContentEntityForm to change the value of another select element I have a ContentEntityForm with two select elements category and data_type. I want to load the options for the second select element when the first select element changes. I have tried to add the following in the buildForm function of the ContentEntity form but this does not seem to be adding the ajax trigger to the element. Any thoughts on what I am doing wrong?

$form['category']['#ajax'] = [
  'callback' => '_ajax_form_category_change',
  'event' => 'change',
  'wrapper' => 'ajax_id_data_type',
  'method' => 'replace',
];
$form['data_type']['#prefix'] = '
';
$form['data_type']['#suffix'] = '
';

_ajax_form_category_change is a function in my module

function _ajax_form_category_change($form, $form_state) {
  return $form['data_type'];
}

I have also added a form_alter in my module to change the options of $form['filing_type'].

SOLUTION: Got this working with the following. You have to set the #ajax property on the widget

// Set the ajax function to run on the change of filing category.
$form['category']['widget']['#ajax'] = [
  'callback' => '_ajax_form_category_change',
  'event' => 'change',
  'wrapper' => 'ajax_id_data_type',
  'method' => 'replace',
];


Drush rsync permission woes (files directory) I'm rsyncing just the files directory (rest of the site is done through git) from my local Ubuntu setup to my centOS server. It worked at least (thankfully), but produced a ton of errors.
First it said:

rsync: failed to set times on "/home/myuser/mycentossite/sites/default/files/ctools": Operation not permitted (1)

Then tmp files and js files stated play up (sometimes happens on Ubuntu setup when clearing cache also)

rsync: mkstemp "/home/mycentosuser/mysite/sites/default/files/js/.js_ouzQFXPVCjfNTxl3b4ONpKTE.js.nghTEc" failed: Permission denied (13)
rsync: send_files failed to open "/home/myubuntuuser/websites/mysite/sites/default/files/tmp/file5GjL": Permission denied (13)

I fixed the permissions errors gradually with CHOWN and things started to work on the site. Though I'm wondering what is the correct way to go about rsyncing between local/remote in regard to permissions? And what happens if I rsync again - will it overwrite the stuff I've changed the permissions for? Or just add the new files?
Somewhat related.. My CentOS setup which uses the DSO PHP handler is also nagging me whenever I visit a page which generates a new folder of some kind. Is there way to set this up without having to go around putting CHMOD 777 on everything? (I'm the only user, so 777 in itself is not a problem for me...)
Thanks for any thoughts :)

Permissions issues are fairly complicated.

First off, the "failed to set times" message occurs because only the file owner can perform this operation.  The solution to this problem, then, is to insure that the 'remote-user' element of your Drush site alias is the same as the owner of the files on the target machine.  When pulling files to the local machine with drush rsync, it works best if you run Drush as the same user that the files are owned as.

What specific sets of permissions you choose after that is largely up to you, as there are a number of options that will work fine.  What I do is make all web server code files owned by a 'www-admin' user on the live site, and owned by my local user on my dev site.  On both live and dev, the files group is the webserver group, usually www-data, with directories that the webserver can write to being group-writable (and all others are set to not be group-writable, of course).  Any file created by the webserver will by necessity be owned by the webserver, of course.

This works well for most situations; however, it does mean that if you rsync %files from dev to live, you won't be able to overwrite anything that was uploaded by the webserver.  You might consider this a useful feature, though, as it prevents accidental overwrites.


How to flag term reference without flagging term? I need do something like the skills system in linkedin.

The logged user with role "employee" have a profile2 called "employee". In this profile I need add a term reference field where the user can add his skills or create some skills new by Autocomplete term widget (tagging)... Like in linkedin.

After that, the other authenticated users can confirm the single skill of a user.

I tried to do this with taxonomy, term reference field (in the profile2 "employee") and flag... The problem is that if a user add the skills by term reference field, eg. term1, term2, and an other user confirms (flags) that skills, the terms are flagged for all users. So if an other user add term1 and term5 the current user visits his page and the term 1 is alredy flagged.

Can you help me?

You may use the Relation module.

Relation allows you the create relations between entities that are entitties too. So the scheme will be:

Create a relation between your users and the skills entities (they can still be taxonomy terms).
Because these relation instances between your users and the skills are entities you can create a flag for this relation entities. So, when a user adds a skill to the profile you will have to create one relation entity with the user (or profile2*) and the skill.
When anotheruser wants to aprove this user's skill she will flag that entity relation. No other user is affected.

I checked Relation time ago and I remember that creating relations was a little bit tricky. I don't remember how to make relations so I can't help you in this point, sorry. You may need some custom code to achieve what you want.

*: to decide between Profile 2 or user take into account how are you going to show this information. For example, think which options fits better with Views.


Granting restricted permission roles As well as the three standard roles for a D7 site, I have created a role for a lesser admin / content creator.  This role is essentially an administrator role with some of the juicy bits taken away.

I would like that users assigned this role can manage other users, but I need to restrict it so that they cannot assign or remove the administrator role, or edit an administrator's profile and account.  I can't see a way to do that on the standard installation, is there a module that could help me?

Edit:
I have looked into the userprotect module.  While it does prevent a lesser admin from editing an administrator, it does not prevent them from granting the administrator role on themselves.

As you mentioned, User protect should work well. Combine this with Role Delegation to restrict what roles they can assign.

Might also be worth keeping an eye on the Administer Users by Role module, although there is no D7 port yet (in progress here).

Let me know how it turns out as I'm going to be solving this issue on the site I'm working on soon.


Make a specific content-type inaccessible I have a content-types that only is linked from nodes of other content types and therefore should not be directly accessible. In other words, I don't want a visitor to be able to access these kind of nodes by going to node/<nid>. Is this possible?

Yes, the Rabbit Hole module was built for exactly that:

Rabbit Hole is a module that adds the ability to control what should happen when en entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

It's highly configurable and works seamlessly in my experience.


Use Rules to create new content and fill the corresponding node_reference field I want to use a button to create a new article.

I write two rules to do the following work

snapshot 2

snapshot 3

The snapshot 2 creates a new content; the snapshot 3 fills the field of the content just created.

I can't fill the node reference field; how can i do that?

The button I put is on a different kind of content type.

I hope some body can help me fix this article.

I found how to fix my own problem

$node->field_YOURFIELD[LANGUAGE_NONE][0]['uid']=$userid;
$node->field_YOURFIELD[LANGUAGE_NONE][0]['nid']=$nid;


Create imagefield and set min width and height programmatically I've created an image field programmatically in Drupal 7. I want to set a minimum width and a minimum height on the image, so it checks whether the image is large enough.

The imagefield I've created:

$form['box_image'] = array(
    '#type' => 'media',
    '#title' => t('Image'),
    '#default_value' => isset($content['settings']['box_image']) ? $content['settings']['box_image'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'max_filesize' => '500 KB',
        'uri_scheme' => 'public',
        // Can I set the min width and height here?
      ),
    ),
);

Is this possible? Thanks.

Problem solved. If you use Media browser, like me you could use:
'min_resolution' => '750x500'.


Customize menu local task links I am looking for a way to customize 'edit', 'view', 'delete' links.

I use bootstrap theme, but i use bootstrap v4 styles for it. I want to add 'nav-link' class to each link.

And find a way to display somewhere, not just below post title.

I couldnt find a tutorial about it. Where should i look for this? template parts (twig) or themename.theme file?

For preprocess function you can use HOOK_preprocess_menu_local_tasks(&$variables) {... where HOOK is the name of your active theme.
And for template suggestions you need to enable debugging and see with inspect element, as usual it must be menu-local-tasks.html.twig


How do I add view header content in code? How do I add view header content in code?

I have seen questions related to this but only where the view is being embedded. I am not embedding any view, but would like to provide content for the view headers in code as I have quite a few views, and I do not want to add the content through the views UI as it is difficult to make changes quickly and as some views have many pages and share the same header.

Currently I have this code.

function MYMODULE_preprocess_views_view(&$vars){
  $function = __FUNCTION__ . '_' . $vars['name'];
  if (function_exists($function)) {
    $function($vars);
  }
}

function MYMODULE_preprocess_views_view_VIEW_NAME(&$vars){
  // do something here.
  $vars['attachment_before'] .= $SOME_CONTENT;
}

Use hook_views_pre_render().

/**
 * Implements hook_views_pre_render().
 */
function cv_views_pre_render(&$view) {
  // dpm($view); // dpm view here to see its properties.
  // and replace $view->name and $view->current_display with actual values from your view.
  // Note that my example uses Global: Text area for header, that's why I use $view->header['area'].
  // Other options available for header have different names. Try to find one that you use.
  if ($view->name == 'homepage' && $view->current_display = 'homepage_page_display') {
    $view->header['area']->options['content'] = t('TEST message');
  }
}


How to set file upload directory by parent node content type and node id I am trying to set the upload directory for a file field to contain the content type (and node id) as part of the path.

The desired path for my public files field is publication_documents/pub/content_type/node_id_of_node_this_was_uploaded_to/filename

I have tokens installed, but it doesn't seem to offer me tokens related to the parent node in the upload directory setting:

Slide 30 of This slideshow seems to indicate that it is possible, but how can I do it?

In case it matters, I'm using the media and file_entity modules.

File (Field) Paths module should help you.


Perform actions on field collection insert or update I have created field collection and added it to my content type. I have created a node, and now user can add field collections on this node. But i need to write into a file(some stuff) when user added new field collection or updated it. I need something like hook_node_insert and hook_node_update, i cant find anything for field collection.

In preprocess_node i have outputed field_collection_field and its returns only ids, and i can get them only by this code:

 $field_ids = array();
            //context_node = my current node,
            //field_block_id == field collection field
            foreach ($context_node->field_block_id['und'] as $element) {
                $field_ids[] = $element['value'];
            }
 $field_collection = entity_load('field_collection_item', $field_ids);

A Field Collection Item is an entity, so the equivalents of the node hooks are hook_entity_insert()

  Act on entities when inserted.

And hook_entity_update()

  Act on entities when updated.


Drupal Views Sorting problem I have a question on views sorting.

I have two content type(TypeA TypeB) which has the same field.

And i use views to list all the content with the sort i want.

Right now my problem is i want to sort my content with A1 A2 B1 B2 B3 B4 A3 A4 B5 B6 B7 B8...

with ratio 2:4 and in each type with another sorting rule like post date or update date ...

How can i do that?

Could somebody give me a suggestion?

Thx a lot

Try using the Views Natural Sort module, it is an add on to views and provides a better sorting option than the build in views sort.

Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."


Statistics module has less functionality The official documentation for the statistics module lists some exciting features. Here is a quote of what I found there.

  Viewing site usage

  The Statistics module can help you break down details about your users and how they are using the site. The module offers four reports:

  Recent hits displays information about the latest activity on your site, including the URL and title of the page that was accessed, the user name (if available) and the IP address of the viewer.
  Top referrers displays where visitors came from (referrer URL).
  Top pages displays a list of pages ordered by how often they were viewed.
  Top visitors shows you the most active visitors for your site and allows you to ban abusive visitors.

Unfortunately I don't  see any of those functionalities in my drupal 8 site. All I see is the number of views on a node, and no way to see the IP addresses, or referal URL or any of the above functionalities. Looking at the source code, I also don't see where the above functionalities are implemented.

What do I need to do to get the functionalities listed above?

Based on Drupal 8.3.1, it appears that documentation is incorrect. Well, they seem to primarily relate to Drupal 7.

The statistics module doesn't appear to store IP addresses or user names.

The module does provide a popular content block, which is based on view statistics.

The module also provides views integration, so you can create reports that have statistics data using views, but it doesn't add any default views similar to the reports mentioned in those docs.


Switch user session programmatically I'm trying to switch user session thanks to Drupal Switch. I want to do this so that when I have a certain role, I can switch to another user account to check some data from the user i choose to switch.

My routing :

double_vue.page_double_vue:
    path: '/double-vue'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::doubleVue'
        _title: 'Double vue'
    requirements:
        _permission: 'access content'
double_vue.switched_user:
    path: '/double-vue/{userSwitchedID}'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::switchUser'
        _title: 'UserSwitched'
    requirements:
        _permission: 'access content'

My view :

switch

My function :

  public function switchUser($userSwitchedID){
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = \Drupal\user\Entity\User::load($userSwitchedID);
    return $accountSwitcher->switchTo($account);
  }

When I click on my to link to switch to another user, I have this error in my logs :

  The controller must return a response
  (Object(Drupal\Core\Session\AccountSwitcher) given)

If I remove the return, I have this :

  The controller must return a response (null given)

How can I fix that so that I can switch to another user account ?

So first, the account switcher is for a temporary switch in the same request, to execute a specific thing as another user, it can't be used for what you want.

What Masquerade does is a lot more complicated and I don't understand why you don't just use that. Masquerade automatically adds itself to the user operations, so if you build a view that lists your users with the operations field then you will have exactly what you want to do.

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.


Drush archive-restore not restoring database nor giving error I have a Drupal 7 site and database in an archive created via Drush. I'm trying to restore it with Drush on a Mac running MAMP.

When I tell it to restore the site it says "[ok]" afterwards and the site files are in their correct destination, but it doesn't create and populate the database nor does it give an error that it couldn't.

I've made sure that their is a database user with the same name and password that is in the settings.php file.

My command is:
    drush archive-restore /Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz dev-sbirt-reg --destination=./dev-sbirt-reg

I added the -v tag hoping it might show me what the problem is and it outputs:

Mime type for                                                           [notice]
/Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz is
application/x-gzip
Executing: tar  -C /tmp/drush_tmp_1395439263_532cb69f676ea -xzf dev-sbirt-reg.20140321_200259.tar.gz
Archive restored to ./dev-sbirt-reg                                  [ok]
./dev-sbirt-reg
Command dispatch complete                                               [notice]

Any idea what I could be doing wrong or at least how I can figure out what I'm doing wrong? I would think at the very least I would get an error saying it can't connect to the database or something.

I'm running this from the directory I've set MAMP to use for holding site documents.

-Thanks

run the same command with --debug and a MYSQL error will likely be outputted to the screen.

So try:

drush archive-restore /Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz dev-sbirt-reg --destination=./dev-sbirt-reg --debug


adding javascript to tpl file from template.php <?php
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/my_js_file.js', 'theme');
?>

I want to add a javascript file just to the tpl file titled

views-view--gurus--page-1.tpl.php

I have this code to enter it to a specific them but what about just a certain tpl file.

I am guessing something like this

drupal_add_js(drupal_get_path('theme', 'mytheme') .'/my_js_file.js', 'view');

This is what I'm using. I don't know if this will have any gotchas in future where the template file I want is in the array but not actually used. So far it's working flawlessly.

function yourthemename_preprocess_page(&$vars) {
    $templates = $vars['template_files'];
    if (in_array('page-node-add-discipline', $templates)) {
        drupal_add_js(path_to_theme() . '/js/create_discipline.js');
        $vars['scripts'] = drupal_get_js();
    }
}

Put that in your template.php


How to add a title text input to an image field node form widget If you have an image field widget in a Drupal node form you can automatically edit the image alt text in there, but is it also possible to add a title text field?

When I install the File Entity module I can add title text to images by editing them from admin/content/files but it doesn't make sense to tell clients to use this admin page to finish authoring their content.

Just to be clear, I don't want to have to make every image into a node, I just want to add form input fields to the image field widget so that the file entities can get a title text in the node form.

You have to enable the title field on your image field in the manage field tabs, at the bottom of the field form. for example at
example.comadmin/structure/types/manage/example_content_type/fields/node.example_content_type.field_example_field

Found the answer after landing here: https://www.drupal.org/project/drupal/issues/2303765


D7 + Views 3 - How to reproduce a teaser with fields in Views I need to build a "News" block on a website that shows teasers of certain categories.

BUT I cannot use teaser views because I don't want the styles that are in a teaser view. This rules out the viewsnodefield module and teaser option available in the first page of view creation.

My question is: how to reproduce a teaser using fields? How do I get the teaser content? How can I rewrite the link by surrounding the url link field?

Thank you for your thoughts

You can use Display suite and Views to achieve the required functionality. Using Display suite, you can control what fields appear in the teaser. Also, Display suite provides views Integration, so you can use your new teaser to show up in views. This article explains more about this.


Will there be any unexpected side effects when I upgrade the Zen theme? I have installed the 7.x-5.6 theme and I want to upgrade to the 7.x-6 version. I have created 2 subthemes from it that I hardly use, and I hardly use the Zen theme itself - it is supposed to be base theme,not actually used in any case.

Is it okay for me just to disable and delete the base theme and the derived themes and install the 7.x-6.4 as though the previous ones were never installed in the first place?

PS. Are there any hidden downsides to uninstalling themes, like some stray database tables etc?

Themes don't create their own database tables.

The changes about the theme status (enabled, default, theme settings) are stored in the system and variable tables, along with many other system settings, it's nothing you should be worried about.

Some themes are accompanied by a special module built especially for them, but Zen isn't one of those.

Yes, you can disable and delete old Zen and its subthemes without consequences. Set Bartik as default theme before removing old Zen out of your system.

It's good practice to backup files before deleting, it's up to you, at least check if there are any files you might want to keep, maybe logo images.

Then download and enable the latest Zen. Create the latest Zen subtheme using the latest Zen procedure.

The latest Zen theme structure and procedures are significantly different from the older versions. You'll have to install some bundles and other dependencies and learn how to build Sass through Gulp (if you want Sass)...

You might experience problems if you want to keep the old subthemes and make them work with new the Zen, but if you want to start fresh there aren't bad consequences if you remove old Zen and its subthemes and then install new Zen.

It's good to remember to clear (theme) cache when changing things like these, even though theme registry is rebuilt on visiting the Appearance page.


Front Page button to add new element in node I'm completely new to drupal and actually building a charity community site on Drupal 8.

I have a content type "PROJECT" with a field "PROJECT MEMBERS" as entity reference to "USER".

Now I would like to have a button on the display of any project node "REGISTER ME FOR THIS PROJECT".

If an authenticated user clicks on that button his name should be added as new Project Member Element in my node.

Is there any way to do this ? Thank you so much !

Cheers,
Tom

There are ways. Here is one:

You will have to programmatically add value to that entity reference field. Here is how you should do it Programmatically update an entity reference field (see the multiple values case)

To make your button work you will need to add a route with arguments (one argument of the content ID you are adding a current user into) see here https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

And in order to add a button you can just update/override a corresponding twig template to inject HTML code of a button there referring the path of the route above with the nid as a parameter.


Taxonomy menu limited to certain number of terms Wondering if anyone can steer me in the right direction on this. I'd like to have a taxonomy menu where I have a few main terms listed with with around 5-7 children terms. When the user is on the page of the main taxonomy term, all of the child terms are shown.

For example, when the user is on the home taxonomy page that lists all of the terms then the menu would show this:

-Term 1
--Term A
--Term B
--Term C
--Term D
<more>

-Term 2
--Term A
--Term B
--Term C
--Term D
<more>

Clicking on  or clicking on the Term 1 page would then show all of the children of Term 1:

-Term 1
--Term A
--Term B
--Term C
--Term D
--Term E
--Term F
--Term G

-Term 2
--Term A
--Term B
--Term C
--Term D
<more>

Here is a link to a site that already does this and that is where I got the idea.

Any help would be much appreciated!!

I believe the easiest way to do this is to create a view that block displays a set number of items in a list (HTML or unformatted list), with a global text field that will link to your term page. You can then style this with css to look like the rest of your menus (if you require to).

This unfortunately will mean that it will not go through the drupal core menu system. You will have to create your own "Admin" view to manage this "menu". I would suggest Draggable Views if you require a webmaster to control the sort order.


Replace Page Title with Image I'm attempting to replace the titles on my pages with images.
I've added an image field to my content type and have created a view that displays the image for the selected page with a contextual filter.

I am embedding the view in my page.tpl.php page with views_embed_view().

I'm having a problem with the conditional statement. If no image exists for the selected page, I want to show the regular page title. Currently, my code will print an empty
 tag on pages with no mages. Can I get some help with this?

I am using Drupal 7 and the Views module version 7.3.3.

<?php $TitleImage = views_embed_view('title_image', 'block'); //Embed View ?>

<?php if (!empty($TitleImage)): //Check to see of View is empty ?>

<?php print $TitleImage; ?>

<?php else: //Display regular title ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>

<?php print $title; ?>

    <?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

I need to replace the page title in the page.tpl.php file. There are 3 content types that have the field_title_image field. I thought that creating a view with a contextual filter would be the best approach, to not display on content types that do not have the field_title_image field.

I came across this comment that helped me with displaying the image.

Below is my revised code. Is there a better solution?

<?php if (isset($node->field_title_image['und']['0']['filename'])): ?>

<img src="/sites/default/files/images/<?php print $node->field_title_image['und']['0']['filename']; ?>" alt="<?php print $node->field_title_image['und']['0']['alt']; ?>">

<?php else: ?>
<?php print render($title_prefix); ?>
<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>
<?php endif; ?>

To answer your specific question; clearly $TitleImage is not empty, views_embed_view is returning wrapper elements or a space. in the view settings make sure "no results" returns nothing using the no results behavior of the field and the view (under advanced).

Why use a view? If that image is on that piece of content then there is no need for a view at all, just use the field:

<?php hide($content['field_title_image']); // So it does not render elsewhere ?>
<?php if (!empty($content['field_title_image'])): ?>

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

<?php else: //Display regular title ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
<?php endif; ?>

(if you are on node.tpl.php the filed will be as above, if you are on page.tpl.php it will be inside $page['content'] array)


Disable cache during development: Templates are not discovered I have followed all steps reported on https://www.drupal.org/node/2598914. However, if I create an new template file in my theme folder, it does not get discovered until I flush the cache manually via drush cr.

Is rebuilding the cache a must to discover new templates, or can I optimize the developer settings to auto-discover templates during development?

try add this in .htaccess  (drupal root)

    <IfModule mod_headers.c>
       //ADD THIS
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires 0
    </IfModule>


From showcase website to e-commerce website I have a big Drupal 7 showcase website, that needs to evolve in a e-commerce website. I know Drupal e-commerce but I don't know if it's ("easily") possible to upgrade a content type to a "product" content type that can be added to a shopping cart?

In order to do that, here is what I did :
 - install Drupal Commerce
 - create the product (name, ref and price)
 - and add the product reference field to the existing product

If that can help...


How to make the UserProfile Info availlable on a block I understand how to preprocess a specific block to make some variable available for that it, but what I don't understand is where I grab these variable that I want to be available in my  block.

I have the following code:

function THEME_preprocess_block(&$variables) {
    $variables['user_profile']= $user_profile;
}

$user_profile is NULL.

So in other terms what i would like is to grab all the data entered by a user during the registration and make it available within block under for instance a user_profile variable.
Is it possible at all?

Well i tried but it doesn't seem to do anything in drupal 7. Also isn't the user variable holding data only for the current loged in user ? I would like to retrieve the data of any user in order to populate the profile page with it.

You need to use the global user object to get info about the currently logged in user, then pass that user object to profile_load_profile:

function THEME_preprocess_block(&$variables) {
    global $user;
    $user_profile = profile_load_profile($user);
    $variables['user_profile']= $user_profile;
}

(code is untested but should work)


Hundreds of unserialize requests I have a large Drupal 7 website on my hands that is very large and has loads of modules (over 200).
I am already seeing poor performance symptoms in the FPM logs with max_children limits reached on the Acquia server.
I installed a profiler (blackfire) and the main issue (on every page) is an absurd amount of calls to unserialize (over 300) coming from DrupalDatabaseCacheprepareItem (autenticated).
This happens even on a basic page.
I am having a tough time coming up with a solid strategy to pinpoint the bottleneck and which module(s) are the culprit.

Anyone can help me with this?

I ended up using the variable debug module, which was incredibly useful in helping me find out the expensive variables I had.


changing role wen opening a confirmation link but auto login with logintoboggan We are using logintoboggan to login new users after registration. After the registration the users get the role 'unconfirmed user' with limited permissions. The users need to open the confirmation link to get another role 'confirmed user' with more permissions.

Logintoboggan disables the option to send a confirmation link to the user.

How can I send an email with a confirmation link to the new user and how can I switch his role when opening the link?

If using rules module, then you will have an event: when user account is activated. when rule fires you can define action add role.

For sending email even: when user account is created and then as action send email.

There is more possibilities. I like to do it with custom modules so I can simpletest the code. If so, use hook_user_insert() and hook_user_login(). In hook_user_login() check for user roles.


how to restrict access in routing.yml based on roles I know how I to restrict access in the routing.yml file based on permissions, but how can I do it based on roles? This is how to do it by permissions:

requirements:
  _permission: 'access administration pages'

How to do it based on roles?

This should work

requirements:
  _role: 'administrator'

See more details here https://www.drupal.org/docs/8/api/routing-system/structure-of-routes