Problem with Facebook Feed: Warning: file_get_contents(): https:// wrapper is disabled I'm having a problem with my Facebook pull feed. It works fine on a development server, but on my live server the block doesn't appear on the page, and I get two php errors, and a single Facebook pull error in my recent logs.

The first php error, which I think is significant is:

Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in _facebook_pull_feed() (line 280 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module).

The second php error is related to the first one:

Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=1392108967676515&client_secret=563ff2dd27ddec75d9b79dc918fe93d4&grant_type=client_credentials): failed to open stream: no suitable wrapper could be found in _facebook_pull_accesstoken() (line 299 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module)

And the Facebook Pull error doesn't give any diagnostic information beyond that the module isn't working.

Put this in your settings.php:

ini_set('allow_url_fopen' , 1);

If that solves the issue you will want to hard code that into your php.ini.


Restrict IFRAME and OBJECT embeds certain domains I would like to allow my users to embed certain IFRAME and OBJECT tags in nodes and comments. Is there a way to restrict them to certain domains, for example maps.google.com to allow embedding Google maps?

Allowing users to input , and doing validation on some subtypes of that, is certainly possible, but far from easy.

It's easy to think, "I can do that with a regular expression!". Read This SO question though, before you try, and save yourself a lot pain.

What you can do instead, is employ an XML parser and process the input from there, but that is far from trivial, and will require quite a bit of work.

What I recommend you should do instead, is create specific tags for what you want to allow. Something like [iframe:http://some.url.here], and then process these manually with an input filter. You would probably want to apply that filter in a text-format after you've run the regular "limited html" filter.

A filter is created by implementing hook_filter_info, and in your process callback you can do string substitution on the [iframe] tag, provided it references an approved domain.


how to develop features delivered by drupal if there is no cms I'm quite familiar with drupal, had done a few projects using drupal. I had an interview where the interviewer asked a few unexpected questions (atleast for me they were like unexpected!!). Few of them were

  How do you develop the same features that you did, if there is no CMS
  (Drupal)?

  What tables/scheme (mysql) do you create to generate all possible
  fields??

  If you are going to attach a pdf file (corresponding to each record)
  where do you specify that pdf file, do you use sql table or else
  what??

These were a few questions that I couldn't explain with full confidence.

I didn't even thought of the process behind drupal. I just used to work with my requirements and needs, I never thought of what the process might be. And more specifically with sql.

Do any of you have any views?

The first one is easy.

  How do you develop the same features that you did, if there is no CMS
  (Drupal)?

With a MVC framework like Symfony, CakePHP or Zen.


EFQ - Sort by published date I'm using the module Publication Date  to store when nodes are published. It uses a simple table of nid and published_at for the timestamp. I need to use EFQ to sort nodes by this date, but I'm unsure if it's able to connect to the table it uses.

->propertyOrderBy('published_at', 'DESC');

obviously doesn't work.

Is there any way I can connect to this table using EFQ, or does it have to be a db_query?

It can be done. You have to add a tag to your EFQ, for example:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addTag('published_at')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

Then you wil have to implement hook_query_tag_alter, in your case:

function mymodule_query_published_at_alter($query){
  // Extend your query with some joins and order statements:
  $query->join('table');
  $query->orderBy('field');
}

The above code is an example, it won't work, but you get the picture :)


Image or icon on particular node output Is there any way to replace image/icon for a particular node output ?

A simple Example:

I am getting input from user sucn as
"is your car running in petrol or diesel ?" if he selects the diesel then in node output instead of displaying diesel it should display the Diesel icon which i provide.

Is there any module for that because i have several input like this..Thanks

If your field is a reference field like node reference or term reference, then you can add an image field in the referenced entity for associating the image. Then in your node tpl file, you can load the referenced entity and print the image. If you do not want to write a custom tpl, then this can be done using the Display Suite module. But unless you need Display Suite for other purposes, the tpl way is better.


Can I allow a user to add additional tabs in quicktabs? In the same way that we can set a field to unlimited, allowing a user to add more than one value, might there be a way to do the same using quicktabs?

Well, this is not so much about quicktabs, but I did find a work around. I ended up using plain old field groups. This module has logic in it where if containing fields have no content, don't display that tab (or "horizontal item" in this case).


How to find the right token to use in a rule for sending an email to the node author? I am having the toughest time figuring out how to send an email to the node author. I created my rule and everything works if I hard code the email but I can't seem to get the right token to use and it seems the tokens available only allow:[node:author] nothing for the node authors email?

Sometimes, tokens aren't shown from the Rules module user interface.
Manually enter [node:author:mail]. If it's not an allowed token, the module would show an error message.


How to get images into a slideshow via json javascript with new itok I have just updated to drupal 7.21, and I have massive errors with the new itok suff: Right now I use json_encode(views_get_view_result('viewsitem')), and decode the result with JSON and JavaScript. My slideshow wants to have the normal path but returns things similar to "...sites/default/files/styles/large/public/field/image?itok=M-zTIVI1/mypic.JPG."

Normally, I get the images using the following code.

if (value.field_field_image) {
  var images = value.field_field_image
  // iterating over the images per nid
  for (var i = 0; i < images.length; i++) {
    slideshow_settings.this_slides += '';
  }

  pics = slideshow_settings.this_slides;
}

How can I fix this?

Your root problem seems to be that you are using a side effect of image_style_url().

When you don't pass in a valid image path, you used to get back the basepath of the image style.  Now, with the token patch, it will include the token, and therefore not really be the basepath.  From what I can gather, this is why a lot of modules broke.

The proper thing to do is to use the API to create the URL for you on the server side, instead of gluing together parts in JS.

This is something that I used on a recent project:

$images = array();
$styles = image_styles();

if (! empty($node->field_my_image[$node->language])) {
  foreach ($node->field_my_image[$node->language] as $image) {
    $fid = (int) $image['fid'];
    $uri = $image['uri'];
    $url = file_create_url($uri);

    $metadata = array(
      'alt' => empty($image['alt']) ? '' : $image['alt'],
      'width' => (int) $image['width'],
      'height' => (int) $image['height'],
    );

    $metadata['styles'] = array(
      'original' => $url,
    );

    foreach ($styles as $style => $unused) {
      $metadata['styles'][$style] = file_create_url(image_style_url($style, $uri));
    }
  }

  $images[$fid] = $metadata;
}

drupal_add_js(array('mymodule' => array('images' => $images)), 'setting');

This dumps all of my image fields into a JS array with all of their metadata, including all of the URLs for the image styles that I may need.  My JS code can then use what it needs from this array without worrying about building paths up.


Programmatically created field doesn't appear in Views fields Here is my little module that adds "markup" field to commerce_product table, but I can't select and display it in Views:

function comm_markup_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['markup'] = array(
    'type' => 'float',
    'not null' => TRUE,
    'default' => 1,
    'description' => 'Price markup field',
  );
}

function comm_markup_install() {
  $schema = drupal_get_schema('commerce_product');
  db_add_field('commerce_product', 'markup', $schema['fields']['markup']);
}

function comm_markup_uninstall() {
  db_drop_field('commerce_product', 'markup');
}

function comm_markup_entity_property_info_alter(&$info) {
  $properties = &$info['commerce_product']['properties'];
  $properties['markup'] = array(
    'label' => t('Price markup'),
    'type' => 'decimal',
    'description' => 'Gross price multiplier (defines profit amount).',
    'schema field' => 'markup',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
}

UPD:

function comm_markup_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('Multiplier. Adds profit to the gross price.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}

Unless you manually describe the new field to views, it won't know about it. You can do that with hook_view_data_alter():

function MYMODULE_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('An amazing field which does something great'),
    // Add the rest of the definition here...
  );
}


sql-dump piping output to the screen I am trying to dump a remote Drupal site to a local SQL dump file. In Drush 8 this worked a treat:

drush @site.alias sql-dump > ~/Dumps/dumpy.2019-02-19.sql

Now, if I run this command in Drush 9 (9.4.0) I see the raw SQL just printed on the screen.

If I add 2>&1 to the command, this does not help.

If I add a --result-file= this creates a file on the remote server (not what I want).

Does anyone have any ideas here?

The output on the screen is caused by a bug in Drush.

From https://github.com/drush-ops/drush/issues/4004#issuecomment-479155241:

  The problem is that Drush is setting tty mode even though output is redirected. This is wrong.

Workaround 1 via the command line:

drush -Dssh.tty=0 @site.alias sql-dump > ~/Dumps/dumpy.2019-02-19.sql

Workaround 2 via the YAML file that defines the remote, as suggested at https://github.com/drush-ops/drush/issues/4004#issuecomment-500157166:

  For anyone coming across this issue. I had a similar problem with Drush 9.7.0 where sql:dump output was sent to standard output instead of a file. Based on the above workaround, I fixed it with the 'ssh' option in the drush alias of the remote site:

site.alias:
  ssh:
    tty: 0


An AJAX HTTP request terminated abnormally I am running a large script using batch api. I am sending newsletter mails to users. Mail sending is in bulk. I mean the mails is going to 8000 users. For testing I sent it to 1000 users and it worked fine. But for 8000 users it showing me this error :

An AJAX HTTP request terminated abnormally. Debugging information follows. Path: /batch?id=34485&op=do StatusText: ResponseText: ReadyState: 4

Or is there any other way to do the same? Following my code :

