Where do I get a webhook url for a facebook messenger bot? I want to check out and explore this interesting drupal module made by the white house: https://github.com/WhiteHouse/fb_messenger_bot

I've successfully installed drupal on my Mac thru MAMP. I've also enabled the said module. But I got stuck on this step of the installation instructions as stated in the README:

"Complete steps 1-4 outlined in Facebook's quickstart documentation including the copying of the page access token in step 3 (note: this module sets up the webhook at /webhook/contact)"

To be more specific, Facebook is asking for a callback url, but I can't find it. Whenever I type https://localhost:8888/webhook/contact as the callback url, Facebook gives me this error message:

The URL couldn't be validated. Callback verification failed with the following errors: curl_errno = 56; curl_error = Received HTTP code 502 from proxy after CONNECT; HTTP Status Code = 502; HTTP Message = Private address

I am completely new to drupal and MAMP. Any help that would point me towards the right direction would be greatly appreciated. Thank you very much!

If you are working in a local development environment, you will need a publicly accessible IP address or domain name to route the FB request to your local server messenger bot webhooks.


Programmatically create new Schedule Updates Entity Reference on Node I’m attempting to populate an entity referenced field created by the Scheduled Updates module within a content type, Event. Within Event I have two Scheduled Updates fields to check and uncheck the Sticky at top of list option.

I also have a product, Promote Event, in which the user is required to add a Begin Promoting Date, an Entity Reference to an Event, and a Quantity. Once a user purchases the Promote Event, I’d like to populate the Scheduled Updates fields within the Event content type with the data used in the purchase.

I can’t seem to figure out how to programmatically populate the Scheduled Update fields within the Event content type after the purchase of Promote Event.

Within my custom module I have:

public function orderCompleteHandler(WorkflowTransitionEvent $event) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event->getEntity();

  // Order items in the cart.
  $items = $order->getItems();
  if($order->bundle() == 'promoted_event'){
    $beginPromo = $items[0]->get('field_begin_promotion')->getValue();
    $beginPromo = $beginPromo[0]['value'];
    $quantity = $items[0]->get('quantity')->getValue();
    $quantity = str_replace('.00', '', $quantity[0]['value']);
    $eventId = $items[0]->get('field_event_to_promote')->getValue();
    $eventId = $eventId[0]['target_id'];
    $endPromo = date('Y-m-d', strtotime($beginPromo. ' + '. $quantity .' days'));

    $node = Node::load($eventId);
    // Get the promote_event Entity Reference
    $promoteEvent = $node->get('promote_event')->first();
    // Get unPromoteEvent
    $unPromoteEvent = $node->get('unpromote_event_')->first();
    if($promoteEvent){

    } else {
      $dateTime = new DrupalDateTime($beginPromo, 'UTC');
      $timestamp = $dateTime->getTimestamp();
      $node->promote_event[] = [
        'user_id' => 1,
         'type' => 'node__sticky',
         'update_timestamp' => $timestamp
       ];
       $node->save();
     }
   }
 }

Here is one example of how to add a ScheduledUpdate to your 'host' entity, in your case a node.

$scheduled_update = ScheduledUpdate::create([
  'type' => 'node__sticky',
  'status' => ScheduledUpdateInterface::STATUS_UNRUN,
  'sticky' => NodeInterface::STICKY,
  'update_timestamp' => $timestamp,
  'entity_ids' => [$eventId],
]);
$scheduled_update->save();
$node->promote_event = $scheduled_update->id();
$node->save();

Good luck!


Should a hook_form_alter be firing both on render and when an additional submit handler is fired? I am trying to add an additional submit handler to the user login form, to simply redirect users to the page they were on before landing on the login page (/user/login).

I have the following code attempting to store the current path/destination in the $form_state storage which is working as I expected when the original form_alter is run on render as it alters the redirect property of form_state to the previous page.

However, when the form is submitted, the form_alter is fired again, but this time the form_state storage is empty, thus the current_path/destination is now set to /user/login which is not where the user should be redirected to.

Here is the code I have at the moment, any help would be appreciated as to why the form_alter is run again on form submit:

function MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = '_module_custom_user_login_form_submit';
  if (is_null($form_state->get('redirect_dest'))) {
    $destination = $_SERVER['HTTP_REFERER'];
    $form_state->set('redirect_dest', $destination);
  }
}

function _module_custom_user_login_form_submit($form, FormStateInterface &$form_state) {
  $destination = $form_state->get('redirect_dest');
  $form_state->setRedirect($destination);
}

I think the chain of events is different. The form gets cached with no or the wrong redirect_dest set. Then the form is submitted and redirected to the form itself. This is now a new form build, because you didn't request a rebuild. Only in a rebuild you keep the form_state.

Solution:

Drupal has the feature to redirect built in. Add the destination on the page linking to the user login:

Url::fromRoute('user.login', [], ['query' => $destination])

Edit (new module):

To add the destination automatically you can use this module:

https://www.drupal.org/sandbox/gnuget/2824414

This is a js solution, so it doesn't interfere with caching. I think in this case you can use a sandbox module, because the site won't break if the js code stops working.


Email to image in ckeditor? I'm looking for a module to convert emails links to an image in the body field to prevent spam.

The closer I found is this one but it's for drupal 6 and I needed for D7: http://drupal.org/project/email2image

Since I'm using ckeditor maybe there is plugin for this?

You could look at

http://drupal.org/project/textimage

  Textimage adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.


Views filter handler for user authored from Custom Form How can I make a custom views filter handler to filter a list of users which the current user created?

For example: The user adds members to the site a view will show only the members that the user added.

In views, there is a relationship for sorting content based on the current user "Content authored" which is similar.

As pointed out by 4k4 there is no user authored data in the tables, so I thought I would add what I did to output a view of users the author created.

For me, I needed to do some of this in my custom module you might be able to do this in the configuration if your use case is easier.

 1. Create user reference field in /admin/config/people/accounts/fields
 2. Install https://www.drupal.org/project/cer/
 3. Add a corresponding reference in /admin/config/content/cer for your field and the user entity.
 4. Create a relationship for your view from the user field.
 5. Output your view as a block list on your user account page.

Now when a user creates a reference the view will shorten to a list of your users.

I took this a step further and created a custom form module to register a user and in code populate the user entity reference field with a form submit for the current user's id. This bit took me a while to work out so hope this helps someone else. :)

$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$user->set("field_your_field_name",$uid);


Show the cart icon only if it exists and it isn't empty I'm looking for an easy way to show on my template a cart icon only if the cart has 1 or more elements (Drupal 8, commerce 2.x); I've tried with a view, but I had problems to identify the cart associated to the current (normally anonymous) user.

Does that easy way exist?

Can anyone point me in the right direction? I've searched on Commerce 2.x docs, but I didn't find anything about the feature I'd like to implement. (I don't want to show the cart, only show an icon when the cart exists and has items.)

I've also used suggestions found on How do I count the number of products in cart programmatically? and I was able to create a twig variable using theme preprocess function, but the variable is never updated. Is it mandatory to develop a module?

Don't know any module that does this but it is simple to do in your theme

Add this to your THEMENAME.theme

function THEMENAME_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'commerce_cart') {
    if ($variables['content']['#count'] == 0) {
      $variables['attributes']['class'][] = 'visually-hidden';
    }
  }
}


How do I use jQuery in page.html.twig? In Drupal 7 I used some JavaScript that required jQuery in the page.tpl.php file using the following code.

<script type="text/javascript">
    (function($) {
    $( ".mobile-menu-button" ).click(function() {
    $(".navigation").toggleClass( "visible" );
    $(this).toggleClass( "active" );
});
    })(jQuery);
</script>

Hod do I do this in Drupal 8? I have tried many ways of adding this code (with and without the jQuery argument above) in page.html.twig without success. I can see the code in the page source, but it fails to work.

You need to write JavaScript in a js file in your theme, declare a library within your theme and attach it globally or inside of a theme page attachments hook. You also need to depend on jquery from core in your library yaml definition as well.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Non-admin user gets empty results when viewing other user data with views I've been searching around now quite a while and couldn't find a solution that worked for me. So, here's my question:

I created a View that basically just a list of all users on my page. The view displays the

User name,
Taxonomy term and
User location.

For admin members the view works fine, but for non admins only the location is displayed, name and taxonomy give no results.

And,

I checked the permissions. The user is allowed to view other user profiles. He's allowed to view published content.
Changing the query settings of the view didn't work

Thanks for your help.

UPDATE:
In the process of elimination I checked/unchecked every single permission. The result: When I give the user the permission to Administer Organic groups permissions the user can see all the fields in the view. But I cannot allow a non admin user to administer og permissions. Any ideas why this is somehow connectd to user information fields?

Try the following,

There is an option in views to not take into account permissions when running the query (dunno if it is on the query level or display level though)

Edit your View at: Advanced/Query settings/, On Query settings page, check "Disable Query Rewritting"

Views UI: Advanced,

Query settings page,


How do I install on Ubuntu 20.04 (LAMP)? I have Ubuntu 20.04. I installed Apache2 and MySQL 8 on it, but I can't install Drupal 8. When I try to add the database information like usual, I get the following error message.

