AJAX callback not added using form_alter I want to perform a AJAX callback to check the value of a custom field during user registration. Because the form is already built, I need to use hook_form_alter.

But, no callback is added using hook_form_alter. Maybe it is overwritten later on? Therefore, I tried $form['#after_build'].
But that fails too for the AJAX property. Adding another form element works perfectly fine.

The code:

/**
 * Implements hook_form_alter().
 */
function member_id_check_v2_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
    case 'user_register_form':
    case 'user_profile_form':
      $form['#after_build'][] = '_member_id_check_v2_ajax';
      break;
    default:
      break;
  }
}

function _member_id_check_v2_ajax($form, &$form_state) {
  $form['member_id_check_v2_callback_wrapper'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
  );

  $form['custom_field']['#ajax'] = array(
    'callback' => '_member_id_check_v2_callback',
    'wrapper' =>  'member_id_check_v2_callback_wrapper',
  );

  return $form;
}

function _member_id_check_v2_callback() {
    watchdog(WATCHDOG_DEBUG,'Callback worked!');
}

What am I missing? Thanks in advance!

You need to do the AJAX callback on #process callback as #after_build callback is too late to inject AJAX.

Check out the this link and the example code:

/**
 * Implements hook_form_alter()
 */
function kf_link_form_alter(&$form, &$form_state, $form_id) {
  if ('example_node_form' == $form_id) {
    //$form['field_link'][$language]['#after_build'][] = '_kf_link_field_link_after_build';
    $form['field_link'][$language][0]['#process'] = array('link_field_process', '_kf_link_field_link_process');
  }
}

/**
 * Custom form api process function
 */
function _kf_link_field_link_process($element, &$form_state, $form) {
  $element['url']['#description'] = '

';
  $element['url']['#ajax'] = array(
    'callback' => 'kf_link_ajax_callback',
    'wrapper' => 'example-link',
  );
  return $element;
}

/**
 * Custom ajax callback function
 */
function kf_link_ajax_callback(&$form, $form_state) {
  $values = $form_state['values'];
  $field_link = $values['field_link'];
  $language = $values['language'];
  $url = $field_link[$language][0]['url'];
  $duplicate_nodes = _kf_link_get_url_nid($url);
  foreach ($duplicate_nodes as $duplicate_node) {
    if (isset($duplicate_node->nid) && ($duplicate_node->nid != $values['nid'])) {
      drupal_set_message(t('This URL already exists in !title', array('!title' => $duplicate_node->title, '!url' => "node/{$duplicate_node->nid}")), 'error');
    }
  }
  $commands = array();
  $commands[] = ajax_command_html(NULL, theme('status_messages'));
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}


How can i integrate geofield module in entityform? Actually i have to add multiple locations in a form of a route and show it after the submit button in a single map using geofield module. How do i do that???The map should locate multiple markers after submit button in one map with their latitude and longitude... the image mentioned in the second is my first image which i am getting now whereas the image been showed at first should be my output image...

i got a better way to do this the thing i wanted was to create integrate multiple locations in one Maps and display the route.. I created this using a HTML file using HTML,CSS, JavaScript and using Markup module i integrated my code in my Entityform. I is working like a charm.


Checking where are users coming from to the landing pages We have a site that contains few "landing pages" of different campaings. Links to those landing pages are sent by newsletter. Now if user visit one of the landig pages I would like to programatically recognize if he is coming from outer source (from newsletter link) or is just browsing the site. Is it possible to recognize if the page is opened from email?

One of the solution could be to append a GET parameter to the newsletter links, but I'm afraid it will be not a good idea to force our customer to do it everytime. The other solution could be to check REFERER, but I'm not sure how reliable is this. If I could to decide that user is coming from outer source it could be enough.

What could be a suitable solution for this task?

If you are able/willing to add some type of query parameters, you should be able to make this work using the Rules module, as detailed below.
Assume a path like /index.php?campaign=123) you can make the value (= 123) of the URL argument (= campaign) available as a new variable to the Rules module. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


save views->execute result as a static variable Does it make sense (performancewise) to store view->execute() as a static variable in order to avoid running same view multiple times?
And then call view->render() wherewer I want to print the view? Does it make any sense? Or are there better options? Thank you

It heavily depends on what you're trying to achieve with caching.
If you're trying to avoid additional DB queries, you won't be adding much here. The view::execute() & view::render() are already making use of its own caching system (if it's enabled on the view in question).
If you're trying to avoid all the theme/module hook execution overhead, yeah that will avoid it. Of course, the trade-off is modules/themes won't be able to modify a view (if that's needed) and you'll have to handle other cache invalidation scenarios as a result of your custom caching.
You'll have to make the call depending on how/what you're trying to optimize it that's worth the trade-off (generally, I would say no but that's opinion).


How to do join on Drupal dynamic query Following the documentation on https://www.drupal.org/docs/7/api/database-api/dynamic-queries/joins I have constructed a very simple dynamic query with join:

$query = db_select('node', 'n')
     ->condition('n.uid', $promoter, '=')
     ->condition('n.type', 'campaign', '=')
     ->condition('n.status', '1', '=')
     ->fields('n', array('nid'));
     $query->join('field_data_field_department', 'd', 'n.nid = d.entity_id');

  $result = $query->execute();
    foreach ($result as $record) {
      debug($record);
}

and it only returns nids whereas the expected results were nids together with the field_data_field_department field values. What should the correct query.

You're only selecting the nid field, you just need some more:

...
->fields('n', array('nid'))
->fields('d', array('fields', 'you', 'want'));


D7 comment form doesn't submit I've successfully printed a comment form on a views-built page using a PHP Views field (as found in this question). The form doesn't submit right away though - instead of submitting, the comment "save" button redirects to the "comment/reply/[nid]" page with blank values.

Comment form print code:

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);

Are there extra details that should be added to the $comment object before or during the drupal_get_form() or render() calls?

Try next:

// ...
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);
$form['#redirect'] = 'CHANGE_VIEWSPAGE_HERE?page=' . (int)$_GET['page'];
print render($form);


theme_preprocess_views_view_fields() function in drupal7 does not accept static variable as index This is my code

function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
    $variables['address1'] = t($variables['view']->result[0]->field_address[0]['raw']['uri']);
    $i++;
}

I wrote the following code in views-view-fields-VIEWNAME--page.tpl.php :

<?php print $address; ?>
<?php print $address1; ?>

the second print successfully printed its relevant value but the first one displayed nothing.

I tried to use this trick but i failed :

<?php
if($i==0)
    $variables['address'] = t($variables['view']->result[0]->field_address[0]['raw']['uri'];
if($i==1)
    $variables['address'] = t($variables['view']->result[1]->field_address[0]['raw']['uri'];
.
.
.

?>

why can't I use static variable as index?

UPDATE

after useful comment of Clive and arpitr I modified my code and I created two THEME_preprocess_views_view_fields functions separately as follow:

function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $view = $variables['view'];
    if($view->name == "MY_VIEW_NAME")
    {
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
    $i++;
     }
}

and this one

function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $view = $variables['view'];
    if($view->name == "MY_VIEW_NAME")
    {
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
     }
}

for the upper one it was the result

Array

and the second one (without $i++) successfully printed the right value.

Static vars aren't special beyond persisting inside the scope of the function they were created, for the duration of a single page build. You categorically can use a static var as an array index.

Take the following code:

function some_test(&$variables) {
  static $i = 0;
  print $variables[$i];
  $i++;
}

$variables = array(
  0 => 'test1',
  1 => 'test2',
);

some_test($variables);
some_test($variables);

Which outputs the following:

test1
test2

Proving that $variables[$i] is accessed as expected.

The problem with you code must be somewhere else, as it's not being caused by a language issue as you suggest.

At a wild guess, $variables['view']->result isn't keyed in the same way you expect it to be (possibly keyed by the result's base table ID instead of a zero-based list). Dumping out $variables['view']->result should tell you pretty quickly what's happening.


Deleting feature[]=logo from .info file, enlarged the whole website font-size? During the theme learning I deleted the feature[]=logo line from .info file  to check its effect at UI. As  expected it got deleted from the toggle list at appearance->theme->toggle option. But simultaneously font-size of whole site got increased, I re-wrote the feature[]=logo in .info, saved, cleared cache, but no effect. Something wrong has happened, has anybody experienced this? I am searching but not getting such kind of issue.

@codenext: Can you paste the screenshot of the css in chrome devtools. So that we can see which css code is creating that problem?


PDOException: SQLSTATE[42S02] - Base table not found So I am in a bind and have no idea where to go. I get the following message now after I tried to add a new field to a content type:

Error message
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wrrc-data.cache_field' doesn't exist: DELETE FROM {cache_field} WHERE (cid LIKE :db_condition_placeholder_0 ESCAPE '\\') ; Array ( [:db_condition_placeholder_0] => field\_info\_types:% ) in cache_clear_all() (line 167 of C:\data\htdocs\wrrc-data\includes\cache.inc).

I have looked everywhere and cannot seem to find the right answer for me, and am hoping someone who has dealt with this hellish nightmare might be able to help.

I have tried dropping the "non-existent" (even though I see it in the file directory) 'cache_field' table, it "supposedly" works and so I go on to create a new table (to replace the failed one). All the sites I went to for this problem suggested the following code:

CREATE TABLE IF NOT EXISTS `cache_field` (

cid varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
data longblob COMMENT 'A collection of data to cache.',
expire int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
created int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
serialized smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
PRIMARY KEY (cid),
KEY expire (expire)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...';

But after starting this sql command, I get the following error:

#1005 - Can't create table 'wrrc-data.cache_field' (errno: -1) (Details…)

Doesn't give me any more information (even the supposed "Details" page doesn't give me squat, all it talks about is the background for InnoDB, nothing to add to the error at hand.

Does anyone have any suggestions? I really don't want to recreate the site at all, as that is what some had suggested on other sites, but this is beginning to wear me down. If I do need to just create another site, is there a way to streamline the process of bringing over my data and formatting without having the error hitch a ride?

Thanks in advance, I really appreciate it. Matt

Chechout the link at https://www.drupal.org/node/2144205#comment-9288889 which suggests this:

  If your cache_field table is corrupt, you should be able to clear it by running update.php or cc all from drush. If you want to empty the table contents without deleting and rebuilding the schema, you can delete from cache_table or truncate cache_table.

Another suggestion is in the same link, located at https://www.drupal.org/node/2144205#comment-8368871 ...

If neither of those links help (or don't work), then investigate which module creates that table as part of it's install/enable process. Then uninstall and re-install that module ...


How to handle caching on a Drupal 8 custom Views access plugin that checks a User's Profile's field value I have a custom Views access plugin that check access against a value in the current User's Profile (entity) field value.

The plugin works but if I change the profile field value the access does not check again until the cache is cleared. I know this is an issue with setting up the cache tags/contexts but I cannot not figure out what is needed so that the cache is cleared when the user profile is updated.

Right now I'm not using any cache tags/contexts in my View access plug and I've tried various combinations without luck. Help!

Current cache functions:

public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $profile = \Drupal::entityManager()->getStorage('profile')->loadByUser(user_load(\Drupal::currentUser()->id()), 'employee');
return $profile->getCacheTags();
  }

A Views access plugin implements CacheableDependencyInterface. So you probably need to set a tag and a context for the current user in these methods:

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return ['user:' . \Drupal::currentUser()->id()];
  }


Which method is more efficient, database query or taxonomy term controller? I tried to find a method to verify if the current taxonomy item page has a parent or children, now I get two but I don't know which one is better for the efficiency.

approach I: use taxonomy item controller

$tid = \Drupal::routeMatch()->getRawParameters('taxonomy_term');
$term = taxonomy_term_load($tid);
$items = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadChildren($tid,$term->getVocabularyId());

approach II: database query

$db = \Drupal::database();
$query = $db->select('taxonomy_term__parent','ttp')->condition('ttp.parent_target_id',$tid)->fields('ttp',['entity_id']);
$result = $query->execute()->fetchAll();

Both method can satisfy my initial demand, but which one is better in
efficiency? And what about the general case, when we need to check
some data, using the data object method or database query, which is
better?

Do you need to load all of the children? Otherwise, loadChildren() will be performing the same query but also loading the full term -- which is a performance dent. The API on the entity storage won't make much of a difference here, honestly.

Have you looked at https://www.drupal.org/project/taxonomy_term_depth? This would be more performant. It caches the depth level in a new base field. If a term's depth is greater than one, you know it is a child.

I would even borrow the concepts from taxonomy_term_depth to add a new base field that is a boolean which caches if the term has children or not. That way you only need to work with the current term entity.


How to create a full project on drupal.org? I have created a custom module in Drupal 7. And now I want to contribute this module via drupal.org. For this I have created my account on drupal.org and created a sandbox project.

Now I am not getting how to make it full project.

For promoting the sandbox module to full project requires for going through a one time review process.

Check:
Apply for permission to create full projects

Before creating an issue for the promotion, make sure you go through the project application checklist to get good reviews.


Multisite for intranet/extranet I'm currently developing a Drupal environment for a school project. I've already read a few books about Drupal, but still need to improve my skills when it comes to programming.

The project exists of developing a new intranet/extranet for existing content. Currently, the intranet/extranet exists of standard html files linked to eachother. The content on the intranet(intranet.example.com) is only available for users on the company network. However, some content needs to be available on the extranet (extranet.example.com).

I'd like to use one Drupal installation to manage all content, users... Is this possible by using a multisite configuration?

Multi-site is designed for a shared codebase with seperated content.
It is possible to share a few tables within all multi-sites without complications (e.g. users, roles, session) but espacially sharing  of content and content-types is not quite easy.

I would suggest Domain Access: http://drupal.org/project/domain

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites


How to get my custom module to recognized a exported view? I have created a view and then exported it normally to a yml file. Then I put this yml file into my mycustommodule/config/install folder.

So current its named mycustommodule.view.user_assigned.yml

However when I uninstall the module and reinstall it to see if it will upload the view, it does not. What am I doing wrong?

Edit: I copied and pasted the yml file itself so there should be no errors there. The only thing I did was remove the UUID string since I read elsewhere it was not needed.

The first part of a config item filename is the module responsible for the config type, not the module installing it.

In your case that's "views", so the file should be named views.view.user_assigned.yml.


How can i only allow published content to appear on the front page? I'm using the Scheduler module to schedule when certain nodes get published&unpublished. Now, they are set to be "Promoted to the front page" and even after the Scheduler unpublishes the content, it stays promoted to the front page where it still appears and leads to a dead link.

How can I automatically set the content to also get un-promoted from the front page when it gets unpublished?

I also submitted a feature support request here: https://www.drupal.org/node/2672500 - and I'll update this post with comments from that post on drupal.org to keep the two threads in sync!

EDIT 1
My front page is the default front page that comes with Drupal 7. I understand, that if I had my own view, I could select what kind of content gets displayed. But how can I do this with the Drupal 7 news feed?

EDIT 2
With mchar's suggestion, I came up with follwoing patch:

--- scheduler_orig.module   2016-02-20 12:52:02.002658565 -0800
+++ scheduler.module    2016-02-20 12:50:57.174657579 -0800
@@ -20,6 +20,20 @@
 define('SCHEDULER_DATE_LETTERS', 'djmnFMyY');
 define('SCHEDULER_TIME_LETTERS', 'hHgGisaA');

+/** [inserted by Ron 02/20/2016] -  to automatically unpromote a node as it gets unpublished**/
+/**
+ * Implements hook_node_presave().
+*/
+function my_module_node_presave($node) {
+  $was_published = !empty($node->original->unpublish_on);
+  $now_is_unpublished = empty($node->unpublish_on);
+
+  if (!$node->is_new && $was_published && $now_is_unpublished) {
+    $node->promote = 0;
+  }
+}
+/** [/inserted by Ron 02/20/2016] **/
+
 /**
  * Implements hook_permission().
  */

As far as I know scheduler module is not responsible for promoting or not nodes to the frontpage, so you have to go with a custom solution.
Try to implement hook_node_presave as follows:
/**
 * Implements hook_node_presave().
*/
function my_module_node_presave($node) {
  $was_published = !empty($node->original->unpublish_on);
  $now_is_unpublished = empty($node->unpublish_on);

  if (!$node->is_new && $was_published && $now_is_unpublished) {
    $node->promote = 0;
  }
}

Hope that helps!


How to send an email notification when a subcription renewal is due? When a subscriber’s monthly subscription is due for renewal, an automatic email should go to that user stating that the renewal is due. There will be two possibilities:

If there is no response to the notification, automatically the CC will be charged as per the current package selected.
The automatic eMail notification will have a link to upgrade to a different package if the subscriber wants to.

How to achieve this?

