Replace Views prev/next pagination with image arrows Is there a template that would allow me to replace Views' prev/next text pagination with image arrows instead? I could do it with CSS but I don't feel that is ultimately an optimal solution.

You can use the theme_pager_link function to override the core pager link. Or you can have a look at this article that may be helpful: https://www.drupal.org/node/318565


Contrib Module JavaScript interfering with Node If one has a contrib module that works fine in most cases, but on a specific page (say /comment/comment) you wish it NOT to appear, but the options in Config don't give you that ability...what's the best practice for disabling functionality (in this case javascript) coming from the contrib module?

I'm using the sharebar module but it's all messed up in my comment/comment page. I tried hiding it with CSS (visibility:hidden) but can't target it no matter what I try. I even hid the html of the page itself and it still shows up! (although nothing else does)...which leads me to believe it's javascript...so how can I disable that for a particular page?

That seems to be a common issue with the sharebar module.  The 7.x-2.x-dev version moves the sharebar into a block so that you can place it anywhere with either the block ui or the context ui.

The 7.x-2.x version is still in dev so you may need to do a little testing before enabling it on production, however, the module maintainer is suggesting that people upgrade to this version anyway.


Multipart Form Fields - Taxonomy Included I'm starting out a new project and I think I've come across something like it before but I can't think of the right search terms or something along those lines...

What I'd like is a module to add multiple fields to one node field. So like a text field and a taxonomy field where I can add multiple of both the taxonomy value and the combined row of the text and taxonomy fields.

I'm near certain I once dealt with something like this once before but I cannot think of it for the life of me.

I have found this: https://www.drupal.org/project/multifield but the problem with this is that it only allows for only ONE value in each field (aka ruining my chances for using it with taxonomy).

So if anyone's run into something similar or can think of a solution to my predicament I would be incredibly grateful for some help. Thanks!

You can use Field collection module

Tutorial:
Using Field Collection In Drupal 7


Conditionally output by content type using Twig I want to theme the display of a Views based on the Content type. In my attempts to do that, I’ve created the views showing All Content Types. I’ve added all the fields I need, and also included a Content: Type field. It is this field that I am trying to use for conditionally formatting the output (if it’s a Blog content type use this html and for all other content types use a different html).

This is what I have tried so far but that condition is not triggering at all

I have created a views-view-fields--myexample.html.twig

{% if fields.type.content == 'blog' %}

{% else %}

   {{ fields.title.content}}
   {{ fields.field_image.content }}

{% endif %}

Probably because {{ fields.type.content }} =
blog

so try

{% if fields.type.content|striptags == {{ 'blog'|t }} %}

If you do not want to have to use |striptags you could strip the markup from the Views UI.

Also, do not check mark Exclude from display in configure field, because if you do this your template file will not have access to that field.

Side note: you forgot to close the div in line 3.

Alternatively

{% if row._entity.gettype == 'content_type_machine_name' %}

 alternate method credit: 4K4


How to change the blog page title with specific user's only blog posts? There is a team page of the company and there are few links to social accounts which every user have, including the link to their blog posts.
This link redirects you to blog page, but only with this user blog articles. The address shows blog/user_id and the title of the page is "Blog". I want the title to be different depending on what user's blog you've entered. Something like this: "John Doe's blog posts". Should I edit blog template? I use Drupal 8.

Tryout this one   Reference

class CustomController extends ControllerBase implements ContainerInjectionInterface
  public function getBlockContent() {
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      $route->setDefault('_title', $some_title);
    }
  }

}


How to use 'session' to check path history of user I want to keep a track of the pages user visited, I got to know i can do this with the help of session and hook_node_view. Being a beginner, i couldn't find any particular help on using session API, can anyone help?

if you just want to track user visiting there are some modules ready for that like user visits .

or if you want to do something and need to write a module for that then hook_node_view will fire when user is viewing a node . you can implement it like below :

function YOURMODULENAME_node_view($node, $view_mode, $langcode)
{
   global $user; //user data is here
}

now you can do what you want with user.


Inherit page id for drupal node I am trying to make a node inherit the url of where it is clicked form.

eg : .com/blue-work/node-1

not .com/node-1

This is so when a link is clicked from a certain destination the node inherits its parents block settings. Is this possible with Drupal?

That sounds like fun.

First, a question: In your example, do you mean that the source page is /blue-work, and you're clicking a link on /blue-work to go to node-1? And you want the destination URL to become /blue-work/node-1 ?

If so, that sounds difficult b/c you'd have an open-ended number of different paths and you'd be telling Drupal to behave differently, paying attention to the tail only (and how is Drupal to know what, exactly, is the tail?). I think it would still be possible, though.

Instead, you could go with what currently works: if you click a link on /source-page to go to /destination-page, then this URL works: /source-page/destination-page.  However, I'd sooner use: /source-page?context=destination-page.

Regardless, you might start with hook_page_alter so you can edit all the links on the source page before it's rendered, adding the source page's url to (the end of) the links.

Then, of course, you're going to have to check the requested URL to get the 'source-page' context and apply it. Perhaps with hook_page_alter again.


Why is css not working as expected with Omega Making site with left side menu items built on Omega responsive grid. Setting up the global.css to theme out some page elements, like this menu.

Problem: Used css not used in the browser. Instead system.menus.css is used.
Question: Why.

CSS: for menu

/*============== Menu Items ====================*/
.menu ul
{
    padding:8px;
    margin:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size:1em;
    color:#FFF;
    list-style:none;
    text-indent:15px;
    background:#0000a2;
}
.menu ul li
{
    background:#0000a2;
    line-height:28px;
    border-bottom:1px solid #000;
}
.menu ul li a
{
    text-decoration:none;
    color:#FFF;
    display:block;
}
.menu ul li a:hover
{
    background:#3ea5ea;
}
.menu ul li#active
{
    background:#3ea5ea;
}

====================================

Chrome inspector data:
media="all"
ul.menu {
border: none;
list-style: none;
text-align: left;
}
dea.harland.tkmedia="all"
.menu {
margin: 0;
padding: 0;
}
dea.harland.tkmedia="all"
p, dl, hr, h1, h2, h3, h4, h5, h6, ol, ul, pre, table, address, fieldset {
margin-bottom: 20px;
}
dea.harland.tkmedia="all"
ul {
list-style: disc;
}
user agent stylesheetul, menu, dir {
display: block;
list-style-type: disc;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
-webkit-padding-start: 40px;
}

Inherited from body.html.front.logged-in.page-node.toolbar.toolbar-drawer.omega-mediaqueries-processed.omega-equalheights-processed.alpha-debug-processed.responsive-layout-wide

dea.harland.tkmedia="all"
body {
font: 0.75em/1.3em Verdana, Helvetica, Arial, sans-serif;
}
dea.harland.tkmedia="all"
body {
font: 13px/1.5 Verdana, Helvetica, Arial, sans-serif;
}

I think your CSS is incorrect. You wrote:

.menu ul li {/*stuff*/}

when I think it needs to be:

ul.menu li {/*stuff*/}

Is this correct?


How to print the best answer field? I am use the Best Answer module. I customize the answer template, node-answer.tpl.php and I want to print best answer field,add

No output result, please help me.

The Best Answer module extends the 7.x-3.x version of the Answers module (disclosure: I'm a (co-)maintainer of it). However, this module has been integrated as a sub-module of the 7.x-4.x release of Answers. This release also has the new theming stuff (if you enable the brand new answers_theme sub-module) as in this sample screenprint of it:

Note the checkbox in the bottom-left of it (shown to the left of the accepted answer), which I believe is the equivalent of the best answer field that your question is about.

So unless you have good reasons to continue with the 7.x-3.x, I strongly recommend you to first upgrade to the 7.x-4.0-rc2 release of Answers, which might possibly obsolete what you're trying to achieve.

Even though the 7.x-4.x release is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. The next release that will become available, will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).

Try the most recent 7.x-4.x release

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x release). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

These Views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).


Can Drupal's search index external tables? Can Drupal's search system index external tables?
I have looked up how external tables can be linked to Drupal using the Data module, hook_views_data etc.,
Can the content of the external tables be indexed and searched by Drupal's search system?

Yes, you can use the search api to specify your additional content. In particular you will need

hook_search_info
hook_update_index
hook_search_execute


How to get RAW Html code from my module? I looked around for a few hours but wasn't able to find any available hooks to get pure raw html code. If you right-click on any webpage and do "get source", it will give you the raw html output.

However, there doesn't seem to be a function or hook available that I can find in Drupal that does this.

Does anyone know if this is possible? Thank you.

It's not totally clear what you mean by 'from my module' but if you're asking how to get the HTML code of any Url into a variable in your module, you can use the drupal_http_request function. Below example comes from https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7.x

$data = 'name=value&name1=value1';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('http://somewhere.com', $options);

You can also use curl via the cURL HTTP Request (chr) module.


How to check if a url exists on my own website I need to check if a url exists in a module that I am creating.  How should I go about doing this? I tried to use a @get_headers() function with php, but sadly that doesn't work. I am wondering if there is a built in drupal function that I can use?

This is what fixed it:

if (!drupal_valid_path($path)) {
  // Not a system URL.
  if (!drupal_lookup_path('source', $path))  {
    // Not a path alias.
    // $path does not exist.
  }
}

Where $path is a relative url.

Source


How can I specify required fields when programmatically loading a node creation form? I'm building out a custom workflow. Newly registered users can create a node that has several fields - some of the fields are required, others are pre-filled, and others are disabled. The benefits for having 1 content type to handle this greatly outweigh the negatives.