I traced the possibilities of the error and be sure of solving it, but it still doesn't work. I didn't find instructions on the net to work on it.

This might be an issue with the new ways MySQL 8 does authentication.

Read more about that in this answer: What is mysql_native_password?

From the docs: MySQL Secure Deployment Guide  /  Enabling Authentication

You need to adjust the authentication method for the MySQl user you're using with Drupal (seems to be root from your screenshot). You can't do that through Drupal, you have to login MySQL through terminal or go through some other way of configuring your installed database server.

If switching to the new way of authentication isn't an option then you can change the user to use the old way of authenticating with  mysql_native_password:

alter user 'root'@'localhost' identified with mysql_native_password by 'whateveryourpasswordis';
flush privileges;

After that Drupal should be able to connect with the chosen database.

This is probably unrelated to your problem, but I've had problems in the past with some special characters in the password (not the database name), I couldn't use & nor # IIRC.


Drush: how to set access to MySQL When I run command "drush status" I cannot see any MySQL settings (user, password or database).

I cannot use commands like "core-quick-drupal" because it requires access to MySQL, before /sites/default/settings.php is created.

How can I set such MySQL connection?

I have installed drush in linux in directory /user/share/php

When I install Drupal from web browser interface, I can see that database support is enabled. I have problem only when installing drupal via drush

core-quick-drupal doesn't require mysql, it would use something like sqlite. drush site-install allows you to specify config options like the mysql connection.  For example:

drush site-install mysite --db-url=mysql://user:pass@server/dbname


How to import external database table into Drupal database table? I imported an external database into my local Drupal database. The database table I am particularly interested in is the default "users" table in Drupal and the imported "USER" table from the imported database (My current Drupal database has both "users" and "USER" tables).

The external "USER" table contains columns that are not contained in my current Drupal "users" table.

I would like to perform either one of the following:

Merge the "users" and the "USER" table, so that all the rows from the "USER" table is now contained in the "users" table.
Allow Drupal to obtain login information from the externally imported "USER" table. By this, I mean if there is a user called "ABC" in the "USER" table, then Drupal should allow user ABC to log into the website.

Any help is appreciated. Thank you.

EDIT:

I have tried using the migrate module, but nothing shows up nor do any options show up for me to migrate my data. I have found a little tutorial that teaches how to import external data using drush and migrate - http://www.gizra.com/content/data-migration-part-1. Is this the correct way to use Migrate?

You have at least 2 choices, none of which is easy in my opinion.

Import the non-drupal-users into drupal using a tool such as Migrate to actually map the new fields into drupal fields, you can use hook_schema_alter() and hook_entity_propery_info_alter() to tell Drupal about these new fields that Migrate is moving over.
If you dont merge these tables permenantly into 1 drupal "users" table you're kinda making more trouble for yourself. You could implement your own authentication method to do an SQL query against your (non-drupal) Users table and if the visitor is found there create a new Drupal user account for them. To do so you'd basically create your own login logic as loosely described here for an external source, Blog Tutorial


What does combined block caching option 'DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE' do? I understand that certain block caching options can be combined. What does it mean if I set the caching option of a block defined in code to DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE?

I am confused by the OR bitwise operator. Does this mean that the block will not only be cached by page, but also by role? For example, if User role A visits the same page as User role B, they will each see different cached versions of the block despite being on the same page?

According to the documentation:

  Page and user settings can be combined with a bitwise-binary or operator; for example, DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change depending on the user role or page it is on.

In other words: When the block is cached, information about the user role and page are stored with it. The cached version is served only in situations where both the current user role and the current page match those of the cached block.

A good example in Drupal 7 core is the Author Information block (see block info, block view). It must vary by page, because every page can have a different author, and it must vary by role, because not every role may have permissions to view the author information.


Need to get field tid from taxonomy Trying to retrieve tid from field_report_group in my module. I can not seem to be able to grab it. Any help would be appreciated.

Assuming you have a variable containing the entire structure that you have added.

Try

$taxonomy['8942']->field_report_group['und'][0]['tid']


Include content of a block in a view template I'm trying to create a Twig view that renders:

Intro block
View content
outro block (yes, made up word for the opposite of intro)

The reason I'm putting these three things in one view is that I have a repeating background pattern; if each item is rendered alone, the background does not display smoothly across/through each element.

I've been trying to put this line - {% include 'block--intro.html.twig' %}, based upon block.html.twig - into the appropriate place of the view twig file, but when the page containing this view is rendered the {{ contents }} of the block is empty.

How should I be trying to do this?

I am using Drupal 8.2.4. The base theme is Bootstrap; we are using a subtheme of that.

You can't mix different templates types like views and block templates. Every template has other variables and so the block template doesn't find the content variable in the views template context.

In your case for a View you could place the block in the header or footer in Views UI. For example a Rendered entity - Block.

In general you can use the module Twig Tweak instead of {% include %} to render a block template or any other entity template:

{{ drupal_entity('block_content', 1) }}

This works, because it renders the entity in its own variable scope and so you can place it everywhere in twig.

While entities normally render in their own template, block content is special, because it doesn't have a template on its own. So the command above only shows the fields. To get the block wrapper you need to use drupal_block().


hook_views_data : join table node twice I try to configure a custom table in hook_views_data. I need to join the same table (node) twice.
The problem is that i can't have the same key for 2 entries in my array :

$data['maz_composition']['table']['join'] = array(
    // Index this array by the table name to which this table refers.
    // 'left_field' is the primary key in the referenced table.
    // 'field' is the foreign key in this table.
    'node' => array(
        'left_field' => 'nid',
        'field' => 'aid',
    ),
);

Is there a solution for that ?
Thanx and sorry for my bad english.

I know it is a bit late. But I had the same problem and ran into this page. So here is how I solved it. It is with my own case, but solution is generic, I hope it will help someone.

I join wootoon_cached_sets twice, the key in $data['whatever'] is only the alias in the query. The actual table is given by the table property. This is confusing because if ignored, this property defaults to the table key.

I end up With the following query:

LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_main
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_main.toon_key
AND  wowtoon_cached_sets_main.active = '1'
LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_second
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_second.toon_key
AND  wowtoon_cached_sets_second.active = '0'

Using the below code:

  $data['wowtoon_cached_sets_main']['table']['group']  = $data['avatar']['table']['group'];
  $data['wowtoon_cached_sets_main']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 1,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_second']['table']['group']  = "second spec";
  $data['wowtoon_cached_sets_second']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 0,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_main']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec'),
            'handler' => 'views_handler_field',
    ),
  );
  $data['wowtoon_cached_sets_second']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec 2'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec 2'),
            'handler' => 'views_handler_field',
    ),
  );


How can I create a Drupal "Page" (not a block) without any theme? How can I create a Drupal "Page" (not a block) without any theme?
I do not want this "Page" to include any header / footer / left / right column.
My understanding is that this isn't possible but could I create an additional theme for my site which is just completely blank, and apply this to the appropriate pages?
We have a salesman that wants to build his own set of pages within Dreamwever and then I would apply this blank theme against just these pages without impacting the existing theme that is utilized for the other pages.

Try the ThemeKey module.

This module has a number of really useful options; relevant to your question, you can have it use a different theme or a stripped down version of your existing theme on certain paths or conditions.


Can the Flag module be used to lock content while editing to prevent concurrent edits? We are trying to figure out a way to use the Flag module to prevent concurrent editing. In our research, we found the Content locking (anti-concurrent editing) module, but we thought since we are already using the flag module, that we could also use it for content locking.

The scenario would be if a user (person a) is already editing content A, and then another user (person b) tries to edit content A, then person b should not be allowed to edit content A until person a is done editing the content.

What is the best way to do this because we are having trouble trying to find the right combination to get this done? We were thinking once a content is being edited, a flag is set to lock the content and whenever another user tries to edit the content, they are prompted with a message "person a is already editing the content. please wait until they are done".

Is this possible with the Flag module? Would I need to use the Rules modules as well?

You can do it by using the node_validate function.

Your relevant part code is that :

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }


drupal commerce product types I'm kind of confused with the product types. Lets say I have 2 products, a laptop and a desktop PC. Both have "brand" as a field. Would I have to create 2 product types or is there a way to have a default product type and apply the extra product typ

Create a product of type "computer".
Then create a list field in "computer" called "computer type", where you can specify "desktop" or "laptop".

You can have another list field named "brand" on the computer product.


how to pull parent term from nested array? I'm building a custom field and formatter in Drupal 8(and teaching myself how to use Drupal & PHP, so bear with me)

I'm not sure how to pull a parent term 'name' value from a nested array.

Right now, I've got this:

$tid = 15
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);

But I'm not sure how to get the 'name' field so I can use it in my #markup.