Part 1 - Sending eMail notifications
Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate renewal date of a specific package. To support multiple packages, just create similar date fields (1 for each package type).
Step 1: Create a field to store the renewal date
Add a field to the "user" entity with machine name (say) field_next_renewal. Allow only 1 date (to store the "next" renewal).
Step 2: Create a Rules "Component"
Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your upcoming renewal",
          "message" : "This is a reminder about the upcoming renewal  on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Message of the eMail may need review / tuning, while you might also want to use some other From eMail ID. The Message-part of it is also where you can add the "link to upgrade to a different package" (as in your question).
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):
{ "rules_on_user_renewal" : {
    "LABEL" : "On user renewal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 259200 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step. It gets triggered any time a user profile is updated (feel free to replace that Rules Event with any other event that might fit).
The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).
Step 4: additional refinements

The date_offset (=259200) in the above rule corresponds to "3 days in advance", which may need review / tuning.

If needed, you could also use the Field Permissions module to set field-level permissions to edit, view and create this renewal field.

Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Part 2 - Tracking possible responses
If you'd also use the Flag module, you could enhance the above Rules logic to also "flag" the user (to indicate that you're waiting for some kind of response to the renewal eMail. By creating a view (using the Views module), you could then simply list the flagged users for which you do not have some desired response (those are the users who didn't perform a renewal).
Happy Rules-ing!


Add a custom action on admin content page I want to add a custom action to the dropdown on the admin content page (/admin/content) as shown in the screenshot below using Drupal 9. The views module is enabled so that form is part of the view.

I have found that actions are now plugins so I should just need to create a new plugin for my custom action.
I've used the actions found in /core/lib/Drupal/Core/Action/Plugin/Action/ as an example for my new action so just created a new plugin that extends EntityActionBase add added the relevant methods.
I have a custom module called shop_scrape.
I created the file shop_scrape/src/Plugin/Action/ScrapeAction.php
That file contains:
<?php

/**
 * @file
 * Contains \Drupal\shop_scrape\Plugin\Action\ScrapeAction.
 */

namespace Drupal\shop_scrape\Plugin\Action;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\Plugin\Action\EntityActionBase;
use Drupal\Core\Annotation\Action;
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Scrape a page.
 *
 * @Action(
 *   id = "entity:scrape_action",
 *   label = @Translation("Scrape a page"),
 *   deriver = "Drupal\shop_scrape\Plugin\Action\EntityScrapeActionDeriver",
 * )
 */
class ScrapeAction extends EntityActionBase
{

  /**'
   * ScrapeAction constructor.
   * @param array $configuration
   * @param $plugin_id
   * @param $plugin_definition
   * @param EntityTypeManagerInterface $entity_type_manager
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager)
  {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
  {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function executeMultiple(array $entities)
  {
    foreach ($entities as $entity) {
      \Drupal::messenger()->addMessage('Scrape ' . $entity->id());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function execute($object = NULL)
  {
    $this->executeMultiple([$object]);
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE)
  {
    $access = AccessResult::allowed();
    return $return_as_object ? $access : $access->isAllowed();
  }

}

Then I also created a EntityScrapeActionDeriver that for now just returns true:

<?php

namespace Drupal\shop_scrape\Plugin\Action;

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Provides an action deriver that finds scrapable entity types.
 *
 * @see \Drupal\Core\Action\Plugin\Action\PublishAction
 * @see \Drupal\Core\Action\Plugin\Action\UnpublishAction
 */
class EntityScrapeActionDeriver extends EntityActionDeriverBase {

  /**
   * {@inheritdoc}
   */
  protected function isApplicable(EntityTypeInterface $entity_type) {
    return true;
    //return $entity_type->getLabel() == 'page';
  }

}

But my custom action is not appearing. Are there other steps I need to take or have I done something wrong?

Here is a sample code which creates a custom action plugin which modifies node title.
action_plugin_examples/src/Plugin/Action/ArchiveNode.php
<?php

namespace Drupal\action_plugin_examples\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\pathauto\PathautoState;

/**
 * Provides an Archive Node Action.
 *
 * @Action(
 *   id = "action_plugin_examples_archive_node",
 *   label = @Translation("Archive Node"),
 *   type = "node",
 *   category = @Translation("Custom")
 * )
 */
class ArchiveNode extends ActionBase implements ContainerFactoryPluginInterface {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Logger service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The path alias manager.
   *
   * @var \Drupal\path_alias\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Language manager for retrieving the default Langcode.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = new static($configuration, $plugin_id, $plugin_definition);
    $instance->logger = $container->get('logger.factory')->get('action_plugin_examples');
    $instance->messenger = $container->get('messenger');
    $instance->aliasManager = $container->get('path_alias.manager');
    $instance->languageManager = $container->get('language_manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $node */
    $access = $node->access('update', $account, TRUE)
      ->andIf($node->title->access('edit', $account, TRUE));
    return $return_as_object ? $access : $access->isAllowed();
  }

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {

    /** @var \Drupal\node\NodeInterface $node */

    $language = $this->languageManager->getCurrentLanguage()->getId();

    $old_alias = $this->aliasManager->getAliasByPath('/node/' . $node->id(), $language);

    $title = $node->getTitle();
    $date = $node->created->value;
    $year = date('Y', $date);
    // $old_alias = $node->path->alias;
    $new_title = $this->t('[Archive] | @title', ['@title' => $title]);
    $node->setTitle($new_title);
    $node->setSticky(FALSE);
    $node->setPromoted(FALSE);

    $new_alias = '/archive/' . $year . $old_alias;
    $node->set("path", [
      'alias' => $new_alias,
      'langcode' => $language,
      'pathauto' => PathautoState::SKIP,
    ]);

    $node->save();

    $message = $this->t('Node with NID : @id Archived.', ['@id' => $node->id()]);

    $this->logger->notice($message);
    $this->messenger->addMessage($message);

  }

}

action_plugin_examples/config/optional/system.action.action_plugin_examples_archive_node.yml
langcode: en
status: true
dependencies:
  enforced:
    module:
      - action_plugin_examples
  module:
    - node
    - pathauto
id: action_plugin_examples_archive_node
label: 'Archive Node'
type: node
plugin: action_plugin_examples_archive_node
configuration: {  }

Note : plugin yml file needs to be in the below format.

system.action.<plugin_id>.yml


Add user email and username under the "View" tab at /user/% Using Drupal 7 and I would like to display the username and email under the view tab of the /user page.

Out of the box it only shows the user History, which I find a bit meaningles. I think that a user should see all his info under the view tab (including username and email) and then when he wants to edit it he can click on the edit tab.

Would be nice if this could be done with a block or similar so that this does not apply to the admin user.

Thanks!

You can always create a block through Views and display this information. Here's how to do that:

Create a new view, choose to show "Users" and create only a block.
Add "E-mail" field.
Add "Contextual filter" for the "User: Uid" field.
For filter configuration choose "Provide default value" and then "User ID from URL".
Show the block in content area, and configure it so it's displayed only on specific pages. Enter the aliased path you use for user profiles. For example: profile/*. This is necessary because the system URL for user profile pages is user/[uid], which you cannot distinguish from user/login, user/register and so on.

Do note that this will make the username/email available to everyone who has the permission to view user profiles.

Hope this helps.


How do I add validation in the node processor before creating a node? I'm using Feeds import module, after importing CSV file, if a row doesn't match content type validation the feeds import saves that node with empty space in that field.

Question:
Now i want FeedsNodeProcessor to validate the node, and if there is a empty space it should throw error for that node or should not create node for that row.

Example:
If i have 40 rows in an excel and 39 rows satisfies the conditions of content type and only 1 row doesn't then it has to like this,
39 nodes created.

Updated:
i have added hook_feeds_prevalidate() in my hook_form_alter module.

 function tracker_custom_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'orientation_node_form'){
      $form['#validate'][] = 'validate_orientation';
}
}
function validate_orientation($form,&$form_state)
{
....
}
function tracker_custom_feeds_prevalidate($source, &$entity, &$item, $entity_id) {
//      dpm($entity->feeds_item->id); - its not printing anything.
//      dpm($item); - its not printing anything.
  if ($entity->feeds_item->id == 'bulk_upload') {
     if (empty($item['Billing Type'])) {
         $entity->feeds_item->skip = TRUE;
         drupal_set_message('ksdhbf');
   }
 }
}

You can add this functionality in a custom module. But you'll have to add the logic that you have in your node's validation here.

/*
 * Implements hook_feeds_prevalidate()
 */
function mymodule_feeds_prevalidate($source, &$entity, &$item, $entity_id) {
  // the $item contains your csv files column values
  if ($entity->feeds_item->id == 'import_name') { // check the feed import ID
    if ($item['some column'] != 'something') { // validate column value
      $entity->feeds_item->skip = TRUE; // skips this row from importing
    }
  }
}

Important: I think you'll need 7.x-2.x-dev in order for this hook to work, I'm using it. This is a new hook and I think it has not been added to 7.x-2.0-beta4 yet.


Delete node references for some content types only Unless there's a method I'm unaware of, node references are not related to their node's content type. I need to delete referenced nodes when the target ids are not of a certain content type. Here's my code so far.

// Get My content type nodes.
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->execute();
/** @var \Drupal\node\NodeInterface[] $nodes */
$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
  // Select the related nodes from each node.
  $result = \Drupal::database()->select('node__my_reference_field', 'n')
    ->fields('n')
    ->condition('entity_id', $node->id())
    ->execute();

  // Determine what content type the related node is.
  while ($record = $result->fetchAssoc()) {
    $query = \Drupal::database()->select('node_field_data', 'nfd');
    $query->fields('nfd', ['type']);
    $query->condition('nid', $record['my_reference_field_target_id']);
    $type = $query->execute()->fetchField();

    if ($type != 'content_type_one' || $type != 'content_type_two') {
      \Drupal::database()->delete('node__my_reference_field')
        ->condition('entity_id', $node->id())
        ->condition('my_reference_field_target_id', $record['my_reference_field_target_id'])
        ->execute();
    }
  }
}

If this line

