Fatal error: Cannot use object of type stdClass Error help! When trying to access my image file from my database i get this error:

  Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\drupal-7.25\sites\all\modules\database\database_ex.module on line 99

note: line 99 is $uri = $value['url'];

function database_ex_form_submission($uri) {
  $result = db_query("SELECT myimage FROM example");
  $records = $result->fetchAll();

  $res = $result->execute();

  foreach ($records as $value) {
    $uri = $value['url'];
    $url = file_create_url($uri);
  }
}

What seems to be the problem?

You say :

  note: line 99 is $uri = $value['url'];

So:

$value isn't an array and you can't write $value['url'];.

In fact $value is an object and you have to use this syntax $value->url;


Invalidate a specific cache tag on any saved taxonomy term I would like to clear cache tag of a particular bundle when any taxonomy terms are update/ saved.

I know the default node tag is saved like node:1, node:2, but I'm confused on how to invalidate a particular bundle.

You don't invalidate entity tags, Drupal does this automatically on CRUD operations.

Instead add a cache tag to all nodes of the specific content type:

/**
 * Implements hook_preprocess_node()
 *
 */
function mymodule_preprocess_node(&$variables) {
  if ($variables['node']->getType() === 'my_content_type') {
    $variables['#cache']['tags'][] = 'taxonomy_term_list';
  }
}

The tag taxonomy_term_list gets invalidated on any taxonomy term saved/updated/deleted.


Configuration syncronization not importing everything I have a remote server which I initially setup with a default Drupal 8.7.7 install.  I have since been building the site on my local development server and would now like to transfer the developments to the remote server.

I exported the configuration using drush config:export

I committed the the exported items to git and pushed them to the remote server.  I then ran composer install --no-dev followed by drush updb on the remote server and logged in.
I then went to the configuration synchronization setting and clicked on the import all button.

Everything seems to be working fine however 12 items will not sync.  I have tried importing them via the import -> single item option and tried importing everything via drush cim, however the following items still will not sync and show no errors:

I have repeated the process a number of times to check it wasn't a one off error.

The only similarity I can see is that they are all core.entity_view_display settings apart from the one core.entity_form_display item.  Each one has different differences.

How can I debug why these items won't syncronize?

It appears as though the issue I had relates to this issue: Display mode configurations don't get updated with new fields https://www.drupal.org/project/drupal/issues/2915036

I haven't tried the patch yet, but after saving the individual display modes the fields then get put into the export and sync properly.


Show content that is tagged to both current node and translation source I'm using Drupal 7, i18n, Views3, translated_entityreference, and Entity Translation.

http://lingtransoft.info/apps/paratext

I have a content type: Training Resource, and each Training Resource is a member of another content type that is connected connected by Entity Reference (field_translation_ref) to the content type Application.

If I add Training Resources in English and choose the application Paratext, they get tagged to node 174, the Original content. If I add a Training Resource in French and Choose the application Paratext, it gets connected to node 399985, the nid of the French translation of the Paratext content.

The following View allows me to see all Training Resources tagged to Paratext(174).

I know that the "Content Translation: Source Translation" Relationship is supposed to give me access to the source node, and "Content: Entity translation: translations" has the potential to allow access to the translated node, but I can't figure out how to configure the view to use these values.

What I want:

Now I would like a view that dynamically aggregates and displays the resources tagged to both Paratext(714) [The Translation Source] and Paratext(399985) [the translated node].

On the English Application page:
Show All Training Resources with Entity Reference to the current NID and also those connected to the Entity translation of this page in French.

On the French page:
Show All training Resources with entity reference to the current NID, and also those connected with the source Translation.

If possible, I would prefer to use the interface and/or some existing modules to do this.

Thanks for any help you can give me.
~Matthew

The problem isn't getting both the source and translation nodes into Views results, that's easily done.

The problem is when you apply the Contextual filter. Because the plain Entity reference field Contextual filter isn't translation aware.

But you can make it aware of translations with the help of the Relationship Content translation: Translations.

I don't know if your filter for Media to be in English will cause any trouble, so try to remove it if you see any problems.

Also as far as I can see you don't need the Entity Reference: Application Ref Relationship, you're not using it in any of the Fields and unless you need it for something not visible here you can safely remove it.

List nodes referencing a node, along with nodes referencing its translations

Here are the steps you need to do on your Views to make it Contextually sensitive to not only the referenced entity, but also to that entity's translations:

You already have Training materials views showing some fields.

Don't include any language filters, unless you plan on allowing all the languages which defeats the filter's purpose anyway.
Add the Content translation: Translations Relationship and configure it:
Don't Require it (although I haven't noticed any difference)
Translation option: All
Add the Content: Application Ref Contextual filter and configure it:
Use the Translation Relationship!
When the filter value is NOT in the URL
[whatever you like, All results or Default Content ID from URL]
When the filter value IS in the URL or a default is provided
Specify validation criteria
Content
Application
Node ID

Now if you enter an Application node ID of any language, you will see all Training nodes referencing it AND all Training nodes referencing translations of the Application node.


Is there any implication/consideration for using the boost module on many different websites running on the same VPS? Is there any implication/consideration for using the boost module on many different websites running on the same VPS?

Boost has options for how you structure the files, you can use the ip address or the host name.

In your case you would want to stick to the host name so the files are separate. Other than that I see no reason why it shouldn't work. Though I haven't tried.


Multi website Subdomains Content Types Is there a way to have a d7 multi-site build with the same database, header, footer, sidebar but when a sub-domain is called it will display a different content type.

You will have to set up multi site with the domain access module and also domain content type


How can I seperately display a view's exposed filter and its content in page.tpl? Using <?php dpm($node) ?> I found the exposed filter, $...->view->exposed_widgets, however I'm not sure how to display it. I tried <?php echo $node->view->exposed_widgets; ?> but that returns nothing.

<?php dsm($form); ?> and <?php dpm($form); ?> both give

  Notice: Undefined variable: form in include() . . . page.tpl.php

Are those deprecated? I see them mentioned sometimes but they've never worked for me.

The only place I see the form in <?php dpm($page); ?> is ['content']['system_main']['main']['#markup'], and that can't be separated, obviously.

As per my understanding, why you want to doing via coding. Create views exposed filter as blocks and place in the sidebar and by default the content will load in the right side of the content area. Now you will get filters and content separately...


Need to send "High" and "Critical" priority only in email subject line itself I'm using Support Ticket System module and I need to send ticket "High" and "Critical" priority along with subject line of an email. Can i do the same through coding part as i have tried from mail settings tab of support ticket system, help if anyone have an idea.

Thanks.

A possible solution might be to use hook_mail_alter to modify the subject. As far as I have seen, the Support Ticket System uses drupal_mail() to send notifications, so this hook would be invoked.

Hope it helps,


How to add some javascript in a form using form API? I need to output some javascript codes as well as form fields.

I am using Drupal 6 and form API to build the form. How can I output those javascript codes? Is there a 'javascript' type like textfield/checkboxes ?

I have tried the code below but string 'Array' is printed on the page instead of js code:

$form['target'] = array(
'#prefix' => '
' ,
'#value' => drupal_add_js('alert("hello)','inline'),
'#suffix' => '
'

);

drupal_add_js() is for adding script tags to the page.
It doesn't go in a form element.

 drupal_add_js('alert("Hello!")', 'inline');

would go by itself on a line. This would add that javascript to the page, so when the page loads you would get a pop-up that says "Hello".

and/or to add markup to the page you would do this:

$form['target'] = array(
  '#prefix' => '
',
  '#value' => t('Hello'),
  '#suffix' => '
'
);

Which would add the text "Hello" to the form in the newuser div.


Merge content (e.g. a forum, with nodes, terms and users) from one Drupal site into another How would I merge content (e.g. a forum, with nodes, terms and users) from one Drupal site into another?

Here's my specific use case:

I have a local site which just contains nodes, terms and users for a forum (these were imported with http://drupal.org/project/phpbb2drupal - and before you suggest just using it on my live site, I can't get it to work there, running into the issues described at http://drupal.org/node/1033316 )
I have a live site which has no forum, but has its own nodes, terms and users.
I'd like to merge the local site forum into the live site, adding the forum to the live site.

If it was just for nodes i would say use this:

http://drupal.org/project/node_export

As you need to migrate users and taxonomy terms as well I would use this:

http://drupal.org/project/migrate

Although there will be some php OOP coding to do.


How to set the first option as the selected in the SELECT form via hook_form_alter I have created a Views with an exposed filter and I tried to use hook_form_alter to convert it to a select list. Now, I need to set the default value as the first option whatever output in the select list. I DONT'T need to have '-Any-' as the default value which usually do. I wonder how can I achieve this. The page keep showing the below message when first visit the page not until one of the option is selected and applied.

  An illegal choice has been detected. Please contact the site
  administrator.

Here the code in my template.php. Hope you can help me out. Thanks!

if($form_id == 'views_exposed_form' && $form['#id']=='views-exposed-form-news-page') {

     //Query
     $query = db_select('node', 'n');
     $query->fields('n', array('title'));
     $query->condition('n.type', 'news');
     $query->orderby('n.title', 'ASC');
     $result = $query->execute();

     // Get Select options
     $options = array();

     foreach( $result as $node ){
       $options[$node->title] = $node->title;
     }

    // Alter the form
        $form['title_1'] = array(
         '#type' => 'select',
         //'#default_value' => ??
         '#options' => $options,
         '#title' => t('Filter By'),
    );
 }

You need to add the following code to your implementation of hook_form_alter():

if (empty($form_state['input']['title_1'])) {
  // set the first element as default value
  $form_state['input']['title_1'] = reset($options);
}


Keep node/user tabs in one language I have 3 languages in my site and also user with 'Webmaster' role.

Is it possible to keep all nodes/users tabs (view|edit|translate|devel etc.) in one preferred language for this role?

What you want, as I understand you, is to have a fixed interface language for a certain role.

You can adjust the user interface text language in admin/config/regional/language/configure. Unfortunately there's no method based on role. You can only use the user method, so users see the interface in their prefered langauge. This setting is for all users, not just for a role.

You may code a new language detection method based on role, but I don't know where you have to start (except checking the i18n module code).


how to add checkbox value as json data I have created a custom module for a form. And  I have json data which I want to add as checkbox values.

$request = drupal_http_request($url);
$jsonarray =drupal_json_decode($request->data);
print_r($jsonarray);
 foreach($jsonarray as $info) {
$output1 =$info[0];
$output2 =$info[1];
$output3 =$info[2];
}

 echo $output1;

Set

'#checked' => !empty($default_value)?1:0,

in your form checkbox field.


Solving "MySQL server has gone away", mysql error 2006 I have a site at hostgator, using their "Business account". It's cheap, and comes with a private SSL cert. HOWEVER, their MySQL settings are such that any db connection goes stale fairly quickly, and then the hostgator staff try to convince you to use a VPS or dedicated server at multiple times the expense.

I'm creating and deploying WebAPIs, which can have a 'conversation' which exceeds 60 seconds. When this occurs, the db connection handle is stale, causing any db operations after my timeout to fail.

I'm in the process of implementing the following solution, but am curious if anyone else has solved this issue (where they can not modify their my.ini or my.cnf to give MySQL more resources) in a similar or completely different manner.

last part of a hook_update:

$ret = db_query( "UPDATE {my_table} set field1 = '%s', field2 = %d ... WHERE vid - %d", $node->field1, $node->field2, ... $node->vid );
if (!$ret) {
       // get private storage directory for this node:
       $cexStorage    = _cex_front_getCexStore();
       $nodeFilesPath = DRUPALROOT.'/'.$cexStorage.'/'.$node->storeDir;
       $fname         = $nodeFilesPath.'/recover.node';
       $readyToWrite  = serialize( $node );
       file_put_contents( $fname, $readyToWrite );
       if (file_exists( $fname )) {
         _dbgReport( 'seems to have worked!' );
       }
    }

Then this is called in my hook_form, right after I determine that node->nid is valid:

function _cex_front_recover_node( &$node ) {
  if (!isset($node->storeDir)) {
     _dbgReport( '**************************** _cex_front_recover_node: no storeDir!!!' );
     return;
  }

  // get private storage directory for this node:
  $cexStorage    = _cex_front_getCexStore();
  $nodeFilesPath = DRUPALROOT.'/'.$cexStorage.'/'.$node->storeDir;
  $fname         = $nodeFilesPath.'/recover.node';
  if (file_exists( $fname )) {
    $recovered = file_get_contents( $fname );
    if ($recovered) {
      // no longer needed:
      unlink( $fname );
      $recoveredNode = unserialize( $recovered );
      // restore the key values I need to proceed with this node:
      $node->stage = $recoveredNode->stage;
      $node->rnid  = $recoveredNode->rnid;
      $node->iris  = $recoveredNode->iris;
      cex_front_update( $node );
    }
    else {
      _dbgReport( '********* failed to read "'.$fname.'"' );
    }
  }
}

I'll be pairing the logic down to only store the key fields I need, but this works! Sure beats upgrading my server at 3x the expense. Anyone else doing something like this?

I had a client on a hosting company that refused to increase the value of max_allowed_packet (2MB), regularly leading to the inability to add info-items to the cache. I solved that by adding compression. See Compress cache data before storing it in the database.

In your case, reducing the resource usage may be done with spreading it out over batch operations.


Not all custom theme styles shown in ckeditor window In my theme.info.yml file I set my theme CSS to be also used in the ckeditor window. The problem is that in my CSS I declared some styles to be only applied within #content section, so it doesn't show in ckeditor. I tried these styles to be shown in the editor through classes like

.cke iframe body ul {
  list-style-type: disc;
}

but it doesn't work...

Ok, the mistake was to use classes outside the iframe. This way it works:

body.cke_editable ul {
 list-style-type: disc;
}


Change button markup of searching form I am trying to find a way out about five hours now, i have studied and tried a lot of different things but i couldn't find the right drupal way to do what i want... Please help with the following.

I have the search-block-form which displays a search input text field and a button. The markup for the button now is the following (produced by drupal core):

<button class="form-submit" id="edit-submit--2" name="op" value="Search" type="submit">Search</button>

I want to add extra markup inside the <button></button>, like the following:

<button class="form-submit" id="edit-submit--2" name="op" value="" type="submit"><i class="fi-magnifying-glass"></i></button>

I know of course how to set the value=' ' and i have to say that i've already tried #prefix and #suffix parameters. I don't want to add markup prior to the button element or after that. I should put markup inside, between the element's tags.
I tried also change the hook theme_button($variables) but my problem is that i want to change only the button for search-block-form and not all the button elements.

As some of you have already understand, i use foundation 5 framework and i want to make the search button like this:

* Updated *

You can do this by overriding theme_button() in your theme. Note that the code here is copied from theme_button(), with the return value adjusted accordingly:

function THEMENAME_button($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled']))
  {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  if(isset($element['#search_button']) && $element['#search_button'])
  {
    return '<button' . drupal_attributes($element['#attributes']) . '><i class="fi-magnifying-glass"></i></button>';
  }
  else
  {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

Then you need to add #search_button = TRUE to the button in hook_form_alter()

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'MYFORMID')
  {
    $form['actions']['submit']['#search_button'] = TRUE;
  }
}

Note: This will render the button as requested. No guarantees that it will actually work with the Form API. That needs separate testing.


Ajax callback never called / triggered I'm working on a payment gateway, so I've created a BasePaymentOffsiteForm form where I'm trying to make an ajax callback, but it is not working.
Can you help me to know what is wrong with my code?
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['content'] = [
      '#type' => 'container',
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    $form['content']['mobile_phone'] = [
      '#type'   => 'textfield',
      '#title'  => $this->t('Mobile phone'),
    ];

    $form['content']['validate_client'] = [
      '#type' => 'button',
      '#value' => $this->t('Validate Client'),
      '#ajax' => [
        '#callback' => [get_class($this), 'clientValidateForm'],
        'event' => 'click',
        'wrapper' => 'validate-phone-number',
      ],
    ];

    $form['content']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromUri($form['#cancel_url']),
    ];

    return $form;
  }

  public static function clientValidateForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Pay',
    ];
    return $form['submit'];
  }

It never gets in cientValidateForm method.

You're never making it to your callback because you don't have your #ajax array defined correctly, callback should not be defined as a hashed key. Take a look at the Adding an AJAX event example on d.o.
This should work:
$form['content']['validate_client'] = [
  '#type' => 'button',
  '#value' => $this->t('Validate Client'),
  '#ajax' => [
    // Change the callback key and update your callback value.
    'callback' => [$this, 'clientValidateForm'],
    'event' => 'click',
    'wrapper' => 'validate-phone-number',
  ],
];

Also note that Jaypan is right, you can't define new elements in your validation callback so you'll have to change that too. You may want to set a $form_state value in your validation handler and use that to add your element inside your build method. You may also need to update the wrapper value in your #ajax definition to align with the other changes.


adding twig variable in html.html.twig from module I'm looking to add a twig variable, which is set in a module, and render it in the html.html.twig template file for my theme.

In my module file I use the hook_preprocess_html() function where I render and set the twig variable like so:

function insusite_cta_bar_preprocess_html(&$variables) {
 $output = \Drupal::theme()->render('insusite_cta_bar_actions', array('items' => $itemsOutput, 'panels' => $panelOutput));

 $variables['cta_bar'] = $output;
}

Then in the html.html.twig template file in my themes folder I simply render the new cta_bar variable like so:

<!DOCTYPE html>
<html{{ html_attributes }}>
 <head>
  <head-placeholder token="{{ placeholder_token|raw }}">
 <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">
 </head>
 <body{{ attributes }}>
  {{ page_top }}
  {{ page }}
  {{ page_bottom }}
  {{ cta_bar }}
  <js-bottom-placeholder token="{{ placeholder_token|raw }}">
 </body>
</html>

This doesn't render anything at all.

However, if I add preprocess_html() function to my .theme file then it DOES work, problem is we're using drupal as a multi-site system so I'd have to find a way to add this in to every theme's html, is there a way to do this?

Just tested what I can of your code, and this works from a custom module:

function examplemodule_preprocess_html(&$variables) {

 $variables['cta_bar'] = ['#markup' => '
Test CTA Bar
'];
}

It then can be output in the theme with this template:

/themes/custom/mycustomtheme/templates/layout/html.html.twig

like this:

{{ cta_bar }}

Of course, you need to register your preprocess function by clearing the cache.

Other than that, I think it must be a problem with your theme function insusite_cta_bar_actions.  Can you give us more info on that?


Drupal 7 Single Sign On possibilities with the Domain Access Module The background:
We (currently) have 2000 domain names pointed at a single IP. Drupal inherently has the ability
to use multisite, but for our particular Drupal 7 install we use a module named Domain Access to
delegate sites. The gist is though that Domain Access will not allow cross site logins, but yeah,
we would like our editors to log in once, and have access to all sites.

The question:
Has anyone made any headway with coming up with a single sign on solution with Domain access to date
for Drupal 7? I've been looking closely at two old modules, one no longer maintained (SSO for D6) and
one still maintained (CAS). I'm worried about using CAS I am not sure if it will work the way I intend
it since Domain Access seems to change quite a bit of Drupal(ly) stuff.

We could potentially use facebook, openid, twitter option, but i thing not having able to offer visitors
or customers a unique id across a network of sites is too me a big loss of identity and privacy.

Are there any solutions that are known to date, or information on what to start looking into? Has anyone in
the Drupal community managed to make a solution that I have not been able to find? The only possiblitiy that
I've found was this thread on Domain Access SSO but am uncertain to what version it pertains to (Drupal.
DA, SSO or otherwise). I tried contacting the author multiple times but never received a response. It looks
like the "Solution" was to create a master table set with users and permissions, then share those across the
domains. Unfortunetly (again) SSO on Drupal 7 is not an option.

Any opinions out there on the who what or why would be greatly appreciated, I honestly just need a start point
to get the ball rolling. Thanks everyone

See: Comparison of Single Sign On (SSO) Modules

Bakery supports SSO for sites with the same domain (site1.example.com, site2.example.com). Have not tried CAS as you noted above it is an option. You could also use an oauth server to authenticate across domains.


Moving to PHP 7 require any system change with Drush or in Drupal GUI? I am using Drupal 8.2.3 and this is my question:

After moving a Drupal site from PHP 5.6 to 7.13, is it a best practice to changed something in the Drupal GUI or from Drush? It's a long story why I ask, but it is very important for me to know if any such action is needed.

No, there's no action that needs to be taken through the GUI or drush when you change PHP versions.


How to associate a node with a menu without adding it to the menu Since menus drive the breadcrumbs by default in Drupal, is there a way to associate a node with a menu without actually adding it to the menu?  I am trying to maintain a concise menu that nodes can be associated with on the node edit page, without having every node that I associate with the menu then becoming yet another item in an ever growing menu tree.

I am not exactly sure of what you are trying to accomplish here, but it sounds like you are trying to use menus to alter the breadcrumb behavior

If that's the case, you should try the menu breadcrumb module - http://drupal.org/project/menu_breadcrumb or the custom breadcrumb module - http://drupal.org/project/custom_breadcrumbs

Hope this helps


Is it possible to count sub-items in view in Drupal 7? I want to count nodes in sub-categories (taxonomy terms using) and view result to category field. how to do this in views?

Example:

category with counter http://3.reshleon.z8.ru/catalog/bytovaya-tehnika

items in category, needs to count them http://3.reshleon.z8.ru/catalog/42

In views, there is an one field called global counter. Render it and it will give you the count. If you wish you could also hide it via display setting.


Best practice caching a variable between page loads In Drupal 7...

In the case of a value that is only set through a module's settings page, and then remains unchanged until an administrator changes it (or the module is updated).

The value is checked each page load to perform a specific action. I'd prefer to prevent a DB read on each page load, for obvious reasons.

I can, of course, use variable_set and cache_get, but I was wondering...

A) Performance and behaviour wise, what is the actual difference between the two (both need database tables as far as I can see)?

B) Is there an equivalent to SESSION variable that this would be better in?

C) Would this be better off in a singleton class / global static value instead?

A) I highly recommend to measure your assumptions. Database might not be as bad as you think. The answer also depends on whether you ask for a sites that you control or whether you are writing a public module that has to play well with the whole ecosystem.

The main difference between variable_set and cache_set is how important the value is. Cache is intended for things that can be generated. Another difference is how modules interact with in. There are alternative cache backends, which won't write the value to the default database but typically some type of key-value store.

B) The $_SESSION variable from PHP can certainly be used by a Drupal 7 module. By default, PHP saves the session as a file in the local file system.

You can also use key-value stores such as Redis or APCu.

C) A class sounds much better from the perspective of testability via PHPUnit, but singletons don't play well with testing either.


How to pass a Flag field's value to a Rules Component triggered by the flag? Assume a flag (created using the Flag module) which triggers a rule, using Rules Event "When something is flagged" (with this flag). And assume that this flag has 2 fields defined for it also, i.e.:

"Date from", with machine name field_flag_a_group_date_from.
"Date to", with machine name field_flag_a_group_date_to.

When such rule is triggered, assume it performs a Rules Component, which contains a Rules Action to "Send an eMail".

Question: How to pass the values of those Flag fields to that Rules Component, so that they can be used in the message body of that eMail?

Step 1 - Add parameters to the Rules Component

Make the "Date from" and "Date to" available as extra parameters to the Rules Component. Here is an example of such Rules Component (in Rules Export format, if you have the Rules UI enabled you can import it in your own site).

{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "flag_from_date" : { "label" : "Flag from date", "type" : "date" },
      "flag_to_date" : { "label" : "Flag to date", "type" : "date" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022 (with Date from = [flag-from-date:value] and Date to = [flag-to-date:value])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nFYI: the \u0022From date\u0022 (from the flag) is [flag-from-date:value] and the \u0022To date\u0022 (from the flag) is [flag-to-date:value] ...\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

The above Rules Component uses these 2 parameters (together with some other parameter "Group"):

"Flag from date" (label), with machine name flag_from_date, and data type "Date".
"Flag to date" (label), with machine name flag_to_date, and data type "Date".

Note how both parameters are shown within "USES VARIABLES" (that's where they are 'defined'). But also note how within the message body of the eMail both parameters are used (referenced), with any "_" in the machine name replaced by "-".

Step 2 - Make the Flag fields available in the Rule

Before you can use the "tokens" related to the Flag fields in a Rules Action (as in Step 3 below), the Rule needs to be made aware about those Flag fields. To do so, simply add those 2 Rules Conditions in the rule that is triggered by Rules Event "When something is flagged" (with this flag):

Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is field_flag_a_group_date_from.
Entity has field, whereas the Data selector for the entity is "flagging", and the value of the field to check for is field_flag_a_group_date_to.

Step 3 - Pass the Flag fields values from the Rule to the Rules Component

After you completed Step 1, Rules "knows" that for any Rules Action that performs the Rules Component, it is required that a value is specified for those 2 parameters that the Rules Component needs (expects).

So if you add a Rules Action like "perform the Rules Component" (from Step 1) to your Rule (not Rules Component!), you will be prompted to specify a Data Selector for each of the 2 parameters (labelled "Flag from date" and "Flag to date"). Here is the trick to complete the rule (puzzle?): if you first completed Step 2 (and only then!), you will be able to:

use flagging:field-flag-a-group-date-from as the Data selector for the "Flag from date".
use flagging:field-flag-a-group-date-to as the Data selector for the "Flag to date".

Here is an example of such rule, which passes the values of those Flag fields to the Rules Component that is performed in the Rules Action (in Rules Export format):

{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_from" } },
      { "entity_has_field" : { "entity" : [ "flagging" ], "field" : "field_flag_a_group_date_to" } }
    ],
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : {
          "group" : [ "flagged-group" ],
          "flag_from_date" : [ "flagging:field-flag-a-group-date-from" ],
          "flag_to_date" : [ "flagging:field-flag-a-group-date-to" ]
        }
      }
    ]
  }
}

If you have the Rules UI enabled you can import this rule in your own site (after you adapted the machine names of the flag fields to fit yours).

Note the 2 Rules Conditions that were added in the above rule (as detailed in Step 2). And how those fields are then also used within the Rules Action that performs the Rules Component (from Step 1).


How to create 'Partial' Search? I'm using Drupal commerce and I was wondering if there is a way to do partial search? Current the search engine is only searching the exact word. E.g. Candy or Battery I'm looking to search with only term 'Can' or 'Bat'. Please advise.
Thank you

You'll want to employ some sort of stemming algorithm for that.

The Porter-Stemmer module is a possible choice:

  This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.


Is there a module for Drupal 7 similar to OG Membership Expiration? OG Membership Expiration is for Drupal 6. Is there a similar module for Drupal 7?

What exactly do you want to achieve?

Assuming that you want to unsubscribe an user after certain time:

In Drupal 7, OG integrates really well with Rules module. It can fire many OG related action based on the condition / event you set.

You can use Rules Scheduler to schedule the action to be fired.

Furthermore, the OG Role Reference Field can:

Grant a group role on a specific event
Use rules_scheduler to remove a group role after a certain amount of time


Display a view inside a field collection with eva I'm trying to display a view inside a field collection via EVA. I've created the view which accepts the nid of the containing content type as the context argument and all is good in that the view shows correctly when the nid is passed in, however I think the problem is that a field collection is stored as a separate piece of content, so the nid that is supplied when viewing is not that of the containing content type.

The view returns nothing when inserted into the field collection.

Is there a specific way to get the containing content-type nid into the view via the field collection? I've looked in the tokens section for the argument input in the eva view, but nothing specifically for the containing nid, only the specific field collection nid.

After thinking outside the box a bit, the answer lies in setting the contextual filter to accept the "field collection item" id using the appropriate relationship (not the field collection item entity).


Using Drupal Commerce, how do you render the "add to cart" button? I have created a custom node.tpl.php file for the product_display content type. I have everything worked out except I have no ideal how to isolate the "add to cart" button, actually the "add to cart" form, and render it within the template wherever I need it.