I used var_dump to see what was there (can't use kint at the moment. Devel caused issues with some other modules)

Here's the array that came back:

array(1) {
[3]=> object(Drupal\taxonomy\Entity\Term)#1187 (26) {
    ["values":protected]=> array(9) {
        ["tid"]=> array(1) {
            ["x-default"]=> string(1) "3"
        }

        ["vid"]=> array(1) {
            ["x-default"]=> string(10) "plant_part"
        }

        ["uuid"]=> array(1) {
            ["x-default"]=> string(36) "2xxxxxx6-5xxb-2xx5-8xx7-axxxxxxxxc"
        }

        ["langcode"]=> array(1) {
            ["x-default"]=> string(2) "en"
        }

        ["name"]=> array(1) {
            ["x-default"]=> string(11) "Term wanted"
        }

I was trying something like this, but no luck:

 $parent['values']['tid']['x-default']

If you check closely with the var_dump() output, you will see, that you actually load an array of entity objects with the type taxonomy term: https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.5.x

This object has a getter method getName() that returns the desired property:

$names = [];

foreach($parent as $term) {
  $names[] = $term->getName();
}

$names_list = implode(', ', $names);


Custom RESTful api GET request only works if user is already logged in, although _access has been set to 'TRUE' Controller outputs a json response. On local machine it works fine weather user is logged in or not. But on the server if the use is not logged in to drupal the single page application that fetches unpublished nodes using ajax call gets 503 (Service Unavailable) error. I have done what this link says and set _access: 'TRUE' in the routing.yml file and tried couple of other things but no luck. Any idea what could be the cause?

The problem of no json output was, it turned out, because the site was under maintenance mode! And like Berdir said 503 is not access denied error!


What is incorrect with this HOOK_node_presave method ?? Trying to modify a FAPI textfield /*
 * Implements hook_node_presave()
 */

function custom_kca_node_presave($node) {
    drupal_set_message('DEBUG: PRESAVE Called');
    if ($node->type === 'product') {
        $node->field_product_short['und'][] = 'test';
    }
}

I created a custom textfield called field_product_short on the product Content Type.

A krumo check on $node after saving reveals $node->field_product_short to have the following:

field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            value (String, 1 characters ) t | (Callback) t();

?!? I'm setting it to a string in my HOOK. Why is it setting it to a value only of 't' with a callback t(); method? Shouldn't it just be reading:

field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            (String, 4 characters ) test

What am I doing wrong?

Your structure is wrong, you are missing the 'value' part. Something like this should work:

$node->field_product_short['und'][0]['value'] = 'test';

I'd recommend to explicitly use [0] instead of [], the first always writes the first field value while the second appends a new one (which is 0 if it is the first). Within it are the actual values of the field, which is, in case of a text field the mentioned 'value'. A term refernence would be tid, a node reference nid and so on.

The reason you are getting 't' is because the field structure is now a string where Drupal expects an array. Example:

$string = 'abc';
echo $string['value'];

This prints 'a', because only integers are supported when accessing strings like this which means 'value' is casted to a 0 and the first character of the $string is 'a'. Welcome to the strange world of PHP.

And another hint. The callback stuff is there because there also exists a function 't'. krumo doesn't know if something is a callback or not (as this is not possible to know in PHP), it simply checks if a function with the same name exists.


Node ID and node title in panels page URL I would like to set up Panels page URL with this pattern: my-site/[node:nid]/[node:title] (i.e. my-site/34/node-34-title).

I don't exactly understand how the Panels page URL setting works with arguments. I can set up the path to my-site/%nid/%title but how can I set it up so that %nid = [node:nid] and %title = [node:title]?

My questions:

How do I configure Panels page to do that?
Panels panes are populated with Views field. Is there anything to do in views to get these arguments?
How can I get transliterated node titles, using Pathauto or Transliterate?

Thanks!

Don't try to change the url with panel page manager:

The path pattern is a way to target some page by there route.

1 - If you want to modify the url pattern, use instead the  Pathauto pattern tool with Token. ex: /[node:title].

Once you build your pattern, it will create some alias every time you create a node, but the internal url is still /node/%node, so you have to use this one to target the nodes pages in the panel configuration.

2- Then, if you need to use the node title in a  panel region, you can create a block view with title, and add a the contextual filter on the ID field, by taking is value frome the url.
https://duckduckgo.com/?q=drupal+8+add+contextual+filter&ia=web

3- If you build a pattern like in 1 - with pathauto and token - the resulting alias will be a transliteration of the node title.


Drupal 7 - How to display the TID of a term reference field in a content type? I have a content type called video and a term reference field called category. I want to be able to output the TID of the term reference field in my content display. Is there a way to do this to expose the TID of the term? I'm able to generate a link from the term in the manage displayed settings, but it has an alias to it so it won't show the tid in the url.

The best way to do this is to make a new field formatter.  You need to implement two hooks, hook_field_formatter_info() and hook_field_formatter_view().  The info hook tells Drupal about your formatter and the view does the heavy lifting.  You can then use this on the Manage Display for the field in your content type.

The easiest way to do this is to clone them from taxnomy.module, and modify.  Something like this would be a start

/**
 * Implements hook_field_formatter_info().
 */
function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_term_name_with_tid' => array(
      'label' => t('Term name + tid'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'MYMODULE_term_name_with_tid':
      foreach ($items as $delta => $item) {
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name  : $item['name']);
        $element[$delta] = array(
          '#markup' => check_plain($name) . '(' . $item['tid'] . ')',
        );
      }
      break;
  }

  return $element;
}


Restrict the node local tabs access to specific content types I have a module_name.links.tasks.yml file for Drupal 8, whose content is the following one.

entity.node.module_admin:
  route_name: module_name.admin
  base_route: entity.node.canonical
  title: Admin Page
  weight: 99

entity.node.check_backend:
  route_name: module_name.check-backend
  base_route: entity.node.canonical
  title: Check Backend
  weight: 100

entity.node.download_webagent:
  route_name: module_name.download_webagent
  base_route: entity.node.canonical
  title: Download Webagent.conf
  weight: 101

entity.node.download_httpdconf:
  route_name: module_name.download_httpdconf
  base_route: entity.node.canonical
  title: Download httpd.conf
  weight: 102

These tabs appear in all the content type nodes. How can I restrict them to  specific content types?

Yes, routing is correct. Routes specify access rules, if you want your route to only be accessible for a certain node type, implement custom access callback and check for that.

The local task will then automatically respect that.

Example from core:

comment.reply:
  path: '/comment/reply/{entity_type}/{entity}/{field_name}/{pid}'
  defaults:
    _controller: '\Drupal\comment\Controller\CommentController::getReplyForm'
    _title: 'Add new comment'
    pid: ~
  requirements:
    _custom_access: '\Drupal\comment\Controller\CommentController::replyFormAccess'

That method then can receive the same arguments as the controller/form, in your case the node (just add NodeInterface $node) and you can check the type there and everything else you want (like permissions)


Entity reference by title I'm using the Feeds module and entity references heavily on my site to add, update, and link content. Unfortunately, the data I'm using has a number of records that are named the same, which causes issues when matching Entity References through GUID.

Is there a way to import entity reference fields through Feeds but using title and content-type instead?

I believe I've found an answer to this problem.

Using the Feeds Tamper module, I can add use the Entity Fields Query Finder plugin to lookup against any other field belonging to a particular content type.

In my case I'm saving the lookup key I need in a field, and then matching against that field & content type.


entityQuery with multiple conditions on taxonomy terms returns no result In my use-case I have an entity which has two fields that reference to unique vocabularies.

News:
 - tag (entity reference)
 - category (entity reference)

If I query on one of those reference I get results however when I query both (an AND filter) I get no results. I have triple-checked it by now and there are entities that contain both the tag and category I am querying.

Is this an user-error or a Drupal bug?

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'news')
;
$group = $query->andConditionGroup()
    ->condition('field_tag.entity.name', ['cars'], 'IN')
    ->condition('field_category.entity.name', ['sport'], 'IN')
;
$query->condition($group);
$nids = $query->execute();

EDIT:
I have found a work-around by querying on the raw value instead of entity.value. This is a non-desirable situation though

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'news')
;
$group = $query->andConditionGroup()
    ->condition('field_tag.entity.name', ['cars'], 'IN')
    ->condition('field_category', [1], 'IN')
;
$query->condition($group);
$nids = $query->execute();

The reason you can't do that is that both of these fields are entity reference to the same entity. That means that the base table is the same base table.
You are asking Drupal to Join the taxonomy_data table to the node table and then make an impossible AND condition on it.
P.S.
You can use condition('field_tags', 1); instead of condition('field_tags', [1], 'IN');
And as mentioned in the comments, the AND condition group is the default, so you don't need to specify it.
P.P.S.
You should have both conditions use the referenced id to be consistent.


Fatal error: Call to undefined function context_get() I got an error after trying to update two modules:

  Fatal error: Call to undefined function context_get() in
  sites/all/modules/context/context_ui/context_ui.module on line 422

Also:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: http://redneckrampage.ee/authorize.php?batch=1&render=overlay&id=78&op=do StatusText: OK ResponseText: Fatal error: Call to undefined function context_get() in sites/all/modules/context/context_ui/context_ui.module on line 422

Any ideas on how to fix this without deleting/renaming the module folder on the server?

Drupal version 7.22

Try installing Context module and if this does not solve, also also try installing the spaces module.


Run code once on each page load In the past there were some hooks, such as described here:
How to run check on each page load?