if ($type != 'content_type_one' || $type != 'content_type_two') {

were

if ($type == 'content_type_one' || $type == 'content_type_two') {

the related nodes of content_type_one and content_type_two are deleted. Using != removes all the related nodes on the node. I only want to remove the related nodes that are not of content_type_one and content_type_two.

What am I missing?

@Jaypan here's the exact code that takes nine minutes to run.

function my_module_update_8008() {
  // Get the nodes.
  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_type')
    ->execute();

  /** @var \Drupal\node\NodeInterface[] $nodes */
  $nodes = Node::loadMultiple($nids);

  foreach ($nodes as $node) {
    // Delete references on the nodes that are not news or story.
    foreach ($node->get('field_entity_reference')->referencedEntities() as $entity) {
      drush_print($node->id());
      if (!in_array($entity->bundle(), ['news', 'story'])) {
        $entity->delete();
      }
    }
  }
}

drush_print() is for debugging purposes. During the run of this code, a $node->id() prints every 1 or 2 seconds. As you well know, to run an update_N hook from the command line, use

drush php-eval 'module_load_include('install', 'my_module'); my_module_update_8008();';

Anyway, it's 160 nodes x ~20 node references for each node. So the drush_print() helps me understand where the time is going.

Thanks for your help. I didn't mean to sound ungrateful. I think referencedEntities() and $entity->bundle() and the like are great, but I find them too slow. Once I have the field table populated with only the records I need, drush cr gets the referenced nodes to print in the text fields on the admin. I'll post my query code when I get it working again.

Btw, it's getStorage() not loadStorage() with entityTypeManager(). Thanks again.

Your code can be made more concise using Drupal APIs. It's rare that DB queries are required in Drupal 8, as the system generally has APIs that handle it for you. Here's how I'd do what you're trying to do. I think the key you were looking for is the line with in_array().

// Load all 'some_content_type' nodes.
$properties = [
  'type' => 'some_content_type',
];
$nodes = \Drupal::entityTypeManager()->loadStorage('node')->loadByProperties($properties);

foreach ($nodes as $node) {
  // Loop through the entities referenced by the field.
  foreach ($node->get('my_reference_field')->referencedEntities() as $entity) {
    // Only act if the entity is not one of the given types.
    if (!in_array($entity->bundle(), ['type_1', 'type_2'])) {
      // Delete the entity.
      $entity->delete();
    }
  }
}


Unable to get all the sub-menu's in the data compare I am trying to add a rule for comment view for which under the actions I click on data compare.As per the tutorial, I have to click the drop down list and choose node.

Whereas when I repeat the exact same steps from the Conditions->data compare I got some lesser menu option :

Now my problem is that as I don't have the node option to choose how am I supposed to complete the tutorial.

This kind of missing options appear quite frequently (when I tried to add an action/replacement patterns/ I had to choose the node type whereas in the options list there was no [node:type]. Again after 24 hours when I re-try this I get the [node:type])

I don't get the reason which is causing this problem. After doing the troubleshooting steps like re-login, clear browser cache, flush cache the options list is still the same.

As a temporary way around I have done the reinstall of 7.34 and installed all the modules from the start.This got me back the menu but I cannot do the un-install every time this problem comes.
I will be losing a lot of time


External URL to internal images Suppose I have a link field for internal images. $node->file_image->uri will for instance return:

internal:/sites/default/files/image/image.jpeg

I need to convert this into an absolute URL for metadata. I can do this manually, of course, but let's see what the usual functions do:

file_create_url() = "https://example.com/internal%3A/sites/default/files/image/image.jpeg"
file_build_uri() = "public://internal:/sites/default/files/image/image.jpeg"
file_create_url(file_build_uri()) = "https://example.com/sites/default/files/internal%3A/sites/default/files/image/image.jpeg"

No cigar, not even close. The new functions?

Url::fromUri()->toString() = "internal:/sites/default/files/image/image.jpeg"
Url::fromUri()->toUriString() = "base:sites/default/files/image/image.jpeg"

So, how to do it without doing it manually, of course? Removing internal: and prepending $base_url is very simple but still a hack.

Found it finally:

Url::fromUri($node->field_image->uri)->setAbsolute(TRUE)->toString()


Export View results to CSV I have a listing view with filters and a button to export the results to a CSV file. How can I send the view's arguments to my export callback after a user applies some filters?

Have you looked at Views Data Export. I've wired in a view to export on button click. You just build or modify a FAPI form to contain a button and give it the url of the view you want to output as csv.

In your case you'd pass the selected arguments into the view. You could use FAPI and Javascript to properly build the url and button action.


How do I update a module manually? I need to update my Views module in Drupal 7. Drupal won't do it automatically. It says the download is not available.

I have downloaded the new version manually, but when I try to install it via 'add new module', the message is 'views is already installed'. How do I update the module?

Updating a module is usually two steps:

Replace the files with the new version you downloaded, for example via FTP.
Run update.php (it is not always needed, but run it to check if updates are needed).

When updating, it can be a good idea to try the update on a local development environment to check that nothing breaks, and do a backup before the live update. Some updates are minor and won't need this.

Views, which stores a lot of configuration in the database and has recently undergone major changes, is one of those modules where you usually want to test it out before upgrading.


Native Android app with Drupal backend and Login I need to create a native Android app, this app will use Drupal as a back end.

The app must be native. All the back end functionality, will be taken care of in Drupal, even the login credentials. I will use JSON to get the data from Drupal

I have a few questions on what is possible.
Login credentials are stored in Drupal DB. How can i login to Android with these credentials? Can i use JSON and what about the password? The password need to be encrypted.

Is there something like a password protected JSON url? I don't want anyone not authorized to see the JSON url.

If you have any advice or suggestion please let me know.
I am new to Android and not an experienced programmer.
Thanks in advance

You didn't mention your version of Drupal, and I cannot speak for D8. But D7 has the Services module, and this provides all the functionality you will need. We use the Oauth2 module (that ties in with Services) to provide the authentication mechanism for the apps we build. With this, the user will first log in with their credentials, from which they will receive an authentication token. This token is then used for all further communication between the app and the server.

The Services module is highly customizable, and can be used to code your own resoures that can be called through the API from the app. You can choose the output format, of which JSON is one option.

Shawn answered your questions regarding protection of the user's credentials. This is the same as with a browser - use HTTPS (SSL certificate) and the credentials will be protected. If you don't use HTTPS, the credentials will be there for anyone who looks.


How to use Rules to send an email to an email id based on a selected in a registration form? I have created a rule for sending an email after a new user registered. I would like to add a Rules Condition to send the email to the target based on the selection in the registration form.

For example: if I select the country as india I need to send to india@gmail.com and for other others@gmail.com.

I have tried adding a condition in To mail receipt address:

$email = ($account->country == 'india'? india@gmail.com : 'other@gmail.com')
echo $email;

Can you suggest how to handle the scenario?

You should be able to get this to work by creating a single rule using the Conditional Rules module (and Rules of course). The rule should be trigger by Rules Event "after saving a new user account".

For some samples to put together such rule (in Rules export format), refer to my answer to either of these questions:

How to set the values of some fields depending on the value of a list box?
How to specify a Rules condition related to select list values?

The actual Rules Action you want to use, should be pretty similar to the Rules Action included in my answer to "How to send an email via a Rules action using a field key?".


login user after form submit I have a form that one of fields is mail field, when form submit I check that email if not belongs to any user I create a user  and assign that node to the created user, Then I want logged in that user automatically after user create a node.

I have below solution  but not work.

function mymodule_form_node_form_alter(&$form,&$form_state,$form_id)
  {
 if($form_id=="my_content_type")
 {
if($user->uid==0){
        array_unshift($form['#submit'], '_tgdev_ss_submit');
   $form['actions']['submit']['#submit'][]= '_tgdev_listing_suserlogin';
  }

   }
}

function _tgdev_ss_submit(&$form, &$form_state)
{
        $mail=form_state['values']['field_mail']['und'][0]['mail'];
    if(!user_load_by_mail($mail)){
        $account = new stdClass;
        $account->is_new = TRUE;
        $account->name = _tgdev_username_pattern_generate();
        $account->pass = user_password(8);
        $account->mail = $form_state['values']['field_email']['und'][0]['email'];
        $account->init = $form_state['values']['field_email']['und'][0]['email'];
        $account->status = TRUE;
        $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
        user_save($account);
        $op = 'register_no_approval_required';
        $status = _user_mail_notify($op, $account);
        $form_state['values']['uid'] = $account->uid;
        $form_state['values']['name'] = $account->name
        }
 }

function _tgdev_listing_suserlogin($form,$form_state)
{
//$user_obj = user_load_by_mail($form_state['values']['field_email']['und'][0]['email']);
$form_state['uid'] = $form_state['values']['uid'];
user_login_submit(array(), $form_state);
// ym($form_state,'message');
 $form_state['redirect']='node/'.$form_state['nid'];
 }
}

appreciate any help or suggestion

You could use something like auto_login_url and generate a url then redirect the user to that URL before you go to the node. This is mainly an API module that allows you to generate URL login links so you will have to code the solution. There are a couple of other URL login modules out there but this one has a pretty easy API to handle with no large learning curve.
From the module page:

Creates auto login URLs on demand and through tokens.
This is mostly a developer's module. The better use for me is to convert all links of a specific text to auto login links.

Similar module urllogin


How to get value of Textarea in node add form? In my node add form I have added one text area :

function mymodule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "contenttype_node_form") {
         if (!isset($node->nid) || isset($node->is_new)) {
             $form['extra']['#title'] = t('Title (Extra)');
             $form['extra']['#type'] = 'textarea';
             $form['extra']['#required'] = TRUE;
             $form['extra']['#cols'] = '15';
             $form['extra']['#resizable'] = FALSE;
             $form['extra']['#rows'] = '5';

             $form['#submit'][] = 'my_trans_submit';

        }
    }
}