Fields that I set the #default_value, #access, or any other FAPI attribute on are working properly, but fields where I set #required = TRUE are not validating and are not stopping the node from being created!

Here's my code:

function my_custom_callback($arg) {
  module_load_include('inc', 'node', 'node.pages');
  $page['node_form'] = node_add('content_type_name');

  if ($arg == 'foo') {
    $page['node_form']['field_favorite_color'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
  } else if ($arg == 'bar') {
    $page['node_form']['field_favorite_food'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
  }
}

If I visit this page with $arg = 'foo',  I can submit this form without entering anything in field_favorite_color, even though this field shows the red asterisk and has the class 'required' and is showing as #required = TRUE in the form's render array when I do a dpm() within the callback function.

Why won't Drupal require that this required fields be filled out? Do I need to rebuild the form somehow after I've altered the fields? If I set the same code in a hook_form_alter() then it works as expected, but in that case I don't have the control that I get through my custom callback to lead the user through a multi-step workflow.

Edit: This is Drupal 7. Tried adding that tag but am seeing 'drupal-7' and 'drupal7' tags are not allowed.

In short, to answer your question "How can I specify required fields when programmatically loading a node creation form?" ... use hook_form_alter() and keep your sanity! :)

Here is what I ended up doing after toying with a bunch of proposed solutions I ran across wile learning hook_form_alter() and Drupal's Form API.

I'm sure this solution could be massively improved, but this worked for me and it seems to be fairly simple to manage/maintain.

Managing a Single Content Type With a Complex Workflow Using Node Edit Forms

First after hours of debugging, I decided not to use a custom callback.  Instead I edited the built in node add/edit form using nothing more than hook_form_alter(). (I like hook_form_FORM_ID_alter() instead of hook_form_alter() as it helps me keep my code organized. A personal preference for sure.)

  Note: Drupal 7 use the Administration theme by default for creating
  new nodes/content. You can get around this by unchecking the 'Use
  the administration theme when editing or creating content'
  field at the bottom of 'admin/appearance' page in the admin panel.

Using the Rules Module To Keep Track Of Workflow Stages

I added a new field called "workflow" to my node type (Added through UI at: http://example.com/admin/structure/types/manage/%content_type%/fields) so I could keep track of what stage the user was currently at.

My workflow field ($form['field_workflow']) was a select list with predefined options (stages).

 'new' => 'New', //Default Value For New Nodes
 'foo' => 'Foo',
 'bar' => 'Bar'

I used the Rules module to move the workflow along.  Rules allowed me to move a bunch of the 'submit function' code into rules configuration.  This made updates simpler as I don't need to make as many module edits.

Rules makes it very simple to do things like 'if the node is new, set the workflow to foo after saving' or 'if the workflow is set to foo, set the new workflow state to bar after saving.'

Organization: Ugh...  Setting Up The Actual Flow

First I tried to keep each stage of the workflow as clean as possible by packing alterations in their own functions with a custom naming convention.

function MODULE_stage_new(&$form) {
    //Insert all alterations here for use when node has not yet been saved. It's new!
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    $form['field_favorite_food'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
}

function MODULE_stage_foo(&$form) {
    //Insert all 'foo' stage alterations here.
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
}

function MODULE_stage_bar(&$form) {
    //Insert all 'bar' stage alterations here.
    $form['field_favorite_food'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
}

/**
* Implements hook_form_FORM_ID_alter().
*/
function MODULE_form_FORM_ID_alter(&$form, $form_state) {
    /**
    * Place any alterations here that apply to all stages here before the
    * 'if' statements below.
    *
    * I generally place my validation callbacks and CSS additions here.
    **/

    if (empty($form['nid']['#value'])) {
        MODULE_stage_new($form);
    } else if ($arg == 'foo') {
        MODULE_stage_foo($form);
    } else if ($arg == 'bar') {
        MODULE_stage_bar($form);
    }
}

Now that hook_form_alater() is being used exclusively without a custom callback, you shouldn't have any issues with the ['#required'] elements.

Occasionally I would have to add an '#after_build' function (yea, yet another function to keep track of...) but did so with a common naming convetion.  For example, if I needed to add a new stylesheet at the 'foo' stage I would use the following functions.

function MODULE_stage_foo(&$form) {
    //Insert all 'foo' stage alterations here.
    $form['field_favorite_color'][LANGUAGE_NONE][0]['value']['#required'] = TRUE;
    $form['#after_build'][] = 'MODULE_stage_foo_after_build';
}

function MODULE_stage_foo_after_build($form, &$form_state) {
    drupal_add_css(path_to_theme() . "/css/foo.css");
    return $form;
}

I hope this wasn't too overkill or off topic.  I honestly found that sticking to hook_form_alter() for node add/edit form modifications saved me a ton of headaches over how I was trying to do it before.  The custom callback method using module_load_include('inc', 'node', 'node.pages'); never worked for me the way it seemed to for people writing the examples I found.  Then again, I'm still pretty new to Drupal. :)


How make surveys with many questions whose answers are very similar I want build a survey with many different questions whose answers are of evaluation range kind (strongly disagree, disagree, neutral, agree and so on) or yes/not kind. I have to create n different fields (I suppose text list and boolean fields) or is there a better way?
I'm using Entity Form module.

I will suggest using Survey Builder module

Key Features

Create survey forms with a drag and drop interface
Re-use questions across surveys (can be disabled)
Respond to surveys
Aggregate responses to surveys with Views

There some other nice modules too, such us LimSurvey Sync or you can use webform together with webform builder which will save you a lot of time.


Can I filter the list of candidates used by the menu system to determine the menu trail? I have a site with a menu structure like so:

- a
- b
  - 1
  - 2
- c
  - 1
  - 2

Now lets say that I have a node that both b2 and c2 point to (I'll call it node/4). When the user clicks either link, I want the site to display as a click on c2. That is to say that the main menu item for c should be highlighted, and the secondary menu for c should be displayed. And of course, the content of node/4 should be visible.

What actually happens is that the node/4 content is displayed, but both b & c main menu items are highlighted and the secondary menu for b is displayed.

I've investigated, and found the menu_link_get_preferred function in core/includes/menu.inc. This function builds a list of candidates that can match the current path, and places them into an array keyed like this:

$candidates[MENU_ITEM_LINK_PATH][MENU_NAME]

My problem is that I have two link candidates that match the same exact criteria:

$candidates['node/4']['main']

and so I cannot control which one ends up in the candidates array. Ideally I would like to have a way of flagging the c2 link so that it was not treated as a candidate. I had thought that this would make a good module, but I cannot see a way of interrupting the execution of the function.

The bit of code I would like to alter is (D7 version, D8 is very similar):

// Sort candidates by link path and menu name.
$candidates = array();
foreach ($query->execute() as $candidate) {
  $candidate['weight'] = $candidate['link_weight'];
  $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
  // Add any menus not already in the menu name search list.
  if (!in_array($candidate['menu_name'], $menu_names)) {
    $menu_names[] = $candidate['menu_name'];
  }
}

In an ideal world I would have added an extra field to the database, so that a $candidate would be discarded on a certain flag. Any ideas how I could achieve this?

Unfortunately menu_link_get_preferred does not sort it's results. If two items match the same paths, it will just return the first result returned by the database. There is an ongoing issue about this: drupal.org/node/1649062

You can workaround this by ensuring the menu you want was added first in the database, but that's not a sustainable way of addressing this. The order might change after you restore a backup, when you compact your database, or after the next Drupal update if they address the issue.

If you cannot work around the issue another way, I think patching core with the patch provided in the issue is safer. The patch sorts the preferred links by mlid, which means you need to create the preferred menu item last (but unlike the workaround before, this will still work even if your database gets re-written).


CCK field migration reproducibly results in server error on node display I am trying to migrate my CCK types to Fields using CCK module in D7, using content_migrate, following the documentation. After migrating all fields of a certain content types, I got a server reset when trying to view any node of this content type.

See also https://www.drupal.org/node/2665208

In Chrome the message is
"No data received ERR_EMPTY_RESPONSE", Firefox says "Secure Connection Failed
The connection to the server was reset while the page was loading". The server log is completely empty for loading this page, so I guess php dies pretty early.

I migrated all fields one by one and tracked it down to a text field that was using an optionwidgets_button widget in D6.

Edit: We found a second broken field. This field does not cause a server reset but a 'The website encountered an unexpected error' from Drupal upon display of any node where this field is set. This field is of type user_reference.

This is the output of from the migration process of the offending field:

Changed field type: The 'field_myfield' field uses a 'optionwidgets_buttons' widget. The field type will be changed from
'text' to 'list_text'.

Rolling back the field suppresses the error; re-migrating this field fully reproduces the error.

no pending dbupdates, Postgres 8.4, PHP 5.3

We have now identified the source of the error. The content-migrate process seems to sometimes generate invalid display settings for fields. We have now seen this for two different fields. To identify the offending field, we did the following to debug:

if possible, (you getting at least a drupal error) get a call stack, so that the offending field type and field name can be searched for (grep for 'field')
to repair offending settings: go to admin/structure/types/manage/<data type>/display
set each field <hidden> in the Label column (yes that is odd, but I guess this setting is enough to trigger generating fresh display settings)
Save
set each field back to original Label settings
Save

If you want to find the culprit without stack trace, one could switch each field off, and reload the content.

I am not sure about the reason for why this works, but I suspect serialized data. Drupal uses a lot of serialized strings to store settings in the database, and the deserialization might not be robust against corrupted settings. I don't think this is really a bug in the migration code, but corrupted settings can occur at any time.

So I guess it might be a good idea to re-generate settings, in any case of a display error of custom content.


How to Control Core Performance Cache Expire Time Of Day Wondering if there is a way to control the time of day that core performance caching will expire and run cache clear all via cron.

I'd like to change my minimum lifetime setting as low as possible and use Expire or Cache Actions and/or Views Content Cache to get away from bulk cache clears on my site... which are causing WAY too much excess mySQL load.
But I want this master cache clear to happen in the middle of the night, just after the daily backup.

Partial answer, but I typically handle exact scheduling and cron-but-not-cron tasks by using a custom script and calling it with wget in a crontab.  You can use cron.php for guidance on how to bootstrap, and then write your own function to clear what you want, then put it in crontab to run when you want.  Just remember to lock down the script in .htaccess or apache config.


How to show taxonomy terms' description field on a node/add form instead of term title only in drupal 7? I find it a bit disturbing that you cannot set which fields of taxonomy terms are displayed when you add a new node and have the terms listed.

There will be a bunch of terms which the user has to select one from. However, sometimes only showing a terms title wont be enough, so I'd like to also show a terms description when adding a new node.

How can you do that?

The following solution slightly alters your requirement. Instead of having the term description field showing up as part of the term select widget, create a view block set to be visible on node/add pages which provides a table listing of each term and its description field.

To do this, create a new view of type "Taxonomy." It will have two fields: taxonomy term, and taxonomy term definition.

You could put help text associated with term_reference field which alerts the user to the block which holds the terms and description.

It would be very difficult to alter any select widget to include the description field in a way that wouldn't make a mess of the page.


Horizontal Tabs rendered as rendering collapsible fields Although I have set up the a Content Type's display to use Horizontal Tabs

It's rendering as collapsible fields:

Does anyone have ideas on how to correct this?

In commons_origins theme's template.php file, fieldset default functions are overridden("function commons_origins_fieldset"), pls comment or remove it to have display as tabs. Or clone this theme as custom theme in sites/all/themes folder and create as new theme by removing this function.


Not able to see < character in front end I am running into a problem when creating content with the < character… It is quite strange as the symbol is showed in the backend, when creating the content, but it disappear when you go to /node/%nid. Actually the whole  text nodes, where the symbol is, disappears. I have disabled all the filters and the problem remains…

By the way, I have a Drupal 7 installation and cKeditor module installed, but switching to plain text editor doesn't make a difference.

Does someone has a clue of why this is happening?

Thanks in advance.

EDIT

After some tests, I have discovered where the problem comes from. It has to do with the "word link" module. When word link is configured to run on a field, then it seems to remove all the text within the scope of the tags where the < appears. Now it seems it's time to surf the word link code...

At the end, I found a work around for the problem. In the word link configuration form we can find a "Disallowed html tags" input text box. We can add a  tag there, so now, whenever I want to include the < character in my text, I wrapp the  tag around it.

I know it is not the cleanest solution but it is enough to keep going until they fix the module.

Hope it can help to someone else.


How to theme a node form from my custom module? I have a node type with machine name "resource", and I'm trying to theme it in my module "modulename".

I've tried doing this:

function modulename_theme() {
  return array(
    'resource_node_form' => array(
      'render element' => 'form',
      // 'template' => 'resource-node-form',
      // 'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

//I've tried both functions, getting nothing

function theme_resource_node_form($variables) {
  dsm($variables);
  return 'Testing';
}

function modulename_resource_node_form($variables) {
  dsm($variables);
  return 'Testing';
}

I've cleared cache, nothing happens. I've also tried with templating approach:

function modulename_theme() {
  return array(
    'resource_node_form' => array(
      //'render element' => 'form',
       'template' => 'resource-node-form',
       'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

And placing resource-node-form.tpl.php in modulename module folder. Cleared cache, nothing happens.

Sure I'm doing something wrong, but I can't figure it out. I've used templates for existing forms from a custom theme, but I'd like to do it this way, this time. Better approach for this project I'm working on, I think.

Thanks for your answers, ask me if you need more info!

Use this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    // Expected format: NODE_TYPE_MACHINE_NAME_node_form
    case 'resource_node_form':
      // Requires devel module to be installed.
      // See all available elements displayed using krumo.
      $dpm($form);
      break;
  }

}

Update:

Depending on the complexity of your layout, check Display Suite and Field Group modules, as their functionality might be what you need.

You can also follow up this article if you want to do this from a tpl file. The approach is similar to what you were trying to do.


Custom content type show taxonomy image What i want is to have a field called Manufacturer so the user can select the product manufacturer. The way to show the field is an image linking to the Manufacturer page.

example: Product "door handles 0001" has a Manufacturer Audi.

I'm thinking using taxonomy terms with one more field in them (image) but when i import the field just show the name linking to the taxonomy term not the image.

I have see that stackexchange but i can't manage to do it,  the patch is a little outdated..

The easiest answer to your problem might be the taxonomy image module:

  "The taxonomy_image module allows site administrators to associate
  images with taxonomy terms. With the association created, an admin can
  then make a call to 'taxonomy_image_display()' from their theme or
  other PHP code to display the appropriate image."

but since you already have a field associated with your taxonomy term, you just want to suppress the output of the tags in your node template and replace it with code that loads the term field and then renders it, ex. roughly:

/* load your term object */
$term= taxonomy_term_load($node->field_tags['und'][0]['tid']);

/* load the entity object (your field names will vary)
$result=field_view_field('taxonomy_term',$term,'field_image','image');

/* display the rendered result, this can be set in manage display for your field to use image styles, etc. */
print render($result);


Views Display output in tpl file not working I'm making use of views 2.xx and pressflow 6.xx and i'v a little issue when it comes to the views Display output template file, it just won't show the rows when i tried to print them like this:

      <?php print $fields["field_genre_value"]->content; ?>
      <?php print $rows["field_genre_value"]->content; ?>

Non of them work....

While not a direct answer, the best thing I've found to do in cases like these is to put a

<?php drupal_set_message('<pre>' . print_r($rows, TRUE) . '</pre>'); ?>

in the template to see what you have to work with.  But if you are talking about the Display template, I am pretty sure by that point the $rows variable has been populated with HTML so you may need to look at another template if you want to get fancier with the output.


How we can get the value entered in search API autocomplete field in jQuery? I got a requirement to send the search text to GTM for tracking purpose. I have a field which is from search api autocomplete module. I am not getting the value in jQuery on click of submit button. I tried like below but no success:

var search_key = $('.path-frontpage .ui-autocomplete-input').attr('value');

Can anybody implemented such thing. Please help

DOM:

<input placeholder="Search MyP&amp;O" data-drupal-selector="edit-keywords" data-search-api-autocomplete-search="search" class="form-autocomplete form-text form-control ui-autocomplete-input" data-autocomplete-path="/search_api_autocomplete/search?display=page&amp;&amp;filter=keywords" type="text" id="edit-keywords" name="keywords" value="" size="30" maxlength="128" autocomplete="off">

This works for me:

var search_key = $('.path-frontpage .ui-autocomplete-input').val();


Get the master parent node id for a node reference field I have 3 content type "A" , "B", "C".
B has a node reference to A.
C has a node reference to B.

B->A
c->B

Using simple query I want to get the master parent node Id of C. which is A node id

c->B->A

How to do this.

If you are looking for a DB query within a custom module, you could do something like the following example function that recursively goes through the reference tree to get to the top for a node.
It will work for N levels, (but not for multi-valued references or nodes with multiple node reference fields).

function mymodule_getTopReference($nid){
    $top_nid = 0;
    //load the node
    $node = node_load($nid);
    //get all reference fields
    $node_reference_fields = array();
    $field_infos = field_info_instances('node',$node->type);
    foreach ($field_infos as $field_name=>$value){
        $field = field_info_field($field_name);
        if (($field['type'] == 'node_reference')){
            if ($field_value = field_get_items('node',$node,$field['field_name'])){
                $top_nid = $field_value[0]['nid'];
                break;
            }
        }
    }

    if ($top_nid && ($parent_nid = mymodule_getTopReference($top_nid))){
        $top_nid = $parent_nid;
    }
    return $top_nid;
}

For example, if your node reference field was called "my_reference" and your example nodes had the following nids:

A = 1
B = 2
C = 3

and your references are as you said:

B->A (2->1)
C->B (3->2)

Then for node 'C'(3) you'd call this function like so:

$top_nid = mymodule_getTopReference(3);

which then would set $top_nid to 1 (A's nid).


How to filter single field in a view I am running Drupal 7 with the latest version of the Views module.

I have a content type called "School," which has an entity reference field for "classroom." The "classroom" content type has a radio button field for whether it has an assigned teacher.

I'd like my view to output a table which will list the total number of classrooms in each school (so school name in the first column, # of classrooms in the second column). After some messing around, I was able to get this working.

However, now I'd like to add a third column where I display the # of classrooms which have an assigned teacher. So if the classroom doesn't have a teacher assigned, it doesn't get included in the count. Anyone know how to accomplish this? It doesn't look like I can filter on individual fields...

If this were an SQL query your new column could be a subquery. I mean this new value of # of classrooms with assigned teachers has its own business logic, seperate from the list of data your already returning.

You can accomplish this using Views Field View. This lets you embed a view result -- per row of your existing view. From the project page:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

  It's highly recommended to use this module in conjunction with views
  caching. Views Content cache and Cache Actions are good ways of
  caching views.

So:

Make a new view; called for instance with the human name of "sum rooms assigned teachers" (the machine name will be sum_rooms_assigned_teachers).
For this View simply use display mode of Show Fields; and include like the NID as a field; Under advanced settings enable Aggregation for the View. For the NID value use the Count aggregation.
Add a contextual filter to this view based on the school name.
Save your view.

Then in your parent view:

After installing Views Field View. Add a new Field your view of Global: View.
select the view named sum_rooms_assigned_teachers. Provide the contextual filter to the view of your school name or ID; it will look like [!field_school_entityreference_id] or something similiar.
Give this field whatever label you want.

Your main view should now show a room count. In the helper view you may want to deny access to anyone but the Administrator or other role -- as this is simply a helper view for this other view; and rather useless by itself.


Using drush @self alias returns nothing According to the documentation for drush (version 5.9) it has a built in alias called @self.

When I attempt to use the @self alias in a command such as:

drush site-alias @self

Nothing is returned. However, using aliases I've defined in my aliases.drushrc.php the commands work as expected.

Does anyone have any ideas as to what might be going on?

In order to use the @self alias, Drush must be able to detect and bootstrap your Drupal site based on the current working directory.  If your settings.php file is in the 'default' directory, then you may cd to your Drupal root directory, or any directory below it, and @self will work.  If your settings.php is in some other directory, then you must either cd to the directory that the settings.php file is in, or provide a --uri option to Drush.

You can also use @self without changing your working directory if you supply --root and --uri options to Drush.


global static variable to be accessed in comment.tpl.php, node.tpl.php and in page.tpl.php I wanted to show some ads inside the content (node, comments) and body.
I decided to add them using the template by adding some lines to comment.tpl.php, node.tpl.php and page.tpl.php

for example in comment.tpl.php I have:

print render($content);
if($id%3 == 1){
  echo "<iframe width='720' height='80' src='#####'></iframe>";
}

I think this is a good way of adding ads

Now that the ad code is repeated in these 3 files, I want to use a Global static variable so that the ad code can be placed in one place and can be access from these 3 tpl.php files

Can somebody please point me how to do it? Or an alternative Method of achieving it?

You can use preprocess functions to add template variables in Drupal.

For example, you could use a generic preprocess function like

hook_preprocess

And add your variable there.

It will then be available in all the other template files.


error_get_last() returns NULL after valid error in Drush I have the following command callback function defined in my .drush.inc file:

function drush_bv_ftp_products() {
  echo $aadfadf;
  var_dump(error_get_last());
}

Assume hook_drush_command() is properly implemented and has an alias of 'abc'.

When I run drush site.local abc I get NULL for output.  What I would expect to see is similar to:

Array
(
    [type] => 8
    [message] => Undefined variable: aadfadf
    [file] => ...
    [line] => ...
)

I'm running php 5.3.28 so error_get_last is there.  Any thoughts from the Drush masters out there as to what could be going wrong here?

Drush sets an error handler via set_error_handler('drush_error_handler');.  This interferes with the operation of error_get_last()`, as php resets the last error when the error handler is called; error_get_last() always returns NULL with an error handler, even if it is the first function called in the handler.

Since there is no way to disable the Drush error handler, this prevents the use of error_get_last() in Drush command files.  For a quick test, you could always temporarily comment out the call to set_error_handler in Drush.


Push value into array using form I am working on developing a type of bucket that would store my selected content in some sort of data container (I am hoping to store it in an array). The selected data comes from default views, I wrote an handler to add a 'ADD' button to the default view.
I am new to drupal and have very less experience with form api and not really sure how to push/store the selected content.

The following is the handler code:

<?php

 /**
 * @file
 * handler class for the new field 'bucket'
 */

/**
* class definition
*/
  class bucket_views_handler_field_actions extends views_handler_field {
 /**
 * Render function: return html output
 */
  function render($values) {
   //debug ($values);
    $biomaterial_id=$values->biomaterial_id;
    $form=array();
    $form['Add']=array(
     '#type'=>'button',
     '#value'=>'ADD',
     '#access'=>TRUE,
      );
  }

You could try creating a session variable. Taken from this question

You can try this.

function lists_session($key, $value = NULL) {
static $storage;
if ($value) {
$storage[$key] = $value ;
$_SESSION['lists'][$key] = $value ;   // I use 'lists' in case some other module uses 'type' in $_SESSION
}
else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
$storage[$key] = $_SESSION['lists'][$key];
}
return $storage[$key];
}

So, to save a variable in Session:

lists_session("s_key", "value");

And to retrieve the value, just use:

$myVar = lists_session("s_key");

EDIT

To attach the above to the form submit (Add), try the following, taken from this question. You can do this in template.php with THEMENAME_form_alter if you prefer not to create a new module, but it would be theme specific if you do that.

You will need to create a custom module with hook_form_alter() implementation.

function [YOUR_MODULE]_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == "YOUR_FORM_ID")
  {
    // target the submit button and add a new submission callback routine to the form
    $form['#submit'][] = 'YOUR_SUBMISSION_CALLBACK_FUNCTION';
  }
}

The code above will execute your new callback function YOUR_SUBMISSION_CALLBACK_FUNCTION AFTER the form's default callback function.

To make your new callback function called BEFORE the form's default callback function, use the following code instead of the giving above:

array_unshift($form['#submit'], 'YOUR_SUBMISSION_CALLBACK_FUNCTION');

To cancel the form's default callback function and force it to use your function ONLY, use the code below

$form['#submit'] = array('YOUR_SUBMISSION_CALLBACK_FUNCTION');


Problem with Node module on website Please bear with me on this one, as I am a complete newbie with Drupal, and am helping out a client on this one, so am trying to relay the problem they are having.

It appears that they are having trouble with a Node module, this module is used to add events and sell tickets to these events.

Currently when a new event is added by 'admin' it is only viewable by admin, so anonymous users can't see any see any events events. We think it has something to do with permissions or a between some modules, but as a say not really understanding the product i'm struggling to get to the bottom of it.

One of our developers also thinks that it could be something relating to a field used in the event, and user doesn’t have access to read this field (permissions).

It seems that for each there is a diferent permision filed in permisions section in admin panel.

Has anyone had this trouble before? Any help, ideas or even questions on this very  welcome. We may have to get someone in to finish this job off.

I may also have most of this backwards, so please ask if you need anymore info, or what I should look at and I can supply this straight back to you.

Thanks for the patience :)

There are a number of permissions that could be affecting this.

First off, node permissions.  The most important one here is 'access content,' so make sure anonymous users can do that. After that, they can be set up so different users in different roles can create, delete and/or edit nodes.

Given that they aren't trying to do any of this, I doubt it's related to these node permissions, so let's go drill down a granularity level and look at permissions on fields in the nodes themselves.  Here, permissions can be set on edit and view.  Given they aren't trying to edit a node, just look at it, I'd look at the view permissions.

Assuming 'admin' is uid 1, s/he can do anything, so look for fields that aren't viewable by the more casual user/role.  Somewhere in there as you surmised above is the field that this module needs to show itself.  (Oh, also, if you are using imagecache, make sure its permissions are set up as well)


How to store user specific data after registration? Let us say you want to collect a bit more information about users during registration.
For example, instead of just username and email, I also want place of residenc. How do I collect and store this data per user?  At the end of the day I want to end up with place of residence of each user by doing an easy query.

PS: Currently, I have added extra fields to the form user_register_form, but I don't know how to associate this data with my new user because I don't have the new user id.

What is the right approach? Because I think this should be a trivial Drupal exercise, but am sweating :).

I am using Drupal 7.1.

// implements hook_form_alter()
// user-register-form id the id in html but id that works in php is user_register_form
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
      $form['placeofresidence']= array(
        '#title'=>'where do you stay?',
        '#type' => 'textfield',
        '#required' => true,
      );
      $form['#submit'][]='mycustommodule_submit'; //add to callback submit list
      break;
  }
}

function mycustommodule_submit($form, &$form_state) {
  $stayswhere=$form_state['values']['placeofresidence']; // how do I associate this with new user?
}

users are a "fieldable entity" in Drupal 7. Just go to "configuration / people / account settings / manage fields" and add your fields. Make sure to check the "Display on user registration form" box.

For the "place of residence" I recommend the addressfield or location modules.


Grouping the nodes based on the taxonomy terms A specific taxonomy page should display its description as well as the grouped teasers of the pages with the other taxonomy terms.
For example: An article (Article1) is having 2 taxonomy terms : Accounting, Finance. Another article (Article2) has 2 taxonomy terms: Accounting, Money.

My output when I see the Accounting term page (Example: http://www.myexample.com/group/accounting), the page output will contain the Accounting term description and the grouping of the remaining Taxonomy terms that the articles are linked to.

Finance

Article 1
Article x

Money

Article 2
Article y

I need a little customization here by grouping the articles with the remaining Taxonomy terms. I tried Views with Taxonomy Display and Taxonomy Views Integrator. But, couldn't organize the output.

Is there a way to alter the output of the 3 different taxonomy terms using Views?

Create a view add two fields:

Node title
Taxonomy Term

Follow these steps :

Taxonomy Term" field to "Exclude from display
Set format = unformatted list in Format section
Set group Field as taxonomy term


Do new routes require a static first portion? Using mymodule.routing.yml, I can successfully create a custom route at /foo/{bar}/{baz}, but I cannot use /{bar}/{baz} or /{bar}/foo/{baz} as path for a route; they just return a 404 error.

Why? Is there any way to create a route for /{bar}/{baz} (with strict requirements for bar)?

I've read the entirety of the routing API and I can't seem to find any answers.

In the routing system you can't do this. What you can do is path aliasing.

Inbound: /{bar}/foo/{baz} -> /foo/{bar}/{baz}

Outbound: /foo/{bar}/{baz} -> /{bar}/foo/{baz}

You need a pattern to apply a regular expression on the path inbound, so /{bar}/{baz} is only possible if the parameters themselves have a distinctive pattern.

I didn't find a tutorial how to build a path processor, but you can use the
PathProcessorFront class as example.

Register both as tagged service in the .services.yml file for the module.

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


Commerce Kickstart 2 Collection - Displaying too much information I'm having an issue, for some reason, the collection page is displaying the product detail, included with the add to cart. Where would I adjust this setting? I was comparing with another product variation, and can't seem to fix this issue.

I was able to finally fix this. I fixed this issue by going into Content Types, and just adjusted the Manage Display setting under Product List.


Webform doesn't send email using MIME Mail My webform forms doesn't send the email if I set Site-wide default MailSystemInterface class to MimeMailSystem.

It works fine if I set Site-wide default MailSystemInterface class  to DefaultMailSystem

Take a look at my captures:

I was working fine until yesterday, then all the sudden this problem is happening.

How can I trace this?

I had a similar, slightly different, issue after updating from webform version 7.x.3.25 to 7.x.3.27

WORKED FOR ME:

Upgrade to webform 7.x.4-branch


Updates for custom module not showing in update.php list I've created a custom module for my Drupal 7 website, under sites/all/modules/custom/tm_general which has the following updates in the tm_general.install (please see image attached).

The site is being installed from scratch, meaning the DB is empty when installing. After installation, I have enabled the custom module through the UI.

The problem I'm encountering is that when visiting mysite.local/update.php the updates won't show up. It says No pending updates.

What am I missing?

Thanks a lot in advanced!

The 'system' table in your db contains the current "version" of modules, so I would check there first.

Also, if these modules are dependencies, you can just include them in your module.info (writing module .info files in Drupal 7) by simply adding

dependencies[] = devel
dependencies[] = views

and so on.


Hide a field for that particular row based on value from custom table I have a custom module where in a user requests access to view a node. I have a view page which currently lists all nodes and has a button "Request Access" to it. When the user clicks on it, an entry for the same is captured in my custom table for that node id. Then the admin approves or rejects it. If it is approved i want the user to view "Approved" status for that node id and for others it should show "Request Access". The name of my custom table is access_node_custom. I tried using the below code (with some static data):

function access_node_custom_views_pre_render(&$view) {
    if ($view->name !== 'access_node_custom'  || $view->current_display !== 'page_access_node_custom') {
        return;
    }

    $results = &$view->result;
    foreach ($results as $key => $result) {
        if($result->nid == 656){
            $view->field['request_access']->options['exclude'] = TRUE; //Hide request access since this is already approved
        }
    }
}

The problem with this is that it hides for every row on that page. I am fairly new to drupal so I don't know how can i do this. Is it possible to use relationship? or query alter?

Thank you.

$view->field['request_access']->options['exclude'] = TRUE;

Exclude will always exclude the field for every single row.

What you need to do is set it to null or empty ''

$result->field_request_access = null; // hide request

A possible downfall is that a user could guess, or have someone tell them the direct link, and still be able to see /node/656.

Thus; in addition, to what you're already doing, should also use hook_node_access

/*
 * Implements hook_node_access()
 */
function access_node_custom_node_access($node, $op, $account) {
  if($node->nid == 656 && $op == 'view'){
    // some db_query here
    if ($something_is_true) {
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
}

If the person does not have access, the above will automatically hide any "view" link in Views.


How to enable Text formats after disabling it in Drupal? In attempting to get pictures inline with text, I did the following:

Configuration>> content authoring >> text formats>> and disabled Full HTML and Filtered HTML formats.

This clearly did not give me the desired result as now all text is no longer visible on my Drupal website.

How do I re-enable this text on the website?

This looks like a bug in Drupal. Anyway the following method works.

Go to your Drupal database (I use phpMyAdmin)
Browse table called 'filter_format'
There You can see list of input formats.  In  'status' column  change
(update) status form 0 to 1. (Disabled status will have 0. So
change to 1 to enable)
Clear your cache. (configuration >> development >> performance)

That's it. Now  all 'Text formats' will be visible under that configuration page.

It works, I tested it :)


Compare specific fields of two nodes side-by-side I have a content type consisting of 15 large text areas fields.

I would like to be able to select specific fields (or maybe just one for start) and review the content of two nodes side-by-side with the selected fields aligned horizontally (in a table maybe). Also these fields should be available for inline edit using the Editable Fields module, so I need this to be done inside a view which would allow me to use the editable field formatter.

I've checked the Node Compare module which is great, but it doesn't allow the user to check which fields he'd like to review side-by-side. I need to be able to filter those by exposed filters or something. Furthermore Node Compare uses a custom view that doesn't allow me to use the editable formatter.

Any ideas how could I achieve this?

Install and configure Node Compare module.

Some more details about this module (from its project page):

  The module to provide node comparison functionality on user request.
  It compares the values of the fields of nodes.


jQuery effect after pressing button Drupal 6. I try to add jquerry effect after pressing button

$(function(){
    $('.node-add-to-cart').click(function() {
      $(".prod-pic").effect("transfer", { to: $("#block-uc_cart-0") }, 1000);
    });
});

But I get error object# has no method 'effect'.
I created a custom js file with this code and put a link to the template.php using drupal_add_js.
According to status report Jquerry UI 1.6 is installed. However, when inspecting html code, among scripts there is no jquery.ui loaded. Should I call it from my custom js file?

Drupal 6 version of JQuery is 1.26 and after install jquery_update it will be updrade to 1.3.2

If you want persist use jquery method likes effect maybe this article,but I think you can't using jquery 1.6 or upper in Drupal 6 .( I don't told you it's impossible but achieve this job is more struggle and maybe cause problem in other part of your site ).

maybe this question be helpful for you.


Cache for logged-in user? I have created simple form and page to list records on form via Custom Drupal 8 Module. This form is accessible to only logged-in users with some specific role. It looks like screenshot. Whenever I submit new entry it lists record in via theme table for admin user but it does not appear for other logged-in users until I clear cache manually.

Please suggest, Thanks!

To display Records :

<?php

namespace Drupal\custom_form\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayRecords extends ControllerBase {

  public function DisplayCustomRecords() {

    // Display theme table

    $table_header = [
      'name' => t('Name'),
      'mobilenumber' => t('Phone Number'),
      'email' => t('Email'),
      'age' => t('Age'),
      'gender' => t('Gender')
    ];

    $results = \Drupal::database()->select('custom_for_data')
      ->fields('custom_for_data', [
        'name',
        'mobilenumber',
        'email',
        'age',
        'gender'
      ])
      ->execute()
      ->fetchAll();

    $rows = array();
    foreach ($results as $res) {
      $formatted_age = \Drupal::service('date.formatter')->format(
        $res->age, 'custom', 'Y-m-d'
      );
      $rows[] = [
        'name' => $res->name,
        'mobilenumber' => $res->mobilenumber,
        'email' => $res->email,
        'age' => $formatted_age,
        'gender' => $res->gender
      ];
    }

    $form['table'] = [
      '#type' => 'table',
      '#header' => $table_header,
      '#rows' => $rows,
      '#empty' => t('No users found'),
    ];

    return $form;

  }

}

Short version: You need to define a cache tag that you can invalidate when a record is created, updated or deleted.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for a lot of documentation on this.

I'd also recommend to look into using an entity type for this instead of a custom table. A bit of effort at first, but you get a ton of functionality with that, including default cache tags and for example views integration, so you can build searchable, sortable listings like that through views.


Add translation files to custom module doesn't work I've created translations files with poedit called nl_NL.mo and nl_NL.po and added them to a 'translations' folder within my custom module.

Now when I try to re-install my module; the translation isn't being imported.

Could this be because my default language is NL or is some other issue?

You might need to uninstall the module completely and reinstall it again, in order to be able to import the translations. Otherwise, they are not picked up automatically. There are a couple of threads in the Drupal forums mentioning this issue: https://www.drupal.org/node/220341 , https://www.drupal.org/node/435706#comment-2711736

Hope that helps,


Restricting Field Access by Role I'm working on a site in which I'd like anon users to be able to create nodes of a certain type, but I only want them to be able to see/edit some of the fields on that content type.

I can't go into details just yet, but the goal of the site is to crowd-source the collection of information and then have a few administrators who will approve and groom the data. That's why I want anon users to be able to create nodes and only access a few fields. Then admins will be able to supplement that data by adding values into the other fields and then publish that node.

How do I restrict access to fields basing on the roles the users have?

You want the Field Permissions module, it does exactly that:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

It gives you granular access control based on role for every field, e.g.:


Check if form field contains particular value, if so, do not allow user save I am having a lot of spam signups on a drupal site. I am even using captcha and mollum, but still getting a lot. I have a field that asks 'why are you signing up?' which, when a human user / non-signup signs up, is filled with proper information, however, it seems there are a lot of robots / fake sign ups that all fill the field with a value which is just the literal path to the node field value like why_are_you_Signing_up[und][0][value]. It is always the same. So I thought I could check for this value and cancel the sign up.
I have looked at hook_user_presave and hook_save. These look like good starting points.

hope I'm not stating the obvious but if your form resides in a template or module you can add server-side validation to the form values using a function like:

function your_form_validate($form, &$form_state) {
  if ($form_state['values']['your_form_field_name']) {
    // Perform PHP validation, and return FALSE if rejected.
  }
}

Also, see Form generation.


Can't get neither CKEditor nor WYSIGYG Module to work! I have the Drupal 7.21 installation and I am using a downloaded theme (premium responsive). I am trying to install an editor for my website entries but I have not been able to get it to work. This is the information on the two I have tried:

CKEditor version 4.0.2 and CKEditor Module 7.x-1.12
OR
WYSIWYG Module version 7.x-2.2 with TinyMCE 3.5.8

I have carefully checked the installation instructions for all and they are correctly installed. I have been able to enable both (not at the same time, obviously) without any errors. However, when I try to add content I don't see the toolbars, only the plain white box.

So far it has been very frustrating. I have checked every thread that describes similar problems and tried every suggestion but it just won't work.

Can anyone provide a suggestion?

Thanks!

Go to /admin/config/content/formats and make sure you have a text format for the role(s) you are working with.
Go to /admin/config/content/wysiwyg and make sure you have added buttons to the editor (click on "Edit" and then under Buttons & Plugins).


Get last accessed timestamp value of a user in Drupal 8 Im trying to display the last accessed field when a user logs in.
For this I tried using User::getLastLoginTime() .
But this returns a fatal error saying

PHP Fatal error:  Call to undefined method Drupal\customize_block\Plugin\Block\ContractDetails::get() in /var/www/html/core/modules/user/src/Entity/User.php on line 265

Here is my block ,in my custom module:

/**
 * Provides a 'Customized contract' Block
 *
 * @Block(
 *   id = "customer_info",
 *   label = @Translation("Customer and contract info"),
 *   module = "user",
 *   context = {
 *     "current_user" = @ContextDefinition("entity:user", label = @Translation("Current User"))
 *   }
 * )
namespace Drupal\customize_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class ContractInfo extends BlockBase {
 public function build() {
 $output='';
 global $base_url;
 $current_user = $this->getContext('current_user');
 $output.='<div>' . $current_user -> contextData . '</div>';

     return array(
      '#markup' => $output,
      '#cache' => array(
     'contexts' => array('url'),
      ),
    );
  }
}

Am I calling this method correct way?

getLastLoginTime is not a static method so you would not be able to call it statically like that. You need to get the current user object from a couple of different ways:

1. Use the Drupal::currentUser.

This is easy, but not recommended to tightly-couple your block.

2. Inject the current_user service into your Block by implementing ContainerFactoryPluginInterface.

The disadvantage is that this also has a dependency on the container, but can be mocked.

3. Use the Context system because blocks extend ContextAwarePluginBase.

This is the recommended option in my opinion because there is already a current user context (as well as node contexts) for blocks.

 * @Block(
 *   ...
 *   context = {
 *     "current_user" = @ContextDefinition("type" = "entity:user", "label" => @Translation("Current User")
 *   }
 * )

Then $current_user = $this->getContext('current_user') will get the current user.

Unfortunately there is not a handbook page about using contexts so documentation is relegated to guessing things based on the change record, which itself was no longer accurate at the time of writing this answer.

Interestingly some IDEs (cough PhpStorm 10 cough) choke on the above annotation syntax because.

Finally...

You should look at the documentation for render arrays and the changes to make markup safe.


Help on error Notice on Modules page I have the following Notices and Warning on the Modules page:

  Notice: Undefined index: name in system_sort_modules_by_info_name()
  (line 951 of /var/www/vhosts/site
  name/httpdocs/modules/system/system.admin.inc). Warning: uasort()
  [function.uasort]: Array was modified by the user comparison function
  in system_modules() (line 802 of /var/www/vhosts/site
  name/httpdocs/modules/system/system.admin.inc). Notice: Undefined
  index: name in _system_modules_build_row() (line 988 of
  /var/www/vhosts/site name/httpdocs/modules/system/system.admin.inc).

I have searched on the internet for examples of this issue and found some, but the answers didn't help me, because it was about an error in a module i didn't have installed or the answer was too complex for me. Could anyone help me with above error?

I don't even know to which module it is related.

This seems to be related to this issue and there is available patch file for Drupal 7 and UTF-8 file encoding.

So your options are:

Disable the notice in site settings or in PHP configuration.
Wait until patch is committed and upgrade your Drupal core.
Disable faulty module.
Apply the patch your-self.
Apply patch manually by opening it and check the changes:

--- a/includes/common.inc
+++ b/includes/common.inc
@@ -7369,7 +7369,8 @@ function drupal_parse_info_format($data) {
   $constants = get_defined_constants();

   if (preg_match_all('
-    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
+    @^(?:\xEF\xBB\xBF)?             # Check for UTF-8 byte order mark and remove it
+    \s*                             # Start at the beginning of a line, ignoring leading whitespace

where on the top is the file to edit which is includes/common.inc (ignore a/b), 3rd line is the line number, then remove the lines which starts with minus and replace them these with pluses (without plus signs). If you got the error, then double check your syntax or revert your file to the previous version.


Check for string in URL How can I check for a specific directory in my URL? I need to display an image if I'm in http://www.mywebsite.com/displayimg/mypage but not if I'm in http://www.mywebsite.com/mypage... would it be something involving drupal_get_path?

You can use arg to check for URL arguments. In your case, the second argument has to be empty, so you can try something like this:

if (arg(0) == 'displayimg' && arg(1) == 'mypage') {
  // Do something meaningful.
}


How to unflag all messages when a users visits the Message page? I am using the Message module in combination with the Flag module in order to build a simple notifications system for my site.

More specifically I have created a page in Views showing all (new) messages for the current user. The page is accessible through a menu link (called "Messages") in the front page. I have also created a message flag so users can flag/unflag there messages as new/old ones.

But instead of forcing the user to manually flag/unflag his messages, I would like all messages to automatically be unflagged (i.e. become old) when the user visits the messages page (or a certain context in general).

Any hints on how to achieve this?

This sounds like a job for Javascript

Flags has an option to allow the link to use AJAX. So I would dig into the Javascript that the flags modules uses and then create your own script that walks over and triggers each link when the page is loaded.


Show block in particular nodes having some string in title I have a block and I need to show this block only in some situations.
For example if title of node includes "abc", block will be visible else it won't.
From visibility settings of block I use this code snippet:

<?php
$match = FALSE;

$url = request_uri();
if (strpos($url, "myword")) {
  $match = TRUE;
}
?>

I'm sure that "myword" is included in full URL of node.
I tried to debug it by adding "echo $url" but it didn't write this line into page.

How can I solve this?

edit: in last line i forgot to add "return $match;" which returned always false.

Try:

if (strpos($url, 'myword') !== FALSE) {
  $match = TRUE;
}

strpos() returns the zero-based index of the first occurrence of the substring.

So if "myword" is at the start of the URI string strpos() will return 0, and since 0 == FALSE in terms of a conditional, it will fail.

I've just tested your code and it works fine with the slight change.


Dim background elements when displaying submenu I am developing a site with Drupal 7 and the requirement that I need to implement is that when a sub-menu is being displayed from the main navigation bar, the rest of the site (all the elements behind the sub-menu) is dimmed (just like when displaying a modal dialog box with JQuery).

I was wonder how I would go about accomplishing the same effect using Drupal's default menu system?

Thanks.

There's a bunch of options.  jQuery is probably the easiest but I could envision a way of doing it with CSS only using some combination of clever sibling and pseudo-class selectors.  You could also do it using an overlay element and some z-index work. Or just use JS/jQuery to dim the other element's opacity either using animate or adding a class that has an opacity transition.  The best choice depends on your requirements and how your HTML is structured.

But the question is a little vague and not particularly Drupal related.  If you want do the last case above, just do on('hover', function() ) {} and set the opacity / class of the elements to dim.


Where is my AJAX call going? I'm very new to Drupal so I hope you'll forgive the silly question: where is the server-side code for my AJAX call?

I've read the documentation on the Ajax Framework, but I can't find any instances of #ajax or callback in my code.

Capturing the /system/ajax request yields some interesting form variables:

form_build_id: form-cBW24WCJRFxgW5TMHSa-9hQ_tVenToYkx2ObzTgnQKM
form_id: commerce_checkout_form_ip_info
_triggering_element_name: ief-36484c27df589bd88b009b3e91d079f24f9559cc-add
_triggering_element_value: %2B+ADD+MEMBER

(There are lots of others, but those seem like the relevant ones.)  I gather that this is a form using the Commerce module, but that doesn't help me much.

Finally, here's the line of code setting up the value of the button that triggers the AJAX call:

$form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']['#value'] = "+ ADD MEMBER";

Hopefully this is enough information to determine what's happening here.

IEF = Inline Entity Form; you should find what you're looking for in that module. If you're new to Drupal the layers of abstraction might make it difficult to understand what's going on though. If there's something in particular you're looking to find out how to alter or understand just update the question.

If you install the Devel module and add

dpm($form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']);

to your alter hook you should find the #ajax property.


Teaser is missing CKEditor when uncollapsed I have text with summary fields on my entity and for some reason the ckeditor is present only on the body, not on the teaser if I uncollpse it. What could be the issue?

Never use "Text and summary" fields. It's a sad/unfortunate fact that Drupal 8 didn't manage to remove them.

Instead, create a separate (independent) summary field.


Validation and Setting value for Multi-value fields Consider for a content type, there is a text field with multiple values capability activated.

How can I check its values by $form_state inside the Validate/Submit function?
How can I set its values by $form_state inside the Validate/Submit function?

The single code line for each of them would be enough for me to see, Thanks.

Further discussion:

I need to set/check the MULTI-VALUE fields' values. It's related to the DELTA value and ... but I don't know how clearly I can do it!

Clearly, for any multi-value field there is a delta value inside each fields' table in Drupal Database, which corresponds to the index of the value for that entity instance.

According to this knowledge, the structure of the form_state variable for a multi-value field with two values (e.g. X and Y) is:

[field_FIELD_NAME] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => X
                                    [_weight] => 0
                                )
                            [1] => Array
                                (
                                    [value] => Y
                                    [_weight] => 0
                                )

                            [add_more] => Add another item
                        )

                )

[0] and [1] are delta values for each value of this filed in the corresponding entity instance. For setting the values of a multi-value filed in FORM submit/validate hook, you should do as follows (consider again we have two values X and Y):

$form_state['values']['field_FIELD_NAME']['und'][0]=array("value"=>'X',"_weight"=>0);
$form_state['values']['field_FIELD_NAME']['und'][1]=array("value"=>'Y',"_weight"=>1);

The above lines ought to be written inside the VALIDATE hook.

For reading values for validation, do as follows:

$values=$form_state['values']['field_FIELD_NAME']['und'];

foreach ($values as $key => $value) {
  if($value['value']...
}


Multi-site, shared users, paid access I'm working on a project that involves multi-sites in Drupal 8. The client specifically wants  to have shared user accounts across all 4-5 sites. As of now the sites share a codebase but not a shared database. After researching I came across the CAS module. Can CAS allow for multiple logins? When one account is made can other accounts be generated in the other 3-4 Drupal sites? Is there a better way to do this in Drupal 8? Also, the client eventually wants to have paid account registries. For example, a user would pay on one site and get access to all 4-5 sites. IS there any guidance for accomplishing this? If not with CAS what other modules / resources would I need to make this doable in Drupal 8?

So far I've seen sites that offer advice on this but largely with Drupal 7 with out a clear path for doing this in Drupal 8. CAS seemed the most stable option but not sure if it will work. There was also the option of sharing users through shared tables, though this was discouraged in the forums I read. What is the best / proper way to do this in Drupal 8? Or should I go back to Drupal 7?

CAS module is a nice option, and it is quiet stable in D8 (using it in production site since more than a year). Morerover, SSO looks more confortable for users that don't have to reconnect when they jump from one site to another.

You should know that each D8 site will have its own user table created by the CAS/Externalauth modules'stuff.
If you plan to grant different access permissions based on something (many payments methods), imho, you should store these infos somewhere regardless to drupal (more precisly : anywhere your CAS server can retrieve, i have not tryed cas_server). Those could be retrieved in attributes sent during connection according to CAS protocol (CAS parameters).

Note : Given the fact each of you websites store its user table, and do not necessarily know the existence of an user "x" until its first connection to this site, you just have to pay attention on duplicates. Easiest way is probably to use email as UID but you undestand the idea.


How to configure annotator and annotation modules in Drupal 7? I would like to provide an MS Word -like annotations (review comments) functionality in some text areas of my Drupal 7 website.

I have experimented with the co.ment and annotator - annotation Drupal 7 modules, and the second solution seems lighter and more appropriate for my requirements.

Unfortunately there is very poor documentation on the annotator and annotation modules and I cannot configure the storing of my annotations.

I have read the annotator library documentation but I do not know how to implement either the store or authentication and permissions plugins on my Drupal 7 website.

From the Annotator module page, what I understood is that by installing the Store plugin together with the Annotation module you use your own storing and not Annotateit.org service.

I have downloaded and installed the required libraries (annotator and Gettext) and from the Annotator configuration page I have enabled the Store plugin with the default Store url options. But my annotations do not get stored and I do not get any exceptions or other info, so that I can see what is going wrong.

Any suggestions please on what may be missing? I can provide more details where needed.

I stumbled across the same problem today. Proper way to install everything:

Download the annotator libraries in /sites/all/libraries/annotator
Download jquery_update and set jquery v.1.8 to be used
Download and enable the annotator module and its dependencies (e.g. libraries)
Download and enable the annotation module
Do not change any configuration options

For a minimal installation, I have just used the markup and store plugins. Some things that might get in the way of the annotations being saved:

You need to have Clean URLs installed
If Drupal is not installed in the root of your domain (for example if it's in http://example.com/subsite instead of http://example.com) you may have to change the configuration of the store plugin to point at /subsite/annotation/api instead of /annotation/api

You can manage the permissions to create, edit, view or delete annotations through the permission system of the annotation module.

Also, keep in mind, that if you create the annotation while you are browsing node/3 through the URL: http://test.drupal/node/3#overlay-context=node/6, the annotation WILL NOT appear if you visit: http://test.drupal/node/3. That caused me a lot of headaches. You can check whether your annotations have been saved in the admin/content/annotation path.

NOTICE:
When downloading the annotator library from github make sure that you download the annotator-full.1.2.9.zip not annotator.1.2.9.zip.


Export modified Administration Views I am using Aministration Views module to have a custom page for content list. I have added some new columns to the view and now I want to export all that in a Features so I can deploy it on my staging server. The problem is that I just can't export it in a feature, when I create the feature, it is just "empty", there is only a depedancy to admin_views but I can't see changes I have made.

Anyone has a solution for this?

To export a view, go to http://example.org/admin/structure/views/view/your_view/export
Then wrap it into a module using hook_views_default_views() and export that module.

Not the easiest way, but reliable.


Create Text Field Programmatically to Media Type I want to create a text field to videos with code. I have the following in the .install file in a custom module:

function video_update_8101() {
  $field_name = 'field_video_alternative_text';
  // Make sure the field doesn't already exist.
  if (!FieldStorageConfig::loadByName('file', $field_name)) {
    // Create the field.
    $field = FieldStorageConfig::create(array(
      'field_name' => $field_name,
      'type' => 'text',
      'settings' => array('max_length' => 64),
    ));
    $field->save();

    // Create the instance.
    $instance = FieldStorageConfig::create(array(
      'field_name' => $field_name,
      'entity_type' => 'file',
      'bundle' => 'video',
      'label' => 'Alternative tekst',
      'description' => 'En beskrivelse kommer her.',
      'required' => TRUE,
    ));
    $instance->save();
  }
}

I get the following when running update.php

Attempt to create a field storage field_video_alternative_text with no entity_type.                                                                                [error]
Performing emu_video_update_8101                                                                                [ok]
Failed: Attempt to create a field storage field_video_alternative_text with no entity_type.

Furthermore, I want this to happen when I install the module. I suppose it's not at this point?

Edit: I got inspiration from this post: How do programmatically create fields for content types, and ADD them to the the content type form

In Drupal 7 fields were shared across all content types; in Drupal 8 they're shared across a single entity type.

As such you've just missed the entity_type when creating the storage:

$field = FieldStorageConfig::create(array(
  'entity_type' => 'file',
  'field_name' => $field_name,
  'type' => 'text',
  'settings' => array('max_length' => 64),
));

As an aside, hook_update_N is for updates only, those functions won't be executed upon install. The point of them is to allow older versions of the module to get up to date with the current version that they're upgrading to. The initial state of the latest version of the module should reflect the state the older version of the module would be in after the update.

You can use hook_install or config files in config/install/*.yml to perform initial setup of your module upon install.


PDOException on Article page : Base table or view not found In my Drupal site, when I tried to save an article page I'm getting the following error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table  'novitawe_icpasld.field_revision_field_tags' doesn't exist:
  DELETE FROM   {field_revision_field_tags} WHERE (entity_type =
  :db_condition_placeholder_0) AND (entity_id =
  :db_condition_placeholder_1) AND (revision_id =
  :db_condition_placeholder_2) AND (language IN
  (:db_condition_placeholder_3)) ; Array ( [:db_condition_placeholder_0]
  => node [:db_condition_placeholder_1] => 138 [:db_condition_placeholder_2] => 138  [:db_condition_placeholder_3] =>
  und ) in field_sql_storage_field_storage_write() (line 382 of
  /home7/novitawe/public_html/icpasld/modules/field/modules/field_sql_storage/field_sql_storage.module)

Could anyone please let me know how can I solve this issue without affecting any of my DB because this site is live.
.

As per @Triskelion comment:

When you created the 'tags' field, two tables (field_data_field_tags and field_revision_field_tags) were created to hold the information. If the first table is present but the second is not, use a statement like CREATE TABLE field_revision_field_tags AS SELECT * FROM field_data_field_tags; to replace the missing table. If both are missing, then you should restore your database from your latest backup.

If the error is showing, the field has already been created and the database is corrupt. If he tries to recreate the field before trying to recover, he might lose all existing information. Better to begin with the restoration attempt, then move to more drastic measures if restoration is not possible.


how to pass param to js for custom page in drupal 8 ? I want to pass variable to js for my custom page. Tried below code which is working fine with static value. But I m not able do same thing with existing variable of custom template.

    function test_theme($existing, $type, $theme, $path) {
        return [
            'test_template' => [
                'variables' => [
                    'nDetails' => null
                ],
            ],
        ];
    }

 function test_preprocess_page(&$variables) {
        print_r($variables['nDetails']); // its showing empty???
        $routeName = \Drupal::routeMatch()->getRouteName();
        if ($routeName == 'test.content') {
            $variables['#attached']['drupalSettings']['test']['data'] = $variables['nDetails'];
    $variables['#attached']['drupalSettings']['test']['dataa'] = "work fine";
        }
    }

class TestController extends ControllerBase {
    public function content() {
        return [
            '#theme' => 'test_template',
            '#nDetails' => "test1"
        ];
    }

Is something wrong with above code? Or there is another way to pass variable to drupal setting from controller itself?

You only see the variable in the preprocess hook of the custom template hook_preprocess_test_template(). But you don't need a preprocess hook at all, because you can attach the drupal settings in the controller directly:

return [
  '#theme' => 'test_template',
  '#attached' => [
    'drupalSettings' => [
      'test' => [
        'data' => 'test1',
      ],
    ],
  ],
];


Show workbench moderation comments on node view page I use the Workbench modules suite: Users do change the state of content items (moderate) and can enter a comment about that change.

This status change history can be seen in the tab node/node_id/moderation.

I want to include that view at the bottom of every node view page.

Do you have any suggestions how to achieve that?  Maybe the Display Suite module is useful for that (it has some computational field stuff)?

I would achieve this using Computed field Module.

Install Computed field module
Create a new field of type computed
In the field settings, On the Computed code (PHP)

$entity_field[0]['value'] = $entity->log;
Now in manage display make this computed field visible. That's it.

Note: This is just one way of achieving it.

Instead of installing any modules, You can also write tpl file for the particular content type and display the log message.


How do I unhook commerce_kickstart_blog_preprocess_node? I am using Commerce Kickstart 2 with the their blog module, which includes a hook_preprocess_node() I need to short-circuit.

I looked at How to "unhook" a hook from a module? and I thought I could put the following in a module.

function my_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'commerce_kickstart_blog_preprocess_node' && isset($implementations['commerce_kickstart_blog_preprocess_node'])) {
   unset($implementations['commerce_kickstart_blog_preprocess_node']);
  }
}

It doesn't do anything. What am I doing wrong?

$implementations is an array whose keys are the short name of the enabled modules; $hook is the name of the hook, without hook_ nor the short name of the module.

You need to change your code to the following one.

function my_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_node' && isset($implementations['commerce_kickstart_blog'])) {
   unset($implementations['commerce_kickstart_blog']);
  }
}

I assume the short name of your module is my; if it were my_module, then you would need to use the following code, since the hook is hook_module_implements_alter().

function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_node' && isset($implementations['commerce_kickstart_blog'])) {
   unset($implementations['commerce_kickstart_blog']);
  }
}


User List of user roles in List field af a content type I would like to add a new field type in my content type. The field is of the type List(Text) and the possible values should be the list of user roles in the system. Is there a way to do it without creating a custom field type?

You can try using Role Field module..

Project page says

  Role Field provides a field for selecting roles that exist in your
  site.

  Please note that there is no out-of-the-box permissions shenanigans
  going on. It just lets you pick from a list of roles. Although,
  combined with Rules the possibilities are pretty interesting.


What are some ways to tell if you are currently on the same Drupal installation as your code? Currently I have to manage a few servers and there are a bunch of Drupal directories that all look alike. I'm also logged in as admin on the site, but what I want to find out is:

How can I tell if I'm working in the correct directory as the site I'm viewing?
What are some drush commands I can use to tell if I am in fact in the correct directory?

drush status may give you some info that you need, but probably not.

If you have unique site names setup, then this should work:

drush vget site_name

If not, then read on...

Is this a multisite setup?  If so, then the mapping of hostname onto sites/{sitename} will be either fully automatic based on these rules or determined by the configuration in sites.php.

If it's not a multisite setup and you instead have fully separate directories for each site then the mapping of hostname > directory is determined by your vhost setup.

In either case, I don't think there's any drush command that will just spit out which hostname you should be using to access the site based upon the directory you run it in.

Instead, I'd suggest you set up some drush aliases that let you be much more purposeful about running drush commands against a specific directory and hostname.  So, if you have a site at example.com, a simple alias might look like

$aliases['example.com'] = array(
 'root' => '/path/to/example',
 'uri' => 'example.com',
);

Then, anytime you want to run drush commands against example.com it doesn't matter what directory you're in, as long as you have access to drush (stick it in your path) you can run:

drush @example.com arbitrarydrushcommandhere

Take the time to set up your aliases and hopefully you'll be more sane.


Link to content within node, from CKEditor WYSIWYG This seems like it should be fairly simple, but I'm having trouble getting off the ground.

I have a content type "Document". This content type has a field of type File, which allows for uploading PDF's. This content type also has a title, such as "My User Manual".

I want to create a simple CKEditor plugin, similar to LinkIt that will allow a content editor to highlight a piece of text, click a button in CKEditor, search for and select Document content types.

The result will be that the highlighted text will be wrapped in an anchor tag with an href to the file (which comes from the Document > File field).

I know there are modules link IMCE which I can use to link to a file in the sites files, but I'm trying to simplify this a bit, as well as maintain only one file(s). I have also tried Entity Embed, unfortunately, this module embeds content, and doesn't necessarily allow for inline linking.

Thank you in advance for any insight you can provide.

There's an option, under "Url Substitution" for linkit Media matchers that allows exactly this, but for Media entities. It should be fairly straightforward to create a new plugin using Drupal\linkit\Plugin\Linkit\Substitution\Media as a reference. (You should just have to update the plugin definition annotation as well as the getUrl() and isApplicable() methods. Then you can exclude your Document content type from any previous linkit matcher and add a new linkit matcher to your profile that uses your new plugin for Url Substitution type to link to Documents.


Password reset on user_save() issue I used user_save to update the field.
However, whenever I run this function and I log out and try to log back the password doesn't work anymore.I think it cause a change in the password. can anyone help me to get the actual password back?

$existingUser1 = user_load($uid1);
$existingUser1->field_group_id[LANGUAGE_NONE][0]['value'] = $g_id;
user_save((object) array('uid' => $existingUser1->uid), (array) $existingUser1);

You probably want this:

$existingUser1 = user_load($uid1);
$existingUser1->field_group_id[LANGUAGE_NONE][0]['value'] = $g_id;
user_save($existingUser1);

You just need to call user_save() on the user object to save the values after you have changed any fields.


How to change the value of a commerce token? When an order is submitted on our D7 site an email is sent to us with all the details of the order, including the payment method.

I use the token [commerce-order:payment-method] in the commerce email configuration page , which works fine, but I would like to change the value of that token to something that is more readable, like "This order is paid".

This is what I have so far in a custom module:

    function mymodule_tokens_alter(array &$replacements, array $context) {

  if ($context['type'] == 'commerce-order') {
    // Find token starting with commerce-order:payment-method.
    if ($value_tokens = token_find_with_prefix($context['tokens'], 'payment-method')) {
      if (!empty($value_tokens['payment-method']) && $value_tokens['payment-method'] === 'card_payment') {
        $replacements[$value_tokens['payment-method']] = 'This order is paid';
      }
    }
  }
}

The token's value still is card_payment, when the email arrives, so I have probably misunderstood something. Anyone?

token_find_with_prefix() doesn't return, in your case, the [commerce-order:payment-method] token, but tokens like [commerce-order:payment-method:date] or [commerce-order:payment-method:client], if they exist.

The correct code you should use is the following one.

function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method']) && $replacements['payment-method'] == 'card_payment') {
      $replacements['payment-method'] = 'This order is paid';
    }
  }
}

As side note, altering the value returned for the [commerce-order:payment-method] token doesn't alter the value returned for similar tokens like [commerce-order:payment-method-title]. If you need to alter the value returned for [commerce-order:payment-method-title], the code needs to be similar to the following one.

function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method-title']) && $replacements['payment-method-title'] == 'the payment title you want to change') {
      $replacements['payment-method-title'] = 'This order is paid';
    }
  }
}

Remember to change 'the payment title you want to change' with the effective payment title you need to alter, which probably isn't 'card_payment' (but that is something you need to verify).


Configuration settings of Authcache for roles I'm not sure about configuration of roles in Autchcache module, specifically with authenticated user role. I want to enable caching for both anonymous and authenticated users, but I want to exclude from caching some roles (administrator and webmanager). My web has a lot of roles but an authenticated user may has one, two or more of them.
For example, my web has the next roles: anonymous, authenticated, administrator, webmanager, rol1, rol2, rol3, etc. Some users may have some roles: rol3 and rol4, but other users may have only rol1 and rol2, etc. I want cahing for all of them except the ones who has webmanager or administrator.
How should I config this behavior in Authcache module?

Authcache will only attempt to cache a page and deliver a cached page respectively if every single role of the logged in user is authcache enabled.

Consider the following example:

Five roles are defined on the website (including the built-in ones): anonymous, authenticated, customer role 1, customer role 2, administrator.
Three roles are enabled for authcache: anonymous, authenticated, customer role 1
User Customer A has the following role: customer role 1
User Customer B has the following role: customer role 2
User Customer C has the following roles: customer role 1 and customer role 2
User Customer D has no additional roles
User Administrator has the following role: administrator

This will lead to the following behavior:

Authcache will kick in for every anonymous user (anonymous role is authcache enabled).
Authcache will kick in for Customer A (customer role 1 is authcache enabled).
Authcache will not kick in for Customer B (customer role 2 is not authcache enabled).
Authcache will not kick in for Customer C (customer role 2 is not authcache enabled).
Authcache will kick in for Customer D (authenticated is enabled)
Authcache will not kick in for Administrator (administrator role is not authcache enabled).