How to add a "viewed" icon to pages that are visited I have a Drupal 7 site where I have a bunch of videos and I could use a little help with understanding the best way to show a small icon next to my video links after a visitor has viewed it. Is there a way to do this if they are anonymous visitors? My site does not have user accounts. Also, each of my videos are on a separate page and have a unique url.

I've looked briefly into the Flag Module, but I'm not sure if this work work as I don't want viewers to click on anything. I only to track their browsing.

Any help in the right direction would be much appreciated!

In my opinion using a cookie could be a nice way to accomplish that need. (Maybe even the only way).   A quick search came up with the user_cookie_save function >> https://api.drupal.org/api/drupal/modules!user!user.module/function/user_cookie_save/7

Use it to save the cookie with the video URL or another identifier and read that cookie when loading the page and set the viewed flag.


Image link does not href to proper page in multilingual site I am honing my Drupal skills by developing a small website: www.find-word.com. It is multilingual with English and French enabled.

On the top right of the screen, I have two flags. The French flag is a link to the French page, but when I click on it, it displays the English page.

I checked with FireBug, and the href is correct:

When I type the full French URL in my browser, it is converted into the English one.

I have no idea what's happening. Does anyone know what is causing this? Does anyone have ideas, suggestions? Thanks.

Your multilingual detection settings may be configured incorrectly.

On /admin/config/regional/language/configure, make sure URL is at the top of the list and enabled.


Create a view to show users who flagged other users I have created a User flag as Report Abuse. Users may flag other users with this flag. Now i want to create a view where the users who are flagged along with the flagging user are shown. However i am unable to show the flagging user (though i am getting the user id of the flagging user). It should have been quite simple. I have added, i think, the required relationships. Here's a screen shot of the view settings.

Well it was quite easy actually. I just added a field in User:Name and added the relationship as Flag User as the required relationship


Drupal views to display content updated today For a drupal view, I want a filter such that in the block I can see Articles (created with a taxonomy term) either

Created/Posted today
Updated today (might be created earlier)
This is what I've done. I've added filters to the view:

Content: Has taxonomy term (= something)
Content: Published (Yes)
And contextual filters:

Content: Created day [With default value to be Current Date]
Content: Updated day [With default value to be Current Date]
With these settings I'm achieving my purpose of getting the posts which were created today, but the posts which were created earlier and updated today are not being picked.

For the filters all you should need is:

Content: Updated day [With default value to be Current Date]

Because you have the created date filter you are currently only getting nodes created today.


How do I create a custom search block? I want to add in my D7 installation a search field inside a special part of the page, and I don´t want to use the default search block (as it will be harder to theme, this box I have already worked on it).

Naturally, if I just type:

<form><input type="text" placeholder="Search"></form>

it won´t work.

What else does this need to actually act like the default search form in the search block? I know there´s this Custom Search module, but I think that I shouldn´t install yet another module for this simple functionality.

Thanks!!

You could simply call drupal_get_form() on the search form_id, which I think is - either search_block_form or search_form

And use drupal_render() on the returned array.

  print drupal_render(drupal_get_form('search_block_form'));

Though I might be wrong about the drupal_render() part, yet it seems to me since the drupal_get_form() returns an array drupal_render should be used on it.

Also this page might be helpful too - http://data.agaric.com/print-form-such-search-form-anywhere-drupal

Hope that helps.


How to properly skip apostrophe in db_select? In my mysql database I have texts full of apostropes which are used as stress marks. I need to implement keyword search ignoring these marks.

I tested it first by using direct sql in PhpMyAdmin:

SELECT * FROM `drupal_corpus_text` WHERE replace(text, "'", "") LIKE "%sinka%"

It perfectly finds the record containing sin'ka.

But I cannot figure how to do it using Drupal features.

Here is what I try to do:

  $apostrophe = "'";
  $query = db_select('corpus_text', 'n')
    ->fields('n', array('text_id', 'speaker', 'text'))
    ->condition('n.text', '%' . db_like($key_search) . '%', 'LIKE')
    ->orderBy('speaker', 'ASC');
  $query->addExpression('REPLACE(n.text, "'.$apostrophe.'", "")');
  $query->execute();

And here is the error I get:

PDOException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column ''' in 'field list':
SELECT n.text_id AS text_id, n.speaker AS speaker, n.text AS text,
REPLACE(n.text, "'", "") AS expression FROM {corpus_text} n
WHERE (n.text LIKE :db_condition_placeholder_0 ESCAPE '\\') ORDER BY speaker ASC

I cannot figure out how I must properly use all the quotes and the apostrophe mark to make it work.

The symbol used in those texts is U+0027.

There are a couple of points here:

Your Drupal query is wrong insofar as it wouldn't produce your example SQL. You don't need to add an expression, rather a where clause
Quotes are fun in MySQL (see SQL modes). Your default mode would appear to be ANSI_QUOTES, which means:

  Treat “"” as an identifier quote character (like the “`” quote character) and not as a string quote character.

Which explains why MySQL is trying to interpret the single quote as a column name. PMA probably sets a different mode per-query, so the same SQL works in that environment.

Taking those into account, this is more like what you're hoping for:

$query = db_select('corpus_text', 'n')
  ->fields('n', array('text_id', 'speaker', 'text'))
  ->where("REPLACE(n.text, '''', '') LIKE :search", array(':search' => '%' . db_like($key_search) . '%'))
  ->orderBy('speaker', 'ASC');

Which produces:

SELECT  n.text_id AS text_id, n.speaker AS speaker, n.text AS text
FROM
{corpus_text} n
WHERE  (REPLACE(n.text, '''', '') LIKE :search)
ORDER BY speaker ASC

Notice that the single quote is escaped with two single quotes, MySQL's way of handling this situation.


Drupal 6 (basic): Change Login Page I want to change default login page to html login page because I like the theme (bought theme but still in html). After googling:
1. I use bluemarine theme,  as a start i modify page.tpl.php and replace all html parts
2. Place assets folder in the "themes/bluemarine" folder and replace "assets/.." to "themes/bluemarine/assets/..", until this step login page has been changed flawlessly

But, I don't know how to routing login page to normal destination. In the html code in point 1, I changed this:

"<form class="login-form" action="index.html" method="post">

to this one:

<form class="login-form" action="?q=dashboard" method="post">

Because I have a custom module called dashboard.

Please help me, thanks before...

You shouldn't be replacing Drupal form code with static HTML code for various reasons. You can redirect users to specific URLs by using Rules or actions/triggers:

https://www.drupal.org/node/683696


Adding own variables on user registration to created user I want to add additional informations to a user on registration.
I have added the fields accountID and clanID to the user .
On registration i load these information according to his entered name from another webpage and i want to have these fields added to the user.

My question is, how can i add these additional values to the fields programmatically?

How about using the Profile 2 module for this? Exceerpt from its project page:

  Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity ... leverage the power of fields!

Refer to this video for an introduction to Profile 2 also.

Maybe you also want to consider something like the answer to How to display a profile form using profile2 module ?


Save customer information at checkout My customers are required to provide an address at checkout (Shipping information pane). They can also create an account after checkout is complete (Guest registration after checkout pane).
But the Customer information / Address form is empty:

Is this normal behavior? Is it not supposed to pre-fill the form with the shipping info the customer provided during checkout? I couldn't find any option in Commerce settings.
Any idea on how I could make this happen? Do I need to implement it by myself?

Drupal core: 8.9.3
Commerce: 8.x-2.20

Not sure this would be the recommended way but I got it working using hook_form_alter. Customers start by filling their shipping address at step 1 (required) and on complete step, I grab this shipping address and copy it to the customer_information address field on guest registration, so the customers don't need to fill the same address again. In case the customer address would be different, it can be modified at this step.
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Commerce checkout form
  if ($form_id === 'commerce_checkout_flow_multistep_default') {

    // Multistep "complete" step
    if ($form['#step_id'] === 'complete') {

      // Get shipping address and copy it to customer profile address
      $profiles = $form_state->getFormObject()->getOrder()->collectProfiles();
      $shipping_address = $profiles['shipping']->address->getValue();
      $form['completion_register']['customer_profiles']['widget'][0]['entity']['address']['widget'][0]['address']['#default_value'] = reset($shipping_address);
    }
  }
}


Drupal 7 chosen module use ajax to fill the select I have two select elements and depending on what I select in the first select element second should fill from ajax call. First one is the simple select second one use chosen. The problem is if I fill .chosen-results ul with li results in jQuery and press on select elemnt it clears all ul.
    'purchase_type' => [
        '#type' => 'select',
        '#options' => _purchases_fill_type_options(),
        '#attributes' => [
          'class' => ['purchases-funds-report-item-type'],
        ],
        '#empty_option' => t('Select type'),
        '#empty_value' => '',
        '#required' => TRUE,
        '#title_display' => 'invisible',
        '#default_value' => '',
        '#cell_attributes' => [
          'class' => ['purchasetype'],
        ],
      ],
      'account_name' => [
        '#type' => 'select',
        '#options' => [],
        '#empty_option' => t('Select account'),
        '#required' => TRUE,
//        '#chosen' => TRUE,
        '#title_display' => 'invisible',
        '#default_value' => '',
        '#attributes' => [
          'class' => [
            'purchases-funds-report-account-name',
            'common-select-report',
          ],
        ],
        '#cell_attributes' => [
          'class' => ['accountname'],
        ],
      ],

Chosen is commented because I initiate it from jQuery adding class on it and sending to attachBehaviors because these rows are added dinamicly:
$('#purchases-report-funds-edit-form', context).on("gridTableRowAdd", 'tr', function() {
      $(this).find('.accountname select').addClass('chosen-enable');
      Drupal.attachBehaviors(this, Drupal.settings);
    });

And the result of ajax :
var li_options = ['
' + Drupal.t('Select account') + '
'];
$.each(data, function (i, value) {
            li_options.push('
' + value + '
');
          });
$this.parents('tr').find('.chosen-results').html(li_options.join(''));

When I press first select and populate chosen select:

Then I press chosen select and it clears:

This approach is working fine when chosen select options are defined from php code and not dynamically added.
My question is there any event that I should fire on that the list was changed so it doesn't clear it, or another way it can be solved?

I'm not completely sure about this, but have you tried triggering "chosen:updated" after updating the options? See Updating Chosen Dynamically

$("#form_field").trigger("chosen:updated");


How do I count multifield for body of block? So I have a custom template for the custom block and I can print each one using the following code.

Body 1: {{content.body.0}}
Body 2: {{content.body.1}}

I need to know how many there are. I tried a whole bunch of variations of {{ content.body | length }} or {{ content.body.getvalue | length }} but nothing is working.

My goal is to add responsive grid support depending on how many bodies there are. How can I achieve this?

Use this in your block.html.twig template:

 {{ content.body['#items'].getvalue|length }}

Although to access the individual items, it may be better to create a field template such as
field--node--body.html.twig

then you can do

{{ items|length }}

in that template.


Translate string in javascript There is a string which gets displayed in the mobile menu.

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>Navigate...</option>', $submenu = $mainList.find("ul").parent();

I want to make this string translatable using t() function. So edited the JS file like this:

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
}, $mainNav = $('#navigation'), $mainList  = $mainNav.find('ul').eq(0), optionsList = '<option value="" selected>'.t('Navigate...').'</option>', $submenu = $mainList.find("ul").parent();

After that the string was available for translation but the menu option was missing from the mobile view. Is there any solution for this? Or am I doing any mistake?

t() is a PHP function. You are looking for Drupal.t() which is the equivalent function Drupal makes available for JavaScript.

These are some example of how Drupal.t() and Drupal.formatPlural() can be used in JavaScript.

var comments = Drupal.t('Comments');
var commentsOnType = Drupal.t('Comments to @type posts', {'@type': typeName});
var commentCount = Drupal.formatPlural(count, '1 comment', '@count comments');
var commentCountOnType = Drupal.formatPlural(count, '1 comment on @type posts', '@count comments on @type posts', {'@type': typeName});

Notice what reported in Translating strings in JavaScript:

For performance reasons, Drupal caches the JavaScript files it has parsed. So, when you add or change strings in a JavaScript file, you have to clear the cache to have Drupal pick up the new strings and make them available for translation.
Automatic extraction does not work for packed JavaScript files. For this reason, module authors should only include unpacked versions of their JavaScript files. Drupal's JavaScript aggregator will create a packed version from these files anyway.

Just replace t() with Drupal.t(), and you are done.

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
};
var $mainNav = $('#navigation');
var $mainList = $mainNav.find('ul').eq(0);
var  optionsList = '<option value="" selected>'+ Drupal.t('Navigate...') + '</option>',
  $submenu = $mainList.find("ul").parent();

Your code also contains a syntax error: . is not the string concatenation operator, in JavaScript; JavaScript uses +, for that purpose.


Add field to node without new content type I need to create a field for a specific node, but I really don't want to create a new content type, for various reasons...

Is there a module that does that?

Say I wanted to create my own module that does that, how do you recommend I approach this?

A field of the Field API is meant to be used in an entity. Nodes are specific types of entities, such as users are. Fields are attached to specific bundles of an entity. Content types for nodes are the bundles of the nodes entities. If an entity type does not support bundles, such as users, then fields are bound to the entity regardless. For more on the subject see Drupal.org: An introduction to Entities.

As such, a field is not designed to belong to a particular entity but rather to an entity type/bundle (briefly, not designed to belong, meaning that the database design and programming logic as is would not support something like that).

So to sum up, it would require some considerable coding effort to achieve something like this and it would be advised to reconsider your design to take into account those factors.


Multi-site installation and one theme: how to know on which multisite user is? I have Drupal multisite, where I have three different sites. THey all use same theme. Now I would need to do small changes to templates that only visible on some sites. How can I tell on template level that what site is used.

For example on site 1's front page I would like to have:

Some content

But then on site 2's front page I dont want that div to be showed at all. Can I achive this somehow? Is theere "native" way to find out thie right site inside template, maybe in template.php?

Thanks.

i would suggest doing multiple themes, one per site/group of sites - where they all have a common theme as parent.

that way you can overwrite specific elements on individual sites without having to worry about adding all the logic to check what site your currently rendering content for.


Cannot download generated files I have a site (Linux/Drupal/Apache) that generate a .xlsx file from custom code and its saved to files, but after that I cannot download it from drupal, it give permission denied.

Forbidden
You don't have permission to access xxxxxxx.xlsx on this server.

The upload file is saved with -rw------- or 600 permission, and the user/group from Apache.

If I chmod the file to 644 it works.

How can I made that any file generated in that way, will be -rw-r--r-- or 644 ?

A few things to check:

make sure there is no .htaccess rule that is preventing the download
(it may be inherited).
If using file entity check: /admin/config/media/file-settings and make sure .xls is allowed.
Could be blocked by server security like modsecurity rules, check the apache logs...


How to allow user's of a certain role to change the node creation date I want to allow some users (a role) to change the node creation date (ideally on the node's form).

I could add permission 'administer nodes' to this role but it's too strong
I could create a new field for this date, but i want to keep the drupal submitted informations on the top of the node

If someone have any idea, thanks

You want Override Node Options module.

  The Override Node Options module allows permissions to be set to each
  field within the Authoring information and Publishing options field
  sets on the node form. It also allows selected field sets to be set as
  collapsed and / or collapsible.

In addition you may be interested in Date Popup Authored to use a datepicker on that field.


What is page_fast_cache? The Cache Router module advertises that it "has an option to utilize the page_fast_cache part of Drupal in order to reduce the amount of resources needed for serving pages to anonymous users."

However, the only Google hits for "drupal page_fast_cache" point back to cacherouter.

What is page_fast_cache?

I believe the project page is referring to page_cache_fastpath(), which is called during Drupal bootstrap from the following code:

if (variable_get('page_cache_fastpath', FALSE) && page_cache_fastpath()) {
  exit;
}

The documentation page reports the following description for the function:

  By implementing page_cache_fastpath(), a special cache handler can skip most of the bootstrap process, including the database connection. This function is invoked during DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE.

The example code reported in that page helps to understand how the function needs to be implemented, and what should do.

function page_cache_fastpath() {
  $page = mycache_fetch($base_root . request_uri(), 'cache_page');
  if (!empty($page)) {
    drupal_page_header();
    print $page;
    return TRUE;
  }
}

If the module reports to utilize it, it means it actually defines the page_cache_fastpath() function, which is called by Drupal core code.
To notice that it's not a hook, but a function. This means that a module called "mycache" doesn't need to implement mycache_page_cache_fastpath(), but page_cache_fastpath(). In fact, the bootstrap code is explicitly calling page_cache_fastpath(), as it is evident in the code I reported at the beginning of this answer.


Multiple submit buttons: Which one was pressed? This may be a duplicate of the following: Multiple form submit, but I am unable to figure out how the answer applies to my situation.  So here is my go at asking this (I admit) quite similar question:

I have a table with a row of data, each row has a submit button.  It may look something like this:

$form['f'] = array();
foreach ($rows as $row) {
  $form['f'][$row['nid']] = array();
  $form['f'][$row['nid']]['nid'] = array(
    '#markup' => $row['nid'],
  );
  $form['f'][$row['nid']]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('sumbit'),
    '#submit' =>  array('f_submit'),
  );
}

I.e. the form consists of a sequence of rows, extracted from the database,  I want to create a submit callback that picks up the value of the corresponding nid field and prints out its value.   I guess I am asking what to put where the comment below is.

function f_submit($form, &$form_state) {
  // Here I want to print the value of the relevant nid field
}

Data about clicked button is stored in $form_state['triggering_element']. You can get the node ID by looking at $form_state['triggering_element']['#parents']. In your case the node ID would be the second item in the parents array. Please note that the name attribute of the field definition needs to be defined and unique. Otherwise the triggering element will point to the last submit button on the form. I would alter your code as follows:

$form['f'] = array();
foreach ($rows as $row) {
  $form['f'][$row['nid']] = array();
  $form['f'][$row['nid']]['nid'] = array(
    '#markup' => $row['nid'],
  );
  $form['f'][$row['nid']]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('sumbit'),
    '#name' => 'submit-' . $row['nid'],
    '#submit' =>  array('f_submit'),
  );
}

Good way to view $form_state is to install the Devel module (for krumo()) and then putting krumo($form_state);drupal_exit(); to top of the submit handler. This will print out a nice structured tree of data.


add next pager to image field views I have a view created from a node with images.
All images are in one field, image field content:afbeeldingen (images)

I have created my view 1 image is one page. I get the next link and previous below my image but now i want to link add a next link to my image in my view how can I do this?

Basically what you want is an image gallery or slideshow. There are many image gallery modules you can install (ie views slideshow, Flexslider).

Then you need to set the slideshow to have a pager of its own, and in the image field you need to take care of the display multiple part (as it is a multi image field) to display one image at a time.

So you will end up with two pagers. One for the view, and one for the slideshow.

Or if you want you can try the Field Slideshow module. It builds the slideshow from one multi-instance field, so half the work is done for you.


Intermittent "Cron already running error" I get the error every once in a while then Cron completes successfully, then the error crops up again some hours later, and after about 3-4 tries the system completes cron again without a problem, all of this without my intervention. I don't understand it! I've googled and found several posts about how to fix the error once it happens but nothing that I could find tells me how to prevent this error from happening in the first place and why it happens so randomly. I'm running the latest D7 with cron set to run every hour. Any insight would be highly appreciated!

  cron  09/17/2013 - 14:15  Cron run completed. Anonymous (not verified)
      cron    09/17/2013 - 14:15  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 14:15  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 14:15  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 13:14  Cron run completed. Anonymous (not verified)
      cron    09/17/2013 - 13:12  Cron run completed. Anonymous (not verified)
      cron    09/17/2013 - 13:12  Cron run completed. Anonymous (not verified)
      cron    09/17/2013 - 13:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 13:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 13:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 13:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 13:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:12  Cron run completed. Anonymous (not verified)
      cron    09/17/2013 - 12:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:12  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 12:11  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 11:59  Attempting to re-run cron while it is already running.  Anonymous (not verified)
      cron    09/17/2013 - 10:49  Cron run completed. Anonymous (not verified)

You have a long running, stalled or erroneous cron hook.

To determine where the error is, try the module

cron_debug

or the temporary core patch listed here:

https://drupal.org/node/1143706


How to use Rules to perform a simple anti-spam validation using specific keywords? My site is under repeated attacks by spammers who create accounts manually with nonsense email addresses and "fake" IP addresses (no way to block them).
I came up with the idea of blocking node creation with the Rules module, using data comparison, but it does not work. Here is a summary of the rule I have:

Event : Before saving content
Conditions: text comparison : Parameter: Text: [node:body:value], Matching text: lexapro, etc. [how to make the list of words/expression? One per line?]
Actions : page redirect

Update: starting from the rule in this answer, I created a rule which will redirect to a page and unpublish the node, but only if the words are both in the title and in the body. I've tried to put an OR in the rule, but it didn't work.
{ "rules_simple_antispam" :
  {
    "LABEL" : "Simple antispam",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "node:title" ], "match" : "lexapro" } },
      { "text_matches" : { "text" : [ "node:body:value" ], "match" : "lexapro" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "death-spam" } },
      { "node_unpublish" : { "node" : [ "node" ] } }
    ]
  }
}

What do I need to change in my rule to make it work?
PS: I'm not a coder.

IMO you should use a captcha, such as:
reCAPTCHA

Uses the Google reCAPTCHA web service to improve the CAPTCHA system
and protect email addresses.

OR
Draggable Captcha

Here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam
If spam still happening, which means they are indeed human and not bots, you could implement a point system. Where users need to gain points by doing something (login x amount of days or comment x amount of times etc..)
To create nodes, users need to have x amount of points.
In addition, you could also implement spam flags, where users can flag content as spam and have the content be auto deleted if x amount of flags are raised.


How do I migrate to a existing taxonomy reference field? Given a source that has a field with the corresponding ID which outputs the id in the field special like the field nid gives back a node id.

I want to map it to a taxonomy term that is already existing on the new site and not migrated.

This is the process part of my custom yml file:

process:
  nid: nid
  vid: vid
  # there were some more fields here that I left out.
  # hardcode destination node type as publication
  type:
    plugin: default_value
    default_value: publication
  # custom fields
  field_special:
    plugin: static_map
    source: special
    map:
      1: 1
      2: 2
      3: 3

I have a field_special as taxonomy term reference field in the node I want to migrate to.

How can I map the source field to be used in the destination field which is a taxonomy term reference field?

I'm using Drupal 8.1.2 with migrate_plus migrate_tools migrate_drupal enabled.

I've rewritten my yml to use:

field_special:
  plugin: iterator
  source: field_special
  process:
    target_id: tid

And written a preparerow function in my class to output an array as source property:

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('nid');

    $result = $this->getDatabase()->query(
      'SELECT
        GROUP_CONCAT(field_special_tid) as tids
      FROM
        {field_data_field_special} fs
      WHERE
        fs.entity_id = :nid
      ',
      array(':nid' => $nid)
    );
    foreach ($result as $record) {
      if (!is_null($record->tids)) {
        $row->setSourceProperty('special', explode(',', $record->tids));
      }
    }
    return parent::prepareRow($row);
  }

This workaround will do for now, but if you have a better answer please post so I can accept your answer.


Is there any way to use SQL Views in Drupal Views I have some very tricky reports to develop (with multiple subqueries) and it occurred to me that the Data module would be perfect: I can create my complex queries as SQL Views (I know how to do this), then adopt them with Data and use them as ordinary tables in Views. Perfect!

Except that although you can adopt a SQL View, it won't show up in Drupal Views (apparently because no primary key) and of course you can't add a primary key to a SQL View.

Is there any way round this by using a module to replace the View SQL query? I have searched a lot on the web and cannot get around the problem without coding object PHP which to be honest I find intimidating.

I dont know your use-case. But look at new Raw SQL Query module, and see its attached screenshost(s) for how you define the SELECT queries and the report pages it generates:

  It builds "tables" (mysql views using "CREATE VIEW" statement) based
  on raw sql queries. I would say it is like a lightweight version of a
  materialized views approach. It uses Ctools to manage data storage and
  PHPExcel to export data into a Excel file :) After installation, go to
  admin/config/development/raw_sql_query Do not forget clean cache after
  you store a query.

It sounds like this module is caching the returned data (I'm not 100% sure). But that would be helpful since a mysql view is literally a SELECT query upon every access to the data.


How can I insert Javascript right before the body in my custom theme? I want to make the same jquery menu in my custom drupal theme but I could not insert the inline script right before the body.

I made a separate JavaScript file, and added to my custom .info file, but this is not the right way to insert inline JavaScript, obviously.

This is my info file.

Not sure this helps but I had a similar problem before. I solved it by using the jQuery syntax instead of the $, like so:

jQuery(window).load(function() {
    jQuery('#a a').css({'background-position','-20px 55px'});
    // and so on
});

You could load your js file by calling the drupal_add_js() in the THEME_preprocess_page() hook in your template.php file.


What are functions that start with 'hook' used for? I understand how to use hooks (mymodule_HOOKNAME()) but what are functions used for that actually start with hook?
Ex: hook_action_info()

When I am creating custom hooks I normally just use: module_invoke('MODULE', 'HOOK_NAME').

hook_action_info and other functions that begin with hook_ exist only to document the contract between the caller of the hook and the module that implements it.


Image cropping only from top I am having some trouble configuring my image cropping styles. I have an image I want to crop and scale from 600x800 to 140x140, But I only want the cropping to be from the top. At the moment the cropping is equally from the top AND bottom. How can I achieve this, because I can't find any offset setting although Drupal 7 cropping functionality in the API supports it.

Thanks in advance

I just tried this on my D7 site I am making and if you go to admin/config/media/image-styles/list you can add a new style. Inside the new style you add an effect to crop and then you can choose the anchor point. The anchor point will allow it to crop from the top instead of equally top and bottom. You can then set your field to display using that style in the display settings or in views or whatever you showing it in.


Webform limit to multiple choice question Anyone know of a way to take a multiple choice (checkbox) question on a Webform and only allow the person to select two or three options and all other options become disabled? Using WebForm module?
Version: 7.x-4.15

Discovered a module called Webform Validation, works fine. But the user will only know that he can't submit more than x answers after clicking the submit button.


How do I display three months in the event calendar view? I used calendar and views template module to create a calendar view for my Drupal 8 site, but the view returns only one month.

I want to display three months. How can I get this?

It doesn't look like there isn't anything in the admin that will give you three months. I've implemented some similar solutions with custom calendars.

There are a few ways that you could do this. I'm not going to get to far into the code, but just describe what I've done (I don't have a multiple-month example).

Method 1) Duplicate the monthly view and  alter the defaults in the contextual filter. Display these multiple blocks or feeds on a page.

Method 2) Create a custom node for displaying 3 months. Pass the contextual filter to the same view. Twig Tweak can handle passing arguments, though you may end up needing to do more preprocessing what Twig Tweak allows.


How to deal with login attempts coming from 1-127.0.01 and what does it means? Recently on my drupal 7 site happens that i find the admin account blocked. Looking to the flood table i see a lot of failed login attempts from ip "1-127.0.0.1". It's an external attack or something not working in my site? The fact that the ip the request comes from is 'localhost' is confusing me. In both cases, how to deal with this problem?

After attempt five login drupal block account automatically

Install the Flood module flood_control
Enable the Flood module
Go to admin/settings/system/Flood control
Change the "Failed login (username) window" from 6 hours to None
Save

Flood Control

  This project is intended to add an administration interface for hidden
  flood control variables in Drupal 7, like the login attempt limiters
  and any future hidden variables.

Flood Unblock

  This module makes it possible for site administrators to remove
  ip-adresses from the flood table, or to remove all ip-adresses from
  the table depending on the event type.

Different ways to reset Drupal admin password

Protect site from flooding when user login is attacked...


Drush not installing correctly I'm attempting to install Drush on a new system OSX 10.10.4.

The process is no longer the simple one it used to be :(

I've complied with the requirement to install via Composer (that was not small feat either), and finally have Drush installed.

However, executing Drush results in the following:

which drush
env: sh\r: No such file or directory

I've seen issues logged similar to this with scripts that had spurious LF/CR. I haven't written any scripts. No idea where this is coming from.

Solutions I've tried include using Composer to uninstall the Drush and install 6. Process appears to work, but results the same when attempting to run Drush.

The error message suggests that the script you're invoking has embedded \r characters, which in turn suggests that it has Window-style \r line endings.

Try to install from other source or something


From Controller to html.twig I have a module that define a Routing and a controller

my.partner:
  path: '/partner/{alias}'
  defaults:
    _controller: '\Drupal\myname\Controller\PagesController::partner'
    _title: 'Partner'

In controller I define the template to use:

$variables = [
         '#theme' => 'page_partner',
]....

But I need to pass some "variables" from this "controller" to html <head>. How can I do it ?

Define the variables in your theme and the pass them as "#variable" = value. E.g. in YOUR_MODULE.module have something like:

function tb_megamenu_theme($existing, $type, $theme, $path) {
  $items['tb_megamenu'] = [
  'template' => 'tb-megamenu',
    'variables' => [
      'menu_name' => NULL,
      'content' => NULL,
      'section' => 'frontend',
      'block_theme' => \Drupal::config('system.theme')->get('default'),
    ],
  ];
}

In your controller use:

$render = [
  '#theme' => 'tb_megamenu',
  '#menu_name' => $this->getMenuName(),
  '#block_theme' => $this->getThemeName(),
  '#content' => $this->getContent(),
];


Images loading from server on every page load I am using the views flexslider with same images on every page but when ever we go from one page to another or come back to the previously browse page it take a time to load images.

It seems like views always loads the images from the server. Is there a way those images could appear instantly on every page. May be loading the images through browser cache ??

EDIT

The problem was actually because of Adaptive Image module I have turned that off and the images are loading normally now.

Caching problem was not with the views, it was actually Adaptive Image module which was causing the frustrating image reload issue.

After trying several caching options, I disabled the Adaptive Styles and use normal image styles and the issue was resolved.

For adaptive images I am now using Adaptive Image Styles and it is working fine. Though this require some modifications in .htaccess file but that is acceptable.


Change User Profile Fields from modules - $form fields not available - Ubercart Roles I have been attempting to change various fields on the user profile to make it more user friendly, most of it going well. However, when I try to access $form for the main user profile via dpm($form) in MODULE_NAME_form_alter not every field rendered onto the page is available. I have been trying to alter the profile forever with no luck!

function admin_dashboard_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'user_profile_form'){
        //change main user profile "Ubercart Roles" form field
        $form['uc_roles']['#title'] = t('Member Expiration');
        $form['uc_roles']['#collapsible'] = FALSE;
        $form['uc_roles']['#collapsed'] = FALSE;
    }
}

I figured it out! My module name was alphabetically before the other modules..."A" (admin_dasboard) comes before "U" (ubercart_roles). I was able to go into the drupal_system table and set my modules weight to 1, where before it was set to 0, the same as Ubercart. Hope this helps someone.


Decide which modules to enable / disable in make file I have a make file in which modules are downloaded, but how do I decide which ones are enabled?

Drush make only downloads projects; if you want to enable some modules, you must do that with an installation profile.  An installation profile contains a make file, plus some code to configure your site.

If you're using Drupal 7 and would like to create a starting installation profile from an existing site, see http://drupal.org/node/1368242.  There is a patch there that will create a profile for a D7 site.  The issue is marked "needs work" because the code templates for D6 are not in place yet.


Can you retrieve the Omega breakpoint settings? As the title suggests, is it possible to retrieve the Omega breakpoints you set in the settings for your subtheme via any kind of function or call? Like the ones from the picture.

For anyone interested in the answer to this, it's retrievable but if you want to use it for adding your own stylesheets in at the same breakpoints (like I did) you have to do it in the template.php file

This is what I did

$theme = alpha_get_theme();
$layouts = $theme->grids['alpha_default']['layouts'];
$keys = array_keys($layouts);
for ($i = 0; $i < 3; $i++) {
    return $layouts[$keys[$i]]['media'];
}

This will return (or print, whatever you want it to do) the media-queries/breakpoints to use for your own sake.


How to include CSS3 Pie in my Drupal site? I would like to use rounded corners on my Drupal site. I came across CSS3 Pie and would like to try it out. But where exactly do I include the code that I download? In the modules folder?

http://css3pie.com/download

There is a module for that:
http://drupal.org/project/css3pie

The instruction on the project page are better than what I could explain it as having to be done.


Using function of views_embed_view may caused high CPU loading I found that a page in my Drupal site is causing high CPU/memory loading, I tried to remove each item(e.g. block, custom PHP code and so on) on this page. Finally, I found that if I remove the code below will drop down the CPU/memory usage from 90% to 10%.

print views_embed_view('flag_compare', 'block_1');

Could someone suggest another function to embed view?

The function itself has not much to do with this, it is a wrapper for creating and displaying a view. The view you are displaying is a block - if you should have chosen to enable the block instead my guess is that the result would have been the same.

The most probable cause is the view you are displaying. Tools like views and panels are great at handling displaying stuff, but it comes at a price. They are usually a lot more ineffective than if you had done it with your own code, but they are also a lot faster to use. I would recommend that you review the view and try to find a way to reduce the workload by simplifying it, or if it's really important to you, do it yourself and skip a lot of the abstractions that Views bring.


disable the preview and delete buttons on node edit form I want to disable the preview and delete buttons on node edit form.I have used the following code.But it is not working. where am i wrong with this?

function mymodule_form_alter(&$form, $form_state, $form_id) {
// Check for a particular content type's node form.
  if ($form_id == 'node-gallery-item-node-form') {
    drupal_set_message("Formid");

    unset ($form['edit-preview']);
    unset ($form['edit-delete']);

  }
}

Since you are not checking for any particular condition in your code, I would suggest that you remove the preview option from the content type settings.

admin/structure/types/manage/[you_content_type]

Regarding the delete button if you can do it using permissions, you should always do it using permissions. If you do not want to revoke the permission but just want to hide for a particular screen then use

$form['actions']['delete']['#access'] = FALSE;


setup cron to browse all pages On drupal 6 I use page caching and I would like to setup cron to browse all my pages on my website (30pages) before they get expired. What are best options to do that?
I know about boost module but I think it is too robust for my needs. Thank you

In short: wget is your friend when you want to warm up your page cache.

In more detail: http://linuxreviews.org/quicktips/wget/ for example. If you want to warm the cache for page requisites (all images, css, js etc linked to from any page) too, you can use wget -p which is not mentioned in that article.

Got more interested about this and found some Drupal specifics: http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer

To summarize: just setup your system's scheduled tasks (cron on *nix for example) to run wget in a manner that finds all your pages before your cache runs cold.


Align fields in created webforms I am new to drupal, and currently i am creating a webpage in drupal from html . i have almost completed. I have created web form for "Contact us" form, after creation it is not in proper alignment. So, my form should be look like the picture shown as below.

So, right now it is like as below image.

So, please someone help me to get out of this issue.

You can theme the webform.
Create a new file: webform-form-81.tpl.php (Replace the number 81 with the node ID of your webform)

Place this file in your sites theme directory (sites/all/themes/yourtheme/webform-form-81.tpl.php)

Inside this new webform-form-81.tpl.php file, insert the following code:

<col style="width: 50%" /> <col style="width: 50%" /> </colgroup>

    <?php print drupal_render($form['submitted']['name']); ?>

    <?php print drupal_render($form['submitted']['email']); ?>

    <?php print drupal_render($form['submitted']['phone']); ?>

    <?php print drupal_render($form['submitted']['notes']); ?>

<?php
// Always print out the entire $form. This renders the remaining pieces of the
// form that haven't yet been rendered above (buttons, hidden elements, etc).
print drupal_render_children($form);

Save the file, then clear your Drupal cache.
Refresh the page with the form on it.


how to make a custom module that has three forms on one page I know how to make a module that has one form : http://www.wdtutorials.com/2012/04/26/drupal-7-how-create-forms#.U_YI1WNab3s

But how can I make a module that contains three different forms on the same page?

Yes you can create as many as forms in one page.
One method is using drupal render function.
Example:

$f = drupal_get_form('call_your_form');
$f1 = drupal_get_form('call_your_form1');
echo  drupal_render($f).drupal_render($f1);

Like this you can display any number of from in one page.


How to make persistent exposed filters in views I'm aware of the "remember" option of views, but it is stored in session data (not persistent if you logout) and I want to keep the selections saved forever (so the users only have to do the selections once when they sign up).

I've done quite a lot of research regarding different options that maybe could do the trick, but haven't found out yet a viable solution to it. The options I've researched are:

1) With the module "views saved searches" (works but for usability reasons is not an option in this case)

2) Coding a way to remember the exposed filters selected via cookies or database (I haven't found anything about this and I don't know how to code a solution myself).

3) Making the selection in a node or profile page (with CCK, Nodereference/Entity Reference or Relation fields) and applying the selection of each user to "personalize" their view accordingly (maybe following one of the two options briefly mentioned in point 3 of this answer: https://stackoverflow.com/a/1409382 or using advanced features of relationships and/or arguments)

Any help would be appreciated.

Thanks!

Take a look at Views Global Filters module. That will solve your problem.

The project page reads

  Use Views Global Filter on sites that feature multiple Views. You want
  the views to be driven by the same filter selection, for instance a
  country, a date range, a search term or even proximity to a post code.


Difficulty getting Rules Scheduler in D7 to publish a node in the future I've set up rules to defer publishing on node save to a specified date. The rules component successfully runs at the later date and sends an email alert to the node author to let them know that their node has been published. But the rules component does not succeed in actually publishing the node.

I am pretty confident that the component works OK, because if I execute it directly, providing the node id as the content identifier (using direct input mode), it works as expected, i.e. sends the email alert and publishes the node.

The issue arises only when the component is run by cron. My best guess - drawing on this stackoverflow Q&A - is that this may be connected to cron, on D7, always being run as the anonymous user.

I'm puzzled, however. There are several D7 discussions around of how to use Rules to defer publishing, e.g. this Drupal Answers Q&A or this drupal.org comment (about using this approach on D7 - it is a comment on a D6 page). The fact that neither of these mention any issue with the anonymous user, make me wonder if I'm getting something very basic wrong and/or have an unusual configuration. It would seem odd that Rules Scheduler couldn't, more or less out of the box, achieve deferred publishing.

I've looked at the 'Configure access for using this component with a permission' option for the component and tried out various settings of that without fixing the issue. I'm not clear I understand the function of this option and haven't found any documentation / Q&As so far that have helped.

For reference, the rules component (that works when executed manually using the node id, but send the email without publishing the node when triggered by cron) is (when exported) as follows:

{ "rules_publish_content" : {
    "LABEL" : "Delayed publish action",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "delayed_node" : { "label" : "Delayed node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "delayed-node" ],
                "type" : { "value" : { "news" : "news" } }
              }
            },
            { "NOT node_is_published" : { "node" : [ "delayed-node" ] } }
          ],
          "DO" : [
            { "mail" : {
                "to" : [ "delayed-node:author:mail" ],
                "subject" : "Your item, \u0022[delayed-node:title]\u0022, has been published.",
                "message" : "Your item, \u0022[delayed-node:title]\u0022, has been published.\r\n\r\n[delayed-node:url]\r\n\r\nnode id: [delayed-node:nid]\r\n\r\nnode date: [delayed-node:field-date]\r\n\r\nnode status: [delayed-node:status]\r\n",
                "language" : [ "" ]
              }
            },
            { "node_publish" : { "node" : [ "delayed-node" ] } }
          ],
          "LABEL" : "Delayed publishing: publish and alert"
        }
      }
    ]
  }
}

It turns out the concern about cron running under Anonymous user was a red herring. Thanks @Patrick Kenny for encouraging more persistent logging.

Diagnosis: the reaction rule that was scheduling the component was triggered by a 'Before saving content' event. In my testing - because of my faulty theory about the cause of the problem - I was repeatedly using an already created node. As such, the node nid was successfully passed to the component and so in logging (and in inspecting the list of scheduled rules) everything looked OK. And the alert email was even correctly generated. It turns out, however, that when the component is scheduled from a reaction rule triggered by a 'Before saving content' event, then changes to the node are not saved when the component executes.  So some things works with the parameter passed from a 'Before saving content' triggered reaction rule, but not others. And for the things that don't work no error or issue is flagged in logging. Glad to know that now.

For anyone coming here just wanting some Rules to import to get delayed publishing up and running, here is the exported component and two exported rules that do the job.

Component to publish a node

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the component. (Import the component at: admin/config/workflow/rules/components)

{ "rules_publish_content" : {
    "LABEL" : "Delayed publish action",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "delayed_node" : { "label" : "Delayed node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "NOT node_is_published" : { "node" : [ "delayed-node" ] } } ],
          "DO" : [
            { "node_publish" : { "node" : [ "delayed-node" ] } },
            { "mail" : {
                "to" : [ "delayed-node:author:mail" ],
                "subject" : "Your item, \u0022[delayed-node:title]\u0022, has been published.",
                "message" : "Your item, \u0022[delayed-node:title]\u0022, has been published.\r\n\r\n[delayed-node:url]\r\n",
                "language" : [ "" ]
              }
            }
          ],
          "LABEL" : "Delayed publishing: publish and alert"
        }
      }
    ]
  }
}

Rule to trigger delayed publication when authored on date is in the future

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the rule. (Import the component at: /admin/config/workflow/rules). In addition, in my use case, I looked at a specific date field on the content type rather than the node:created, i.e. 'Authored on', value. If you want to do that then, after doing the import, add a new condition that checks your added date field and remove the condition that checks the standard Drupal created date field.

{ "rules_publish_node_future" : {
    "LABEL" : "Publish node (in the future)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_insert", "node_update" ],
    "IF" : [
      { "data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "node_unpublish" : { "node" : [ "node" ] } },
      { "schedule" : {
          "component" : "rules_publish_content",
          "date" : [ "node:created" ],
          "identifier" : "Delay publication of node: [node:nid]",
          "param_delayed_node" : [ "node" ]
        }
      },
      { "drupal_message" : {
          "message" : "\u003Cstrong\u003EPublishing will be delayed until (up to 3 hours) after: [node:created:long].\u003C\/strong\u003E This is because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "type" : "warning"
        }
      },
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "\u0022[node:title]\u0022 publication will be delayed until [node:field-date]",
          "message" : "\u0022[node:title]\u0022 publication will be delayed until (up to 3 hours) after: [node:created:long].\r\n\r\n[node:url]\r\n\r\nYou have received this message because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Rule to cancel delayed publication if node is saved with a date in the past

This rule cancels any scheduled publication of the node. It does not set the node to be published. Depending on your setup, you might want to add an action to this rule to publish the node.

{ "rules_publish_node_future_cancel" : {
    "LABEL" : "Publish node (in the future cancellation)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_publish_content",
          "task" : "Delay publication of node: [node:nid]"
        }
      }
    ]
  }
}


Can Pathauto fallback to another pattern if the first pattern yields an empty path? I want pages to have an auto generated path if they are in a menu and another one if they are not in the menu; not an empty path like Pathauto currently generates if the page is not in a menu.

How can I do that?

Details: I'm using this pattern for my pages content type which works perfectly when a page is in a menu.

[node:menu-link:parents:join-path]/[node:menu-link]

The problem is, when a page is not in a menu, it gets an empty path. I want to give it another path based on the "title" of the page, for example.

You can now achieve this using hook_pathauto_pattern_alter().  Something like:

<?php
/**
 * Implements hook_pathauto_pattern_alter().
 */
function mymodule_pathauto_pattern_alter(&$pattern, array $context) {
  // Alter any node entity path patterns we need to
  if (isset($context['data']['node'])) {
    $node = $context['data']['node'];

    switch ($node->type) {
      case 'page':
        // Check condition, and change the pattern when appropriate
        $pattern = '[node:title]';
        break;

    }
  }
?>


Creating a new Form element in ajaxcallback function not affecting form state I am trying to insert new form fields into exiting wrapper within ajax callback function.

I succeeded doing so, but trying to get those new fields values inside submit function failed because they are listed in the form state values array.

How can I make their values available to be used inside the submit function.

$form['test'] = array(
        '#type' => 'select',
        '#options' => array('- Please select -' => [1=>'one',2=>'two']),
        '#ajax' => array(
            'callback' => '::testSelectedCallback',
            'wrapper' => 'fields-wrapper',
            'effect' => 'fade',
            'event' => 'change',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        ),
    );
$form['fields-wrapper'] = array(
        '#type' => 'container',
        '#attributes' => ['id' => 'fields-wrapper', 'class' => ['hiddenselect']],
    );

public function testSelectedCallback(array &$form, FormStateInterface $form_state) {
$form['fields-wrapper']['new_item']= array(
'#type' => 'textfield',
'#title' => 'My new item',
);
$form_state->setRebuild(True);
return $form['new_item'];
}

You cannot add fields in ajax callback functions - assuming that level2SelectedCallback() is your ajax callback (you named it something different in your form element defintion).

All form elements need to be added in the form definition. The ajax callback is only used for determining which elements need to be inserted into the page when the AJAX is returned.


How can I suppress the "connection to @remote closed" message? I'm running Drush 10 and have set up site aliases for my local and the remote Drupal site. When I run the following command for my local alias:
drush @local dd

This returns:

var/www/html/abc

But when I run the same command for my remote alias:
drush @remote dd

This returns:

var/www/html/abc
Connection to "remote" closed

Why is the output different? Is there any chance to avoid the "connection closed" message?

--ssh-options="-o LogLevel=QUIET" suppresses the SSH message but still produces a blank line. Although I couldn't put this into the command line I was able to add this to the self.site.yml file.
ssh:
  options: -i /cert.pem -o LogLevel=QUIET


Scroll to search results on Views Exposed Filter submit button Hi I've made an 'Advanced Search' using Views + Display Suite in Drupal 7.

https://www.oldertenants.org.au/research-library-advanced-search

There's too many search filters so the default behavior of the submit button scrolling the user back to the top of the #content div confuses the user to think there are no search results.

How can I scroll the user to the results div instead (i'd also have to work out how to include a #results id in the results div) - or perhaps just not link to any div, simply refresh the results?

It would be ideal to achieve this using ajax but if its easy not a problem to be refreshing the page on search.

Thanks in advance for any suggestions!

You can do this in your theme when the page loads and has search results

Create search_results.js

(function ($) {

  'use strict';

  $(document).ready(function() {
    if( $('.views-row-1').length ){
      $("html, body").animate({ scrollTop: $(".views-row-1").offset().top }, "slow");
    }
  });

}(jQuery));

which on page load sees if the first result is not empty and scrolls to it

Load file on specific view page

In your template.php

function THEMENAME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'view_resources_advanced_search') {
    drupal_add_js(drupal_get_path('theme', 'THEMENAME') . 'js/search_results.js');
  }
}

Of course make sure you change THEMENANE and make sure the view machine name is correct in the template.php file


Print module doesn't work with Panelizer module. Why? I need to make print pdf module work on the panelizer node. But on page printpdf/node/nid, I see only the node title and panelizer field is not shown.
How to fix it?

The Print module uses hook_preprocess_node which is not used with panels_everywhere/panelizer. In a similar issue (with panels everywhere) I  used a patch 565856-panel_support_print-39.patch.

Background discussion and the patch you can find here:
https://www.drupal.org/node/565856

Hope this will help.


Textfield value not saving to database I am having a problem with saving values of a textfield in the database.

Usecase:
Users with a certain role should add two things on their accountpage the first time they login.
1.change their password
2.agree with terms.

Point 2 is the trouble part.
I have a text field with two values:
'Agree' and 'Not agree'
Now i like to hide the second option but with my current code the value of the agree option is not getting saved to the database.

Help appreciated
Thanks

Used code

<?php
function regform_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  global $user;
 // Making password required when role=In between role.
if( ($form_id == 'user_profile_form') and (isset($form['account']['pass'])) and (in_array('In between role', array_values($user->roles))) ){
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#required'] = TRUE;
    $form['account']['pass']['#type'] = 'password_confirm';
    $form['account']['pass']['#required'] = TRUE;

   // Disabling and hiding 'Dont agree field' field

  $form['field_agree'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
   'Agree' => t('Agree'),
   'Do not agree' => t('Do not agree'),

 ),
);
hide($form['field_agree']['Do not agree']);
 }
}
?>

It is not necessary to hide the 'no' option from checkbox - just go the the field settings and make it a single on/off checkbox, that way you will not have to deal with this at all.

Then, go to the field settings and set the Default value to off (see screenshot).


Views: expose filter - filter out results between a specific set of dates I have a views (content type = car, Create date filter"exposed" and some fields to display in the result in a table).

is there any way to display all the node not created in the date that selected using the filter?
Thanks

You should be able to add a view filter that uses the operator of "Is not between" when referencing a date.

You can have multiple filters for the same value, so you could allow people to search for dates, but have a second filter that removes results between X and Y


How can I properly duplicate Fields on entities? I have an entity that has an image field attached to it. This field can hold multiple images.
I would like to be able to display a single/first image with one field formatter from this field at one place and all images with another formatter from this field in another place.

~~So I need to somehow clone this field, most likely via custom configuration to store some basic data and attaching it via hook_entity_base_field_info().

What I am not sure about is how to use the proper field type for this "computed" field so I can use proper field formatters, how to set proper source of data(the original field) and how to properly use isEmpty() method on that field so this field won't show up if the original field is empty without using my own field class to do that(since I would lose the compatiblity with proprr formatters).~~

Sorry, that was a bit misleading. I only need to be able to display the field with different formatter which means I only need another instance of that field in the entity_view_display.

hook_entity_extra_field_info() seems like the best solution, but it does not allow formatter settings.

One way of doing this is in the theme layer. In this approach you don't need to have two fields. You could have a single Images field, and in a node template preprocess function you can break it up into two separate variables that are provided to the *.tpl.php file. So you could take the rendered output of the first image, put that in one place, and the rendered output of the rest of them could go somewhere else.


#ajax form_set_error I'm using the below code to query a webform field's value against database, and if the value exists, I want to use form_set_error, however I can't, since it requires rewriting the page. I have found this post but it doesn't have an answer, hence my question.

function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'event' => 'blur',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    $commands = array();
    $commands[] = drupal_set_message('Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

How do I go about that?

PS: drupal_set_message does its thing only when I refresh the page, whereas form_set_error doesn't do at all.

EDIT: I tried to replace the above with the below code:

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    drupal_add_js(drupal_get_path('module', 'tubitekuz') . '/js/tubitekuz.js');
    drupal_add_css(drupal_get_path('module', 'tubitekuz') . '/css/tubitekuz.css');
  }
}

and in tubitekuz.js I am doing

$(document).ready(function() {
    var username=jQuery('#edit-submitted-kullanici-adi');
    username.addClass('err');
    setTimeout(function() {
      username.removeClass('err');
      }, 3000);
});

and in tubitekuz.css I have the below:

.err {
  border-color:red;
  border-width:2px;
}

however, CSS rules are not applied even though class is added. What is the cause of this? All I'm trying to do is use form_set_error with #ajax

Your code needs to be adjusted to something like:

function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi'] += array(
        '#prefix' => '
',
        '#ajax' => array(
          'callback' => 'kullanici_adi_form_login',
          'wrapper' => 'kullanici-adi-container',
        ),
        '#suffix' => '
',
      );

      // Check the form state to see if an e-mail address has been specified.
      if (!empty($form_state['values']['kullanici_adi'])) {
        $mail = trim($form_state['values']['kullanici_adi']);

        if ($account = user_load_by_mail($mail)) {
          form_set_error('submitted][kullanici_adi', 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
        }
      }
      break;
  }
}

function kullanici_adi_form_login($form, $form_state) {
  return $form['submitted']['kullanici_adi'];
}

You will probably have to play around with some of the arrays, etc. to get the correct values, etc.


Advanced content layout in drupal I've been evaluating drupal and I'm at a point where I have my header, footer, and sidebar set up properly. I have a basic page node type and I've created a few test pages. My test pages have been very simple, just headers and paragraph tags. What do I do when I want something more complicated?

If my client wants a certain page to have text and images split into multiple columns at different points in the page instead of just one how can I accomplish this when the only input the end user has is a wysiwyg form?

Is there a module for this type of thing or does it require knowing in advance how the client will want to layout each of the different pages and make templates for them all?

What you're asking about is usually referred to as "theming", and it is a huge subject.

I suggest you read up on "starter themes", which are Drupal theme projects that are specifically designed for the type of flexibility you want.

As you can see, there are several of these. One that is both popular, well-documented and well-supported is Zen.  Getting a grip on Zen takes some effort (it seems both useless and bone-ugly out of the box).  But Zen, together with one of the avialable grid frameworks (Zen Grids, 960.gs, Gridset App) gives tremendous flexibility.  It is well worth the effort to get to grips with.


How do I show the publishing date instead of the creation date? When I create an article and I don't publish it, so I could edit the article later and publish it when it's finished, I notice Drupal shows the creation date, not the publishing date.

Is there a way to change it so the items on the front page show their publishing date and not the creation date? Is there a different field in the database for that functionality?

I am using the Workbench module, which gives draft nodes. If nodes are not published, it will display them in a draft list.

I think that this module should be fine for Drupal 7:

Publication Date

It adds a field on every node that says Published on: and then the date.


How to hide body field in a view only on certain content types I have a search result view of different content types, and i want to show the body field (trimmed) on some content types, but show no body on other content types. Since they all share the same body field, I would need to exclude the body field from displaying on the content types that I don't want to see them on.

Right now I am doing this with Views rewrite results and CSS. I add the content type field and exclude, then add the body field. Under rewrite results I rewrite the output of the body field with this:

[body]

I then hide the content type bodies that I don't want to see with CSS:

span.search-body-MY-TYPE1,
span.search-body-MY-TYPE2 {
  display: none;
}

This works "visually", but the class and the trimmed body are still rendered in the HTML. Is there a better way to do this perhaps with a views_pre_render hook?

(I am completely inexperienced with PHP.)

This can be done really easily with views_conditional module. Once you enable the module, having the content type and body fields already added and excluded from display, do the following steps:

add a views conditional field
set the if condition to the [type] == Indexed Content: Content Type
set is condition to contains
Set the value to the content type name for the body that you want to display
Then in Then output this... Use the [body] replacement pattern

Works like a charm!


How do I check a value when creating new content? My rule fires after saving new content. The first condition to configure has to be entity is of bundle Src. I don't know how to setup this condition correctly. I chose Entity:node, Type: MY_CONTENT_TYPE, Bundle:Default. Which doesn't work.

What would I have to enter to make this work using the Rules module?

You should try to use the "entity has field" Rules Condition (instead of entity is of bundle). In my experience that one works to make that field available as a token in subsequent Rules Conditions and Rules Actions.

If you have other reasons why you need to add that entity is of bundle condition also (I doubt, but one never knows ...), that's fine too, but make sure to do so only after the "Entity has field" Rules Condition.

Refer to the answer to "How to specify a Rules condition related to select list values?" for an example rule.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

PS: I'm assuming this question is about D7 ...


Creating a new user role with Drush I can do loads of user-related stuff with Drush, but I can't see how to create new user roles. Is it possible to do this with Drush?

This functionality is available in Drush 8.x-6.x:

 role-add-perm (rap)   Grant a specified permission to a role.
 role-create (rcrt)    Create a new role.
 role-delete (rdel)    Delete a role.
 role-list (rls)       Display a list of all roles defined on the system.  If a
                       role name is provided as an argument, then all of the
                       permissions of that role will be listed.  If a
                       permission name is provided as an option, then all of
                       the roles that have been granted that permission will be
                       listed.
 role-remove-perm      Remove a specified permission from a role.
 (rmp)

Unfortunately, this has not been backported to the 7.x-5.x branch, so it probably won't be in the soon-to-be-released Drush-5.9, and isn't in Drush-5.8.  For now, you'll have to use the dev branch to get it.


How to edit the Comment Administration Page I've already edited my comment and comment-wrapper.tpl.php files for public consumption. But I'm finding I'd like to edit the administration page where our staff administers comments that are pending approval. Is it possible to wrap that page in a  tag or something so I can apply styles?

I'm talking about the pages at http://mysite/comment/1#comment-1 (for example, and so forth)...

I'm not too familiar with the comment system in Drupal, but you should be able to.

First check that the commment admin page is loading the theme you are using and not a system  admin theme (Link to a screenshot if you are not sure).

If it is loading your custom theme then inspect the elements that you want to wrap as you may already have unique classes that you can use to style. Even the body tag should have unique classes for the comment admin section or you could add unique body classes in the template_preprocess_page function in template.php

If it is loading an admin/default theme you have 2 safe options:

Set drupal to load your custom theme for admin pages (but then you would have to style all the admin pages)
Copy & rename the admin theme, and set Drupal to load the copied theme for admin pages and change the styles in the copied theme.

If you know PHP well enough you could add your own template but you would have to override the default Drupal hook -  hook_comment_admin_overview() and add a template to the form with the theme() function (if a template file doesn't exist) but that could be quite difficult to get working without breaking.

Finally, if all else fails the quick dirty way would be to add html wrappers with jQuery but this is not recommended.

EDIT

Please check in your theme's html.tpl.php you have this code snippet:

<body class="<?php print $classes; ?>"

There should already be classes that are added to the $classes variable when editing a comment.


Mapping split taxonomy terms to new vocabs in nodes in migrate_d2d I have a use case in a D6->D7 migration (using migrate_d2d), where I need to split terms from a large vocabulary into two new vocabularies in the D7 site. I achieved the splitting into two new vocabularies just fine in the taxonomy migration (see here for details on how), but the problem is getting the new mapping to work during the blog node migration so that the nodes are attached to the proper vocabulary field in the destination node.

So here's the setup:

D6

People and Organizations (vid 4)

D7

People and Organizations (field_people_organizations, vid 9)
Journalists (field_journalists, vid 5) Non-Journalists
Non-Journalists (field_non_journalists, vid 7)

In my blog node class constructor, I've added this:

$this->addFieldMapping('field_people_organizations', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_people_organizations:source_type')->defaultValue('tid');
$this->addFieldMapping('field_journalists', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_journalists:source_type')->defaultValue('tid');
$this->addFieldMapping('field_non_journalists', 4)
  ->sourceMigration('PeopleOrganizations');
$this->addFieldMapping('field_non_journalists:source_type')->defaultValue('tid');

However, what this does is just populate all three taxonomy reference fields with all terms from the People and Organizations field in the source. For instance, if the D6 People and Organizations field has Term A, Term B, and Term C, and in D7, Term B should be in Journalists and Term C should be in Non_Journalists, I get all three terms in each term reference field instead of Term A in field_people_organizations, Term B in field_journalists, and Term C in field_non_journalists.

I did a query that joined the D6 db with the D7 db using the migrate_map_peopleorganizations table in the D7 site, and the terms themselves are correctly populated in the D7 tables, so I know that's not the issue. I suppose I could do some wrangling in prepare() to move the terms to the appropriate field in the blog node, but it seems there should be an easier way to map to the new vocabulary. I'm guessing I would create a field on the fly and map to it in prepareRow(), but I'm not sure what I would put in that field, since the second parameter in addFieldMapping() for taxonomy terms is the source vocabulary, and there is no source vocabulary for the new ones.

Thanks.

As a possibility I mentioned above, I did some wrangling in the prepare() method to move the terms from field_people_organizations to field_journalists and field_non_journalists.

  function prepare($entity, stdClass $row) {
    // Turn off pathauto generation for the node so we end
    // up with only one alias record.
    $entity->path['pathauto'] = 0;

    // Need to manually move any items that should be in the Journalists and Non-Journalists
    // vocabularies there from People and Organizations, since migration mapping doesn't
    // seem to be working.

    // First, see if the nb_migrate_users array is already cached.
    $nb_migrate_journalists = & drupal_static(__FUNCTION__);
    if (!isset($nb_migrate_journalists)) {
      if ($cache = cache_get('nb_migrate_journalists')) {
        $nb_migrate_journalists = $cache->data;
      }
      // Not cached, so we need to generate it this time through.
      else {
        //Get new tids for terms mapped in migrate_map_jounralists.
        $query = db_select('nb_migrate_journalists', 'nmj');
        $query->fields('nmj', array('journalists', 'non_journalists'));
        $query->innerJoin('migrate_map_peopleorganizations', 'mmp', 'nmj.tid = mmp.sourceid1');
        $query->addField('mmp', 'destid1');
        $result = $query->execute();

        foreach ($result as $record) {
          // Use the target vid for the vocab; 5 = Journalists, 7 = Non-Journalists.
          if ($record->journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 5;
          }
          elseif ($record->non_journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 7;
          }
        }
        // Cache the array.
        cache_set('nb_migrate_journalists', $nb_migrate_journalists, 'cache');
      }
    }
    // Move terms in array based on values in field_people_organizations and $nb_migrate_journalists.
    if (isset($entity->field_people_organizations[LANGUAGE_NONE][0])) {
      foreach ($entity->field_people_organizations[LANGUAGE_NONE] as $key => $term) {
        if (in_array((int)$term['tid'], array_keys($nb_migrate_journalists))) {
          if ($nb_migrate_journalists[$term['tid']] == 5) {
            $entity->field_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          elseif ($nb_migrate_journalists[$term['tid']] == 7) {
            $entity->field_non_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          // Remove term from field_people_organizations.
          unset($entity->field_people_organizations[LANGUAGE_NONE][$key]);
        }
      }
    }
  }

I still think there is probably a better way to do this within the class constructor, so if at some point in the future you read this and know that answer, please add it here.

Thanks.


Show VIEW attachments in a block i have a page-view that shows all avatars from the community.
This view has an exposed filter.

This community-view has two attachment-views:
- most comments
- best authors

Now i want to have the attachment-views shown in the sidebar as a block.

How can i handle the attachment like a block?

Thanx Michi

You can create a block-view display with no content and then attach those attachment-view to the block-view display. This may be a possible hack if i understand you correctly.


Migration of Users very slow with d2d I'm wondering what could be causing my migration to run so slowly.  I'm using dev versions of migrate and d2d as I always have without issue.  There are over 120,000 users and the first 2000-9000 import within a few seconds.

After that it only processes 2  at a time (about every 30 seconds).

d2d code:

  $common_arguments = array(
    'source_connection' => 'legacy',
    'source_version' => 6,
  );

  $arguments = $common_arguments + array(
    'description' => t('Migration of users from Drupal 6'),
    'machine_name' => 'User',
  );

  Migration::registerMigration('DrupalUser6Migration', $arguments['machine_name'], $arguments);

include file:

class User extends DrupalUser6Migration {
  public function __construct(array $arguemnts) {
    parent::__construct($arguemnts);

    $this->addFieldMapping('roles', 'roles')
      ->sourceMigration('Roles');
  }
}

The legacy database the data is coming from is on my local machine on the same SSD the new site is on.  Any ideas on why this is running so slow?  At the rate it's going out it will take over a month to import all of the users...

In settings.php set:

  $conf['password_count_log2'] = 1;

You will speed up how drupal handles user passwords: The problems reported here: https://www.drupal.org/node/2200181 ... seem to match yours, first 2000 in X seconds second 2000 in X.Y seconds etc...

Also, in php.ini set:

  max_execution_time to 0 (for unlimited) or a high number like 3000 rather than the default 30.

NB. Be sure to return the execution time to its default setting after the migration.


Display Taxonomy Field vs Default Taxonomy text w/out New modules I have a node with taxonomy term reference fields. The taxonomy term has an image field. Without installing extra modules (I already have WAY more than I should have) is there a way to display a specific field for the taxonomy instead of the textual? And do it from a Childtheme?

I have the DEVEL module installed and after selecting the specific field I still get no ideas. I have dug around inside the field, looking through the various attributes of that field without any ideas.

Array > 'element' > '#field_name'
Array > 'element' > '#field_type' = 'taxonomy_term_reference'
Array > 'element' > '#items' > 'tid' = 4
Array > 'element' > '#items' > 'taxonomy_term' > Object = Recursion

It feels like I am 'right there' and should be able to grab something like ['element'][0]['field_taxonomy_term_image'] and render, but I can't find anything. I realize, after searching stackexchange, and google, that I could install Views and tweak around with it to get the desired output, but I know I've seen somewhere that you can (without coding) get the output of a taxonomy term to be another field than 'title' but I don't remember where I saw it.

UPDATE: I have found the path, but can't figure out how to output it. I did a DPR versus a KPR and just dug through the text. Here is what I see. Inside of template.php inside of a drupal-based custom function THEMENAME_field__content_type($variables) I dpr'd $variables['element'] and found this object/array/path.

[#object] => stdClass Object
    [field_faction_affiliation] => Array
        [und] => Array
            [0] => Array
                [taxonomy_term] => stdClass Object
                    [field_faction_icon'] => Array
                        ...
                        [uri] => public://Faction - Jinteki.pnp
                        [filemime] => image/png
                        ...

So I feel like... I could theoretically, create a new $variables['faction_icon'] to pass on to my tpl.php using the pieces above to generate an img tag. Any ideas?

UPDATE: After a bit more digging around I got this to dpr and output what I expected.

$variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]

So... now the tough part is figuring out how to generate an image path from a URI... of which, I am fairly clueless, but I will start searching.

UPDATE: After tweaking the function listed above I get this to work.

$faction_icon_url = file_create_url($variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]['uri']);
$output = "<img class='faction_thumb' src='". $faction_icon_url . "' />";
return $output;

Now I have to figure out how to make this image link back to the taxonomy_term like the original output of text did.

Ok... so following all of the steps above, I was able to cobble together what I wanted.

In template.php I have a custom function:

THEMENAME_field__CONTENT_TYPE($variables)

Inside this function, I check for $variables['element']['#field_name'] in a switch statement. IF the switch statement equals the field that has the taxonomy reference (i.e., 'field_faction_affiliation') then I do the following:

case 'field_faction_affiliation':
    $base_path = base_path();
    $faction_icon_href = $base_path . $variables['element'][0]['#href'];
    $faction_icon_title = $variables['element'][0]['#title'];
    $faction_icon_url = file_create_url($variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]['uri']);
    $output = "";
    return $output;
    break;

I'm almost 100% certain that the base_path hobble I did is NOT drupal 'Best Practices' so if anyone has a suggestion for correcting that, please let me know. Otherwise. This is how I got what I wanted.


why and how the view is putted in the sidebar first block I am studying the distrbution OpenAID
http://drupal.org/project/openaid
---
I have a question:
in the block : sidebar first. there are some special view related with the url.

but in admin/struction/block. the sidebar first is none.

so question: why and how the view is putted in the sidebar first.

I get a clue : Exposed form , but more confuse is left.

resolved it
use context module.
Conditions select view
Reactions select block - sidebar first


Method of initiating a text trim at a matching string? Using Drupal 7, I'm creating nodes by email using Feeds and Mailhandler. The body of the email is mapped to the body of the node. I'd like to trim the text to eliminate boilerplate language from the email so that it's not in the body of the node. I can't initiate the trim on a character or word count, because that will vary with each email. Is there a module, or a method in either Rules or Feed Tamper, by which I can initiate a trim when encountering a particular text string? If not, is there another method (like rewriting the string) that would achieve this? Thanks!

I'm answering my own question... To eliminate a text string in an imported node, I used the Feeds Tamper "find replace regex" plugin on the node's body.The regex to find was:

  /(?=FirstWord )(.*)(?<=LastWord[.])/s

Where FirstWord was the first word of the string to be eliminated, and LastWord[.] represented the last word of the string followed by a period. If you don't want to include punctuation, eliminate the [.] completely.

The trailing "s" indicates "single line mode," which makes the dot (before the asterisk) match all characters, including line breaks.

Of course, the replacement value was empty.


tag is not being parsed This is the RSS I want to import. I want to write mapping to fetch the <img> tag within the <description> tag. When I import I get this.

 xpathparser:3 :
   <description>&lt;img
   src="http://www.moneycontrol.com/news_image_files/2013/a/acquisitions_yahoo_tumblr.jpg"
   alt="Tumblr had $16.6 mn in cash when Yahoo acquired it" title="Tumblr had $16.6 mn in
   cash when Yahoo acquired it" border="0" width="75" height="75" align=" left"
   hspace="5"/&gt; The deal for Tumblr was the largest since Yahoo Chief Executive Marissa
   Mayer took the role in July with a focus on reversing a long decline in Yahoo's
   business and web traffic. The deal also made Tumblr founder and CEO David Karp, 27, a
   multimillionaire.</description>

What should be the xpath to get the <img> source?

I've tried Feeds Tamper to convert &lt; to < and &gt; to >and the following xpaths, but nothing works.

   //img/@src
   description[1]
   description/img
   description/img/@src

I am using Drupal 7.

This cannot be done the way you are trying. HTML embedded in XML is no different than regular text in XML. XPath has no way to look inside the HTML to query it.

There is some work being done, essentially adding another parsing step, https://drupal.org/node/1459870.


How do I get the name and URL alias of a vocabulary using only  the vid? I need the URL alias of the vocabulary, not the term and not the machine name; I need the name that appears to the user.

You can use taxonomy_vocabulary_load() to obtain the machine name of a specific vid.

Example usage:

$vocabulary = taxonomy_vocabulary_load($vid);
$machine_name = $vocabulary->machine_name;
$name = $vocabulary->name;

Vocabularies aren't exposed to the user like terms are, so they don't really have an url-alias. The name which is presented in the vocabulary list is $name in the above code.


Custom Path Alias with Initial Letter as Token For various reasons, I need to change my custom path alias for a taxonomy type as follows...

FROM:
/composers/aardvark

TO:
composers/a/aardvark

So I'm looking at either creating a custom token, or a computed field to figure out the first letter of the term and feed into the pathauto module...

I'm having trouble figuring out either... Could anyone suggest the correct code to use for either of these? Most of the examples I am finding are node specific, and not taxonomy term specific...

The reason I'm looking to do this, is to provide a contextual filter to a views block... But if anyone could suggest a good way to pass 'a' from 'aardvark' into the block - so that both of these paths passes the same contextual filter, that would be equally good!

/composers/a

/composers/aardvark

Thanks in advance for your help!

There are many ways to achieve this, as you said.

The less-coding way I see is to use Custom Token and create for each node a token using the following code :

return substr($node->title, 0);

Then you use this token in your URL alias pattern like [yournewtoken]/[node:title].

If you have a multi-lingual site, the first letter might not be the same in all languages, you may update this code to fit this.


Set a boolean (single on/off checkbox) value while creating a node I am creating a node (in Drupal 8) with the following code.

use \Drupal\node\Entity\Node;

$node = Node::create([
            'type' => 'calendar_data',
            'title' => 'testing finaly 1111111111111111111111111 ',
            'field_current_month' => date('Y-m-d'),
            'field_date_type_value' => '1',
        ]);
$node->save();

The value of field_date_type_value is set to 0, not the expected value (1) I am using in the code.

Sorry for late response, but I had the same problem few days ago. What worked for me was first of all creating the node and then setting the boolean value:

$node = Node::create([
        'type' => 'calendar_data',
        'title' => 'testing finaly 1111111111111111111111111 ',
        'field_current_month' => date('Y-m-d'),
    ]);
$node->field_date_type_value->value = true,

$node->save();

The 'inline' field setting didn't work neither for some other fields for me. But the explicit version is working very well.


How to automatically assign a role based on email address domain? How do I automatically assign a role to new users based on the email address domain?

For instance if the email address is someone@examplecompany.com, and the condition is that all users from examplecompany.com should always have the role specialclient. How do I acheive this?

I am using Rules, but there are no specific email conditions to be found. Can I create my own Rules Condition? If so, I would be very grateful for any tips on how to accomplish this.

Yes you could create your own (custom) Rules Condition. But in this case I don't think that's needed. The clue to what you're asking for, is a Rules Condition which is a "text comparison".

In that comparison, you use a regular expression to indicate "the email address should end with "@examplecompany.com".

For an example rule which also uses such RegEx-expressions, refer to the answer to "How to use the Rules module to perform a simple anti-spam validation using specific keywords?".

Be aware: I'm not a RegEx expert ..., but here a few dozens of similar examples using a RegEx ...

However, I predict you'll have multiple domains/roles to be processed. So the real Rules fun starts when this (typical) question arises: "I need to add something like a Rules Condition inside the Rules Actions, how can I do that?"

To resolve this typical question, there are basically 2 approaches (that I am aware of):

Use the Conditional Rules module. For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".
Rework the relevant part of your Rules Action(s) into performing a Rules Component. Because in a Rules Component, it is possible to also add Rules Conditions.


Expand views visible fields with ajax I'm searching for a module that can expand the number of visible fields in a particular view result with a mouse click. I'm probably not searching with the good words because I only thing I found is thing like "infinite scroll" or "view load more" module and that's not what I nead.

Example of what I nead : You have 10 view nodes showing the title and the image of a content type. And when the user pays "Read more..." the node is reloaded with Ajax adding the description to the result of this result.

Did somebody know a module that can do a thing like this?

Thanks a lot and sorry for my bad English, English isn't my first language.

The screen cast from Sean Buscay : How to use Drupal 7's built-in Ajax framework almost do that. The only difference is that the loaded nobe is always display on the same div base is id.

<?php

function ajax_reader_init() {
  drupal_add_js('misc/jquery.form.js');
  drupal_add_library('system', 'drupal.ajax');
}

/**
 * Implements hook_menu().
 */

function ajax_reader_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-reader'] = array(
 'page callback' => 'ajax_link_response',
 'access callback' => 'user_access',
 'access arguments' => array('access content'),
 'type' => MENU_CALLBACK,
  );
 return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
  $output = _ajax_reader_load_noder($nid);
  if ($type == 'ajax') {
    $commands = array();
    $commands[] = ajax_command_replace('#block-block-6', '
' . $output . '
');
    $page = array(
      '#type' => 'ajax',
      '#commands' => $commands
    );
    ajax_deliver($page);
  }
  else {
    $output = '
' . $output . '
';
    return $output;
  }
}

function _ajax_reader_load_noder($nid = 0) {
 return views_embed_view ('front','block', $nid);
}

Now the problem is I don't wan to send the result always to the same div. I wan to replace the view row by the new ajax loaded view. But I don't know how to pass the result to the good div.

    $commands[] = ajax_command_replace('#block-block-6', '
'

Lets say I click the title of the third view row the nid of this third element is process in the module but I nead a way to pass the parent div class (view-row-3) to the function ajax_reader_menu()

Did anybody can guide me on that, thanks
I know that I'm not super clear, but all this still vary obscure for the moment, sorry.