function my_trans_submit(&$form, &$form_state){
  $swed_title = $form['extra']['#value'];
}

Above code display one textarea just after title field in my node form. I Need the value entered in this text-area when user click on save node and then I want to use that value and save translation by running node save function. I can get this on form submit, but at that time node is not created and nid is not available.

How can I get value entered by the users in the above textarea once the node is saved and the node ID will be available, allowing me to use node_save()? Do I have to use a form field? I was not using a form field as it creates a new entity table.

Shortly put, you need to do the following:

Use hook_form_alter, the way you do already
Use hook_node_submit, to update the field_title field on the node object, before it gets saved. In your hook implementation you will have access to both $form and $form_state, which should carry your custom textarea submitted value. Even if the nid is not there, your changes should still get stored in the new node.

Hope this helps!


Install drupal under subfolder I'm using a 3rd party hosting service for a Drupal 7 installation, and would like to put my Drupal site under the public_html folder like this:

public_html
|
|
|---->mysite
       |
       |-->includes
       |-->misc
       |-->modules
       |-->profiles
       |-->scripts
       |-->sites

However, I'm not sure what settings.php values I need to set, nor what if any .htaccess settings need to be changed?

You should be fine.  You will probably need to change the

$base_url = 'http://my-path/subdir';

in your settings.php so that drupal is aware of it.  Also in your .htaccess you will see

RewriteBase /drupal

that is commented out.  Uncomment this and add your path


How to check if maintenance mode is enabled in Drupal 8? I've been searching for a way to check in PHP if the maintenance mode of my Drupal website is enabled, but I only found some solutions for Drupal 7, which doesn't seem to work on D8.

Have got any ideas?

Thank you.

The maintenance mode of the site is a boolean value stored in a state. You can access it like this:

$state = \Drupal::state()->get('system.maintenance_mode');


Apache SOLR indexing stop working solr indexing has suddenly stop working.

Here is all the detail which i got from system admin

while running cron we are getting message during run cron.php through command

PHP Notice:  Undefined index:  REMOTE_ADDR in /var/www/XXXXXXX/includes/bootstrap.inc on line 1670
PHP Fatal error:  Exception thrown without a stack frame in Unknown on line 0

where should i look first and what are the possibility for apache solr indexing to stop suddenly.

The not to good solution was, deleted all the index of apache solr and tried with the fresh indexing and all of sudden all thing work well.


Check performance of drupal websites using some modules or tools My website starts well and after few days of access it goes terribly slow. Is there any module or any external tool to check the performance of the drupal website. So that we can point out where we are facing issues in drupal so that we can solve them. My pages are built out of average 5-6 views, does this effect the performance of the website ?

You could try new relic, it will give you insight into how expensive database queries are or where you have a bottle neck which is slowing down your site. It has some integration with Drupal and could also show you if you have a problematic module...

Also if your pages use a lot of views, have you tried caching the views? It is part of default views module, go into your view edit under "advanced" on the right. Click caching and turn this to time based. This means that rather than running each view query / view rendering on every page load - It will run it on the first load and retrieve a cache until it expires. The caveat here is that you will have a lag on the results for how ever long you choose to cache.


Module (or code) to display character count? I would like to add a simple character counter on a form textarea.

Is there a module that does this?

I don't want to limit the number of characters that can be input; I only want to display how many characters have been input in the textarea so far.

The Maxlength module has that functionality baked right in:

Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node)
When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation.

It works great for textfields and textareas alike. This is (roughly) what a textarea looks like after Maxlength is applied:


Why are some of my teasers only show up inside the view preview and not on the page? I've got a view that is displaying a couple different content types in teaser form. Everything looks fine in the view preview but when I look at the actual page, only one content type is displaying the teaser. I've tried comparing them and don't see any differences that would make any difference. Does anyone have an idea what the problem could be?

This is a screenshot of my view.

For each content type, go to "manage display" and then "Teaser". Make sure all the fields in there are set the same way as the content type that is working.


How can I implement a required disclaimer page? Whenever a user enters the site I would like a page with a disclaimer to appear, and only when you agree to the conditions can you enter the site.

What can I use to do this?

I'm assuming that once someone "Agrees" to your terms, you do not want them to have to agree on subsequent visits?

I'd like to recommend a forced registration. You can restrict the contents of your website to authenticated users only. To do this - go to admin/people/permissions and uncheck all permissions for anonymous users.

If you do not want to mess with site permissions, you can check out a great module:
https://www.drupal.org/project/anonymous_login
Anonymous Login will redirect anonymous users to the login page whenever they reach any admin-specified page paths.

Then I would customize your user registration process accordingly. Make it as lightweight as you want. I would check out the Site Disclaimer module to add your site terms functionality:
https://www.drupal.org/project/site_disclaimer

Also - if you're looking for a quick way to make the login/registration pages nicer - check out the "Better Login" module.

Depending on your version of Drupal - check out the "Agreement" module.
The Agreement module allows the administrator to present a text-based agreement (think "Terms of Service") that users of a particular role must accept before they are allowed to access the site.

Let me know if you would like more clarification. I hope this helps put you in the right direction, but you didn't provide much background info for me to help. (i.e what have you done so far, etc).

-Wrench


How do you change which content type a field is attached to (which one owns it?) While exporting configuration for my site using the Features module, I noticed that one of the fields I use on many content types was initially created on the "news" content type instead of the "article" content type. This presents a problem, since it means all of the features that I export are now dependent on a completely unrelated module (news) to provide a common field (field_image).

What I'd like to do is change the entity that "owns" field_image to be article. This will let me export one base feature which provides a bunch of common fields, and have the rest of the features depend on that instead of having them all depend on news.

How can I change which content type owns field_image without breaking everything?

Well, this isn't the perfect solution, but may be a way to find it.

Change your content type to what you want to have it and export the feature. Them take a difftool (winmerge) and look at the diffrences between the old version of your features module and the new  one.

There's a good chance that you find out what to change.

Don't forget to take a DB Backup before you start.


Automatically add users to the same group as their group admin I am using the Organic group module. I created 2 groups on my site. To each group I assigned 1 user as group admin. Group admins have the permission to create users.

My question is how to automatically assign the users which got created by a group admin to the group admin's group?

In Drupal 7, you can achieve it using hook_user_insert and OG function og_group.

hook_user_insert : Called when a user account is created
og_group : Set an association (e.g. subscribe) an entity to a group

 /**
     * Implemention hook_user_insert
     * @global type $user
     * @param type $edit
     * @param type $account
     * @param type $category
     */
    function HOOK_user_insert(&$edit, $account, $category) {
        global $user;
        $usr_grps = og_get_entity_groups(); //get all user groups
        if (count($usr_grps) > 0) {//if any groups
            $grp_mgr_grps = array();
            foreach ($usr_grps['node'] as $key => $gid) {
                $group_type = 'node';
                $group = entity_load_single($group_type, $gid);
                if (is_object($group)) {
                    if (!empty($group->uid) && ($group->uid == $user->uid)) {//subscribe only the groups where the user is group manager
                        $grp_mgr_grps[] = $gid;
                    }
                }
            }
            if (count($grp_mgr_grps) > 0 && is_object($account)) {
                HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account); //subscribe the group
            }
        }
    }

    /**
     *
     * @param type $grp_mgr_grps : array of group ids
     * @param type $account : Object of the user we want to add to the group
     */
    function HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account) {
        foreach ($grp_mgr_grps as $key => $gid) {
            $group_type = 'node'; //All groups are of type node
            $values = array(
                    'entity_type' => 'user',
                    'entity' => $account->uid,
                    'field_name' => FALSE,
                    'state' => 1,
            );
            og_group($group_type, $gid, $values);
        }
    }


How to grant User Points equal to the price of a Commerce Product? I would like to grant User Point to product owner in amount of product price after a product is sold.

For this I defined a rule as below:

Events: Completing the checkout process
Actions: Loop (commerce-order:commerce-line-items)

And I defined a Rules Component as below:

Conditions: Entity has field (Entity: commerce-line-item, Field: commerce_product)
Actions: Grant points to a user: (User: commerce-line-item:commerce-product:creator, Points: commerce-line-item:commerce-product:commerce-price:amount)

But when I save component it generates this Error message:

  Data selector commerce-line-item:commerce-product:commerce-price:amount for parameter points is invalid.

How I can do that?

At first I tried to answer your question using rules and userpoints module, but I saw that while adding Grant points to a user as action there is no such data selector for selecting the user who has created the product. I found the data selector for selecting the user who is the owner of order, but that is not your requirement. (That is why I clarified this in comments).

I found a module solution to your question. The module uses hook_commerce_checkout_complete(). From the hook page:

  Allows modules to perform business logic when an order completes
  checkout.

  This hook coincides with the "Customer completes checkout" event. Only
  business logic should be performed when this is invoked, such as
  updating the order status, assigning the order to a user account, or
  sending notification e-mails. Interaction with the user should instead
  occur through checkout panes on the checkout completion page.

This is the coding of the module I designed:

YOURMODULE.info file:

name = YOURMODULE
description = Module description
dependencies[] = commerce
dependencies[] = commerce_cart
dependencies[] = commerce_checkout
dependencies[] = userpoints
core = 7.x