The product reference itself renders as the button. In your product display content type, make sure the product reference has the "Add to Cart form" format, then render it thus:

<?php print render($content['field_product']); ?>


What hook_form_alter code do I need to change an exposed filter from a text field to a select box search? I have a view that has an age to and and from fields, and others also that I want TO and FROM.

These are integer fields, so drop down select doesn't work, better exposed filters is also not an option.

What CSS, or Java script can I put in the Hook_form_alter to make this work?

Website that has the form is www.vuxi.com

If you would like to go for specific implementation using hook alter this would be great option.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
      $addition[$field_name] = array(
        '#attributes' => array(
          'class' => array(
            // you can define you class overhere
          ),
        ),
      ),
    }
  }
}


How to programmatically create a flag? How do you programmatically create a flag in drupal 6? I wish to capture this in code so that I can stage flags between different environments. The current stable release of flag does not support features.

Check out the flag API. There are examples for creatig flags, flagging a node and more. Here the example for the flag-creation:

$flag = flag_flag::factory_by_content_type('node');

// Absolutely required, will break your site if not added properties.
$flag->name = 'my_flag_name';
$flag->title = 'My Title';

// Properties required by the UI.
$flag->roles = array(2); // An array of role IDs. 2 is for "authenticated users".
$flag->types = array('story', 'page'); // An array of node types.
$flag->flag_short = 'Flag this';
$flag->unflag_short = 'Unflag this';

// Optional properties, defaults are defined for these (and more).
// Use a print_r() or dsm() to see all the available flag properties.
$flag->global = TRUE;
$flag->flag_long = '';
$flag->flag_message = '';
$flag->show_on_form = TRUE;
$flag->show_on_node = TRUE;
$flag->show_on_teaser = TRUE;
$flag->link_type = 'toggle'; // For JS link. Other options: 'normal' and 'confirm'.

// Save the flag.
$flag->save();


Multilingual translation for anonymous users I have enabled i18n module in my site. But it didn't work properly for me.

I have created two quizzes in three languages with english language as a source language. I am using language dropdown block for switching to different languages.

The problem is that, the quizzes are translating to corresponding language well for administrator and authenticated users. But the quizzes are not properly translated for anonymous users. It remains in english only.
   Same problem for basic page also.

I have checked permissions but I found there is no issue in permission. Please tell if anybody knows solution for this. Thanks in advance.

I found solution for my problem. The problem is in row weight of url present in detection and selection method in the path admin/config/regional/language/configure.

The row weight for url was -5 and row weight for default method was -6.
Then I changed row weight for url to -7. It works. Now the quizzes are translating properly for anonymous users also.


Make shipping optional ubercart How to provide option for users to select whether to ship a product or not at time of chekout using ubercart in drupal ?

Make a new flat rate shipping quote called 'No shipping' with zero cost. Then in the Delivery method pane at checkout the user can choose between your shipping option and your no shipping option.

You make shipping quotes at /admin/store/settings/quotes specifically the 'Add flat rate quote' link /admin/store/settings/quotes/methods/flatrate/add

Obviously you need both the ubercart shipping quotes module and ubercart fulfilment flat rate module enabled.


Pages are not searchable by Google anymore After migrating my Drupal website to WebHosting, I noticed that my pages aren't searchable by Google. It finds nothing, even though it should clearly find my website. Same thing happens when I want to know the ranking of my website. I haven't used the Pathauto module yet, but I think it should find the domain main page at least.

Do you know where the fault could be?

Check your root folder for a robots.txt file. Using Google Webmaster Tools you can test this; see Block or remove pages using a robots.txt file.


Provide contents of file field at node URL I'm trying to set up my Drupal website to host files (more specifically, PDFs) at clean URL's and have some download statistics about them. For example, I would like "test.pdf" to be available at "/publications/test.pdf". I read about all the file managers such as IMCE, but they do not seem to provide this feature. Therefore I'm now trying to set up a Publication content type with just a single field of type File, use the URL path settings to get the clean URL and use the Download Count module to provide me some download statistics. However, I cannot seem to have Drupal return the PDF in the file field when a user visits the URL of such a node. The closest I get is rendering a link to the file, using the display settings of the file field.

Is this the way to go for what I want to achieve? And if so, how can I provide the contents of a file field at the URL of the node containing that field?

Thanks in advance.

Its not a good idea to provide contents of file field at node URL.

Instead use File Aliases module which will let you use node properties in the resulting file url.

  The File Aliases module allows you to use token customizable aliases
  for your uploaded files, giving you the ability to keep your file
  system organized as per usual while providing clean looking paths
  (i.e., no more '/sites/default/files/').


How to preprocess output of $user_picture in Drupal 7? By default user picture output markup looks like this:

I need change markup of user picture output to something like this:

Remove unnecessary markup. But question is how?

I have read:

The user-profile.tpl.php file won´t be recognized in my Drupal 7 installation

Changing user picture HTML output on user profile

Will be very appriciate for helping me out.

In the core user module you can find user-picture.tpl.php. Copy this file to your active theme, edit it and be sure to clear cache.

If you need to go deeper, put this in your theme's template.php. Original can be found in user.module.

function yourthemename_preprocess_user_picture(&$variables) {
  $variables['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      // @TODO: Ideally this function would only be passed file objects, but
      // since there's a lot of legacy code that JOINs the {users} table to
      // {node} or {comments} and passes the results into this function if we
      // a numeric value in the picture field we'll assume it's a file id
      // and load it for them. Once we've got user_load_multiple() and
      // comment_load_multiple() functions the user module will be able to load
      // the picture files in mass during the object's load process.
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      // If the image does not have a valid Drupal scheme (for eg. HTTP),
      // don't load image styles.
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }
}


How do I display two different views for a single content? I'm quite new to drupal and trying to learn this after working with a very different CMS system the past ten years.  Here is my issue/question:

I have a content type that I'd like to have two distinctly different views. The first view contains a form (that does not use any drupal module).  When a user submits the form, I'd like to show a 'confirmation page' view for that same content type (since it has info that I'd like to show in the confirmation view).  What would be the url to use for the different view?

You will need a module for your form in this content type, there is no other way. (unless you want something complicated within an iFrame).

Either write a custom module yourself, or use the usual Webform module


drupal_set_breadcrumb() function doesn't work on "Add content" pages! I have written a custom block and put it inside the panel of "Add Content" page, but it can not change the breadcrumb. Actually the code in module includes drupal_set_breadcrumb() function, which doesn't work on “Add content” pages. My code is working on the others pages!

I need your help to change only the breadcrumb of each "Add content" page without using the available modules for drupal breadcrumb. Because I have written my code and the customization level is so high which can not be obtained with those modules.

Ok, I just solved it! It's too easy! Using the below function in template.php file:

function mytheme_breadcrumb($variables) {
  $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']) . $sep;
  }
  else {
    return t("Home");
  }
}

and using the arg() values and $variables['breadcrumb'] values in above function can enable you to check every pages path. Such as adding the below piece of code the above function:

  $breadcrumb = $variables['breadcrumb'];

  $is_add_content=false;
  foreach($breadcrumb as $key=>$value){
    if(strpos($value,"node/add"))
      $is_add_content=true;
  }

References:

https://www.drupal.org/node/64067
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_breadcrumb/7


Upload a file to Drupal server from an outside URL I am trying to cache in the server the profile images provided by the Facebook Graph API.
So far what I did unsuccessfully was getting the path of the image then calling:

$file = file_save_upload($big_pic_url, array(), $dest, FILE_EXISTS_RENAME);

This returns NULL every time. I tried several syntax for the destination path, and also for the Pic URL path, nothing seems to work.

I am doing this the right way? Can file_save_upload() take an external link as part of its argument?

Here is a solution I've used recently for a Facebook module. Set the image path to $path variable (ie. http://graph.facebook.com/username/picture). Then do the following to store it via Drupal's managed file system:

$image = file_get_contents($path); // this is a PHP function to get a string representation of the image file

$destination = 'public://path/to/store/this/image/name.jpg'; // a stream wrapper path where you want this image to reside on your file system including the desired filename

$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);

if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
   $file->status = 1;
   $file = file_save($file);
}


Get array of all entities from entity reference field On one of my content types I have a taxonomy term reference field that allows for multiple values. Normally if I wanted the term from a field I'd simply do

$node->field_taxonomy_term->entity;

However this doesn't work if there are multiple entities. Normally I would expect getValue() to do the trick but that just gives an array of the ids with target_id as the key. I sort of have a round about way of getting them with this method

    $entity_storage = \Drupal::entityTypeManager()->getStorage('taxonomy');
    $ids = [];
    foreach ($this->field_taxonomy_term->getValue() as $item) {
        $ids[] = $item['target_id'];
    }
    $entities = $entity_storage->loadMultiple($ids);

But when getting one is as simple as $node->field_name->entity I had a feeling that I'm doing more work than necessary. Is there a simpler way to obtain an array of entities from a field or is what I'm doing the most efficient way to do it?

I can't say for sure on that specific field but usually there's the referencedEntities() method you can call

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.4.x

So something like this perhaps:

$entities = $node->field_taxonomy_term->referencedEntities();


How can I view a list of pages to link to in the Navigation module? I am learning Drupal, and currently creating my first navigation menu. When I click 'Add Link' I can see this view:

This allows me to type a value into the path field to link to, however what I am looking for is a list of current Pages or Content nodes within the site to link to. Surely you cannot be expected to remember the list of current paths that exist within the entire site everytime you want to add something to your navigation menu.