<?php
function testingmail() {
    $batch = array(
        'title' => t('Sending Mail...'),
        'operations' => array(),
        'init_message' => t('Connecting'),
        'progress_message' => t('Processed @current out of @total.'),
        'error_message' => t('An error occurred during processing'),
        'finished' => 'skeleton_batch_finished',
        'progressive' => FALSE
    );
    $result = db_select('customsendemail', 'c')->fields('c')->execute();
    $userslist = array();
    while($users = $result->fetchAssoc()) {
        $userslist[] = $users;
    }
    for($i=0;$i<count($userslist);$i++) {
        $userslist[$i]['user'] = explode(",", $userslist[$i]['user']);
    }
    $finallist = array();
    foreach($userslist as $value) {
        foreach($value['user'] as $key => $value2) {
            $finallist[] = array('mail' => $value2, 'subject' => $value['subject'], 'message' => $value['body']);
        }
    }
    foreach ($finallist as $userdetail) {
        $batch['operations'][] = array('skeleton_batch_worker', array($userdetail));
      }
    batch_set($batch);
    batch_process('<front>');
}

function skeleton_batch_worker($userdetail, &$context) {
  if(!isset($context['results']['processed'])) {
    $context['results']['processed'] = 0;
  }
  $context['results']['processed']++;
  $context['message'] = 'Sending Mail to '.$userdetail['mail'].' and subject '.$userdetail['subject'];
  $params['subject'] = $userdetail['subject'];
  $params['body'] = $userdetail['message'];
  drupal_mail('custom', 'mynewsletter', $userdetail['mail'], language_default(), $params, 'my@email.com', TRUE);
}

function skeleton_batch_finished($success, $results, $operations) {
  if ($success) {
    db_delete('customsendemail')->execute();
    $message = format_plural($results['processed'], 'One email sent.', '@count email sent.');
    variable_del("customnewsletter");
    watchdog("Custom Newsletter", "Custom Newsletter end.");
  }
  else {
    $message = 'Somer error in newsletter sending.';
    variable_del("customnewsletter");
    drupal_mail('custom', 'mynewsletter', 'my@email.com', language_default(), array('subject'=>'error in newsletter sending', 'message'=>'sending error'), 'my@email.com', TRUE);
  }
  drupal_set_message($message);
}

I have setup a cron job that sending mail to 500 users in every half hour.


Associating a timer on flag click on individual nodes for individual users I have a custom field "Time to Finish" in my custom content type in Drupal7. The "Time to Finish" is basically a timer of sorts. whenever the users click a flag (which is placed on nodes of that custom content type) the timer should start. The difficulty associated with this is that:

  Every node of that content type has different Time to Finish
  The timer should start on flag click (the flag is same on all node, "Start Flag")
  Every user would have their own timer then depending on when they click on the Start Flag

The admin while creating the content should have the option to fill in the field "Time to Finish" and on flag click the timer should start. Any suggestions. Would really appreciate it.

Thanks

Edit: I found this module which solves half of my issue,i.e, to assign every individual node their own Time To Finish field. Countdown Timer Field helped with this. Now i need that on "START FLAG" click the timer should start, not before that.

EDIT 2: i have opened a feature request issue for this at http://drupal.org/node/1948958 but can anyone help me do this. It will not only solve my use case but i think is a necessary feature to be added

EDIT 3: if there is any other solution i am eager to hear it as well.

Create tpl file for field field--field-name.tpl.php. place it to your

  if Field nameis: field_page_photos then File name will: field--field-page-photos.tpl.php

clear cache.

paste below code to your tpl field file.

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>

START FLAG

  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>


How to create a rule that loops the line items of a completed order and do a data comparison on a custom field that's on a product? I'm trying to create a rule that triggers on the event 'Completing the checkout process' that will then loop through the line items of the order. For each line item I'd like to do a Data comparison on a custom field that's on a commerce product.

This is the rule I created:

"LABEL" : "User needs approval for anything over 500",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "site:current-user:profile-educator" ],
      "field" : "field_borrow_level"
    }
  },
  { "AND" : [
      { "data_is" : {
          "data" : [ "site:current-user:profile-educator:field-borrow-level" ],
          "value" : "need_approval_greater_than_amount"
        }
      }
    ]
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : []
    }
  }
]

And this is the component that I was trying to run through the loop:

"LABEL" : "Check price of each line item",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_price" ],
"USES VARIABLES" : {
  "current_line_item" : { "label" : "Current Line Item", "type" : "commerce_line_item" },
  "current_product" : { "label" : "Current Product", "type" : "commerce_product" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "current-product" ], "field" : "field_purchase_cost" } },
  { "AND" : [
      { "commerce_price_compare_price" : {
          "first_price" : [ "current-product:field-purchase-cost" ],
          "operator" : "\u003E=",
          "second_price" : { "value" : { "amount" : 50000, "currency_code" : "USD" } }
        }
      }
    ]
  }
],
"DO" : [
  { "drupal_message" : { "message" : "You need School Administrator approval to check out any item valued over $500." } }
]

For some more context: This site is a library for special education teachers to be able to check out software and hardware for their use in the classroom. Which means that the price for each item is zero since the site is loaning out items at no cost to the teachers. The hang up in this case is that there are three different ‘borrow levels’ for a teacher. The ‘borrow levels’ are: 1. You can check out any item. 2. You can check out any item up to a $500 value. If an item is above $500 you need approval from your school administrator before the order is approved. 3. You need approval from your school administrator to check out anything.

My question here pertains to users with a ‘borrow level’ of 2. Since the products all have a price of zero we added a custom field to the commerce product that has the replacement cost of an item. So, when an order is placed and the user is borrow level 2 I need to look at each item in that order and determine if the replacement cost is over $500. If nothing is over $500, then the order can be flagged as approved. If there’s one or more items that have a replacement cost of $500 or more we need to send an email to that teacher’s school administrator telling them they need to log in and approve or deny the request the teacher has made.

First things first ...:

Your "AND" (in your rule, and in your component) appear to be redundant. If you doubt/wonder about that, have a look at my answer to the question "Which is the difference of combining rules with AND or just leave them follow one each other?".
So I'll ignore those already.
The list_item in your Rule (within the loop) is a variable name you get out-of-the-Rules-box. But to improve readability of your Rule, I suggest to rename that to something like current_line_item (and description like "Current line item").
While building (developing) your Rule (and component), I find it a handy facility to start with a rules action like "Display a Message" (which you can find within the "System" group). And for the actual message to be shown, already include tokens that may be interesting to know more about. Typically some "id" and some "description".
With the above Rule refinements, do some first unit testing, so that at least you get 1 Drupal message for each line item (produced via that Rules Action in your loop).

Remaining refinement(s):

Do some research/experiments to see how, starting from your current_line_item (my suggested new name for list_item!!!) you can find your way to the product the line item is related to.
You should be especially interested in something that smells, sounds and looks like the "ID" of the product the line item is about. If you think you found it, add that token to your message being displayed (to be sure you have what we should be interested in).
Assuming you found the product ID somehow, ADD a subsequent Rules action to perform a "fetch entity by ID", to actually fetch the product, with ID ... you guessed it ... the token you found in the previous step.
From then on, you have everything you need (I think) to add an extra Rules Action to simply perform your Rules Component, passing it the corresponding parameters.
In the end, when everything works as you want, you may want to remove or refine that "Show a message" Rules Action from before.

PS 1: The above is based on the assumption that I don't know "Drupal Commerce" at all ... hm, hm.

PS 2: I'm assuming this is about D7, though it will probably also work in a similar way if some day the question is about D8.


Verification code when adding new telephone number i used Sms Framework send sms to user if someone comment on their nodes system run ok, no problem.
And also i create new cck field for users phone, when user goes their account they able to add
or update  this field.
My question is how should i control if this telephone number belongs to user. How can i verificate this.

You can follow verification message method. When a user add/updates a phone number, you can send a unique random number which he must enter to verify his phone number.

Create a table that will contain three columns phone-number, unix time stamp and the verfication-code. When a user adds a phone number, create and store the random number. When the user inputs the verfication-code(random number), look it up in the database and then authenticate the user. Once he is authenticated, you can remove the entry from the database.

If you mention that verification code is valid only for 5 mins, then you can run a cron job to clear the database entries which are older than 5 mins.


Create a commerce product and add it to cart using Services I am using commerce_services module and poster as addon in firefox for my services. I want to create a commerce product and add it to cart using Services. I don't know what are the parameters and url to be provided. Please help...

Here is the poster.

Here's a link to the Commerce service's README.txt which includes a bit more detail on what kind of abilities it brings out of the box.

  The following grid indicates what callbacks have been defined so far
  out of the current target set of resources:

Resource         | Index | Retrieve | Create | Update | Delete
-----------------|-------|----------|--------|--------|--------
product-displays |   Y   |    Y     |   -    |   -    |   -
products         |   N   |    N     |   -    |   -    |   -
carts            |   N   |    -     |   -    |   -    |   -
orders           |   N   |    N     |   N    |   N    |   N

  The additional relationships and targeted actions are slated for
  development:

  product-displays: products products: add to cart carts: empty, convert
  orders: payments

So then the question is: Can you do what you want with commerce_services?

Can you create a product? Not according to the README

Can you add a product to a cart? Not according to the README


Content type provide to menu link I'm using Drupal 7 and different content types.

I've got 'News' content type and want this be like a blog. So, provide News content type to menu link.

Click Content Type and after menu settings, selected parent item main menu but not seen on frontpage.

How can i provide News content type to menu link?

Have a look on the Menu Position module. This allows you to map a specific content type to a menu item without generating "hard linked" menu entries.


"Call to a member function label() on null", while it's defined I'm using a module_suggestions_alter hook to force (or not) which template must be used in a specific case. The custom template I chose must is used in several cases, but sometimes, the default template must be used instead.