UPDATE
As suggested by Clive, I have changed the module file so that this custom module will also work with multilingual sites.

YOURMODULE.module file:

/**
 * Implements hook_commerce_checkout_complete().
 */
function YOURMODULE_commerce_checkout_complete($order) {
  // Iterate through every commerce line item added in product.
  foreach (field_get_items('commerce_order', $order, 'commerce_line_items') as $line_item_id) {

    // Load commerce line item by line item id.
    $line_item = commerce_line_item_load($line_item_id['line_item_id']);

    // We do not want to include shipping cost in userpoints.
    if ($line_item->type != 'shipping') {
      // Load commerce product by product id.
      $product = commerce_product_load(field_get_items('commerce_line_item', $line_item, 'commerce_product')[0]['product_id']);

      // Create parameters.
      $params = array(
        'uid' => $product->uid,
        'points' => commerce_currency_amount_to_decimal(field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['amount'], field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['currency_code']),
      );

      // Grant userpoints programmatically.
      userpoints_userpointsapi($params);
    }
  }
}

Reference links:

userpoints_userpointsapi($params)

commerce_checkout API

commerce_line_item_load($line_item_id)

commerce_product_load($product_id)

Userpoints: deduct points programmatically

commerce_currency_amount_to_decimal()


How to programmatically print a webform block with caching enabled? When displaying a Webform inside a normal block (using admin/structure/block) Drupal manage to correctly cache the page, the HTTP header displays X-Drupal-Dynamic-Cache: HIT.
However we need to display this webform inside a paragraph so we tried the following :

use twig_tweak module and {{ drupal_block('webform_...') }}
programmatically put the block in a template preprocess like this :

$my_form = \Drupal\webform\Entity\Webform::load('contact_new');
$output = \Drupal::entityManager()
          ->getViewBuilder('webform')
          ->view($my_form);
$variables['contact_form'] = $output;

Both solutions seem to make the page uncacheable: X-Drupal-Dynamic-Cache: UNCACHEABLE.
What would be the correct way to put a block in a paragraph while make the page cacheable ?
How to mimic the standard block system to display a in our template ?

The Dynamic Page Cache needs to placeholder the dynamic part and it can only do so when it is built in a lazy builder:
/mymodule/src/WebformLazyBuilder.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class WebformLazyBuilder implements RenderCallbackInterface {

  public static function buildWebform($webform) {
    return  [
      'webform' => [
        '#type' => 'webform',
        '#webform' => $webform,
      ],
    ];
  }

}

Then you can put the lazy builder in a template preprocess hook:
$variables['contact_form'] =  [
  '#lazy_builder' => ['\Drupal\mymodule\WebformLazyBuilder::buildWebform', ['contact']],
  '#create_placeholder' => TRUE,
];

Blocks are placed in a lazy builder by default, see BlockViewBuilder::viewMultiple.


Render user login form with custom theme I have written a custom module, inside which I would like to create a custom user login block with custom theme applied. Now my question is "Inside my custom module, how do I get the user login form?"

You can use drupal_get_form() to get the rendered form:

$form = drupal_get_form('user_login');

To override the default theme for the form have a look at Theming the contact form in Drupal 6 which goes through all the necessary steps very thoroughly.


Minimizing cache clearing during development I'm suffering from very long (several second) load times when developing locally with Drupal 8 when developing/debugging twig templates or in general having ALL caching disabled.  Rebuilding cache makes my admin pages needlessly require a rebuild for example.  When I'm not actually working on them I'd like them to remain cached.

I'd like to be more specific in my cache clearing so that I can clear only the parts I'm actively working on - ex a view or block - instead of constantly invalidating the entire site cache which is rather expensive.

I've found that cache tags may work, but I can't find documentation or the location where I might find a listing of available cache tags or really much else on clearing specific caches.  So if tags are effective, where can I find all registered cache tags on my site?

Is there more information I'm missing on how targeted caching is implemented in Drupal 8?  Are there alternatives to tags that might work better?

Edit:  I should mention my environment, in case there is an alternative solution.

I'm running Drupal using docker, with Nginx/PHP-FPM and MySQL containers , on Docker for Mac which has known issues with file mounts so I'm only mounting my custom modules as volumes into any containers.  I profiled the difference between mounting everything and am now spending negligible time doing file operations whereas previously it was very expensive.

Now it appears that my bottleneck is calling the Database many times per pageload, I imagine this is because I'm rebuilding the entire cache meaning I'm adding/removing it from the DB over and over.  I may try memcached or redis and see if that helps.

My ideal solution here is to just invalidate portions of the cache I actually want to invalidate instead of the entire thing though.  Cached pages are ofc incredibly fast in this environment.  My staging environment which is using native Docker does not have the FS issues but still suffers when caches are turned entirely off.

Define all caches disabled, how do you do that?

The recommended approach is to only disable the render cache (as per the example local settings.php), but if you have a complex site and a slow, especially virtualized environmment, that can still take some seconds on every request.

Make sure you don't have xdebug or so constantly enabled. Use PHP7 if possible, that's basically 50% faster. It doesn't make mysql faster obviously, but unless you have very slow/bad queries, that is likely a smaller part of the whole response than you think. And if you have slow queries, then you need to find ways to optimize them, since it will get much morse when you have more parallel page requests.

If you clear cache manually, make sure you use drush cc render and not drush cr unless you actually change something that requires a full cache clear.

Cache tag invalidation doesn't really help that much, you could of course find out the cache tag of your specific block/view and invalidate just that, but there is no drush command for that yet). You could write your own cache backend that extends from the default and allows to ignore cache writes of cache IDs that match a certain pattern. But invalidation will require you to figure out the cache id of the thing, unless you work on the same thing for quite some time, that won't be worth the effort.

For more specific things, you'd need to profile the site to find out what is actually slow.


User relationship one way relation block and unblock option Im using user relationship module for twitter like one way relationship ,

But i find any option to block the user from following me and in future.

Only remove option is there to remove and once removed, the user again start following me.

Any option to block the user from following me?

Thanks,
Edie :)

This feature does not currently exist, you can not implement it without hacking the module.

There are feature requests open for this, I suggest have a look at these:

http://drupal.org/node/203364


How to display or hide a Views field based on it's length? I have 2 fields in Views the first of which is always displayed, and the second I would like to display only if the first field has more than 70 characters. I have tried to do this using Views Conditional module but for some reason it does not work.

I have also tried this using Views PHP module by using drupal_strlen and replacement patterns, but this isn't working yet either. Below is the code that I am using:

<?php

if (drupal_strlen($row->comment_body) >= 70) {
  print $row->php;
} else {
  print $row->nothing_1;
}
?>

How can this be done?

In the views conditional field you are comparing the string value to the value 70, not the length of the string.

And the $row variable in views is very limited.

For the field that you want to do a length comparison on, if it is a PHP field already, then before you do the print statement set the following:

<?php
$data->custom_len_70 = strlen($output);
?>

$output is whatever you are going to print as the value of the field, so your naming is obviously different.

Then create another PHP field after that one, exclude it from display, and set its output code to:

<?php print $data->custom_len_70;?>

You have now created a hidden field which has the value of the length of the field you require.

Now you can use the Views Conditional field to do a comparison.


Map JSON data to relevant fields I have to display some data from a CRM system. I need it like following.

Let suppose I have a content type "Cars" which have following fields

Car ID,
Car Name,
Car Model,
Car Price

I am creating a node from Cars content type and want the above fields to grab data from CRM. So if Car ID is 1 then Car Name, Car Model and Price will be fetched from the CRM system.

I want to know if the data from the CRM could be available as JSON, how can we map that with these fields?

You can do this with the Drupal 8 Migrate API, which allows for setting up mappers from JSON: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview


Slow Search on Drupal 6.x site with 60.000+ nodes We use Drupal 6 for http://www.boekwijs.nl. But when you search for something (which hasn't been searched for before, in other words; not in cache) it's very slow. At the moment there are 60.000 nodes with CCK fields and taxonomy terms.

What is the best way to optimize this? Are there any modules available? Do we need to use another search engine (SOLR?) or maybe another database structure?

60,000 nodes in the search index is definitely a lot. Not only is it slow and suboptimal to use Drupal's default search with such a large number of nodes, but it is going to progressively put more pressure on your infrastructure as you continue adding nodes.

The solution would definitely be to offload your search to another tool. Two options:

Solr: 60,000 is child's play for Solr. It could suffice you for a lot more even on a commodity machine.
Elastic search: Another tool built on top of Apache Lucene. This one's newer and does not have as many supporting modules for it as Solr does (for Drupal). But it is faster than Solr and can handle concurrent commits much better.

In both these cases, I'd recommend installing the search tool on another server.


Is it possible for a view to have two outputs The reason I need this because I create a view to search through document and need two outputs. One being the document and the other being the files are part of the document group the file is associated with.

*Is this possible with one exposed filter

Thanks for any help with this

You can use an attached View. An attached View is a View display that is attached to another View display, a compounded View.

In this question is explained its purpose:
What is the purpose of Views "Attachment", "Content pane" & "Context"?

  The Attachment option is to create yet another view that you can attach before and/or after any of the displays on your current view.