to execute arbitrary code on each page load.

Now this has been replaced with an event based approach. I wrote this to check it out:

class MyModuleEventSubscriber implements EventSubscriberInterface {
    public function onLoad(GetResponseEvent $event) {
        \Drupal::logger('my_module')->info('test');
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[KernelEvents::REQUEST][] = ['onLoad'];

        return $events;
    }
}

However, it seems like there is any number of requests on each page load—it actually captures each request, and in my case there are five (5). My intended code, however, has to call an outside API, and I'd like to avoid unnecessary calls.

Is there an event that is guaranteed to run just once on each page load, without saving a state on my side (that seems quite complicated for this problem)?

You can see an article on the subject here without using Events

https://chromatichq.com/blog/replacing-hookboot-and-hookinit-functionality-drupal-8

Possible that it will meet your needs.

  Replacing hook_boot and hook_init Functionality in Drupal 8

  The change notice page states:

  Using StackMiddleware

  This comment on the hook_boot change notice page provides an example
  of using StackMiddleware. It provides 95% of the functionality needed
  to run logic on cached pages by utilizing a tagged service with the
  http_middleware tag. Since the new class is a service, it will have
  full access to other core and contrib services, allowing for much
  greater functionality. The example shows the following for a module’s
  *.services.yml file:

services:   http_middleware.mymodule:
  class: Drupal\mymodule\StackMiddleware\MyModule
  tags:
    - { name: http_middleware, priority: 180, responder: true }

  This is a pretty standard service definition, but note the items added
  to the tags property that register our service with the
  http_middleware tag and also set a priority. In order to bypass the
  page cache, understanding the page_cache.services.yml file is helpful.
  There, a similar definition can be found, but with a higher priority
  value.

services:   http_middleware.page_cache:
    class: Drupal\page_cache\StackMiddleware\PageCache
    arguments: ['@cache.render', '@page_cache_request_policy', '@page_cache_response_policy']
    tags:
      - { name: http_middleware, priority: 200, responder: true }

  Higher priority services are run first. So to trigger logic before the
  page cache module takes over the request, a priority greater than 200
  is needed.

services:   http_middleware.mymodule:
    class: Drupal\mymodule\StackMiddleware\MyModule
    tags:
      - { name: http_middleware, priority: 210, responder: true }

  With this change in the services files, and proper setup of the
  service as described by the comment, the http_middleware.mymodule
  service should now be called on every page load, even on fully cached
  pages.

namespace Drupal\example\StackMiddleware;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Performs a custom task.
 */
class ExampleStackMiddleware implements HttpKernelInterface {

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Creates a HTTP middleware handler.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The HTTP kernel.
   */
  public function __construct(HttpKernelInterface $kernel) {
    $this->httpKernel = $kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Custom logic goes here.

    return $this->httpKernel->handle($request, $type, $catch);
  }
}

  Verifying the Results

  A quick and easy way to test all of this is to simply add
  \Drupal::logger('test')->notice(‘not cached’); into the functions
  triggered by each of the approaches above. Ensure that the Drupal
  cache is enabled, and simply refresh a page while watching your log
  (drush ws --tail). Then verify the logic is being called as expected.


Drop down select list by author id I have a website that has users with role "sellers".
The website has a nodes/stores that belongs to the sellers.

So let's say I have 3 users and 10 nodes for their objects. The names will be fictive, just to explain better this specific task.

Users with role "sellers":

John
Mark
Cindy

Nodes/stores

John's store 1
John's store 2
John's store 3
Mark's store 1
Mark's store 2
Mark's store 3
Mark's store 4
Cindy's store 1
Cindy's store 2
Cindy's store 3

Every seller will be able to login into the website and see his/her stores, but cannot create or edit a node/store. Only admin will do that. When creating these stores the admin will make author by the user name. For an example:

John's three stores nodes will have author as John, so the seller John when log into his user pages, will be able to see his stores. That's ok and already accomplished.

When John's wants to make some new offers will send a form that will be sent to the admin. The specific thing is, John will be able to select a drop down list with his stores (in this case 3) and select what stores will have this new offer, so on sending the email, the admin will know for which stores is the new offer.

How can I create this kind of drop down select list based on author id?

I have acknowledge with custom modules and lot's of hooks, so creating a custom form wont be difficult.

Code to fetch Stores of a user -- Replace node_type with your node type...

global $user;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid and type = :type', array(':uid' => $user->uid, ':type' => 'node_type'));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}

Create a Custom Form -- Form API Reference

Create two fields

Select Field - Options Source - Run a query against node table to get list of node id's given user id filtered by type and status of node
Offer Request - Text Area

On Submit handler
Read Select Field Values , Offer Request Text
Send Email to admin using hook_mail


How do I combine two content types in one Views block and get them to sort correctly? On my site, I have content types for Tradeshows and Webinars. I would like to have a block that shows the next 5 upcoming events by date, coming from either content type. I have Views set up to retrieve items from both types, and have the sort criteria set up with the date field from each type (they are different fields), in ascending order.  Ie., the Sort Criteria section looks like: Webinar Date (asc), Tradeshow Date (asc).

If I set the Views pager to display all items, I see a list of all the tradeshows, followed by the webinars.  It looks like Views retrieves the items from each content type, and sorts them correctly within their own group, but doesn't weave the two sets together, according to date.  This means that if I set the pager down to 5 items (the goal), then I'll only see tradeshows, since there are more than 5.

Is there a way to get Views to shuffle the two types together, and show the next 5 events, combined?

Edit: attaching screenshot

In the end, using hook_views_query_alter() turned out to be the simplest solution for my needs. I used code similar to that found in the solution below.

https://drupal.stackexchange.com/a/53128/18497


Can't render a block due to recoverable fatal error I had code to programmatically render a block.

$block = \Drupal\block\Entity\Block::load('bartik_search');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
return array('#markup' => drupal_render($block_content));

After updating to Drupal 8.2.x, I get the following error:

  Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface

How do I fix this error?

The error:

  Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface

usually is caused by viewing the invalid block (NULL). So for some reason Block::load() fails to load your block (bartik_search). So clear your caches and check whether the block exists at Block Layout page, theme is enabled and permissions are configured properly. If this still happening and the block is definitely there, please raise a relevant issue ticket.

You can always add the condition or try/catch block whether the code loads the block correctly.

Please also note that drupal_render() is deprecated and you should return $block_content instead.@googletorp Or use \Drupal::service('renderer')->renderRoot() instead.

See also: How can I programmatically display a block?


How to pull in dynamic content in hook_filter_FILTER_process? I'm creating a custom input filter to replace a placeholder html comment with a simple form. However, calling drupal_get_form within a hook_filter_FILTER_process function causes the php memory limit to be exceeded.

Elsewhere I tried to do a node_load within one of these functions and the same thing happened.  I was able to work around that but this indicates it's nothing to do with the form (which is displayed elsewhere on the site anyway, and only contains a couple of fields).

The memory limit is hit whether I actually perform any filtering or just return the unfiltered text.

Any ideas what I'm doing wrong?

Thanks

Depending on your settings, hook_filter_FILTER_process() will be invoked (albeit in a round-about way) from within the drupal_get_form() and node_load() functions.

So at the moment you're simply creating an infinite loop that PHP cannot escape from (node_load() calls hook_filter_FILTER_process(), which then calls node_load() again), hence the out of memory error.


Replacing menu items with images I'm looking for a way to display a menu items as images (with rollover) rather than the usual text links. I found the module Menu Icons, but as the name implies, it's designed to place the icon next to the link. Does anyone have a technique for doing this? Perhaps I have to create some sort of custom block or panel, but I thought maybe there was an easier way.

You can use the Menu Icons module to implement the functionality you are looking for - I've done this multiple times.

You simply need to customize the menu_icons_css_item.tpl.php file so that the image is displayed using the CSS image replacement technique rather than positioning the image as an icon-like background. For roll-over functionality, each image you upload with the image icon module would need to include the static and roll-over versions of the menu image.

Here is sample content of a menu_icon_css_item.tpl.php file I've used before. This is for Drupal 6, so some of the syntax may need to be updated if you are using Drupal 7.

<?php
$base_url = $_SERVER['DOCUMENT_ROOT'];
$image_info = getimagesize($base_url.$path);
$width = $image_info[0];
$height = $image_info[1]/2;
?>

ul.links li.menu-<?php print $mlid ?> a {
  background-image: url(<?php print $path ?>);
  background-repeat: no-repeat;
  background-position: 0 0;
  height:<?php print $height?>px;
  text-align: left;
  text-indent: -9999px;
  width: <?php print $width?>px;
}

ul.links li.menu-<?php print $mlid ?> a:hover {
  background-position: 0 <?php print $height?>px;
}

After you've created a customer menu_icons_css_item.tpl.php file in your theme, you will need to delete the CSS file that the Menu Icons module previously generated, so that it will generate a new file using this template. It should be in your sites/default/files folder.

Of course, if you do not need to allow site admins to update menu item images via the Drupal UI, you could just implement the CSS image replacement technique within your theme, without needing a helper module like Menu Icons.