As an example of what I mean, if you create a link in the Wordpress backend, you are shown a dialog which shows a list of current site content to link to as below:

How can I view a list of pages/content to link to in the Navigation module?

Drupal has designed this a bit differently. Instead of creating content and then creating the menu, you can add a menu link when you create or edit content.


Why multilevel dynamic local tasks doesn't work? I want to have tabs, but since they need to be dynamic I am making use of local tasks. In the class extending DeriverBase I have written the following function:

public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();
    foreach ($this->moduleFormatManager->getDefinitions() as $key => $definition) {
      $this->derivatives[$key]['title'] = $definition['title'];
      $this->derivatives[$key]['route_parameters'] = array('module_format' => $key);
      $this->derivatives[$key]['route_name'] = 'module.format_configure_' . $key;
      if($key == 'xyz') {
        $key = 'newkey';
      $this->derivatives[$key]['title'] = 'newkey';
      $this->derivatives[$key]['route_name'] = 'module.newkey';
      $this->derivatives[$key]['parent_id'] = "module.format_configure:xyz";
      }
    }
    foreach ($this->derivatives as &$entry) {
      $entry += $base_plugin_definition;
    }
    return $this->derivatives;
  }

In the above code, a tab for each key is being generated: my problem is in the if condition. In the if condition I am trying to generate a sub tab for a particular type of tab by declaring parent_id. But the code doesn't work for me.

What changes should I introduce in order to make it work? I used this link to learn about local tasks.

My module.links.tasks.yml file looks like this:

module.format_configure:
  title: 'Configuration'
  base_route: module.configure
  tab_root_id: module.configure
  deriver: 'path to deriver'

All the mentioned routes have been declared in *.routing.yml file.

You said your file is called module.links.tasks.yml. The correct filename is module.links.task.yml (note links word is pluralized, but task is not).


Disable login at all I want to disable login at all on my drupal site, even better also hide the form. If i need login i will enable it from a ssh session and after working disable again.

I will prefer to do this with rewrite rules in .htaccess but i cannot figure out the right rule.

Update (as this seems to be a popular question)

I ended up with .htaccess like this:

 # disable well known Drupal user login endpoints
  RewriteCond %{QUERY_STRING} q=user
  RewriteRule ^/?$ http://%{HTTP_HOST}/? [R=307,L]
  RewriteRule ^user$ http://%{HTTP_HOST}/ [R=307,L]
  RewriteRule ^user/register$ http://%{HTTP_HOST}/ [R=307,L]

  # goto user login with that "secret" URL
  RewriteRule ^op9__P87? /user [NC]

Another way is set the access to false to the login form. Whenever you want to re-enable the login, just comment out the hook.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#access'] = FALSE;
  }
}


Twitter feed on Drupal from multiple accounts I want to add several Twitter profiles on my Drupal and create groups of them and show their tweet feeds. At the moment, I found a module which let me add only one Twitter profile. Here is an example:

Group A: User 1, user 2, user 3
Group B: User 4, user 5
Group C: User 6, user 7, user 8, user 9

The create blocks (probably with Views?) and show all the tweets from each group. Another problem, I had with the module I have is that it needs the user to authorize his profile to get his tweets.

Is there any other way to do it without ask from user to authorize and with multiple profiles feature?

The twitter module allows you to get the tweets from various accounts and display them  via views.

So you can have a view for your first 3 users and then another one for the other two and so on...

Now, you will have to provide an authenticated account  via the twitter apps api. But then you'll be able to pull tweets from other non authenticated accounts.


Session is not getting maintain in settings.php drupal 7 I have Created one php file on root of drupal7 and access it using URL.I have one form in that file which has dropdown values and submit button. Now in settings.php i am getting those value in POST. Based on That post value i want to select DB for drupal. But it Throws error because session is not getting maintain.
This is my code in settings.php

session_start();
$_SESSION['data'] = $_POST['year'];
if(!empty($_SESSION['data'])) {
  $databases = array (
    'default' =>
       array (
        'default' =>
          array (
            'database' => 'mydbname'.$_SESSION['data'],
            'username' => 'root',
            'password' => '',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
          ),
      ),
  );
}
else {
  header("Location: welcome.php");
}

You can't start session_start() the second time, since Drupal is already started it.

So either remove it, or wrap it into the condition, e.g.:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Parsing input user variables is not a good idea, so it's better if filter it out, e.g.

$_SESSION['data'] = filter_input(INPUT_POST, 'year', FILTER_SANITIZE_STRING);

or better use db_escape_table().


How to pass variables between preprocess functions I've some problem with themes and preprocess functions.

I see that, if I declare a variable in, for example, MYTHEME_preprocess_region(&$vars), this variable is available ONLY in region.tpl.php (I'm using Omega).
But in preprocess_region and region.tpl there is the $vars['node'] variable (if I'm displaying a node), so in these functions I can't create variable based on $node.

In my example, the $vars['node'] variable is available in preprocess_page and preprocess_node.

The question is: if I want to add on region.tpl.php (or preprocess_region) a variable based on $node how should I do?

The "general" question is: how can I declare a variable in a theme function, in template.php, and let this function available in other functions?

Hm...

First of all you should control order of preprocess functions execution.

preprocess_block executes earlier than preprocess_region, preprocess_region earlier than preprocess_node, and so on...

In first preprocess, you should declare static variable, like here.

$var = &drupal_static('variable_name_that_will_be_placed_in_static_stack');
if (!isset($var)) {
  $var = $value_to_store;
}

So, you can access this var from later executed functions.

$var = &drupal_static('variable_name_that_will_be_placed_in_static_stack');

As for your problem, it's more easy to get node from menu_router:

theme_preprocess_region(&$vars)
  $node = menu_get_object();
  if ($node) {
    // get required value
  }
}


Disabled AJAX paging with embedded views when used in Views template files I am using a View in two different pages: page--front.tpl.php and views-view-grid--inside--page-1.tpl.php which is a custom display of a view.

This is the code that is used in both of these

print views_embed_view("loadcover","block",$nid);

and I also set Use AJAX:Yes in the Views settings. The problem is the View's Ajax paging works in the page--front.tpl.php but it's Ajax paging doesn't work in views-view-grid--inside--page-1.tpl.php, In this page the pager is appeared as a link not ajax. What is the problem?

UPDATE:

I tried

print views_embed_view("loadcover","block",$nid);

in page.tpl.php and it worked with Ajax, Is there any problem with Views template files?

I found Disabled AJAX paging with embedded views when used in page.tpl.php it gave me some clues but still I'm unable to solve the problem.

UPDATE:

This is the complete code, This code is exactly the code that is works in page--front.tpl.php. I moved the print views_embed_view("loadcover","block",$nid); in different places of this code but it didn't work again. I guess the problem might be because of js codes that are not loaded in this page.

<?php
global $base_url;
global $language;
$menu  = new stdClass();
$menu = buildMenuObject($menu);
$bookCounter = 0;
while ($bookCounter < sizeof($view->result)){
    $nid = $view->result[$bookCounter++]->nid;
    if($bookCounter <= 6)
    {
        $top = 222 + (188 * floor($bookCounter/7));
    }
    else
        $top = 252 + (188 * floor($bookCounter/7));
    $node = node_load($nid);
    $wrapper = entity_metadata_wrapper('node',$node);
    $title = $wrapper->title->value();
    $detail = $wrapper->field_detail->value();
    $writer = $wrapper->field_writer->value();
    $edition = $wrapper->field_edition->value();
    $translators = $wrapper->field_translators->value();
    $publisher = $wrapper->field_publisher->value();
    $year = $wrapper->field_year->value();
    $nop = $wrapper->field_nop->value();
    $jelds = $wrapper->field_jeld->value();
    print "
";
        print "";
        print "
";
            print "
";
                print "
";
                    print $title;
                print "
";
                print "
";
                    print $menu->writer." : ". $writer;
                print "
";
                print "
";
                    print $menu->edition." : ". $edition;
                print "
";
                print "
";
                    print $menu->translators." : ". $translators;
                print "
";
                print "
";
                    print $menu->publisher." : ". $publisher;
                print "
";
                print "
";
                    print $detail;
                print "
";
            print "
";
            print "
";
                print "
";
                    print views_embed_view("loadcover","block",$nid);
                print "
";
                print "
";print "
";
            print "
";
        print "
";
    print "
";
}

?>

It looks like you are adding some chunks of code logic to your theme templates?  This is not usually recommended in a drupal instance.  Have you tried adding a context to include your loadcover view block on the view generating your grid, so that you do not need to print embed in the tpl?
https://www.drupal.org/project/context

Enable the module and go to /admin/structure/context/add  Set the name of this context, something like Book Grid Display.  We use a "Layout" tag group for things like this, but you could use "custom" or just about anything you want, it is optional.  Under the Conditions dropdown select Views, and on the list that appears to the right check the box in front of your Inside grid view.
Under Reactions select Block.  The theme regions will appear as well as the different groupings of blocks available on your system.  The last grouping is Views, select your Loadcover view and click the +Add on the theme region you are wanting (I assume Content since you were printing this in the content template).

The page content will have a weight of 0, and the drag-and-drop reorder likes to start at weight -10 so use the Show Row Weights to get it under the view grid if desired.  Or at least that is a quirk I have seen when using this method.

Another note, the views_field_view that was mentioned in a comment would allow you to add your Loadcover view as a field in your book grid view, so that you did not have to inject it with custom code from the theme logic layer.  If you were wanting to invoke LoadCover for each cell in your grid and I missed that part, then yes views_field_view would solve the problem for you instead of this context solution which will get you one instance of Loadcover.


Migrate import with authentication onto external site What configuration is needed in to use the MigratePlus authentication plugin. I need to authenticate the migrate import requests so that I can successfully import files behind a login.

Can you provide a little more detail? What sort of authentication do you need? The migrate_plus module has three authentication plugins - basic, digest, and oauth2. The first two take 'username' and 'password' in their configuration - oauth2, naturally, is quite a bit more complex.


How I can delete all node/field revisions? I have a drupal 7 sites, where it keeps node and field revisions. I keep revisions for the case where by mistake a new faulty version is saved and I want to revert back.

But, now I want to clean and optimize the database so to take less space in hard disk.

What are some methods of deleting all the revisions except the current one, for all nodes/fields of the site?

There's not yet a stable release for Revision deletion but a D7 port is on its way (not sure if its functional at all).

In this thread someone suggested using VBO to isolate revisions and delete them.

If you feel comfortable with the API, make a loop through all your nodes, retrieves the revisions using node_revision_list() and delete them using node_revision_delete().

As a last resort and if you like messing with the DB (like I do) you can delete revisions' rows in field_revision_* and node_revision tables. Try this:

WARNING: not tested at all !

DELETE FROM field_revision_body
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE vid = revision_id
);