In which template file is the create new account/log in/request new password page rendered? I would like to not render the request new password tab (/user/password), when I am not the log in page (/user). In which template file does drupal get told to render the create new account/log in/request new password page? Drupal 7, Bartik.

They are just menus. You can find those menus and their page callback in drupal core user module at hook_menu section.


How to limit showing of a block just in home page? I have a library book and in the first page or homepage of my website I want to show just 4 random books in center of my page.

How to set a View block to just show in home page?

You can do this by following below way :

After creating Views Block.
Goto Admin -> Structure -> Blocks (Search your block)
Configure -> Your block
Goto Pages section. Click on "Only the listed pages" & write <front> & Save block.


Continue saving node under some condition Is there a drupal function can i use to check some condition, if it return true the node will be saved if not it should be return to the creation form.
Thanks.

You can use hook_node_validate() to check your condition.

  Perform node validation before a node is created or updated.

  This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.

  To indicate a validation error, use form_set_error().


Would I be in "Blacklist" to send bulk mail by Simplenews? We have thousands of subscribers who sign up through our Simplenews. Now, we would like to send newsletter(eblast) through Simplenews with Simplenews Content Selection too all subscripbers. Will our server getting "blacklisted" by doing this?

PS: The newsletter has unsubscribe URL on footer

As far as I'm aware, your ip gets blacklisted if a couple of people click 'report spam' in the email browser.  Consider setting the SMTP on your server to use a web service such as MailJet who have all kinds of advice on what to do and what not to do.


admin/content/comment/approval -> 410 Gone error (linked from content -> comments -> unapproved comments) I have no idea when this happened (I've been trying to fix Mollom + PostgreSQL, to the point where I tried, and removed, some core patches), but when I go to Content / Comments / Unapproved Comments (which leads to admin/content/comment/approval) I get a 410 Gone error.

Was this supposed to be a view? How does one recreate such core views? Is the link the result of some module long since uninstalled?

You could try installing the module

admin_views

As well as converting core administration pages (admin/content/node, admin/people etc.. ) to use VBO, it will add a view to admin/content/comment/approval

Recommended.


How can I make views exposed filter case-sensitive? When I use the exposed filter, if I search for "IMAG" all results showing image show up.  Is there a way to have the exposed filter search case sensitive?
UPDATE
I added a screenshot to explain more.  I have tried the operators: is equal to, contains, contains any word, contains all words, and regex.  Neither of them are case sensitive.

For the solution I used the hook_views_query_alter and used the LIKE BINARY operator in my condition.
condition('node_field_data.title', "%{$word}%", 'LIKE BINARY')


unable to create new site I am new to drupal. Trying to understand the possibilities of drupal, I have installed drupal8 and followed some tutorials to create a site with a custom theme, custom modules and custom blocks.
So far so good.

Now I have this first test site working (installation in public_html), I wanted to create a second site, served by the same installation. I want to try and make a drupal8 version of an existing site of my company.

Following more tutorials, I have tried several things, but I am unable to get it working. I did the following:

my first site's URL is http://localhost, I tried to get the url http://localhost/owtest working
In public_html I have created a symlink with name owtest
In sites/ I created a directory owtest, containing a settings.php and an empty directory files/

I created a database for the new site. The first site's database name was 'DRUPAL' with user 'DRUPAL', for the new site I created database 'OW' with the same user.
in owtest/settings.php, I changed the database name to OW
I ran update.php, thereby clearing the cashes.

If I now go to 'localhost/owtest', it looks the same as the 'localhost' site; if I add content to the site, the same content appears to the 'localhost' site. It seems the new site does not use the new database.

Clearly, I am missing a required step. Who can help me in getting this to work?
My sites/owtest/setting.php now contains

$databases['default']['default'] = array (
'database' => 'OW',
'username' => 'drupal',
'password' => 'drupal',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);

thanks for helping me, Ruud

I managed to get it working. The missing link was the sites/sites.php file.
Although I did provide that, it started working after I put the following in it:

$sites = array(
   'localhost.owtest' => 'owtest',
   'localhost' => 'default',
);

I can now browse to localhost/owtest and have a completely different content collection that is used by the localhost site itself.
Now I am facing a style problem, I keep tring...

Ruud


How to get taxonomy term reference fields value translated in twig I have a taxonomy vocabulary with terms.
In a content type, I have a referenced field with this taxonomy.
I can get the taxonomy term in twig like this :
{% for item in node.field_lorem %}

    {{ item.entity.label }}

{% endfor %}

It works. But I don't know hot to get the translated terms when I switch language.
All other basic fields are translated. The multilingual configuration seems ok.
Example, a text field {{ content.field_text }} is translated.
The translation is activated for taxonomy (Taxonomy term is checked).
/admin/config/regional/content-language

The termes are translated :
taxonomy/term/11/translations

Is there something I miss in my twig ? Actually, I always get the terms in default language.

Maybe I poorly explained the question but the solution was possible without preprocess.
In a content type, the referenced field with a taxonomy is called field_lorem
For this Entity reference field (Type of item to reference : taxonomy term), we select in Manage display (admin/structure/types/manage/content_type_name/display) « Rendered entity » instead of Label :

In the node template (node--lorem-ipsum-content-type--full.html.twig), we have simply {{ content.field_lorem }}
Then, we are able to see twig suggestion template name for this field based on taxonomy_term.html.twig :

In this twig, we can style independently all of the fields of the taxonomy term :
    {{ content.field_image[0] }}

    <p>{{ name[0] }}</p>

With this solution, translation of vocabulary terms works and we are able to have a custom template with all the field (in example an image field and name of the term)


Views strips/merges unlimited values/fields of same field into one I have a content type and a Text field 'Achievements'. Now it is set to Unlimited so every time when creating that content I enter an achievement per field. So then I have a nice list of achievements listed in separate divs where I can apply CSS and etc.

I made a view to list those content types including achievements fields and Views merges in all achievements into one view-field and makes a total mess and it becomes unlisted/unordered and no CSS cannot be applied because all divs and classes (even/odd) are gone.

It works fine via original node, but divs are stripped via Views.

If you are displaying fields, you need to configure the settings for multiple values.

From the edit screen for the view, select the properties of the field set to unlimited.  Then scroll down and find the part that says Multiple field settings:


VBO or Administration Views problems It's difficult for me to judge which module is at fault, but since I enabled Administration Views to be able to filter content by name, actions stopped working. For example:

Publish selected content gives a confirmation message that the operation was successful but the content remains unpublished.
Change author lets me select a user and then displays a confirmation message but the author remains unchanged.

Recently I have also opened an issue for the Deploy module, where the action items "Add/remove to deployment plan" did not show up until I disabled Administration Views.

Is there any secret to successfully operating those modules?
(I cannot look up the issues right now as the site seems to be temporarily down).

Module Versions

Views: 7.x-3.3
Administration Views: 7.x-1.x-dev
VBO: 7.x-3.0-rc1+11-dev
CTools: 7.x-1.0-rc2

The problem was that by default the Bulk Operations actions are set to enqueue rather than be fired directly.


Where are the result and facet summaries for a search api view? I had a solr search api search view all set up and working with the results showing properly, and an area at the top showing how many results had been found and what facets were applied with little links to cancel those filters.

Unfortunately I had to rebuild the entire thing because of a change in the content types in use.

Now I cannot figure out how to get that results/facets summary bar back.  How do I get that?

What I was looking for was the Current Search Block which is a module that comes with facet api.  It wasn't showing up for me because I needed to go into the block configuration, and update what search page it should appear on.


Check if field has value (content) I have code which checks if field exists, but I try to change it to check if field has value (content) or not.

In views I have one field to show all content (Rewrite results). So all fields are loaded always. Thats why I need code which checks does field have content or not.

This is what I got now, but it adds "has_no_field" to all - no matter if field_image has content or not.

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (isset($row->field_image['und'][0]['value']) == 1) {
      $vars['classes_array'][$id] = 'has_field';
    }
    else {
      $vars['classes_array'][$id] = 'has_no_field';
    }
  }
}

Try changing