Can't choose a Taxonomy term as a Context condition I'm trying to create a context based on taxonomy. When I use the Context UI, the Taxonomy form is not populated with my taxonomy terms. Here's a screenshot of my empty taxonomy selector.

I have three terms in one vocabulary, and all terms have at least one node associated with them.

What's going on?

Turns out this was user error. I wasn't the one to set up the taxonomy vocabulary in the first place, and it turns out that the guy who did set the vocabulary to be Tags. You can't use Tag vocabs in Context conditions. I unchecked the "Tags" box and now everything works as expected.


How to add extra menu source and access it in a theme The Menu module contains 2 sources to assign menus to my site.

How do I add a 3rd source?

Reading through the Zen theme code, I see the variables $main_menu, and $secondary_menu.

I would like to access this 3rd menu source through a variable called $global_menu.

How do I set this variable from a module?

EDIT

I put this at the bottom of the zen_proprocess_page hook in template.php

$global_menu = menu_navigation_links('menu-global-menu');

and was able to access it with this in page.tpl.php so thank you for that advice

<?php if ($global_menu): ?>

      <?php foreach ($global_menu as $key => $value): ?>

          <a href="<?php print($value["href"]); ?>" class="global-link" ><?php print($value["title"]); ?>

      <?php endforeach;  ?>

 <?php endif; ?>

EDIT

Moved multipart question to new question

To be able to put it in a theme variable I think you're looking at something like the following.  Please note I haven't tested this, but i should put you in the right direction.

In your template.php or a module:

function MYTHEME_preprocess_page($vars){
  $global_menu = menu_navigation_links('menu-global-menu');
  $vars['global_menu'] = theme('links__menu_global_menu', array('links' => $global_menu));
}

Then clear your theme registry/caches.


How to translate taxonomy terms displayed via an exposed filter in views? I'm using the Views, i18nviews, and Entity Translation modules.  All of my terms have already been translated using Entity Translation.  In views displays, the translated terms appear in the correct language except in exposed filters.  In exposed filters, the terms always appear in the default language for the site.

A search of the issue queues reveals a thread of monstrous length here.  So, while support for this is still a work in progress, is there any way (quick and dirty hacks are ok) to get this working today?

Editing the View, try to add a new Filter Criteria and look for one you want to translate. There should be a duplicate entry, but the second indicates: (translated). You should use add this (exposed) filter, and delete the other one.


How do I find out which base fields are available for an entity type? If I have an entity type id as a string, how I can tell which base fields are defined for that entity type?

For example, how do I programatically check that an entity type has the "changed" field?

How to get the base fields for an entity type id:

$base_fields = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type_id);

You get an array. The keys are the field names. Example how to loop through this array:

foreach ( $base_fields as $field_name => $definition ) {
  echo "$field_name: ", $definition->getDescription(), "\n";
}

Edit:

The method has moved to the service EntityFieldManager:

$base_fields = \Drupal::service('entity_field.manager')
  ->getBaseFieldDefinitions($entity_type_id);


Differences between 'Add existing field' and 'Add new field' It is possible to reuse the already created fields via Add existing field option. From optimization perspective and the way Drupal stores and manages such fields in database I would like to know, does adding fields this way cause any extra efficacy or not?

Add new field is used to create a new field; Add existing field is used to connect the existing field with another content type.

I don't think it's a big difference but it's a good option for developer to attach their fields to other content types. For existing field, after you have created the new field, you can attach that field to multiple content types.

See also When should I use an existing field?


Programatically define Menu links I want to show Login link in the Menu navigation, only for guest User.

clinical_trial.login:
  title: Login
  description: 'Login'
  parent: main
  menu_name: main
  route_name: user.login

This is my Custom Menu links code.

What to add?

If you are creating a menu link from a custom module, you can check this

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

Quoting the documentation:

requirements (required): Determines what must be met in order to grant access to the route.
    _role: A specific Drupal role, eg. 'anonymous'.

Alternatively you can use this module: https://www.drupal.org/project/menu_item_visibility
"It exposes configurable and extendable visibility settings for menu links."


How do you keep the login block on the same page when validation fails? On pages where the login block exists, I need to stay on that page (and preserve query string arguments) if the validation fails when submitting the form.  Does anyone have any idea how this could be done?

You are looking for Ajax Login/Register module, it will not redirect on error, instead the login and register forms can validate using ajax and stay on same page.

  This module provides a smooth way for the user to login, register and
  request new password via AJAX at any Drupal site.

Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


Theming long lists of checkboxes- How can I divide lists of checkboxes into multiple columns? Some of the fields on my user edit pages contain very long (more than 10 items) lists of checkboxes.  How can I theme such lists so that they are displayed in multiple columns instead of one long list?

Quick and dirty:

.form-radios,
.form-checkboxes {
  margin-left: 5px;
}

.form-radios .form-item,
.form-checkboxes .form-item {
  font-size: 64%;
  width: 19%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  margin: 0px;
}

and play around with the font-size and width to your specifics.  If you want to restrict this to a specific form, just add its id to the mix, eg:

#FORM .form-radios, ...


Is FIELD COLLECTION VIEWS module only for showing data in table format? I am using field collection module and in search of formatting it I came across field collection views module. But whatever tutorial I came across, in all it is display data in Table form only. Is there possibility that we can use field collection views module as Views module so we can have lots of option for formatting? Or Field collection views module is limited to show data to Table format only?

At admin/structure/types/manage/[node-type]/display/full changed the view mode for my field_collection where format = "Table of field collection items". The view mode setting is ignored, as viewing the original node still shows all fields as configured in the "Full content" display mode.

field_collection_table.patch


Use a different theme when your site is being embedded in an iframe We have the requirement to make a trimmed back version of the website, for use for other websites to embed via an iframe. For instance, there will be no left navigation, no global navigation, and all elements will be re-flowed to fit in a smaller width.

I would like to do this with a separate theme (more than likely the iframed theme would be a sub theme of the main site theme).

What is the best way to ensure the site loads the alternative theme when it has been embedded (and switch back to the main theme when it is not)?

A thought I had:

Use a different sub-domain e.g. www.example.com and iframe.example.com

I am after what you think the best way to solve this would be

Create a custom module and put this lines there:

/** Implementation of hook_init **/
function yourmodule_init(&$vars) {

  //here put any condition to you want, for example a domain
  $url = url("<front>", array('absolute' => TRUE));
  if( $url == "http://mydomainiframe.com") {
    global $custom_theme;
    $custom_theme = 'new-theme'; //setting a new theme for this domain.
    init_theme();
  }
}

Also you can avoid create a whole new theme creating only a new page.tpl.php and using it.

/** preprocess_page **/
function your_module_preprocess_page(&$vars) {

  //here put any condition to you want, for example a domain
  $url = url("<front>", array('absolute' => TRUE));
  if( $url == "http://mydomainiframe.com") {
    $vars['template_file'] = 'page-iframe'; //setting a new page template
  }
}

And the page-iframe.tpl.php will be used instead of the page.tpl.php of your theme, in this way you can reuse things to you have in your actual theme.


Is there any way to show a "computed field" value in edit mode? I have a content type (Structure) to which I added a text computed field.
In a module I added the following code.
function computed_field_field_reference_compute($entity_type_manager, $node, $fields, $delta) {
  return GedProjectUtils::computeReference($node);
}

It works: In view mode, the field is well calculated.
Now I would like to show this field on edit mode. I added this code to the module.
function gedproject_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_structure_edit_form') {
    $form['field_reference']['widget'][0]['value']['#type']='textfield';
    $form['field_reference']['widget'][0]['value']['#title']='Référence';
    $form['field_reference']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
  }
}

The field is shown empty.

What do I need to change in the code I added?

So the solution found is :
I catched the node id from $form_state and then catched the field value from the node like this :
 /**
 * Implements hook_form_alter
 *
 */
function gedproject_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_structure_edit_form') {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof EntityForm) {
      $entity = $form_object->getEntity();
      $value = $entity->get('field_reference')->value;
      $form['field_reference']['widget'][0]['value']['#value'] = $value;
      $form['field_reference']['widget'][0]['value']['#type']='textfield';
      $form['field_reference']['widget'][0]['value']['#title']='Référence';
      $form['field_reference']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
    }
  }
}


Serving an image programatically I want to serve an image programatically and execute custom code, something usal and simple in plain php.

<img src='test.php?image=1234.jpeg' />

Then you just serve the image in "test.php" and execute your custom code.

However I have not idea how to achieve this in Drupal.

The code should be in a module of course, but, how to I create a path equivalent the one above, that execute that custom code in my module?

Another solution could be to trigger a rule each time an image is download but that is too heavy. Even another could be something like URL alias to a content, and on display rewrite the output of that content? Is this possible?

You should be using hook_menu() to create a custom page from code. The hook_menu() allows to define a URL and page callback which will be called when user hit the url. Check the example below:

/**
  * Implements hook_menu().
  */
function [MODULE_NAME]_menu() {
  $items['MODULE_CALLBACK'] = array(
    'title' => 'My Custom URL',
    'page callback' => '_MODULE_NAME_page_callback',
    'access arguments' => array('access content'),
  );

  return $items;
}