A while ago, I discovered that having too much templates for one node causes Drupal to choose the wrong template. I also discovered that I can remove the other suggestions so that I'm sure Drupal will choose the right template.

Now, I'd like to do the following: if the node type is equal to "node type 1" or "node type 2" (for example), then I unset every suggestions so Drupal uses the default template, node.html.twig. If not, I leave my custom template as a suggestion

  Disclaimer : I don't know if my "method" is the best one, but this is all I could think about. Feel free to tell me if this is heresy.

Here is my code:

function module_pdf_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  $node_type = ['node type 1', 'node type 2'];
  $view_mode = "node__module_pdf";
  $type = $variables['elements']['#node']->type->entity->label();
  // Outputs 'node type 1' if I do a die(kpr($type));

  if(in_array($type, $node_type)) {
    $view_mode = '';
  }

  if($variables['elements']['#view_mode'] === 'module_pdf') {
    foreach($suggestions as $i => $suggestion) {
      if($suggestion !== $view_mode) {
        unset($suggestions[$i]);
      }
    }
  }
}

So, as I told you, if the node type is equal to one of the elements that I set in the array, it will "erase" the $view_mode content. This way, the foreach will unset everything, and tell Drupal to use node.html.twig.

My main problem however, is that even though $type gives me the correct node value when tested, it will cause a server error if I use it in my foreach, and I don't know why. Error output is the following:

Error: Call to a member function label() on null

I tried a verification to check if the node type existed, but nothing changed. How can I fix this?

You have to check if you are in a node hook:

if ($hook != 'node') {
  return;
}

In other hooks you don't have a node object and the function label() is called on null.

Though you might want to check the machine name of the node type, because the display name can change when you have multiple languages:

$node->getType()


Hierarchy of content types with taxonomy as parent What would be the best way to implement a hierarchical structure like this:

(A) Taxonomy term from single vocabulary

(B) Some content type with parent of type A

(C) Some content type with parent of type B

There are reference fields from (B) to (A) and from (C) to (B) but not from (C) to (A).
Basically i need to implement something like this:
Topic (taxonomy term)
|___ Subtopic (custom content type)
         |___ Page (custom content type)
         |___ Page (custom content type)
         |___ + N
|___ Subtopic (custom content type)
         |___ Page (custom content type)
         |___ Page (custom content type)
         |___ + N

I tried using entity reference in all flavours but with not much success. I don't know how to:

Implement path aliasing when i add content of type (C) so i have hostname/(A)/(B)/(C) so i
don't have to enter the url manually (tried with url patterns but couldn't do it)
Create a view that displays content belonging to (C) with Context Filters on hostname/(A)/(B)/(C) url

Any help is much appreciated!

The most suitable structure in your case seems to be to create two-level Taxonomy for your Topic and Subtopic, and a Content Type with Taxonomy term Entity Reference Field.
If you want to limit which Taxonomy level appears when creating new nodes you can configure the Entity Reference field to use the Views Entity reference Display that filters and shows only the second level.
Use Pathauto module to set up automatic URL patterns based on the Taxonomy field and node title.
With Views you can create a Page with Contextual filters for the Taxonomy with Depth or Parent term, and the actual term the node is tagged with. These are two Contextual filters, each gives you one argument in the path.
With the first Contextual filter you filter out all the nodes that are tagged with the the child of the parent from the first URL argument. When you add the second Contextual you narrow it down to the particular Child term.
The third Contextual can be added for the node title, or node ID.
ER fields store entity IDs, not their names, so if you want the actual names in the path as arguments, and not the ID numbers, you'll have to add the Relationship for the ER field. This will open up more options in Views for the Vocabulary fields.
The solution I've described isn't trivial. If you're inexperienced in setting up Contextual filters try to practise first on simple examples. You can find many examples here with answers about Contextuals, Names, and Relationships.


Configuring Node Reference URL to auto populate with outbound (internal) link (node title) I have this Node Type called "Services", and I have a Node Type called "Booking". The latter is a form to request a booking of one of the Services. So by default, every "Services" node has a link to this form. I have Installed Node Reference and Node Reference URL and in the form (because of the configuration of  the mentioned modules) I have a Select List where the client can choose all "Services" available (It's the titles of the nodes of the Type "Services")

How could I achieve that, instead of the client having to manually select the Service from the list, it is already marked the title of the node corresponding to the URL the user is accessing the form, from. (meaning where they were at when they clicked the link to the form)

THANK YOU in advance.

Adding the node reference field step 1:

Adding the node reference field step 2:

a) Choose your Content type from 'Content types that can be referenced ' select list
b) Fallback behavior *-> choose Use select list widget , leave all other options if you not need

All the settings are over.

Now access your create content type with the node_id, in url

sitename.com/node/add/{the content type}/23, where 23 is the node id passed from the link

You can find that the options with particular node is is selected in the list box

Creating links - it is well explained in modules readme.txt please go through well


Search API - how to have blank page on initial page load I am using Search API with Apachesolr module. I have created a view on the index, but for some reason, before I do any search (or if I search for a blank screen) I get full results. How do I make the initial search screen blank? I tried setting the No Results setting in the view, but that only sets the text when you entered a bad search entry.

This is more of a Views question than a Search API or Solr one, since the answer applies even when not using the latter. You want to set your "Exposed form style" to "Input required." See this answer for helpful screenshots.


Views to Display Nearby nodes according to user current location(latitued/longitute)GPS I have Content type named Restaurant, When creating restaurant nodes I am imputing the Latitude/Longitude  using the GEOFIELD  module.

I have managed to Display all the restaurants in One Map using Views, Leaflet and leaflet Markercluster modules, you can see the attached screenshot.

My task now is to create a page named Nearby, where all restaurants near to user's current location(Latitude/Longitude) will be displayed, let say restaurant within 2km from the current users location.

To get the current user location, A prompt will appear on his/her browser asking them to share their location this is more specific for anonymous users.

I believe there must be a way to accomplish this task using Views or custom module.

Please Guide me step by step on how to make it happen.

any help will be highly appreciated.

Having messed with many Drupal mapping modules, I've found IP Geolocation Views & Maps to be the best overall helper (along with Leaflet, which I love). Give it a shot! It has lots of options, supports lots of maps, has geolocation stuff built in, marker clustering and some other stuff.


why do my cache entries all double up with a #cache_redirect item? I'm caching a piece of render array by adding cache keys to it. It's getting cached correctly, but I see two rows for every instance of it.

One looks normal -- contains the render array, with a cid that looks like:

CACHE_KEY:[languages:language_interface]=en:[languages:language_url]=en:[theme]=MYTHEME:[user.permissions]=HASH

The other one had data that starts like:

a:2:{s:15:"#cache_redirect";b:1;s:6:"#cache";a:5:{s:4:"keys";a:1 ...

and its CID is:

CACHE_KEY:[languages:language_interface]=en:[theme]=MYTHEME:[user.permissions]=HASH

It looks like this is something to do with language negotiation, but why, and is this normal? The page I am loading when I am testing this is using the language prefix, so I'm not getting redirected.

It's still a bit unclear what you are asking, but to be more precise about my comment. The bubbled up cache contexts depend initially on the content of the render array, but this content can be dependend on other things. For example a rendered link can depend on a configured language negiotiator which provides a path processors rendering links differently dependend on the language and so bubbles up the cache context you have identified.


Multiple problems after updating to 7.54 I am working on a D7 site with the latest stable version of Commerce and several Commerce Contrib modules. I recently applied the core 7.54 update from 7.53 and it appears to have caused several problems with my DC set up; specifically 1) the Store Admin UI; 2) Cart Shipping Calculations; 3) the addition of Coupons; 4) the system message list (particularly for cart actions doesn't clear, and builds up).

First, all of these symptoms seem to be related to 7.54 because I have the same code base (same module versions) on a test server without the issues.

Commerce Admin UI whatever is happening has broken part of the commerce store ui. I cannot add line items to an order (not coupons, not products, not shipping). When I select one of the line item options and click "add line item" the spinning icon appears but it stops. The same behavior occurs regardless of which line item type I choose. I can confirm that this functionality is preserved with 7.53. This seems to be caused by an ajax error "Invalid Form POST Data".

Commerce Shipping I have three commerce shipping services, two flat rate, one based on the Postal Code and Weight Module. When a user proceeds through the cart checkout process, the Shipping calculation is not performed and the user can proceed to payment without shipping charges being applied to the order. I receive the follow watchdog error: "Invalid POST data" from ajax referred  by mysite.com/checkout/294/checkout. If the user were to go back to checkout page, the shipping charge is calculated.

Warning: Missing argument 1 for addressfield_default_values(), called in /home/phislub9/public_html/sites/all/modules/commerce_shipping_postal_code_weight/commerce_shipping_postal_code_weight.module on line 81 and defined in addressfield_default_values() (line 374 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Warning: Missing argument 2 for addressfield_default_values(), called in /home/phislub9/public_html/sites/all/modules/commerce_shipping_postal_code_weight/commerce_shipping_postal_code_weight.module on line 81 and defined in addressfield_default_values() (line 374 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Notice: Undefined variable: field in addressfield_default_values() (line 375 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Notice: Undefined variable: instance in addressfield_default_values() (line 375 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Notice: Undefined variable: instance in addressfield_default_values() (line 376 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Notice: Undefined variable: field in addressfield_default_values() (line 408 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).
Notice: Undefined variable: instance in addressfield_default_values() (line 409 of /home/phislub9/public_html/sites/all/modules/addressfield/addressfield.module).

I am led to believe that this is an issue with core version 7.54 because these errors don't occur on the 7.53 codebase.

Commerce Coupon Adding percentage based coupons also fails with the "Invalid Post Form Data" notification in watchdog. Coupons can be input but they are not applied when submitted. The form simply clears.

System Message Box Unclear if this is related, but the system message box also seems to be affected. The system message box keeps every cart action in the box, leading to a larger and larger box. This clears after flushing the cache as an admin, but users do not have this option and therefore cannot clear the message box.

I'm not sure what else to add here, other than recently the server has been throwing PDO errors and crashing with the mysql server going away. It is a large codebase (over 100 modules).

UPDATE the module suggested in the comments here worked. Truncating the cache tables did not work.

Try to apply the patches that commerce kickstart uses .. https://www.drupal.org/project/commerce_kickstart/releases/7.x-2.45

where

http://drupal.org/files/drupal-865536-204.patch

is form related

the others may not be needed:

http://drupal.org/files/1275902-15-entity_uri_callback-D7.patch
http://drupal.org/files/drupal-1470656-14.patch
http://drupal.org/files/issues/drupal-7.x-allow_profile_change_sys_req-1772316-28.patch
http://drupal.org/files/issues/install-redirect-on-empty-database-728702-36.patch


Can't find the place to add in image caption I installed image caption module and enable 'Image caption filter' under Home » Administration » Configuration » Content authoring » Text formats.

But I can't the place to add in the image caption.

The project page is somehow missleading and most of the info there is for D6 version. But at the bottom, it clearly states:

jQuery caption
  Less module code
  No configuration needed
  Better javascript captioning logic

You can also refer to this issue for more info.


Image upload field won't show I have added a image field with upload widget to my content type. It is shown when I try to add content as administrator, but not with other user types. Any ideas what may be wrong? Probably some permission or something, but I am simply unable to find out which setting this may be. Any help?

Seems like the fields are visible if I disable the "OG Field access" module. But when I enable it again, I cannot see the fields.

If it's a permissions problem you should go to the People tab at the top of your nav bar. Then under People click on "Permissions" and see if you can find the permissions for the image field and give other users permission there.


Unable to post new forum topics in Drupal site When I try to post a new forum topic getting this error

Fatal error: Allowed memory size of 157286400 bytes exhausted (tried to allocate 91 bytes) in /sai/vij/modules/field/field.attach.inc on line 696

i have a free space of 4389 MB in server. and I given a memory_size as -1 in php.info file.

     Any ideas for implementing this in drupal is appreciated.

Yes i think @No Sssweat is right. You need to increase PHP memory limit.

ini_set('memory_limit', '256M'); in your sites/default/settings.php file.

Increase PHP memory limit

Increase PHP's memory limit, e.g. to increase it to 256M you could try adding:

memory_limit = 256M to your server's main php.ini file (recommended, if you have access)
memory_limit = 256M to a php.ini file in the Drupal root
ini_set('memory_limit', '256M'); in your sites/default/settings.php file
php_value memory_limit 256M in your .htaccess file in the Drupal root


Ajax best practise for custom links I was reading up on AJAX requests in Drupal 7 at http://codekarate.com/blog/drupal-7-javascript-ajax-framework-example-link

Where the AJAX framework is explained in detail, when used on custom links and potentially other HTML elements.

Now it got me wondering,

In a more "custom" point of view, I have created some (regular) hook_menu() implementations in the past, (without any /ajax or /nojs stuff) that would just return json data.

So, basically I implemented links in my custom module that would get called via a custom jQuery file (via $.post or $.get), via a click() event or something like this, that in turn fired the hook_menu() mentioned above.

This would then return some json data after processing the request, this returned data would get fetched by my jQuery script, and the DOM would be updated with the data that was returned by the ajax call (json, ...).

Now I am just wondering on the pro's and con's of both ways of doing things.

It figures that the first one is more "the Drupal way", and the second one is much more custom...

Since I never had any issue with using the second way of things, I am very curious to hear what you all have to say on this matter.

Thanks in advance.

Best

Guardian

yes - you can always do custom stuff, but miss all the features of the framework.

some pros:

works with javascript disabled (/nojs)
you can use the form-api 1:1 (more or less ..), so forms are reusable
you can use predefined commands (like replace or alert) and create your own
it's all ready for jquery ui
you can write your own and overwrite behaviors (and it's settings) from other modules
you can use drupal translations
with ctools it gets even more powerful, like modals, AJAX Responder etc.
there are a lot of modules you can use (qucktabs, modal forms, masonry .. you name it ..)
you can have all JS libraries managed
for JSON with website content you can use views datasource module

the contra is you need to be willing to learn and adapt :D


Infinit loop when I 'print_r' variables like $form_state, $form I don't understand, I want show some vars during my dev. I work on windows and Linux.

On windows, When I use print_r for show $form or $form_state (from the hook form_alter). There isn't any problem, when the page is loaded, I can see the content of theses vars.

But on linux, when I use print_r, I see the RAM (via top/htop) rise continuously until 4Go and my OS freeze x) The page I request is never loaded.

I don't understand because I don't think have a special configuration. My configuration is recent.

On Linux (Mint)

php -v : 5.6.14
apache2 -v : 2.4.10 (Raspbian)

Solution

Activate the sub-extend drupal Kint from the devel package :)

You might not like the answer, but it's still true: Don't use print_r() for $form/$form_state, entity or other complex objects. It just doesn't work.

Try kint() from the devel module instead, make sure to install the kint submodule too.


Get post information in drupal function I posted JSON array from my script using jQuery.post , to get the posted data in my drupal module function I am using

$json = file_get_contents("php://input");

but is there a better way or a 'drupal-way' to get posted data in a drupal function?

Assuming that you're using Drupal 7, take a look at the module Content as JSON. This should take care of the details and put you within the realm of the "drupal-way". There's also the Services module which might be overkill for what you're doing.

If you stick with file_get_contents then don't forget json_decode:

$received = file_get_contents("drupal://input"); // Use inputstream module.
$received = json_decode($received, TRUE);

Then you can play around as much as you'd like with the $received value.

Additionally, the inputstream module is invaluable in letting you get to the input stream more than once (if you try using php://input more than once, the second time, and those following, will return NULL).


How to record how much time user has spent on my node? I want to record the time a user has spent on my particular node so I could show a pop up to the user to register once the user has read 3 article. But the user must have spent at least 30 seconds on each node.

There is the Time Spent module available, but I wonder if I can merge it with another (custom) module I have created (which records the number of nodes user have visited)?

Without using any custom modules

Drupal core doesn't have any such feature. So if you don't want to consider using a contributed module, the only options you have is to:

Write a custom module (or further enhance the custom module you already have for it).
Add something like a javascript to the theme(s) you're using.
Wait for a future release of Drupal (core) that may include such feature.
Consider using a contributed module (e.g. as further explained below).

Using the Javascript Timer module

The Javascript Timer module (available for D6 and D7) seems to be a possible answer to your question. Here is a quote from its project page:

  ... provides a timer API that can hook HTML elements to javascript widget objects. This is useful if you want a moving timer/clock or a widget that updates every second. It comes with widgets for a count-down timer, a count-up timer, and a clock. It uses jQuery and a single event loop to handle as many timers as you need on a single page.

Its Readme.txt file contains various examples, both Inline HTML Examples and PHP Input Format Examples.

Comment #4 in issue #1195560 contains an interesting comment that may help to get you going:

  It allows for redirecting to a new URL or refreshing the existing page.
  On the setting page it is called "Timer complete redirect". If you use a "redirect path" of <reload> it will just reload the current page.


Remove core and contrib. modules css files I would like to prevent several contributed modules from using their own css files. Constantly having to reset their css and then apply your own is a waste of bandwidth IMO.

I tried this out with nice_menus and it didn't seem to do anything.

Placed in template.php

    function phptemplate_variables($hook, $vars) {
        $css = drupal_add_css();

        $rm[] = drupal_get_path('module','nice_menus').'/nice_menus.css';
        $rm[] = drupal_get_path('module','nice_menus').'/nice_menus_default.css';

        foreach ($rm as $key => $value) {
            unset($css['all']['module'][$value]);
        }

        $vars['styles'] = drupal_get_css($css);
    }

I think the function should be named MYTHEME_preprocess_page.  Though a more common method is to add

stylesheets[all][] = nice_menus.css

to your theme's .info file.  nice_menus.css will be replaced by the one provided by your theme, or suppressed entirely if your theme doesn't contain this file.


Weform: Send email to the email field in the node reference field using rules I have content type Organiser. and it has an email field Organiser email.

I have created a webform and added a node reference component which is referencing the Organiser content type.

I want to send an email on webform submission to the email address entered in the Organiser email in referenced node.

Is it possible with rules without entering the php code in the rules action?

I have done some work around to get this functionality.

Created a hidden component to the webform.

Then through hook_form_alter, get the organiser email from the referenced node and set it as the default value to that hidden field.

Then in the webform email settings, I selected that hidden webform component as the "Email to address".


How on node forms do I show weight of all menu items? I'm wondering how it is possible (with a hook) to show the weight next to the menu title in the parent drop down found in the Menu Settings tab.

So this is what it is at this moment:

And this is what I want it to be, so the admin knows what weight to fill in to place the menu item at a certain place:

Doing a hook_form_alter on the node edit form should do the trick:

  use Drupal\Core\Form\FormStateInterface;

  function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** to appear on the node/add/page form, change this or add more for other content types **/
  if ($form_id == 'node_page_form') {
    $menuItems = $form['menu']['link']['menu_parent']['#options'];
    $menuItemsWithWeight = array();
    foreach ($menuItems as $menuKey => $menuValue) {
      $storage =  Drupal::entityManager()->getStorage('menu_link_content');
      $uuid = ltrim(strstr($menuKey, ':'), ':');
      $uuid = ltrim(strstr($uuid, ':'), ':');
      $link = $storage->loadByProperties(['uuid' => $uuid]);
      if(count($link) > 0) {
        $link = reset($link);
        $weight = $link->getWeight();
        $menuValue = $menuValue . ' ('.$weight.')';
      }
      $menuItemsWithWeight[$menuKey] = $menuValue;
    }
    $form['menu']['link']['menu_parent']['#options'] = $menuItemsWithWeight;
   }
  }


How do I add custom meta tags to a view page? There doesn't seem to be an answer for Drupal 8 yet. I have the metatag module installed, it's a great module, but doesn't seem to address views at all. This post for Drupal 7 says that it comes with a 'metatag views' module, but, this doesn't seem to be true for Drupal 8. I've also tried to install metatag quick, but, that fails to do anything at all. So I'm stuck. Is there a way to do this programmatically in D8? How can I get this done?

Current version of Metatag module includes a submodule "Metatag: Views".
Enabling this, you get a new section in your views editor to set all metatags available (specific tags are available in other submodules in a very drupal way).


Add user permission to content node I'm creating a collection manager for movies and books in Drupal 8. Now I have a content type called "collection" and one that is called "Movie". The collection is just a collection of different movies. Now I'm searching for a way that a user can give another user access to his collections and movies.

How can I achieve this in my module?

Your question looks like a perfect fit for the Group module, which can be used to create collections of content (nodes) that can be accessed by sets of users and with variations of access levels, such as none or read only.

Have a look at the answer to What are the alternatives for the Organic groups module? for a brief introduction to the Group module.

For this specific question, here is a blueprint of how it could be used/configured:

Group Type: Collections
Group Roles (refer to "What are the various roles supported by the Group module?" for more details):

Group Owner
Group Fans (or whatever fits), used for those who have access to a selected collection.

Groups (adapt the group titles to fit your collection names):

Collection 1 of user A.
Collection 2 of user A.
Collection 1 of user B.
Collection 2 of user B.
Collection 3 of user B.
...
Collection I of user X.

If a user creates a new group, then automatically assign role "Group Owner"-role to the user who created the group.
Group permissions: grant permission to the user with role "Group Owner" to perform actions like "Add members" or "Invite members to join".

To use the Group module from within a custom module, start from its Development guide and/or have a look at its API for D7 or API for D8.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Other questions tagged with the group tag.

PS: Even though this question is tagged for D8, this answer applies for either D7 or D8 ...


How to redirect all 404s to the same path on a different server I want to redirect all 404 errors on my site to the same path on a different server.

For example:

http://drupal.example.com/url/not/in/drupal should be redirected to http://othersite.example.com/url/not/in/drupal

The sites are not on the same server and the other site is not running Drupal.

I know I can use the redirect module to redirect specific URLs but I don't have a complete list of the URLs on the other site so building the list is not practical.

Suggestions for modules or pointers to the appropriate hooks if I want to write my own module would be appreciated.

Here is small trick:

Enable module PHP Filter, add PHP filter to administrator

Create a node can use php filter, add code: (We are using header here, not use drupal_goto because handle 404 workfollow of Drupal will redirect to the node first.

<?php
  $url = drupal_get_destination();
  header('Location: http://other.example.com/' . $url['destination']);
  drupal_exit();
?>

Config Drupal using 404 page is the node you was create.


How to display the description of the article with 150 characters? My site is with Drupal 8, I have a content type "Article" with a body field.

I copied the twig node.html.twig file into my theme.

If I put the following code, the description is displayed:

{{ content.field_article_description }}

The parameter of the display of the field, allows to choose the number of characters. But he stops at the first sentence, cuts the word and does not display the elipse (...).

I want the description to be cut to 150 characters right after the word (I do not want the last nmot to be cut) and I want to add at the end an elipse (...).

I want the field to be displayed in plain text (without html tags).

Is it possible to add parameters to the description field with twig ?

Can you help me ?

Check out Smart Trim module.

  Smart Trim implements a new field formatter for textfields (text,
  text_long, and text_with_summary, if you want to get technical) that
  improves upon the "Summary or Trimmed" formatter built into Drupal 7.


Comments custom fields access by role Ive added a custom comment field to comments of my node i.e. new fields beneath comment_body that being field_flag_reason and field_unflag_reason

I want to hide these two fields for specific roles so I'm looking to use a hook with the logic to display when appropriate, the difficulty I'm having is I'm confused as to what element I should be trying to target in the rendered array and any changes I try don't seem to take effect, think I might be going about it the wrong way, any help would be greatly appreciated.

Have you ever tried Field Permission. I think it'll help to solve your requirements. Check the video tutorial to use that module Drupal 7 Field Permissions Module


Stuff added to  not included in cached version I have a page on drupal 7 where I have the text format set to PHP Code.  I am using the drupal_add_html_head() to include a few CSS/JS files, and an RSS link.  My problem is that everything I add with drupal_add_html_head is only visible for a single view after the caches are cleared.  After that single view they do not show up in the view source.

It can be demonstrated with a Body that is as simple as below.  The first view will show an alert.  If you reload the page, the script is not added, and alert() is not called.

<?php
drupal_add_html_head(array(
  '#tag' => 'script',
  '#value' => 'alert("Hello world!");',
  '#attributes' => array(
    'type' => 'text/javascript'
  )
), 'jscripttest');
?>

You should see "Hello world!"  But you don't unless you have just
cleared the cache.

I have also tried drupal_add_css, and drupal_add_js with similar results.  The CSS/JS is displayed after the cache is cleared, but only once.

This is a totally valid question in my opinion. Using the PHP input filter (or eval() in general) is almost never a good idea, but the fact that this code only runs once is not intuitive.

That said, I actually can't reproduce this.

My first thought was that the rendered HTML was being cached in the cache_filter table. But by default, the PHP Input filter is not cached in the cache_filter table. php_filter_info() from php_module:

function php_filter_info() {
  $filters['php_code'] = array(
    'title' => t('PHP evaluator'),
    'description' => t('Executes a piece of PHP code. The usage of this filter should be restricted to administrators only!'),
    'process callback' => 'php_eval',
    'tips callback' => '_php_filter_tips',
    'cache' => FALSE, // <- This is set to FALSE in the module
  );
  return $filters;
}

My next guess was that the anon user Page Cache was somehow ignoring the fact that those functions had been called. But I tested both drupal_add_html_head and drupal_add_js (the latter with both an external file and inline JS) and even for anonymous users, the JS was loaded and executed on all page views with and without the page cache enabled. I also tried all of these scenarios in the default body field and with a field added with the Field API.

I guess that means that my answer is one of the following:

Something is overriding php_filter_info() to set 'cache' => TRUE
You have an additional layer of caching that's causing this on your server
Something else???


Show publication date in search results I've got a website with lots of content that has been migrated. For each node I've added the original date as the Authored on date. However, search snippets show the date a node was last updated.

I've read the search-result.tpl.php file and can't figure out how to change the $info_split['date'] variable so that it shows the publication date instead.

How can I display the Authored on date instead of the updated date in the search results?

Use a the preprocess function, template_preprocess_search_result() to add a custom authored on date variable to your search-result.tpl.php template.

function MYTHEME_preprocess_search_result(&$variables) {
  //$variables['result']['node'] is the node object returned in the search results
  //the $variables['result']['node']->created property contains the authored on date
  if(isset($variables['result']['node'])) {
    $variables['created_date'] = format_date($variables['result']['node']->created, 'short');
  }
  //$created_date will be available in your search-result.tpl.php for printing
}

It's probably worth mentioning that the base template is printing out the $info variable which is the concatenation of a few vars in $info_split. Changing $info_split won't change the printed date without changing search-result.tpl.php.


Allow user to flag only those node that associated to a particular term of a vocabulary? I have content type  "product" term referenced by Taxonomy "Product category" having terms
-Cook tops
-Heaters
-Chimneys

Now if i flagged nodes associated with term "Cook tops" , after that if i flag node associated with "Heater". I should get a error message.

Actually I am using this flag to show flagged item in BASKET(as done in many shopping site). But i do not want to put a "Cook tops" node with "Heater" nodes.

Found these links which solved my question
https://www.drupal.org/node/2235353
https://www.drupal.org/node/952114


How can we go to particular #div on a page using drupal_goto()? There is one scenario where I want to go to particular div on page using drupal_goto().

Below is my code:

$path = '#textarea_comment'.$alert_id;

$options = array('bid' => $bookingid.$path );

drupal_goto("/fsaclientservice/viewreservation", $options);

In the above code the # is get replaced with %23 in URL and due to this I am not able to redirect to particular div on a page.

I have tried :

encodeurl()
rawencodeurl()

But still the URL is coming as %23 etc. Please help.

You just use the second argument the function takes.

drupal_goto("fsaclientservice/viewreservation", array('fragment' => 'add-reservation-note-form'));

Notice that in the code I wrote here, 'fragment' is a literal string you need to use as it is, and 'add-reservation-note-form' doesn't have any leading #.
The documentation for that parameter is in url() because drupal_goto() calls that function to build the URL.

  $options: (optional) An associative array of additional options, with the following elements:

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.
  'absolute': Defaults to FALSE. Whether to force the output to be an absolute link (beginning with http:). Useful for links that will be displayed outside the site, such as in an RSS feed.
  'alias': Defaults to FALSE. Whether the given path is a URL alias already.
  'external': Whether the given path is an external URL.
  'language': An optional language object. If the path being linked to is internal to the site, $options['language'] is used to look up the alias for the URL. If $options['language'] is omitted, the global $language_url will be used.
  'https': Whether this URL should point to a secure location. If not defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can only be enforced when the variable 'https' is set to TRUE.
  'base_url': Only used internally, to modify the base URL when a language dependent URL requires so.
  'prefix': Only used internally, to modify the path when a language dependent URL requires so.
  'script': The script filename in Drupal's root directory to use when clean URLs are disabled, such as 'index.php'. Defaults to an empty string, as most modern web servers automatically find 'index.php'. If clean URLs are disabled, the value of $path is appended as query parameter 'q' to $options['script'] in the returned URL. When deploying Drupal on a web server that cannot be configured to automatically find index.php, then hook_url_outbound_alter() can be implemented to force this value to 'index.php'.
  'entity_type': The entity type of the object that called url(). Only set if url() is invoked by entity_uri().
  'entity': The entity object (such as a node) for which the URL is being generated. Only set if url() is invoked by entity_uri().


How to get the translated term name by tid? I'm looking for a working method to get the translated term name by tid.

The following code returns the original term name but not the translation.

global $language;

$lang_name = $language->language; // en

$term_id = 788;

$term = i18n_taxonomy_term_get_translation($term_id, $lang_name);

Most examples provided in "how to get the translated taxonomy term programmatically?" seem not work for Drupal 7.

I managed to make it work! This is my code

$tree = taxonomy_get_tree(9); // Your taxonomy id

foreach ($tree as $term) {
  if (module_exists('i18n_taxonomy')) { //To not break your site if module is not installed
    $term = i18n_taxonomy_localize_terms($term); // The important part!
  }
  print l($term->name, 'taxonomy/term/' . $term->tid); //print the terms
}

That sould do it! Diadeuf!


May I use Bootstrap-CDN on Subtheme for production site? Follow up of my other question with less files ;-)

As I don't need de less files on production site, could I then switch to BootstrapCDN for js files? Or would it overrule style.css too?

Thx for your support guys!!

Yes you can use the BoostrapCDN for js and your own style.css. I'm not sure if would overwrite but if those you can create a separate file that is not style.css on the info file to add your CSS or your JavaScript.

If you are using the Bootstrap project by default it allow you to use the CDN.


Random default image for a CCK image field Is it possible to use a random default image for a CCK image field, if the user doesn't provide an image?

Module called image field random does the job you specified.

Description:
Populates an image field with a random image on save.


How do I add a variable to $node from a module? I would like to perform a lookup on $node->uid from a module, fetch a field from the user profile and then attach that field to $node for use in template files.

I can do this within a theme preprocess method, but my understanding is that adding data (and performing queries) the "Drupal Way" means doing it in a module.

I guess I'm asking what hook I want to target. (Please note that this module did not implement the content type I want to alter.)

Try hook_node_load(). With this hook you can add info to a node.


How do I get the currently logged-in user? I have a site running on Drupal 8 with a login module. I want to get the user ID for the currently logged-in user to later execute a database query.
This is the code I am using.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$uid = $user->get('uid')->value;
echo $uid;

In the controller of a custom module, this code works only between all using and the class controller uses the following code.
namespace Drupal\CoopMatha_adh_apport\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Node\Entity\Node;
use Drupal\CoopMatha_adh_apport\Repository;
use Drupal\matha_tools\Controller\ListeController;
use Drupal\matha_tools\Controller;

$userCurrent = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($userCurrent->id());
$uid= $user->get('uid')->value;
echo $uid;

class RapportsController extends ControllerBase {

  // I want the user ID here.
  public function filtrer($firstLetter='', $nbr_ligne='') {
    // …
  }

}

How do I get the currently logged-in user ID in the controller class?

How do I get the currently logged-in user ID in the controller class?

Controllers have a currentUser method:
public function filtrer($firstLetter='', $nbr_ligne='') {
  $current_user_id = $this->currentUser()->id();
}


Pagination in apache solr search page To control the number of search results showing in a solr site search page there is a text field in admin/config/search/apachesolr/search-pages/core_search/edit

In advanced option tab, there is an option called Results per page to specify its count. but I need to alter the pagination displayed in search page. It displays 1 to 9 pagers by default I want them to be 5. what should I alter??

This could be done by using theme_pager in TEMPLATE.PHP and by applying some if condition to be specific on just the search page

if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}

These two lines did the magic !!!


How to get product image URL from product page? I'm developing a module for Drupal Commerce - Drupal 7 and I need to get the product image URL from product page but I couldn't find a solution for this.

I'm successfully fetching the product name, title, url but not the its image URL which really bothers me as I am used to WooCommerce where there is a very simple way of getting the image URL.

I have found a quick fix for this issue.

$product = commerce_product_load($productId); // loads the product by id
$productImage = drupal_json_encode(file_create_url($product->field_images['und'][0]['uri'])); // gets the main image of the product if it has multiple images and formats the link properly


Adding a body ID to a view page I would like to add a body id to a view page in Drupal 6 - would I modify template.php? I'm trying to figure out where to make the correct modification

You can do this in a couple ways.

Easiest, if you have only one Views page that needs this, you could go into your theme's directory and copy page.tpl.php to page-PATHTOVIEWPAGE.tpl.php and then inside there, put in the id, eg,

<body id="ID" ... >

Just change any /s in your path to this page to -s in the template name and you should be all set.  Take a peek at Drupal 6 Template Suggestions for more info.

Now, if you are going to want to do this in multiple pages or need it to be more extensible, then, yes, you will most probably want to add in a preprocess_page() hook in template.php as well as another custom page.tpl.php template file.

What you could do would be to copy page.tpl.php inside your theme to, let's say page-with-body-id.tpl.php.  Then, inside there, you could put something like this:

<body id="<?php print $body_id; ?>" ... >

Then, inside template.php you would add in a preprocess_page() hook, eg, something like this:

function YOURTHEME_preprocess_page(&$variables) {

   $whereami=$_GET['q'];  // eg, www.yourhost.com/WHEREAMI

   switch ($whereami) {

     case 'events':
     case 'news':
     case 'press':

       $variables['body_id']=$whereami;
       $variables['template_files'][]='page-with-body-id'; // and use this new template

       break;

    }

    // any other page preprocessing goes here

 }

Just make sure you don't create a page template that would match an existing path on your system.  I doubt www.yoursite.com/with/body/id exists but you never know :)

Otherwise, another good place to look for info is here: Overriding Theme Templates in Drupal 6.

Also, if you can use a body class instead of an id, this is even simpler:

function YOURTHEME_preprocess_page(&$variables) {

   $whereami=$_GET['q'];  // eg, www.yourhost.com/WHEREAMI

   switch ($whereami) {

     case 'events':
     case 'news':
     case 'press':

       if (empty($variables['body_classes'])) {
         $variables['body_classes']='view-' . $whereami;
       } else {
         $variables['body_classes'].=' view-' . $whereami;
       }

       break;

    }

    // any other page preprocessing goes here

 }

which will add view-WHEREAMI to the list of classes for the body in (most) default page templates.

RE: How do I do an if conditional based on a view in template.php, you can also do something like this in the appropriate spot:

$mgi=menu_get_item();

if ($mgi['page_callback']=='views_page' && $mgi['page_arguments'][0]=='WHATVIEWYOUARELOOKINGFOR') {

  // you are on the views page you are looking for

}


How to have multilingual custom 404? I have a multilingual Drupal 7 site for which I have set up a translated 404-page accessed at mydomain.com/404 and mydomain.com/en/404. In the Drupal settings for 404-page I enter just the path 404.

However, when visiting a non existant URL on the English version, the default language is still being used.

What did I miss?

With i18n module pack, there is a module for translating settings, like front page and 404 pages. This means you can setup your 404 page per language, fx node/1 for en and node/2 for fr etc.


Returning all items in Views for Dates with Start dates AFTER Now as well as no date set I have some items that have dates and some that do not. For items that have dates I do NOT want to show items that are past due (ie. events that are before today's date (or 'now' is fine). However I also want to display items that have no dates set.

In my view if I filter on dates I can choose to display events that are on today or later, and that works fine. But then it doesn't display any items that have no dates.

So, my question is, how can I customize my filter to show items with no value for event date as well as items that start on or after 'now'?

You can use OR conditions with the filters, and have one group of filters checking for the date value, and the other one checking for empty date field.

You would end up with something like:

*Some filters group you probably have here*
AND
  Date >= NOW
    OR
  Date IS EMPTY

Here is a post for some info on how to work with these - http://www.webomelette.com/drupal-views-filters-and-or-logic


entityQuery with multivalue date field Is there way to use entityQuery in order to select nodes with multiple value date field. For example we have a content type event with a field field_event_date which may contain unlimited number of dates. Is there any way to select all event nodes that occur on a certain day? E.g. we have field_event_date equals to

[
  10.09.2018
  11.09.2018
  13.09.2018
]

the node with this field should be returned for when "10.09.2018", "11.09.2018", "13.09.2018" is passed, and omitted for any other date (including "12.09.2018).

Try this Out:

use Drupal\node\NodeInterface;

    $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', 'event')
    ->condition('field_event_date', ['10.09.2018', '11.09.2018', '13.09.2018' ], 'IN')
    ->range(0, 10);

  $result = $query->execute();


Clone Commerce Product Option Sets This issue hints it's possible to clone Option sets https://www.drupal.org/project/commerce_option/issues/1319618

  To reproduce:

  On page admin/commerce/products/option-sets Click 'clone' on any
  product option set. New option set appears as [original option set
  name] (cloned) Selecting 'Manage Fields' shows no fields and selecting
  'Manage Display' shows no fields added.

But there is no Clone button anywhere to be found under admin/commerce/products/option-sets following that instruction.

Does it require any additional module?

Commerce Product Option is an unsupported module. You should not be using it. If you want similar functionality with core support (e.g. options on an Add to Cart form that aren't required to correspond to unique SKUs), use custom line item types with line item fields instead.


Drupal 7: Collection of nodes field Which is the best way to attach a collection of nodes to another node?

I'm creating a meal and ingredients nodes. I want to assign multiple ingredients to a meal and I'd like to do it programatically via modules ( content types )

Which is the best way to achieve this? Can you point me to the right direction ( links, etc...)

Thanks

What about a taxonomy vocabulary for the ingredients list, and then just reference those taxonomy terms in your meal node?
You could try the Insert View module, create a view with whatever other nodes you want, and then display it at the right place in your node
If you want something a bit more complex, you could relate the meal node with the ingredient nodes, and collect them with a view, and then use Insert Views.

As a general note though, Views sounds like what you want to use -- it's perfect for that collecting of different information from other nodes and displaying it.


Drush migrate-upgrade error I have run drush migrate-upgrade successfully previously, but not when I run it, I am getting

  "An option named "Configure-only" already exists."

I get this error regardless of if I have --configure-only in the command.

The command is:

drush migrate-upgrade --legacy-db-url=mysql://user:password@localhost/db --legacy-root=http://example.com --configure-only

Has anyone seen this error?  I am not seeing anything on any forums about it.

I ended up resolving this by uninstalling and reinstalling all of the migrate-related modules.  Not an ideal solution, but it worked.


Programmatically get the product name from $order I need to get the product name using the $order variable in Ubercart. How can I achieve?

In ubercart uc_products table stores the product details. You can get product id from the $orders array and can fetch the required product data from
uc_products table.

$query = "SELECT * FROM uc_products WHERE nid = ". $pid;

Refer the links for more details
https://www.drupal.org/node/1940926


Flickr module not showing any photos I am attempting to use the Flickr module 7.x-1.x-dev to display a block of recent photos from a photostream on Flickr. I have setup the API keys and correct user ID, but the block is not producing any output. I've checked the Drupal logs and can't see any issues. I've also run cron and cleared the cache.

Does anyone know how to get this module working or of any alternatives to this module that work in 7? I tried Flickrippr but it produced a lot of PHP errors that brought the site down.

Use the block Flickr: User photos corresponding with a node's taxonomy term, location and/or date field and under FILTER / SORT ORDER
leave Flickr tags as node taxonomy terms (choose a vocabulary to use) on none.

The sandbox demo at https://simplytest.me/project/flickr/7.x-1.x shows an example in the sidebar. Log in there and check the settings used with your own.


Which Rules condition can be used to email a user when an admin updates their profile? I am trying to set up a rule (using the Rules module) that will email a user if their user record has been updated by an admin.

It is easy to generate an email when their profile is updated, but I can't see any way to make a Rules condition that the logged in user has a specific role.

Interesting Rules question! Have a look at this rule (in Rules export format, just import it in your site and check the results of it):

{ "rules_notify_user_about_profile_updates_by_an_admin" : {
    "LABEL" : "Notify user about profile updates by an admin",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Bingo ... it seems to work ..." } } ]
  }
}

To verify if it does what you're looking for, perform these steps:

use a userid with role "administrator" (which I assume to be role id = 3, if not adapt that to the role id you're using for admins).
edit any existing user profile.

If you get a drupal "message" like "Bingo ... it seems to work ...", then adapt the Rules "Action" with that "easy to generate eMail" you seem to already have (or know about).

Of course, if you have another userid available that has permission to edit user profiles, but without admin permission, then that should NOT result in such a "Bingo ...".

For anyone wondering what the actual missing piece of your puzzle was (= the "clue"): adding the condition with entity_is_of_type makes the user_has_role available. That role is related to the user performing the profile update (the "logged in user") ... which of course is different from the account being updated ...


How do I display a node in a block? I would like to display a node as a block in Drupal 8, but I don't know how to do this. I know in Drupal 7 I could use the Nodeblock module to accomplish this task, but there isn't a Drupal 8 version of it (and it looks like that there never will be).

Can this be accomplished using another module that I am not aware of?

You can add a file to your module at src/Plugin/Block/YourBlock.php

namespace Drupal\your_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a block.
 * @Block(
 *   id = "your_block",
 *   admin_label = @Translation("YourBlock")
 * )
 */
class YourBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $nid = 2;
    $entity_type = 'node';
    $view_mode = 'teaser';

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $storage = \Drupal::entityManager()->getStorage($entity_type);
    $node = $storage->load($nid);
    $build = $view_builder->view($node, $view_mode);

    return $build;

  }

  ...

I'm sure with a little effort you can continue this by using blockForm, blockSubmit to set the node id/type/view_mode etc.


Node form redirect based on submit button value I've read and experimented with several ways to redirect a form once submitted. However, I only want to redirect a node form if the operation is t('Save').

If I set $form['#redirect'] = 'blah' in form_alter, it will redirect on all types of form submits. If I add a submit handler and then set $form_state['redirect'], this just gets overridden by drupal's node_form_submit.

What is the correct way to redirect a node submit only if the submit operation was say t('Save')?

NOTE: I found out that the generic form_alter attempt of $form['#redirect'] interferes with the node delete submit handler, as it has to redirect to node/%node/delete. So hence I am looking for a more accurate method.

The answer was to attach my submit handler to the submit button rather than the form, and then the $form_state['redirect'] would work as needed.


How do I get a form field value out of a config entity data blob? I am trying to add a form field in a existing config entity form.
The value of the field is stored in the data blob of the correct config entity but I am not able to get it out of it.

/**
* Implements hook_form_FORM_ID_alter().
*/
function my_module_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
 $someEntity = \Drupal::entityTypeManager()->getStorage('some entity');
 $form['my-field'] = [
  '#type' => 'number',
  '#title' => 'some title',
  '#weight' => 1,
  '#min' => '0',
  '#max' => '50',
  '#default-value' => $someEntity->getValue('my-field'), // Here I would like to get the Value that is stored in the db
 ];
 $form['#validate'][] = 'my_module_field_config_edit_form_validate';
}

@Berdir

I tried your answer but the value still won't be set as default_value

    /**
     * Implements hook_form_FORM_ID_alter().
     */
function comment_limit_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
  $comment = $form_state->getFormObject()->getEntity();
  $form['edit-limit-per-user'] = [
    '#type' => 'number',
    '#title' => 'Comment limit per user',
    '#weight' => 1,
    '#min' => '0',
    '#max' => '50',
    '#default_value' => $comment->getThirdPartySetting('comment_limit', 'edit-limit-per-user', FALSE),
  ];
  $form['#validate'][] = 'comment_limit_field_config_edit_form_validate';
  $form['#entity_builders'][] = 'comment_limit_form_field_edit_form_add_form_builder';
}

/**
 *
 */
function comment_limit_form_field_edit_form_add_form_builder($entity_type, FieldConfig $comment , &$form, FormStateInterface $form_state) {
  $comment->setThirdPartySetting('comment_limit', 'edit-limit-per-user', $form_state->getValue('edit-limit-per-user'));
}

comment.type.comment.third_party.comment_limit:
  type: mapping
  label: 'Comment limit per user'
  mapping:
    edit_limit_per_user:
      type: number
      label: 'Comment limit per user'

Did I miss something?

This works for me:)

The entity is already available with $form_state->getFormObject()->getEntity(). That basically answers your question.

Note that stuffing arbitrary keys into a config entity is not supported, you should use the third party settings API instead. See http://larowlan.github.io/meet-third-party-settings-interface/#/12 for a simple example (but make sure you also check the slides before about config schema). The initial part is not necessary anymore as all config entities support third party settings out of the box now.


How to fined the fields biggest weight in form I have made a content type in /admin/structure/types/add and then, created for this content type  extra fields from /admin/structure/types/manage/CONTENT TYPE_NAME/fields/add-field.
 After i created a module that will alter this content type by hook_form_BASE_FORM_ID_alter() in .MODULE file, and after i reset the default button that has content type that is SAVE button, and added new button:

    $form['register'] = array
  (
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('NAME_OF_A_FUNCTION'),
    '#weight' => '?',
  );

But when I do this the button is rendered first and after comes the content type fields. How to change the button row weight so that the button will always will show at the last plaice. In aver words how to get from all fields that has content type form and search for the biggest weight that has field and put this 'value + 1' in my new submit button '#weight' => '?'.
Dose anyone has solution for that...
Thanks in advance

the solution is in this code:

  $elements = Element::getVisibleChildren($form);
  $weight = 0;
  foreach ($elements as $el) {
    $check = strpos($el, 'field_');
    if ($check !== FALSE && $form[$el]['#weight'] >= $weight) {
      $weight = $form[$el]['#weight'];
    }
  }

  $form['register'] = [
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('NAME_OF_A_FUNCTION'),
    '#weight' => $weight + 1,
  ];


What are differences/advantages of Invite vs. Referral modules? Are there any distinct advantages for choosing either the Invite or Referral modules for the purpose of allowing existing site users to get their friends to check out the site and create an account?

I'm trying to determine which module will be the best solution for us, but they seem like they essentially do the same thing. Am I wrong?

We'll want to be able to award points for successful sign ups, and maybe some other type or rules integration to reward those who get more people to sign up.

http://drupal.org/project/invite
http://drupal.org/project/referral

Invite module is more popular and is a more active project. The last commit was 4 weeks ago, while User Referral git repository has been inactive for more than 1 year. Considering that the last version of User Referral is still in beta, I would check Invite first.

Back in 2007, there was an idea of merging the two into Invite, but apparently did not happen.

You can see some differences between them discussed in the previous link. Some of them are:

Invite sends a coded registration link by e-mail whereas User Referral displays it.
Referral's tracking uses a session variable to store referral information. Invite's tracking code is lost if the user moves away from the registration page.
Invite codes are always unique and can be used only once.
Invite codes have an expiry date.
User Referral display a referral link (such as referral/123) in the user's page.

They also seem to provide integrations with different modules.


How to put up a notification about scheduled maintenance? I'm using Drupal 7.5 and I want to put up a notification about the website going into maintenance mode on x scheduled date and time. What is the best way to do this? Are there any built-in options for posting server maintenance notifications or must I create a custom block for it?

Forgive me for this super basic question, but I did a search and the other questions on this were more advanced.

Note: this site is run on a Commons Profile and developed by someone else.

Drupal Core has in built option to put site on maintenance but out of the box it does not have option to show maintenance message prior to scheduled date. In order to do that you can Scheduled Maintenance module.

  Scheduled maintenance allows users to schedule an upcoming maintenance
  and show site visitors a warning message in advance.


How to translate the book pages content using the Book Translation module? My requirement is that a user can see the complete book pages in the selected language (English, Hindi, Bengali, etc) as per the preference. That's why I installed the Book Translation i18n_book_navigation module.

As I installed the module and enabled the language block but it didn't translate my node's content. It only translate the inbuilt of Drupal taxonomy like View, Edit, Outline, etc into other languages. Do I need to configure some other settings for translating the book pages content or am I missing any module to install or enable?

If I understood your question correctly, you need to enable translations for the "Book page" content type.

Go to /admin/structure/types and click on "Edit" next to the content type you use for storing the book pages.
Under "Publishing options" make sure that "Multilingual support" is set to "Enabled, with translation".
Save the content type.
After you save this, you can go back to the edit page and configure extended language options in "Multilingual settings" tab.


Minutes in date value displayed never the same as value entered I have a weird bug.  On many content types, I have a Date field using the Pop-up calendar widget with the format "February 3 2014 - 2:35".

When that date is displayed, the minutes are never the same as the minutes that I entered when I saved my content. If my date field has the time value 4:15, the time displayed will be 4:12. If I change the minutes again for let's say, 4:52, the time displayed is still 4:12. And when I edit that content, the time I entered is still there, so I know it's saved correctly. If I change the hour, that change is displayed properly but the minutes stay the same.

Also, when I check recent log messages, for a given hour, the minutes displayed are always the same. Like every event that happened between 2PM and 3PM has the time 2h02.

Does anybody know what the problem might be ?

I'm on Drupal 7.34 and using Date 7.x-2.8.

Well, turns out the discrepancy was due to a bad date format ... I was using "m" for the minutes instead of "i".

My bad !


Customize login block's position in page.tpl I'm trying to position my login block in my page.tpl file. Everytime I insert the code

<?php print drupal_render(drupal_get_form('user_login')); ?>

in my page.tpl file. It throws an error. The error it throws is

  Strict warning: Only variables should be passed by reference in include() (line 79 of C:..\sites\all\themes\neptune\templates\page.tpl.php).

How can I fix this issue?

You can do it like this:

if(!user_is_logged_in() ){
    $userLoginForm = drupal_get_form('user_login');
    print drupal_render($userLoginForm);
}

because drupal_render receives argument as reference..


How to create a token to render nodes in content? The goal is to place one ore more polls and/or slideshows anywhere within my blog post.

Step 1 is easy:  With the Token Filter module, I can place tokens anywhere in my content.

Step 2 requires a module that creates a token which takes a nid as an argument and renders the node within my content, e.g. [render-node:1].  The rendered node would have a content type of poll and/or slideshow.

Is this a good way to go, or is there a better way?  If this is the way to go, how would I go about creating a module to do this?

Even though Mołot made a point about your question, I will give you an answer:

Using dynamic tokens with parameters is possible, but some coding is necessary. See pass parameters with tokens for more info.

You can also achieve what you need with some contrib modules, more specifically Field Collection (https://drupal.org/project/field_collection) and References (https://drupal.org/project/references). With these two, you can create a field collection for your content type which includes one field for text and one field for node reference. Field collection module makes it possible to have multiple values, so you could slice up the text and insert the node references in between. To render full nodes with node reference field, go to manage display and set it to Rendered node. You will end up with something like this (administration):


How do I pass arguments from URL into panel page block? I have created a view with a contextual filter set to a taxonomy term. I am attempting to use the view block in a panels (page manager) page and pass the taxonomy term from the URL into the block. I could do this in Drupal 7 but I can't seem to figure it out in D8.

The page URL will be something like /reports/term1. I would like to pass term1 into the block.

For the panel page I have a URL like /reports/! (I also tried % as the place holder). Though I have seen some recommendations to use a context to pass the term, I have not been able to do so.

I am working with Drupal 8.7.1, Panels 8.x-4.4, Page Manager 8.4-4.0.

Any suggestions on how to accomplish this?

I have not used Panels with D8, but...

With D7 Panels I remember there was a way to set/pass a contextual filter value, but one thing I noticed was if I did not set it in Panels and instead set it directly in the View's settings, it also worked.

So all you have to do is edit your View block, under Advanced, for contextual filters add Has taxonomy term ID

In the settings for that, select Provide default value and for type use Taxonomy term ID from URL

Alternatively, you could do


#default_value for select form elements does not work <?php
namespace Drupal\dishes_dropdown\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Component\Utility\UrlHelper;

/**
 * Desarrollo de un formulario en drupal 8
 *
 */
class DishesDropdownForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'dishes_dropdown_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $maxlength = 250;

        $tax_terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('dish_type', $parent=0, $max_depth=NULL, $load_entities=FALSE);
        $taxs = array();
        foreach ($tax_terms as $tax_term) {
            $taxs[$tax_term->tid] = $tax_term->name;
        }

        $form['dish_dropdown'] = array(
            '#type' => 'select',
            '#options' => $taxs,
            '#chosen' => true,
            '#multiple' => false,
            '#maxlength' => $maxlength,
            '#default_value' => $form_state->hasValue('dish_dropdown') ? $form_state->getValue('dish_dropdown') : '' ,

        $form['submit'] = [
            '#type'  => 'submit',
            '#value' => $this->t('Ir al tipo de plato'),
            '#weight' => 50,
        ];
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Display result.
        $id = reset($form_state-> getValues('dish_dropdown'));
        $aliasManager = \Drupal::service('path.alias_manager');
        // The second argument to getAliasByPath is a language code such as "en" or LanguageInterface::DEFAULT_LANGUAGE.
        $alias = $aliasManager->getAliasByPath('/taxonomy/term/' . $id);

        $url = new TrustedRedirectResponse($alias);
        if (isset($url)) {
            $form_state-> setResponse($url);
        }

        return;

    }
}

I do not load the "default_value" in select. I have tried a thousand ways in the "build" but there is no way. I want a blank default value but without forcing it load it. It's like if you read the "default_value".

The #default_value for a select element should be an integer value matching an array key in the #options array.

In your case, lets say

$taxs = [5 => 'blue dish', 9 => 'red dish', 15 => 'green dish'];

Then an option for the value for *#default_value will be one of 5,9 or 15.

In your case the function $form_state->hasValue('dish_dropdown') will return one of "blue dish", "red dish" or "green dish" which is not an array key in your $taxs array.

So what do you do?

Either select one of your dish types as the default OR
Add a default value - None -

For example:

$taxs[0] = '-- None --';
$reverseTaxs = array_flip($taxs);
$form['dish_dropdown'] = array(
        '#type' => 'select',
        '#options' => $taxs,
        '#chosen' => true,
        '#multiple' => false,
        '#maxlength' => $maxlength,
        '#default_value' => $form_state->hasValue('dish_dropdown') ? $reverseTaxs[$form_state->getValue('dish_dropdown')] : 0 ,

    $form['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Ir al tipo de plato'),
        '#weight' => 50,
    ];
    return $form;


Disable Webform Componotent (field) after certain number of submissions I'm working on a registration form that collects student information and the class session they're signing up to. Class sessions are of select type and has four options (sessions). Each sessions has a cap of 38 students. Is there any way to automatically disable options once submission count reaches the cap..? Please note that this is a field level condition, not the entire form level.
Would that be rules? Any pointers... thanks!

I would approach this by using

hook_webform_submission_insert (which is triggered after the submission is inserted into the database)

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook_webform_submission_insert/7

Once in that hook i would use webform_get_submission_count to get the number of submissions , if this was the last allowed submission i would then unpublish the node and create a redirect to a "this class is now closed page".

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21includes%21webform.submissions.inc/function/webform_get_submission_count/7

You could also approach it by using hook_webform_submission_presave or a custom form validator to generate a form error.


Create node link in views header and open in popup Is there any option to include "Node Add" link in Views header, which to be opened in popup?

I think you are looking for hook_menu_local_tasks_alter to create the 'add node' link.  As for the popup... perhaps you are speaking of the administrative overlay?  If that is the case and you have the overlay enabled, the 'add node' task should open in the overlay automatically.

You're probably looking for something like this (taken from this post):

function YOURMODULENAME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  switch($root_path){
    case 'path_of_your_page' : // for example 'page/view/news'
      $item = menu_get_item('node/add');
      if ($item['access']) {
        $data['actions']['output'][] = array(
          '#theme' => 'menu_local_action',
          '#link' => $item,
        );
      }
    break;
  }
}