if (isset($row->field_image['und'][0]['value']) == 1) {

to

if (!empty($row->field_field_image)) {


Drupal 7 css and js compression When I turn on Drupal 7 css and js compression in the performance part, it is aggregating too much files.(5 css files and 5js files). Why?

The page:

Is there any way to force drupal to aggregate more the files?

No, not really, and you wouldn't want to do this.

The thing is, Drupal aggregates CSS files into groups to be able to easily load different CSS sets for different 'media' and 'browser' values, as well as for different pages being viewed, without the need to regenerate them.

If you look into $groups variable generated by drupal_group_css() in includes/common.inc, there are 5 keys which different combination of values between each group: type, every_page, media, preprocess and browsers.

This allows for different groups to be loaded on different pages/in different situations without regenerating them (or including not-needed CSS), which would be the case if only one aggregated CSS file would exist.


How to place one region below the other while reducing the width in drupal 7? Currently, I am creating a single page responsive website in Drupal 7. After making the page responsive, I added a block with two regions: about us and ethics side by side that is in two columns. When reducing the browser width, the content still remains in two columns!!! I want the region about us to be below ethics, but I am not aware how to do it!! Can anyone guide me with the aforestated question.

You can either use float:left on both elements with fixed widths that will automatically stack when the page width is reduced enough.

Or use a CSS media query to make the regions adapt once a certain screen width is reached.

HTML:

CONTENT1

CONTENT2

CSS:

.container {width:100%}
.region1 {width:50%}
.region2 {width:50%}

@media only screen and (max-width: 767px) {

.region1 {width:100%}
.region2 {width:100%}

}


Do multi-level multi-value relationships work in a view? In Drupal 8, I have a content type Story, with a multi-value entity reference to content type Project, which, in turn, has a multi-value reference to Team-Member, which has a single-value reference to Person. In my story node, I want to show a list of projects, and within each, a list of team members.

I have an embedded view (content type Story), to which I'm passing the nid as a contextual filter, with 3 relationships defined: referenced Projects, referenced Team-Members, and referenced Persons. I've added fields from all 3 types, each using the correct relationship, I'm pretty sure.

I'm getting Project fields correctly, each Project in a row. But I'm not getting anything for Team-Members or Persons.

Am I asking this view to do something views can't do, by having multi-value references 2 levels deep? Is there a better approach? Am I missing something?

Am I asking this view to do something views can't do, by having
  multi-value references 2 levels deep?

Yes, to my knowledge there is no way to go 2 levels deep for this scenario.

One possible solution, to work around this constraint, would be to use Views Field View and...

1) Create a team member view that uses the project nid as a contextual filter.

2) Add the project nid (content id) as field to your original view so you can pass it to the views field view.

3) In original view, add a views field, select the team member view you created in Step 1 and pass it the project nid (content id).


Is there a way to upload files to the theme directory I use the following code to upload images should be used in slideshow of the theme settings theme-settings.php:

for ($i = 0; $i < 7; $i++){
      $form['best_responsive_settings']['slideshow']['slideimages'][] = array(
        '#type' => 'managed_file',
        '#title' => t('Image').' #'.$i,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')),

      );
  }

Those files are uploaded to: sites\default\files\theme\backgrounds I want to change the uploading location to sites\all\themes\best_responsive\images\backgrounds. How could I change '#upload_location' to do that?

It doesn't look like the file module places any restriction on the upload path, so in theory it should be as simple as:

'#upload_location' => DRUPAL_ROOT . '/' . drupal_get_path('theme', 'MYTHEME') . '/images/backgrounds';

However, having your theme folder writable by the web server would usually indicate that permissions are not set correctly. It would be a better idea to fix those, and save your images in the proper location (i.e. sites/default/files); see Securing file permissions and ownership for full details.


Twitter Card Preview is failing with twitter:image I'm trying to add Twitter Cards to my site so that tweets referencing my blog posts will be expandable and show extra info. I've installed the metatag module, enabled the Metatag: Twitter Cards sub-module as well as patched the Twitter Cards sub-module to fix a problem with it generating <link /> tags instead of <meta /> tags.

When I include a twitter:image tag, the Twitter Card fails, but when I remove it, it works just fine. What am I doing wrong?

<meta property="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta property="twitter:card" content="summary" />
<meta property="twitter:description" content="I can&#039;t speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, &quot;Why do atheists celebrate Christmas?&quot; my first thought often is: Better Question: Why do Christians celebrate Christmas?" />
<meta property="twitter:creator" content="@kennywyland" />
<meta property="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta property="twitter:image" content="http://liberalgeek.com/sites/default/files/styles/large/public/Christmas%20Tree.jpg" />

I have tried <meta property= as well as <meta name= and they behave the same way.

The image is publicly visible, it's large enough without being too large... what is wrong?

To be clearer, by "failing" I mean that Twitter refuses to acknowledge there is a Twitter Card for that URL, so the preview is not shown along with the tweet. When I test this on the twitter card preview page, this is the result I get:

However, when I remove the twitter:image tag and generate the preview again it works just fine and looks like this:

During further testing I found the STRANGEST thing. If I change the domain from liberalgeek.com to www.liberalgeek.com, the Twitter Card successfully generates, although the thumbnail image is a broken image. (That may just be due to high twitter volume, but I'm not sure.)

I want the Twitter card to work, even if they don't include the unnecessary www.

Notice that:

The .htaccess file is the standard one installed with Drupal
I don't think I'm using gzip compression
Apache isn't sending back the wrong headers
The error log doesn't shown any error
The access log shows entries with a return code equal to 200, and a correct content length value, when Twitter tries to access the image

I found a site on my server which twitter handles just fine:

<meta property="twitter:image" content="http://www.geekqi.com/images/StylizedYinYangRedLucida.png" />

But I'm not sure what the difference is between this and all of my other sites.

I made a test with this values

<meta name="twitter:url" content="http://liberalgeek.com/content/why-do-atheists-celebrate-christmas" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:creator" content="@kennywyland" />
<meta property="twitter:description" content="I can&#039;t speak for all atheists, I can only speak for myself, so please leave a comment below and explain why you celebrate Christmas! When I hear someone ask, &quot;Why do atheists celebrate Christmas?&quot; my first thought often is: Better Question: Why do Christians celebrate Christmas?" />

<meta name="twitter:title" content="Why do Atheists celebrate Christmas?" />

<!-- the following line causes the problem -->
<meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg">

Changing the image, the card works normally in the preview tool.
I would try to check if you have some restriction on the file.
Have a look at the crawling section of the API docs

  Twitter's crawler will respect robots.txt when scanning URLs. If a
  page with card markup is blocked, no card will be shown. If an image
  URL is blocked, no thumbnail or photo will be shown.

UPDATE
As suggested by the author of the question, changing robot.txt could not be enough. Since Twitter could have cached your file, you need to wait at least 24 hours to let it expires.
I add that the same problem could be found not just on robot.txt file, but also on images. Indeed, wrong Twitter cache could lead to a 404 error and a broken preview image.


How do I add classes to blocks? I am using Drupal 8 Panels and it is working fine. The problem currently I have is, that I want to add classes to individual blocks on the panel layout page. Is there a way to add classes to blocks on panel pages?something like the Drupal 7 version of CSS properties on panel panes?

For custom blocks it's pretty easy to add classes without any module. Simply add a text (plain) field - or whatever fit's your needs best, get the value in the block.html.twig (maybe use Twigs |clean_class filter) and add it to the classes.


How to fetch X random entities of a given type using rules? I have a custom content type "project" with several CCK fields. One of them is named "field_old_intranet_url". No i want to assign a (random) user to every node of type "project". The author field or any other user_reference would be fine.

My first thought was to create a rule which is triggered when a user logs in. Fetch X random "projects" without an author and save the current user as the nodes author.

The problem is, that you can either fetch nodes by id or property. nid is not working, since i dont know the id. When fetching by property one can only compare the property with data from the current user or the current page. In my opinion it is not possible to fetch X random nodes.

Another solution would be, to trigger the rule by content creation or when content ist saved or whatever and then assign a random user. But this isnt possible either, because you cant fetch X user without a property to compare.

I hope my problem is clear and you can come up with quite different solutions!

Edit: It is possible to fetch every possible combination of X nodes of whatever type with Views Bulk Operations. This part of the problem is solved. Now the remaining challenge is to assign one entity of one of the lists (users / nodes) to a random one from the other, is this possible?

One solution would be to fetch a random node using views, is this possible?

Investigate the Views Module.  It can create lists of nodes for you.  Investigate node_load() and node_save().  They will allow you to modify those nodes.


Having issue with multiple calls of same view I am using the function views_get_view and it's working fine if am using this once in a function. But when I am calling this function multiple times with different arguments in the same function the result is going to lose. In that case, the result always be same as coming with first-time arguments. Following are my code.

 $viewname = "profile_match_with_job";
  $display_id = "block_3";
  $view = views_get_view($viewname);
  $view->set_display($display_id);
  $view->set_arguments(array(138,70)); // views Contextual filter parameters
  $view->pre_execute();
  $view->execute();
  $myresult =  $view->result;
// here $myresult array showing the correct result

But I am calling the same thing with dfferent argument then the result is not corrct like this

 $viewname = "profile_match_with_job";
  $display_id = "block_3";
  $view = views_get_view($viewname);
  $view->set_display($display_id);
  $view->set_arguments(array(138,80)); // views Contextual filter parameters
  $view->pre_execute();
  $view->execute();
  $myresult =  $view->result;
// here $myresult array showing the same result but in that case I have chnaged the param values from 138,70 to 138,80

Yes, this issue arises because you have a current copy of view and you not destroy it. Kindly use below code for multiple use (suggested to be every-time).

$viewname = "profile_match_with_job";
$display_id = "block_3";
$view = views_get_view($viewname);
$view->set_display($display_id);|
$view->set_arguments(array(138,80)); // views Contextual filter parameters
$view->pre_execute();
$view->execute();
$myresult =  $view->result;
$view->destroy();


Drupal 7: can't get ckEditor module configured for inline editing Drupal 7: I using ckEditor module for editing within the textarea fields and I noticed on the ckeditor website that you can do inline editing like:
http://ckeditor.com/demo#inline

I can get the ckEditor module to work for regular editing but I can't seem to get it configured for inline editing like the demo listed above.

I believe you need Quick Edit, which is the Drupal 7 backport of the Spark core initiative for Drupal 8.