function _MODULE_NAME_page_callback() {
  $image_name = (!empty($_GET['image']) ? $_GET['image'] : '');

  // Write code here.
  $data = $image_name;

  return $data;
}

The _MODULE_NAME_page_callback() callback will be called when user hit the URL as sitename.com/MODULE_CALLBACK?image=imagename.jpg.


How to add a "Remove Taxonomy term" option to VBO instead of only "Add taxonomy term"? In Drupal 6 VBO I had an option to check if I want to add, remove term for example

In drupal 7 view I can just add it (check the box) and not remove it for some reason, what am I missing

I am attaching a screenshot from Drupal 6 where I could add, remove, even replace terms, how to do it in D7 is the question

You could try to perform a bulk operation using logic expressed in a Rules Component. More details below ...

VBO comes, out of the box, with some predefined (hardcoded) operations that is to be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. In your case "Add the selected terms" seems to be one of those. While something like "Remove the selected terms" (as per your question) is not included.

However using Rules (Conditions and/or Actions) you might probably get it to work, i.e. by execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique, and perform a remove instead of an add of a term.

Note: to process 100.000 nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


Configuration page in Modal Forms not working I already install Modal Forms in my localhost website and it worked perfectly, but now when I installed for my online website I can’t make any change in the configuration page, always forbidden page coming when I change the configuration and save it while I am admin user [Uid=1]

In Drupal 7, the installer tests for compatibility with Clean URLs as a part of the installation process. If the environment is tested as compatible with Clean URLs, it will be enabled as part of the installation process and no further action is required to enable Clean URLs.

If you need to enable Clean URLs post installation, Drupal will run the clean URL test automatically when you navigate to the Clean URLs configuration page;

Administer > Configuration > Search and metadata > Clean URLs, show the results, and allow you to save configuration.

You can enable or disable it at a later time by following these steps:

Navigate to the Clean URLs configuration page;

Administer > Configuration > Search and metadata > Clean URLs.

Wait for the automated Clean URLs test to run.

Check or uncheck the Enable clean URLs checkbox.

Click "Save configuration".

Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server.

If your clean url is not working enable rewrite_module from server.


Using the Feed Import module, I can not map for “address field” I use the Feed Import" to import nodes. The other fields were OK, but I cannot map the address field provided by the Address Field module.

I edited the feed, used "Enter field name," and set to "FIELD_CONTACT_ADDRESS: LOCALITY," but it doesn't work.

I also tried "FIELD_CONTACT_ADDRESS:LOCALITY," "FIELD_CONTACT_ADDRESS_LOCALITY," "FIELD_CONTACT_ADDRESS-LOCALITY," but they don't work.

You may need to set your country.  I've seen feeds import the data into the tables, but nothing displays because there is no country set.


Showing a block in specific content types and URLs I have a block I want to show in specific content types and some URLs.

I tried adding the following code.

  $match = FALSE;
  // block is visible on the content types entered here
  $types = array('story' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }
  // block is invisible on URLs entered here
  if (strpos($url, "edit")) {
    $match = TRUE;
  }
  // copy paste these for additional URLs
   if (strpos($url, "taxonomy/term/8")) {
    $match = TRUE;
  }
  return $match;

Is it possible to use wildcard or something to include all the child in this taxonomy, instead of using taxonomy/term/8?

If you want to check all children of specified term below code can help you

first load all children of it ,then check its term ids one by one

$tids=array_keys(taxonomy_get_children(8));
foreach($tids as $tid)
 if (strpos($url, "taxonomy/term/".$tid)) {
    $match = TRUE;
    break;
  }


How to build a specific administrable page layout? I have a HTML layout provided from a template and I need to make an administrative page to fill the template with a content.
The page layout looks like this:

I want to have an admin page where can I (the user) preferably change all the blocks at once. Also there can be arbitrary many of those small blocks at the bottom, so there must be an option to add the bottom block in the admin page.
Also the page requires some custom HTML markup.
I know how to do this with 2 custom content types and 2 views (one for the frontend, one for the admin backend). But is there an easier or more drupal-way to solve this?

Sounds like a job for Panels

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


Prevent the loss of EXIF using imageCache does not work I want to limit image dimensions on upload, but obviously the exif information gets lost then. I am using the imagecache actions module resp. the imagecache autorotate, which actually works fine when I don't restrict image dimensions on file upload.

How do I set a maximum image resolution on upload and keep the exif so that imagecache can rotate images afterwards?

Drupal (7 by itself, 6 via ImageCache) uses GD library. GD cannot handle EXIF, so if EXIF are ever kept during operations, it's more by accident than by design. If you need to keep EXIF, either avoid any processing based on GD (and that means any Drupal and ImageCache provided operations, both in Drupal 6 and 7), or save EXIF to text field on first upload, for example with EXIF Custom, and then add it back on download.


Connecting 3 content types together entity reference/field collection - adding references in reverse? I have 3 content types:

1. Client
Fields: business name, description, contact name (all standard text fields)

Field collection (called 'client campaign'): Fields: Entity reference field to campaign content type - so I can select campaign to tie this client to.

2. Campaign
Fields: Campaign brief, campaign duration, campaign budget, campaign monthly hours (all standard text fields)

Field collection (called 'collection publishers'): fields, publisher status (paid, live, dead, pending) [select list], publisher live date [pop up date], publisher payment amount [integer], Entity reference field to publisher field - so I can select publisher from drop down

3. Publishers

Fields: website url, name, contact email, payment method (all standard text fields)

If I now:

1) add a client (create one client node)
2) add a campaign (create one campaign node)

I now can add publishers to my campaigns via the field collection added to this content type (collection publishers) This is set to unlimited to I can add as many as I want, in each one I can add in details for each publisher such as 'payment amount' 'live date' and all the other fields that are within this collection.

This all works fine but I need to be able to see all my publishers in one view with details of them and 'reverse' add them to a campaign all at once, perhaps via checkboxes. This will save loads of time. I tried an editable view but cannot seem to get this to work. I am not sure why. It is almost like I need to somehow write to the database without opening up the publisher node..

Was wondering it anyone out there can give me some pointers here or just tell me I am doing it all wrong! I don't mind which.

(the end goal here is to track publishers working across multiple campaigns and then I can see what's gong on at all times through views I'll create)

ADDED A SCREEN SHOT OF THE 'LOGIC' BEHIND THIS!

Thanks for any help in advance.

Screengrab 2 shows how the current campaign node edit form looks - the field collection is showing the publisher nodes.

Screengrab 3 shows how I would probably like this to look, an editable view of publishers that I can assign a campaign to then save. However, this may not work as publishers can work over many campaigns...

It looks like you need Corresponding Entity References:

  It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.


How i can use the feed module for uploading the images in the image field of the content type? How can I use the feed module for uploading images into the image field of a content type,  using a .csv file and storing the images inside a directory on server?

Just put the url of the image in your csv and the feeds module will import the image.


How to create custom search filter for entity list I want to make my entity list/table searchable, but the docs are not helping. I created custom module that generates

My table:

I have entity Event and it has NAME variable. The result i want to get is like in domain/admin/people - Search by name

You are using an entity list builder? There is no standard support for filters/sort, if you want to implement something you have to do it yourself.

All content lists that use filters like admin/people and admin/content are views, expose your entity type to views if it is a content entity type.

One special case is admin/structure/views, which is a config entity list builder that has support for filters. But that's actually a client-side implementation done with javascript.


Displaying a table from local menu (Drupal 7) I have added a menu item to one of my nodes and I would like to display a table when the user selects this menu.  Here is my menu implementation:

function arcade_projects_menus_menu() {
  $items  =  array();
  $items['node/%/versions'] = array(
    'title' => 'Versions',
    'description' => 'Configuration for the User Warn Module.',
    'page callback' => 'versions_view',
    'access callback' => 'arcade_versions_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

and here is my page callback:

function versions_view() {
  $block = array();
  $rows = array();
  $header = array('Project Name', 'Screenshot' , 'Updated');
  $format = 'l, F j, Y  - G:i';
  $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');
  $block['content'] = theme('table', $table);
  return $block;
}

I would expect this code to display an empty table saying 'No terms found' but instead I get a blank white page.  Is it possible to display a table from a page callback?

From a page callback you need to return something that can be run through the render() function. This will either need to be a string, or a properly formatted render array.

You can use:

$block = theme('table', $table);
return $block;

or

$block['content'] = array(
  '#markup' => theme('table', $table)
);
return $block;

or even

$block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
);

The last method is probably the most preferable in terms of extensibility, as it potentially allows other modules to alter the table before it's rendered. Using either of the other methods will render the table into an HTML string, and other elements in the system will no longer be able to alter it before it's displayed.


performant way to load many complete node-objects I need to load a bunch of node-objects and apply some algorithm to them.
Usually I'd use an iteration and node_load() within, but I was wondering if there's a better (speaking of performance) way to load node objects.

I think that being able to cache the algorithm's result on a per-page basis would be sufficient.

node_load() is the preferable way to load a node object, especially if the node object is passed to some functions.
Take in mind that, in Drupal 6 the result of node_load() is locally cached in a static variable by default; if you are going to load a bunch of nodes, it is better if you call the function as node_load($id, NULL, TRUE). If you are sure that, for some reasons, the code could load the same node in consecutive calls to node_load(), then you can consider resetting the static value after X calls to node_load().
The result of node_load() is not cached, if the $revision parameter passed to the function is not NULL.

Caching the value obtained from node_load() is possible, and your code could use its own cache for that purpose. The cache should be invalidated when nodes are updated, which includes also the case when a node is reverted to a previous revision.
Rather than implementing a cache in your own module, it would be better to use a module that caches the nodes for third-party modules.

In Drupal 7, both node_load() and node_load_multiple() accept a $reset parameter that resets the node cache kept as instance variable from the object of class NodeController that is created from Drupal, which uses the instance variable implemented by DrupalDefaultEntityController, the class that implements the default methods necessary for an entity controller.


OG assign existing content to group I'm adding OG to and existing site with hundreds of existing nodes. I'm looking for a way to assign existing content to groups. Sort of OG after-the-fact. Does anyone have any recommendations?

You can use the og_group provided by the OG module.

  // The id of the group to which you need to assign the nodes
  $gid = 123;

  // The node which should be added to a group.
  $node = node_load(1);

  $values = array(
    'entity_type' => 'node',
    'entity' => $node,
    'state' => OG_STATE_ACTIVE,
  );

  //Add the current node to the group using the funciton provided by OG
  $result = og_group('node', $gid, $values);


When I add the comments to each node in a Views content list am I creating a n+1 database query problem? I have a node type product and a node type review. The review has a node reference field pointing to the node type product. Using the Node Reference URL module a user can click a link on the product page and create a review of that product. The View that renders a list of the reviews is show below the product node on the node type product view page.

I tried to add comments to the View by configuring in Views UI Format -> show -> content -> full content -> show comments. However, this did not render any of the comments. Instead I created another View of type comments using the Entity Views Attach module. So each content type review now has a field that loads a View of comments using its nid.

This works great. Still there is a now few extra queries run for each review of each product which I think is a case of the n+1 select problem.

I enabled the Devel performance logger to look at how much of a hit this causes to performance. Without rendering the extra comments and attaching them to each rendered node of type review the number of queries is 165 and the query time is 95MS (my computer is super old) with the comments rendered for each node of type review the number of queries is 189 and the query time is 111MS.

(edit) I had to hack Views to test if using the content with comments was faster than adding a different View as a field to the Review content type. Oddly the number of queries was 188 with a query time of 138MS so the slightly more convoluted method was faster.

Will I be shooting my self in the foot with a bad performance bottleneck with this configuration?

If you are having a difficult time visualizing this, it is just like Stack Exchange. With a node type question that has comments. There is node type answer that is rendered in View attached to the node type question view page. Each answer can have comments too. Same thing.

You are creating a n+1 select problem, but you would do that if you created a list of full nodes since extra queries will happen on every full node display.

This isn't necessarily problem though, as you probably don't want to display 100 or 1000 nodes this way, but instead use a pager. When using a pager, n will never be more than your pager count which could be something like 10 or 20. 10 or 20 queries is not ideal but hardly a problem either unless you need to run a very high performance site, but if that were the case, you probably wouldn't use views anyways.

Views has some cache options which could be used to optimize, and reduce all of the queries to a single query on the cache instead. That is an easy of increasing performance.


view list on user profile, to show content of that user I currently have a view that shows on the user profile page (as a block). I got it to show results of the content for the current logged in user.

This works great for normal users as they will only be able to see their current profile page. However, I want it to show the content for the shown profile, not the current user, since admins that view other user profiles will not see that user's content.

Is there a way to set the view to get the uid of the profile page rather than the logged in user?

These are the view settings I have right now are:

CONTEXTUAL FILTERS
   Content: Author uid
      Provide default value: User ID from logged in user
RELATIONSHIPS
   Content: Author

You need to adjust where the contextual filter is retrieving the UID from.

When you provide a value for your contextual filter, you want to retrieve the raw UID value that's coming from Drupal's path system. To do this, look at the When the Filter Value is not available section.

Selecting Raw value from URL will use Drupal's internal path for the currently viewed page (e.g. /node/XXX, /user/YYY, etc.). The path component refers to which one of the "subdirectories" in the path to reference (e.g. 1 = "user", 2 = YYY, in the previous example).

In your example, you want a Path Component of 2 (i.e. the UID from /user/XXX profile page).


How to Create content type per organic group Hi i have created a content type and i have 4 groups using organic groups.

Is there any way i can restrict content type to one of the organic group.so other groups cant create any content with the content type.

Please help me thanks a lot.

You could simply add taxonomy terms to differentiate different content types.


Empty page.tpl.php renders data too I created my own theme in Drupal 7. It is not sub-theme. Simple I created a folder at sites/all/themes/my_foundation, a template.info as usual, then an empty page.tpl.php.
I expected that a blank white page is obtained after enabling the new theme and visiting the home page. However, I have got a page with some contents as screenshot:

I need to know how it was occurred and how could I get the expected behavior?

This is the expected behavior if page.tpl is missing:

Since your theme does not print anything in page, the Core system module (the one that defines page.tpl.php etc) takes over and drupal uses system's page.tpl.

I suppose that if page.tpl is empty the default page array is rendered with any region that exists in your theme's.info and has content.If regions exist, Drupal will try to render them even without template.


Array and Select Options I have the following code working together with a script that populates fields on autocomplete.

What I would like to do is instead of having an autocomplete text box - use the city field in a drop down / select option field so instead of the user typing the city they select from the drop down.

$cities = array(
    array('city'=>'New York', state=>'NY', zip=>'10001'),
    array('city'=>'Los Angeles', state=>'CA', zip=>'90001'),
    array('city'=>'Chicago', state=>'IL', zip=>'60601'),
    array('city'=>'Houston', state=>'TX', zip=>'77001'),
    array('city'=>'Phoenix', state=>'AZ', zip=>'85001'),
    array('city'=>'Philadelphia', state=>'PA', zip=>'19019'),
    array('city'=>'San Antonio', state=>'TX', zip=>'78201'),
    array('city'=>'Dallas', state=>'TX', zip=>'75201'),
    array('city'=>'San Diego', state=>'CA', zip=>'92101'),
    array('city'=>'San Jose', state=>'CA', zip=>'95101'),
    array('city'=>'Detroit', state=>'MI', zip=>'48201'),
    array('city'=>'San Francisco', state=>'CA', zip=>'94101'),
    array('city'=>'Jacksonville', state=>'FL', zip=>'32099'),
    array('city'=>'Indianapolis', state=>'IN', zip=>'46201'),
    array('city'=>'Austin', state=>'TX', zip=>'73301'),
    array('city'=>'Columbus', state=>'OH', zip=>'43085'),
    array('city'=>'Fort Worth', state=>'TX', zip=>'76101'),
    array('city'=>'Charlotte', state=>'NC', zip=>'28201'),
    array('city'=>'Memphis', state=>'TN', zip=>'37501'),
    array('city'=>'Baltimore', state=>'MD', zip=>'21201'),
);

// Cleaning up the term
$term = trim(strip_tags($_GET['term']));

// Rudimentary search
$matches = array();
foreach($cities as $city){
    if(stripos($city['city'], $term) !== false){
        // Add the necessary "value" and "label" fields and append to result set
        $city['value'] = $city['city'];
        $city['label'] = "{$city['city']}, {$city['state']} {$city['zip']}";
        $matches[] = $city;
    }
}

// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);

And the following is my script:

  Drupal.behaviors.mywebform = {
attach: function (context, settings) {
    var ac_config = {
        source: "/devtest/sites/democities.php",
        select: function(event, ui){
            $("#edit-submitted-info-city").val(ui.item.city);
            $("#edit-submitted-info-state").val(ui.item.state);
            $("#edit-submitted-info-zip").val(ui.item.zip);
        },
        minLength:1
    };
    $("#edit-submitted-info-city").autocomplete(ac_config);
  }};

Any suggestions?

probably not really drupal realated. But here you go:

Drupal.behaviors.mywebform = {
  attach: function (context, settings) {
    $.ajax({
        url:'/devtest/sites/democities.php',
        type:'POST',
        dataType: 'json',
        success: function( json ) {
            // if #edit-submitted-info-city is not a select you will have to make it one, or take the select that is in, or create one select in it.
            $('#edit-submitted-info-city').append('<select>').attr('id', 'stackexchangeExample');

            $.each(json, function(i, value) {
                $('#stackexchangeExample').append($('<option>').text(value.city).attr('value', value.city));
            });
        }
    });
}};

you might want to make sure that you run this only once, adjust the creation of the select element accordingly. or add a once() implementation


How to pass argument in ctools_modal_form_wrapper? A very strange issue come across while using ctools_modal_form_wrapper and ctools-use-modal. I have written a menu item and passed two arguments in it.

$items['a/b/c/d/e/%/edit/%ctools_js'] = array(
    'page callback' => 'generate_tpls_callback',
    'page arguments' => array(5,7),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'tpl_popup_create.inc'
  );

Now in this callback I am getting both 5th and 7th argument. But when I pass it to $form_state, form is unable to get this 5th argument. I will explain you more with the help of code.

function generate_tpls_callback($cid, $ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Display box to change title'),
            'cid' => $cid,
        );
        $output = ctools_modal_form_wrapper('myform', $form_state);
        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }
        print ajax_render($output);
        drupal_exit();
    } else {
        print_r("helloooo");
//
    }

}