DELETE FROM node_revision
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE node.vid = node_revision.vid
);

You can find the complete list of your revisions' tables in the information_schema database:

SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'field_revision%'
AND TABLE_SCHEMA = 'your_database';


Handle file requests I'd like to be able to intercept calls to files (.pdf for instance) in order to run some custom code before the user accesses/downloads the file, and add a cover page accordingly.

From what I understand this can't be done by Drupal alone, and requires some server-side configurations as well. Could anyone guide me towards a solution and/or the hook to intercept file downloads? (hook_file_download seems appropriate on the first glance)

Yes hook_file_download() is the one you want to implement, assuming you're using the private file system. The docs have examples of how to use that hook.

There's no built-in way to do this (at least no way that involves Drupal) for public files, as those are served directly at the web server level without the application ever getting involved.

You'll be able to implement a solution for public files based on modifying the .htaccess file to not pass those files straight through, and implement your own path system similar to the core private files one; the particular functionality will obviously depend on your exact requirements, if you decide to go this route I'd recommend spending some time looking at the core system and file modules to see how the mechanism is implemented.

Unfortunately it's not a few-lines-of-code job so I can't provide an example, it's something you'll have to put together yourself.


Get menu tail arguments of node route I saw in this post that D8 does not support the passing of extra menu arguments. Several posts on DA gives workable solutions, but they don't fit this use case.

The contrib module I am porting depends heavily on using those the extra arguments passed to on the route /node/1/my_thing. Adding my_route causes a page_not_found error.

my_thing is not a tab but a parameter that generates content to merged into the view of the node.

As far as I know I cannot alter the behavior of core's route entity.node.canonical

To answer my own question:

So in my case the route entity.node.canonical is not defined by my own module and although I want to use it in my module with an extra parameter, I don't want to mess with it.

I have chosen to use a query parameter (using ?) instead.

http://example.com/node/{nid}?id={id}

if you need the id you can get it from the request object:

$id = \Drupal::request()->query->get('id')


Display related media entities We are using the Basic Page content type and it has an Entity Reference field (field_document) that points to the Document (Media bundle), which has a field_document_tag (taxonomy term field). The field_document is not a reference to the taxonomy term, but the Media bundle itself. On the Basic Page we add a Related Documents View at the bottom of the page.

Setup

Illustration of relationship

Example

Goal

Based on the current page's Linked Document, fetch it's field_document_tag values and return other Basic Pages that have a Linked Document who's Linked Document->field_document_tags match.

How would we use the field value from the current page's field_document to pull other related Basic Pages with a similar Linked Document->field_document_tag values?

Basic Page Fields

Linked Document (Entity reference - Media - Document bundle, single value, machine name field_document)

Media - Document Bundle fields

Document Tags (taxonomy term - vocabulary = tags, machine name = field_document_tags)
Name (text field)
File

Here are the view settings we tried, but it does not return other related Basic Pages even when we add any field under Contextual Filters and Relationship:

Format

Unformatted list
Show: Content | Teaser

Filter Criteria

Content: Published = Yes
Content: Content type = Basic Page
(field_document_tags: media) Media: Document Tags

Contextual Filters

content: id -> When the filter value is not available ->provide default value-> content id from url & more -> exclude = enabled
Relationships -> field_document: media

Additional relationships added under contextual filters

Taxonomy term referenced from field_document_tag: relationship -> field_document: media
content using field_document: relationship -> field_document: media

Expected results

when i am on page 1, i expect to see none return
when on page 2, I expected to see page 4 is returned since the linked document->field_document_tags are the same

Current results

All pages are returned

The combination of Relationships and Contextual filters to make it work isn't random, it actually follows your requirements just as you've written them, you only need to add them to your Views configuration the way you describe.

How Views types work