So, the issue is, when I click a link say "generate tpl" a popup appears that contains form items. I want the above 5th argument appears in this form. i.e. $cid. How can I do this. Please help.

You must use $form_state to do it.

$form_state['build_info']['args'] = array($node);

function generate_tpls_callback($cid, $ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Display box to change title'),
            'cid' => $cid,
        );
        $form_state['build_info']['args'] = array($myvar);  //Check form below
        $output = ctools_modal_form_wrapper('myform', $form_state);
        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }
        print ajax_render($output);
        drupal_exit();
    } else {
    }

}

function myform($form, &$form_state, $myvar) {
...
}


What is wrong in my code for replacing the text of 'add to cart' button? Can somebody tell me what is wrong in my code, please? I'm trying to replace the regular text for 'add to cart' button for two types of product. I'm using Drupal Commerce module. But something is wrong in my code. Works just first part of code.

function modulename_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {

  $product_types = commerce_product_types();

  if (isset($product_types['product']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy this product ' . $price_display;
  }

  if (isset($product_types['product_2']))  {
    $product = $form_state['default_product'];
    $price = commerce_product_calculate_sell_price($product);
    $price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);
    $form['submit']['#value'] = 'Buy these products just for ' . $price_display;
  }

}

try this

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}


Vallidate exposed filters in View I created a view with Search API.Could you please help how to validate exposed filter(Textbox)
with in a view.

I tried using contextual filter it never worked.

I would alter the exposed form and add a validation handler.

If I remember correctly, the form ID is views_exposed_form. Just do a check on the view object (which I think is in the $form_state variable) to only add the handler to a certain view/view display.


Registration email showing default mail message as well new custom message How to stop default mail , i want to override default mail with my custom body message?
Here is my code :
function mag_api_mail_alter(&$message) {
  // only alter register forms
  if (!empty($message['id']) && $message['id'] == 'user_register_no_approval_required') {

  // make it a bit neater to access fields

    $nids = \Drupal::entityQuery('node')->condition('type','email_template')->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $data_fields = array();
    foreach ($nodes as $new_data){
        $data_fields[] = $new_data->get('body')->getValue();
    }
    $contact_message = $message['params']['account'];
    $first_name = $contact_message->field_first_name->value;
    $username_email = $contact_message->get('name')->value;
    $pass = 'test';
    $app_url = 'abcd.com';

    /*custom field added through configuration*/

    $to_replace_keys = array("[user_name]","[user_email]","[user_password]","[app_url]");
    $replace_keys =array($first_name,$username_email,$pass,$app_url);
    $success_email_msg = str_replace($to_replace_keys, $replace_keys,$data_fields[0][0]['value']);
    // Assigning new message to mail body.
    $message['body'][] = $success_email_msg;

   }
}

Its is working but i am not able to find out why is this showing default mail message as well new body message.
I just want to show my custom body message.

$message['body'][] = $success_email_msg; is appending your variable to the existing array. You'll need to remove the default content from the $message['body'] array if you don't want it
e.g. unset($message['body']['whateverkey']) to remove a specific part. Or $message['body'] = [$success_email_msg]; to reinitialise the variable as a new array


Displaying block only when user visits his own profile page I want to display the block only when the current user visits own page.
So in block visibility I use the following PHP:

global $user;
if ($user->uid == arg(1)) {;
return TRUE;
} else {;
return FALSE;
};
endif;

But that block returns on every page.What am I doing wrong?

If you are using the php code in the block visibility option than I guess the following should work:

<?php
global $user;
$user_id = $user->uid;
if (('user' === arg(0)) && ($user_id === arg(1))) {
  return TRUE;
} else {
  return FALSE;
}
?>

If your site is multi-lingual than may be you have to change the if condition as: if (('user' === arg(1)) && ($user_id === arg(2)))


Limit Entity Reference to published nodes Here is a content type structure called Bill :

  Bill_ID => Int
  Bill_Date => Date
  Services => Entity Reference (Target Type : Node , Target Bundle : Service , Widget : Auto-complete)

The only problem is that the end user shouldn't be allowed to make a reference to an unpublished Service.

So how can we limit user to only make a reference to published contents ?

Create a view with entity reference display. Click add and in the drop down you will see entity reference.

Now create a view and create a filters normally as you do. Now go to your content type services field settings and click views instead of simple selection

Select the views you created and your options will be limited to the result of the view.


Get Url Alias in Algolia I have implemented an Algolia search in my drupal instance and would like to use the node url alias (/some-example-path) rather than node id (/node/{nodeId}). Is there a quick and easy way to do this using the Search API?

Use PathAuto module

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

For learn how work with it read How to Use Pathauto in Drupal 8


How do I enable a menu link only when the user has created a node? In my website the user can create a node. I want a menu link to appear only after the authenticated user has created the node and not before that.

Is it possible to enable a menu link only when the user has created a node?

For example, the menu items that appear when users log in are:

Item 1
Item 2
Item 3

When users add a node, I want another item that points to another page to appear in the menu. If users didn't create a node, they don't have access to the new item.

How can I do this?

I created another role when the user creates a node using the Rules module, and set permissions for the user with the new role to view the new menu item.

Here are the steps

For example If you want give permissions for authenticated users to create 'Basic page'

Go to Home » Administration » People (admin/people/permissions) and check the checkbox

Basic page: Create new content and Administer menus and menu items for AUTHENTICATED USER

That's it now authenticated  user can create basic page (node/add/page) with menu item.

If you want to generate URL/path aliases automatically, use the Pathauto module

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


Synchronize data between 2 sites dynamically I currently have two Drupal sites and I would like to synchronize in a specific way the data of each one.

More precisely, the first one contains detailed informations and the other only has the main data necesary for its work. I would like to refresh (create/update) the data of the second one when the first one is modified and also would like to refresh (create/update) the first one when the second one is modified, taking into account the content types and field names are not the same in both. In my case, the data that should be manipulated are nodes and users.

I have already tried to find solutions through web services or feed import, but I didn't succeed to build a correct one. Moreover, I also studied the possibility to schedule periodic import from web services but it would be slow the site performance, due to the very important amount of data contained in each site.

Can someone help me?

You need to work on the database a little bit.

I think it is impossible to make it work if you just write php. Because it will generate a lot of database login errors.

There might be a lot of ways to do that, but the only way I know is to:
First, Combine two database into one, two different databases with two different prefix.
Second, delete all the attributes you want to synchronize in the second database.
Third, link the synchronized field in the second database to the first database, you can do this in the settings.php in the second drupal site.

But there might be some dependency problems when you do step 2. Don't forget to backup at first.

This link might be helpful How to connect to multiple databases within Drupal


Get author id in field template - or make an edit button on a node's teaser I am using Display Suite to display Teasers of a custom content type Project in a View.
I want to show link on each Teaser to edit that node if the logged in user is the author of the node.
Our requirements do not allow us to use Contextual Links with the little hover gear.

Things I have tried:

I was also able to make a Display Suite field for [node:author:uid] and display that field in the Teaser.
I was able to create a Display Suite field to hold the link and display it in the Teaser.
I was able to create a custom field template for that Project Edit Button field I just made and display it in the Teaser. field--field-project-edit-button.html.twig.
This is where I hoped to wrap the content of that field (the link) in a conditional statement.

However

In the past I have been able to access fields in a different field's template using this technique. {{ element['#object'].field_name.value }}
I was able to do this with a Display Suite field for [node:nid] and then do {{ element['#object'].nid.value }} (where nid is the machine name of my [node:nid] Display Suite field) in the Project Button field template above.
It also works to use it in a conditional statement like {% if element['#object'].nid.value == 6 %}.
But this same technique is not working with {{ element['#object'].aid.value }} (where aid is the machine name of my Display Suite 'Author ID' field). It just comes back empty.

So

What is different about my [node:author:uid] and [node:nid] fields?

Why am I seeing the actual Author ID field properly but not {{ element['#object'].aid.value }} in the edit link's field template?

How do I make this silly button? I am completely open to other ways of doing this as long as it meets my requirements at the top of this post.

FULL SOLUTION, thanks to No Sssweat below

Display Suite token field:

 Edit [node:title]

In the .theme file under mytheme_preprocess_field

/* Make the current user id available in field templates */
$vars['uid'] = \Drupal::currentUser()->id();

In that custom field template:

{% if element['#object'].getOwner.uid.value == uid %}
  {% for item in items %}
    {{ item.content }}
  {% endfor %}
{% endif %}

Assuming in your use case an Author is a user on your site, I believe you will be able to access to Author's ID using

{{ element['#object'].getOwner.uid.value }}

No need to create a custom field to hold the author's value.