You want a list of nodes, that is why you create a Content Views Display. Content Views display information that is stored on nodes. When a node has an Entity reference field, that field stores only the information about what entity that is, usually the entity ID. For example, when referencing files what is stored in the Entity file reference field is the FID. The node (the node's table in the database) doesn't store anything more about that field.

The entity that is being referenced may have fields of its own. These fields are stored with the entity data (in the database they are stored in the related "entity table"). Simply put; nodes have their own tables of data, other entities have their own separate tables of data. The connections between nodes and other entities can be done through small "bridges" that are Entity reference fields that store only the connection between two IDs.

When you create Views of a certain type, you're basically choosing which entity database table to pull information from. To overly simplify for clarity: If you want to list nodes, views set nodes table and you can only show data stored in nodes, if you want to list documents, views set files table and you can only show data stored in files.

How to show referenced data in Views

But what if you want to show more information about the related entities, like in your case? You need to add Relationships towards the related entities. Relationships make other database tables data available into your Views!

Once you add some related entity Relationship to your Views you will see new options appear under Fields and Filters, options related to the referenced entity, options you didn't have before you added the Relationship.

And that is what you need to do to your Content Views. Your content references some Files and you want files data to be available in your content views. If you wanted to list content that shares the same file reference you would then add another Relationship, the "backwards" Relationship pointing towards the content that uses the file field we added the Relationship to, and add a Contextual filter that uses that second "backwards" Relationship.

How to show data that is referenced by referenced data

But in your case, there is one extra layer of connection, and you need to add 2 more Relationships. You're not matching the referenced files, you're matching the taxonomy terms that are referenced from files that are referenced from content:

Page > File > Term < Other Files < Other Pages

Here are the steps for your case:

Create Content Views Block Display listing Page nodes
Add Relationship towards your "Linked Document" field, you can require it since you won't have nodes with empty document field in the results
Add another Relationship Taxonomy term referenced from field_document, it will use the first Relationship automatically, you can require it since that field won't be empty either, so you won't be excluding any nodes you don't need to if you require it

So far we've been going in the direction from nodes to their referenced files, to terms referenced from those files.

Now we have all that information in Views, we can start matching "backwards" to get term siblings and file second cousins.
Add the third Relationship Taxonomy term using field_document_tag and make it use the second Relationship. You can require it
Add the fourth Relationship Content using field_document and make it use the third Relationship, you can require it

This fourth Relationship is pointing to nodes that reference files that refrence terms that are referenced from files that are referenced from nodes listed in this Views.
Now we can add a Contextual ID filter from Content Category, and configure it:
Make it use the fourth Relationship (the only one available)
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Basic Page
Hide View if the argument doesn't validate, or some other options that makes sense to you.
Place the Block on Basic pages, adjust the Node from URL and other Block options.

Remove the current node from the list

The node you're currently viewing will also be listed. To Exclude it add the second Contextual ID filter:
    When the filter value is NOT available
    Provide default value
    Content ID from URL
    More
    Exlude


When I add the shipping line item that was selected to the orders view in commerce it duplicates orders This seems to be related to how many products were in the order, as adding this shipping line item from the order to the view it shows every product that that applies to.

Is there a way to change the settings in views to only show the one listing that shows the shipping option and hide all the duplicates?

I found this module called Views Grouping Row Limit which works


Setting fallback values for a template based on a parent entity via entity reference I have a node content hierarchy of Chain (parent) and Property (child), related by an entity reference (ER) on the Property back to Chain.

Each of these node types has an ER to a Skin (custom entity) - these Skins furthermore contain ERs to Slides (another custom entity) but I don't think that's important right now (Shirley!) This is all held together with Inline Entity Form.

I have a situation that I can't work out after many attempts. There is a multi-value field on the Property create page:

Make a new Skin (use the IEF on this page)
Use the parent values (use the Chain's skin)
Use fallback mechanism (where Property has no value set, use the Chain value)

This means I need to either:

process & inject the Chain's Skin into the Property's Skin template as an additional variable, and perform the either/ors in there based on the multi-value
preprocess the Skin so that the correct values are already present in the template so I can just "go ahead and render" based on the multi-value.

Ideally, I'd like to be able to just use the normal {{ content }} variables in the end template, either way. The first suggestion I tried, but I have got no idea, I've tried lots of things. The second looks like it might work with some sort of hook_entity_view[_alter] or similar, but I have been unable to deduce the correct approach or find a suitable example to copy.

Had to post an answer as I need to put more code.

The desired outcome is I can do this:

{% if property.multivalue.value is fallback %}
  {% if property.somevalue is set %} {# check property for a value #}
    {{ content.field_image }} {# from property's skin entity #}
  {% else %}
    {{ chain.field_image }} {# FALLBACK value, from chain's skin entity #}
  {% end %}
{% end %}

I've got as far as this in code:

function tap_preprocess_skin(&$variables) {
  // on skins where the owner node is a Property
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'property') {

      // set a flag to decide how to handle this skin (content = inherit|fallback|new)
      $variables['skin_source'] = $node->field_property_skin_source[0]->getString();

      // additionally set a parent (chain) skin in the template
      $variables['chain_skin'] = $node->field_ref_chain[0]->entity->field_skin[0]->entity;
    }
  }
}

This gives me a scenario where I have the raw entity in the child skin template. For example, in any given node, I have {{ content }}  and also there is a {{ node }}. Here, I have (for my skin), {{ content }} and {{ skin }} and {{ chain_skin }} (latterly, as per above code). However this means I have to render the fields manually, and some of the contents of the skin is more ERs and I don't really want to have to do some massive coding exercise when there's blatantly a way to make a preprocess take #skin from Chain and make let's say {{ chain_skin_content }}, rather than the raw {{ chain_skin }}.

I'd be perfectly happy at this stage to do the logic in the preprocess but I've had no luck there either. I'm sure there's some sort of entity API function that is the right point to tap into but I've not been able to deduce it.


Would replacing hooks with events be a good practice? Do you think it would be a good practice to replace hooks with events? I mean dispatching an event inside a hook to subscribe afterwards.

For example if you have 20 hooks in your module, is it recommended to dispatch an event for each hook, or just keep using the hooks as usual?

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function my_module_node_insert(EntityInterface $entity) {
  // Dispatch the node insert event so that subscribers can act accordingly.
  \Drupal::service('event_dispatcher')->dispatch(NodeInsertEvent::NODE_INSERT, new NodeInsertEvent($entity));
}

Perhaps. I know other developers are using Hook Event Dispatcher because they want to guard against if the hook system goes away in D9. Thus, saving time in the future if indeed they go away.

Whether they go away its pure speculation at this point.


ubercart zip/postal code reformatting in views using php Is it possible to rewrite in views (possibly with php field) ubercart's customers zip numnber? The original format is "12345". I need to put a empty space after 3rd digit like "123 45". Can anybody help me with php code?
I put

  chunk_split($data->delivery_postal_code, 3, ' ');

inside custom php field inside value field but views output empty field.
Thank you very much

for anybody interested - this is the working code

 return chunk_split($data->uc_orders_delivery_postal_code, 3, ' ');


How to rename Sticky at top of lists? I am using Drupal 8 theme and i am wondering is there any way to change the phrase Sticky at top of lists which appears when creating new posts, to something different like Appear in Search Results or Trending?

In a custom Drupal module do something like:

function sfusd_scheduler_form_alter(&$form, $form_state, $form_id)
{
    // Let's change sticky at top of lists to client preferred verbiage
    $form['sticky']['widget']['value']['#title'] = 'Pinned to top of announcement list';
}


How do I avoid the error "out of memory"? I'm currently working with Drupal 7, and I've the following modules installed, all updated to their respective last version:

Views - 7.x-3.0-beta3
CTools - 7.x-1.0-alpha4
Panels - 7.x-3.0-alpha3
Rules, ACL, Advanced forum, Forum Access, User Points, BUEditor

I keep getting "PHP Fatal Error: Out of memory." My server's limit is at its maximum allowed by my provider (32 MB). Those errors appears mostly when interacting with the modules page, but it's also appearing for any user who tries renewing his password, or editing nodes.

Thus, would you have any advice on how to lower the memory usage?

P.S.: I've noticed most of those errors include views and views plugins .inc files. But it also concerns .inc files from the core modules and system... I could copy some there if you want me to.

There's really not much you can do in this case. Drupal 7 requires fair bit of memory and so do Views, Panels, etc.

If upgrading to a hosting plan where you have at least 128MB is not an option I would at least make sure the following modules are kept disabled:

Update Manager
Database Logging
Field UI
Views UI
Panels In-Place Editor
Any other "UI" module

Do your development locally and use version control & Features to update your production box.


Unable to retrieve node object in a block without access permission to said node I'm trying to do a little statistics on nodes and display it on a block. I utilized menu_get_object('node', 1, $path) to get the node object of those nodes with the properties that I want.

So my problem is, in admin accounts, this works fine and well. however, in a normal user account, menu_get_object('node', 1, $path) returns null for any node that the normal user has no access to. is there any way to circumvent this?

So far I've tried using node_load(), and I also tried putting all the data analysis code inside a hook_cron(). Neither worked.

Using db_query() is not an easy task either, as I'm trying to obtain the node's parent node,and that parent's node parent node. That data is serialized. If it matters, I'm using Open Atrium, and I'm trying to obtain the topmost Space for a particular node.

What you can do is impersonate another user for a while. More details here https://www.drupal.org/node/218104

At the start of the function:

$session_prev_status = drupal_save_session();
drupal_save_session(FALSE);
global $user;
$actual_user = $user;
$impersonated_user = user_load(1); // This will impersonate user 1, an administrator.
$user = $impersonated_user;

Then, at the end of the function:

$user = $actual_user;
drupal_save_session($session_prev_status);


Masking event title if marked as "private" (Views, Pathauto…) I'm creating a calendar in D7 using an Event content type, which will include a Private checkbox. If it's set:

Users with the appropriate permission will see the node title as it was entered.
Everybody else will see "Private event" as the node title.

How would you approach this? (A code-based solution is fine.) Immediate concerns are ensuring "Private title" gets substituted in regular node displays, views -- and also pathauto URLs. Thanks!

Edit -- Alternate strategy:

Leave the node title alone (as "Private event" if the event is private), which will enable desired pathauto functionality without any changes.
Add a "private title" text field. This is where admin users would enter the actual name of the event, for internal reference.
On display, if the current user has admin permissions, alter the node title to display the private title value.

This seems like it would be a much simpler strategy. What do you think?

hook_node_load() should be suitable for changing the title based on the private status and current user.

Changing the path will be the hard bit.

Pathauto can only have 1 configuration per bundle so you'll need to use hook_node_insert() and hook_node_update()
to act on events being added or altered to set the private path alias. path_save() can be used to actually save the new alias, but you will need to code the logic to come up with the alias yourself. This post on drupal.org may help.

Once the additional alias is set you will need to make sure to use the correct alias when building links to the content based on the current users permissions.


One time URL doesn't re-direct the user to change the password In Home » Administration » Configuration » under the email messages section when a user is invited to the site the [user:password] is not generated and the one-time-login URL doesn't re-direct the user to change the password (It just logs him in and he doesn't know the password!)

What can I do to fix this? I have also installed this module

That's what's rpt does .. no ??

  (password fields in registration form will be hidden).

So with this module you won't be able to set a password manually i guess.


Filter to only nodes with an image in an imagefield I'm sure this can't be difficult, but it has me stumped.

In my view, I want to exclude nodes that do not have an image in a specific field. The field allows an unlimited number of images. I don't care about the exact quantity, just that there are more than 0.

How do I create this filter and what do I filter on?

If you filter by one of the image field's subfields (e.g. fid, delta, language, width, height, etc), you may end up with duplicate rows in the results, which is usually not desirable. To avoid that, just filter by the "image_field_name:delta" field instead, setting the Operator to "Is equal to" 0. That should filter out all rows without images, and without creating duplicates.


Entity field value inherited from another entity programmatically? I'd like to setup two content types in a parent -> child relationship.

Node A of content type "parent" has custom field:

(text) Description

Node B of content type "child" has custom fields:

(text) Description dynamically inherited (referenced) from parent node.
(reference) to parent node

When the description of Node A changes, Node B automatically reflects this change.

I'd like to achieve this entirely on the backend, no UI or forms needed.

I will be creating the child nodes programmatically.

Topics I've found have danced around what I'm trying to do but lack the details I need to execute it.
inheriting fields from a base content type

I have experience with Drupal 6 & 7 but am new to Drupal 8's entity apis.

A detailed explanation or example of how to achieve this would be greatly appreciated.

Thanks

One possible solution:

Store the parent node's updated date in the child node.
Upon loading the child node, lookup the parent node's updated date, if it differs, copy the parent's field value to the child.

The parent node will not be updated frequently.

The way I would tackle this is to create a new field type called “parent_value”.Design it in such a way that it doesn’t actually store any data in the database but instead uses the existing object’s entity reference value to look up the value from the parent. This way you don’t have to rely on any sort of Dripal trigger to alter the value in the child, which will ensure that if values are updated programically, they will still match.

There is also the added advantage that creating a custom field will teach you everything you need to know about Drupal 8 plug-ins.


Views displaying only one record on pagination Created a view which displays all user on the website, I have added pagination which displays 10 records on the page.

I am not sure but its displaying only one records but correct pagination link.

Go to your view and Click on Pager settings. and change the items per page


Force Logout for Specific Users Our Drupal 7.5 website is having an issue where users click logout but they are sent to the front page still logged in. I believe it's related to a bakery module, however, the question I am asking here is this: how do I force logout for specific users (not all users) via command line?

I tried:

drush uinf <username>

(To get user ID)

drush sql-query "DELETE FROM sessions WHERE uid = <uid>;"

The end result was a sql deadlock that crashed the site momentarily, and when it came back up, the user was still logged in. Should the sql command have worked? If so, then I may need to troubleshoot other issues.

Update: I disabled the bakery module and the problem went away, so the command was correct, but something about the module was wrong. I don't know why.

I disabled the Bakery module and am now able to clear the flood tables using the command without getting the deadlock.


Drupal duplicate filename throws AJAX error I am using the managed_file in a form to upload a file to Drupal. As you know Drupal saves the name of this file into its database and stores it in the path you give.

Unfortunately, when a user uploads a file which has the filename of a previously existing file, he receives an AJAX error that arises from SQL. Even though Drupal manages to store this file with a different name in the folder, I can't prevent the AJAX error.

Is there a solution for this?

Thanks.

As per Drupal structure you need to add option "FILE_EXISTS_RENAME" during save file for example :
 $file_temp = file_save_data($attachment->data, 'public:///' , FILE_EXISTS_RENAME);


How do i get the all the regions available in the current theme programatically? I want the list of the names of all regions available in the current theme in drupal 8. How to do this ?  And is it possible to get the list of the blocks placed on that region ?

Active ADMIN theme & active SYSTEM theme might be different.(By default active admin theme is seven & active system theme is bartik)
Get the current theme used by the below code(if you are in admin section it will return seven, else bartik)

$theme = \Drupal::theme()->getActiveTheme()->getName();

As we need the system theme, below code will do the job

$theme = \Drupal::config('system.theme')->get('default');

And pass the theme name to get all the regions

$system_region = system_region_list($theme, $show = REGIONS_ALL);

This will give you all the regions in array format

$region_list =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

Second part of the question

Get the blocks in particular region . Below is the code snippet which can get the blocks placed in pre-content region:

  $blocks = \Drupal::entityManager()
      ->getStorage('block')
      ->loadByProperties(array('theme' =>  \Drupal::config('system.theme')->get('default'),'region'=>'pre_content'));


Pass data to hook_entity_insert How can I pass data to hook_entity_insert() given that the arguments it takes are fixed?

I'm writing to the database during entity save, and need to be able to pass some data in this hook.

Since you're not initiating the hook, you'll have to find another way. Maybe call a hook in the hook you're implementing?

If you would've been initiating the hook, you could've just passed on more parameters and used func_get_args to get the parameters, ie:

function sum ($a, $b) {
  $sum = 0;
  foreach (func_get_args() as $arg) {
    $sum += $arg;
  }
}

and call it with

sum(1, 2, 3, 4)


Views Row style Node heading between different dates I need a view that display full nodes. So I have set my row style to Node. SO I have.

Node 1
Node 2
Node 3

What I want is

11/05/2010

Node 1

10/05/2010

Node 2
Node 3

I want to place a heading between each group of nodes on a certain date. Can this be done?

I think you need fields to group by date. You can use Views node field to have a field that shows as a node (with a choice of build mode). I think that should work.


Route Parameter Validation Problem I have limited experience with D8 and custom routes.

Current mobile video system for client takes a scheme-less url for the video like so

https://example.com/mobile-video/some-video-desktop.azureedge.net

The routing has worked fine until we had a vendor change for video hosting and the new URLs include slashes and query strings which may or may not be the issue.

mobilevideo.routing.yml  looks like

mobilevideo.content:
  path: '/mobile-video/{vguid}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.\/?=]+'

Prior to today the validation was just '^[-a-zA-Z0-9.]+'

So testing the new URLs I am getting 404s.  But if the parameter passed to the mobilevideo.routing.yml fails validation a 404 is the correct response so I assume the issue is validation.   https://www.drupal.org/docs/8/api/routing-system/parameters-values-validation-in-routes

So I changed the validation from vguid: '^[-a-zA-Z0-9.]+' to  vguid: '^[-a-zA-Z0-9.\/?=]+' that had no effect and I also tried '.+' and also the original without ? and =   with no change.

I should note that the original URLs with no slashes worked continously through all of this and that each change was followed by clearing all caches.

Also tried removing validation entirely and that also failed so I am wondering if my path cannot include slashes in the parameter for reasons beyond validation?

What should my next step be in debugging this?

A full example URL will look like

https://example.com/mobile-video/someidhere.cloudfront.net/sessions/forty-characters-or-more-of-vguid-here.mp4?invocationId=thirty-more-chars-here

UPDATE
Based on info re optional parameters and the comments on this post I added four more parameters and default values of '' for each updating mobilevideo.routing.yml to

mobilevideo.content:
  path: '/mobile-video/{vguid}/{vguidtwo}/{vguidhtree}/{vguidfour}/{vguidfive}'
  defaults:
    _controller: 'Drupal\mobilevideo\Controller\MobileVideoController::content'
    _title: 'Mobile Video'
    vguid: ''
    vguidtwo: ''
    vguidthree: ''
    vguidfour: ''
    vguidfive: ''
  requirements:
    _permission: 'access content'
    vguid: '^[-a-zA-Z0-9.]+'
    vguidtwo: '^[-a-zA-Z0-9.]+'
    vguidthree: '^[-a-zA-Z0-9.]+'
    vguidfour: '^[-a-zA-Z0-9.]+'
    vguidfive: '^[-a-zA-Z0-9.]+'

Then updated the controller to use public function content($vguid, $vguidtwo, $vguidthree, $vguidfour, $vguidfive) { and assemble the URL based on that array.

Attempting to flush the cache gets The website encountered an unexpected error. Please try again later..  What did I miss?

My solution was to modify the javascript directing traffic to the mobile video page so that it replaced the slashes with triple underscores.

urlNoProtocol = src.replace(/\//i, "___");

The validation in mobilevideo.routing.yml was updated to vguid: '^[-a-zA-Z0-9._?=]+'

Then in MobileVideoController.php the content() function was updated to reverse the replacement.

$url = preg_replace('/___/','/', $vguid);


Use views to display taxonomy children terms from parent I'm hoping there might be a solution to this, but I do not have too much hope after searching a bunch. Currently I have some articles that have terms associated with them and these terms are 2-3 levels deep. For example I might have 10 articles that have the term 'green'.

-Fruit
--Apple
---Green
---Red

I then would like it to have the user be able to view all the video's associated with a specific taxonomy term including all of its children. So if the user goes to www.site.com/fruit/apple, then ALL of the apples will show (Both Red and Green).

Here is the problem. I can only make it work if I assign each article all the parent terms leading up to the child term, but unfortunately, the way that my site is constructed, I can only have it so that my article has the deepest term associated with it.

Does anyone know if it's possible to create a view that will look at all the children of a term and include that in the view? I hope I am explaining it correctly. :)

Ex. User goes to www.site.com/fruit/apple and then they get all the articles that are only tagged with 'green' and only those with 'red'.

Thanks guys!

P.S I have hierarchical select installed, but that does not help me because I cannot have it assign parent terms to my articles. So that won't work.

With in view there is a an option to add a contextual filter Content: Has taxonomy term ID (with depth) There you can select the depth of till which you wan to show the children. So if you select say 5 all the child nodes till a depth of 5 would be shown. I think that should do what you are looking for.


Computed field that displays the full username of the author I am using a computed field and I want to display the field_first_name and field_last_name, which are properties of the user that created that node.

I have been trying things, but it seems like $entity does not have a uid?

I have no idea how to get load the user. These are the variables I have:

  The variables available to your code include: &$entity_field,
  $entity_type, $entity, $field, $instance, $langcode, and $items. To
  set the value of the field, set $entity_field[0]['value']. For
  multi-value computed fields continue with $entity_field[1]['value'].
  Here's a simple example which sets the computed field's value to the
  value of the sum of the number fields (field_a and field_b) in a node
  entity: $entity_field[0]['value'] =
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_a'))) + array_pop(array_pop(field_get_items($entity_type,
  $entity, 'field_b'))); The first pop fetches the last (or only) item
  from the field while the second pop fetches its ['value'] contents
  (assuming it's the only key that's set).

Not 100% clear what your use case is, but it's possible that the realname module will do exactly what you're after https://www.drupal.org/project/realname

under /admin/config/people/realname enter tokens for the fields you want eg [user:field_profile_first_name] [user:field_profile_last_name] then whenever the username gets printed it will display these fields instead


How do I change the front page? In commerce guys demos store I toggled off the main menu in commerce kickstart template and have enabled the main menu block to stay on sidebar first block. I want to get a vertical main menu instead of a horizontal one like the demo store default installation.

Besides, I disabled the slide show content. I want to get the products of a specific collection to be displayed in front page. So I went to Site settings > configuration > System information and changed the default front page URL to collection/my-collection.

But the page doesn't display the main menu on sidebar first. The my-collection colletion is displayed but lose that tiny margins that wrap the products.

I follow this drupal.stackexchange post and tried to comment out the lines

function omega_kickstart_alpha_preprocess_page(&$vars) {
  if ($vars['is_front']) {
    unset($vars['page']['content']['content']['content']['system_main']['default_message']);
  }
}

in both profiles/omega_kickstart/preprocess/preprocess-page.inc and profiles/commerce_kickstart/preprocess/preprocess-page.inc, but didn't work.

Could somebody please help me?

Check the block configuration for the menu, might be set to only on the default front page, changing the default home page changes the url, so your block needs to be configure to display on the url for your "new" front page. At least I think this is what's going on.