Metatags and Commerce - pass taxonomy metatags to commerce product view I have a Commerce Product view that pulls in products based on a taxonomy term in the url (category/taxonomy-term).  This is done using relationships.  Ideally, I would be able to edit metatags for each individual term (which I can) and have those metatags populated on the view page (which I can't figure out).

If I create a metatag default for taxonomy term, it works correctly on /taxonomy/term/%tid, but not category/term-name.  If I create a metatag default for that view, I don't have access to the metatags as token replacement values for the term being used.  There is a [metatags:description] token, but it is empty when using it on the view.

Thanks for any direction/insight/help!

The short answer is that the metatag module will provide metatags entered for terms if your view path matches the core taxonomy path (taxonomy/term/%).

In metatag_views_post_render(), metatags checks if your view display path matches the path from the entity's info before it will proceed.

This gives you a couple of options.

1) You can make sure your view uses the taxonomy/term/% path and use Pathauto to make the aliases for your terms for that vocabulary (or all terms) match the desired 'category/term-name' pattern.

2) You can mimic what the metatag module does for your specific view using a custom module and these hooks:

/**
 * Implements hook_views_post_render().
 */
function MYMODULE_views_post_render(&$view, &$output, &$cache) {
  // Build a shortcut to the current display object.
  $display = $view->display[$view->current_display];

  // Only proceed if this view is a full page, don't process block or other
  // Views display objects.
  if ($view->name == 'MY_VIEW_NAME' && $display->display_plugin == 'page') {
    // Check if this is an entity display page, if so trigger
    // hook_entity_view().
    foreach (entity_get_info() as $entity_type => $entity_info) {
      // Entity paths will include an auto-loader that matches the entity's
      // name, thus the path will be 'some/path/%entity_name'.
      if (isset($entity_info['path']) && $entity_info['path'] == 'taxonomy/term/%taxonomy_term') {
        // Only proceed if this entity type supports meta tags.
        if (metatag_entity_supports_metatags($entity_type)) {
          // There must be at least one argument and the first argument must be
          // numerical.
          if (!empty($view->args) && is_numeric($view->args[0])) {
            // Only the first argument is used.
            $entities = entity_load($entity_type, array($view->args[0]));
            // Only if the entity actually exists.
            if (!empty($entities)) {
              $entity = array_pop($entities);
              MYMODULE_entity_view($entity, $entity_type, 'full', NULL, TRUE);
            }
          }
        }
      }
    }
  }
}

/**
 * Implements hook_entity_view().
 *
 * Provides additional argument to allow the display to be forced, to work
 * around problems elsewhere in the APIs.
 */
function MYMODULE_entity_view($entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
  // Only run this function once per page load.
  static $i_will_say_this_only_once = FALSE;

  // Only proceed if this entity object is the page being viewed.
  if ($entity_type == 'taxonomy_term' && $view_mode == 'full') {
    // Some API calls need to force the data loading.
    if (!$force) {
      // Only run this function once per page load.
      if ($i_will_say_this_only_once) {
        return;
      }
      $i_will_say_this_only_once = TRUE;
    }

    // CTools uses 'page_manager' view mode to indicate the full entity display
    // page rather than 'full', so streamline the internal processes.
    if ($view_mode == 'page_manager') {
      $view_mode = 'full';
    }

    // Generate metatags output.
    if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
      list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
      $instance = "{$entity_type}:{$bundle}";
      // We need to register the term's metatags, so we can later fetch them.
      // @see metatag_page_build().
      metatag_page_set_metatags($instance, $output);
    }
  }
}


Build a form dynamically with the results of a view? I'm working on a view block in which I load several nodes.
I don't know how many nodes will be loaded because it depends on an exposed filter.
I have twig file for the display, I also have a twigExtension php file to call custom functions.

For example, the output of my view looks like this :

Reference
ABCD
BCDE
CDEF

I would like to get a form :

Reference | Quantity (Select dropdown)
ABCD | 0
BCDE | 1
CDEF | 0
<Submit Button>

Once the user clicks on the Submit Button, it creates 3 nodes of a Custom Content Type.

The lead I'm investigating for now is to use a form but I don't know how I could pass the results to this form, build it with these results and get something like :

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['ref_1'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 1'),
        '#default_value' => 'ABCD'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_1'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 1'),
        '#options' => array('00', '01', '02', '03'),
    );

    $form['ref_2'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 2'),
        '#default_value' => 'BCDE'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_2'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 2'),
        '#options' => array('00', '01', '02', '03'),
    );

    $form['ref_3'] = array(
        '#type' => 'textfield',
        '#title' => t('Reference 3'),
        '#default_value' => 'CDEF'
        '#attributes' => array('readonly' => 'readonly')
    );
    $form['quantity_3'] = array(
        '#type' => 'select',
        '#title' => t('Quantity 3'),
        '#options' => array('00', '01', '02', '03'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

    return $form;
}

Or maybe should I look at the exposed filter function, maybe is there a way to modify the way it works to call my own function before display ?

How would you do it ?

Thanks.

Build the custom form from inside the view and attach it to the view before rendering:

mymodule.module

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render($view) {
  if ($view->id() == 'myview') {
    // get field values from the view result
    $values = [];
    foreach ($view->result as $row_id => $row) {
      foreach ($view->field as $field_id => $field ) {
        $values[$row_id][$field_id] = $field->getValue($row);
      }
    }
    // build form with the view result
    $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $values);
    // attach the form to the view
    $view->attachment_after = $form;
  }
}

Use the view result for building the form:

/src/Form/MyForm.php

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, array $values = NULL) {
    // build form with $values
  }


How do you use 'drush site-install' to install a multisite with separate databases using a single command? I regularly use drush site-install to install single Drupal 8 sites from the command line. It works great.

I'm now working on building a Drupal 8 multisite. It'll have separate databases per site.

Can drush si be used to install a multisite from the command line? Does it use Drupal8's sites.php?

I saw Need Steps to Install multisite configuration using only drush. i.e multi-site install having different database, but I'm not clear on what's actually done there.

I figured it should be able to, but I can't find any HowTo docs for multisite.

In the link you provided, @greg_1_anderson mentioned using --sites-subdir. This option is used to create a site folder under <DRUPAL_ROOT>/sites/.

For example, if you run drush si --sites-subdir=example1.com, it will create a example1.com folder under <DRUPAL_ROOT>/sites/, settings.php will also be generated in this folder. It contains the database configuration.

Since it is a multi site structure, you may not want to share the same database. You have to specify the database information with --db-url.

For example:

DB: MySQL
root username: username
root password: password
host: localhost
table name: example

You can specify above information with --db-url=mysql://username:password@localhost/example.

A more complex example involving setting more sites for a multi-site configuration could be the following.

drush si --sites-subdir=example1.com --url=mysql://username:password@localhost/example1
drush si --sites-subdir=example2.com --url=mysql://username:password@localhost/example2

Moreover, if you want to have different database credentials for different sites, you can dynamically create the separate username and password at the same time.

drush si --sites-subdir=example1.com --url=mysql://user1:newpassword1@localhost/example1 --db-su=username --db-su-pw=password
drush si --sites-subdir=example2.com --url=mysql://user2@newpassword2@localhost/example2 --db-su=username --db-su-pw=password


How to extend Views Plugin ViewsSelection.php to have $form_state I need to add in the current $form_state into the ViewsSelection. I have copied the file /core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php to /modules/custom/fsed_entry/fsed_project_entity_reference_options/src/Plugin/EntityReferenceSelection/ProjectsSelection.php where I have the file overriding views' implementation. However, I can't seem to figure out how to get $form_state into my variables so that I can use a value from another form element. I have been trying to experiment with FormCache but I have not been successful. Any ideas on best approach here?

For background, I need the $form_state because the field that is being rendered (and this plugin is used on) here was ajaxed in and I want to pass in a value that I can add onto the handler_settings -> view -> arguments that this plugin uses.

There is no form state, at least not with autocomplete. And since the same code is designed to work with autocomplete and other widgets, it can't rely on form state anywhere.

If you have autocomplete you can possibly pass in the settings in the entity_autocomplete form element which should be passed to your plugin. Not sure about other widgets, you might need your own widget to be able to do that.


Are deleted entities automatically excluded from entity queries? I'm trying to figure out if deleted entities are automatically excluded from entity queries. IE, if I did:

$num = \Drupal::entityQuery('my_entity')->count()->execute();

Would the number of entities found go down if I deleted one through the ui? How could I include/exclude deleted entities in this query?

Deleted entities are not excluded because they are gone. They can't be excluded nor included as they do no longer exist in the database.

So they can also not be counted anymore.

This might change during 8.x, as there is work going on for archiving/putting them into trash instead of actually deleting. The details of that and how that affects entity queries are still being discussed.


Some of the user profile fields on registration page not showing in user edit page I have customized user profile edit page as page-user-edit.tpl.php in drupal 6 and created custom fields in user profiles like COMPANY SIZE with radio buttons, NO OF EMPLOYEES  etc.

It is configured to display these field during registration based on role. It works well. My problem is these fields are not being displayed on user edit page (user/*/edit). Is there any way i can display the fields on user edit page to update values.

Here is my code on page-user-edit.tpl.php

<?php if(arg(0) == 'user' && arg(3) == 'profile' && arg(1) != '0' && trim($user->roles[3]) == 'Corporate Profile'  ){ ?>

<?php print $help; ?> <?php print_r($content); ?>

<?php } ?>

I think the custom fields comes under a new tab. The tab name would be the value you given in the category field . please check


Update order status with administrator comment I need a way to be able to allow an admin user post an order comment when they update the order status that the owner of the order would then get posted on their order. This would both be viewable from the owner of the order, when the owner of the order was logged in under their order history view of that particular order, but would at the same time, get an email with these update comments. Ubercart 2 did this quite well. I imagine Drupal Commerce is capable, but how?

In Commerce this is not provided as a part of core.
It is provided by the Commerce Message module.
In addition to that, the Commerce Backoffice module provides an improved view that allows you to view a summary of an order (and send a message) directly from the order view.

Both are included in Commerce Kickstart, in case you want a quick demo.


Add CSS class to fieldset div element without extending the template I only want to add a class to the  inside the fieldset from fieldset.html.twig. It's a bit overkill to extend the template for just to add a class.

How can I achieve this with a preprocess function?

function mytheme_preprocess_fieldset(&$variables) {
// $variables['children']['attributes']['class'][] = 'mb-4';
}

Under a fieldsets 'Advanced' settings tab, you can add custom attributes to the fieldset.


When does caching kick in? I'm trying to limit certain views on certain pages, like preventing certain articles from appearing on /node, and I'm using hook_views_query_alter() with \Drupal::service('path.current')->getPath() to figure out when to do that.

Is this going to work, or will view cache kick in before this hook can be used? How can I write my own rules into the view so that it will only cache after I've been able to add in my excludes?

It might be a better idea to set a contextual filter on the path. You can still do some tweaking in hook_views_query_alter(), if needed (you can do a lot of things with contextual filters in the ui), but at least views knows by doing that which cache contexts it has to set.


How to use URL parameter and page callbacks for tab menus correctly? I'm using Drupal 6 and I'm trying to display two tab (menus) on a page that has the URL /vehicle_info.
Both pages that the tabs link to should take a node's nid as parameter.
My current code looks as follows:

  $items['vehicle_info/%/basic'] = array(
    'title' => t('Basic & Bookings'),
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('administer fleet'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 10
   );
  $items['vehicle_info/%/history'] = array(
    'title' => t('Service history'),
    'page callback' => 'vehicle_service_history',
    'page arguments' => array(1),
    'access arguments' => array('administer fleet'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 20
   );

I'm running into 2 issues:

The tab "Service history" does not open the page "vehicle_service_history" (which is actually a view with the URL vehicle_service_history). It opens a page with the URL
"vehicle_info/123/history", which does not exist (123 stands for the current nid).
The default tab "Basic & Bookings" does not link to the URL "vehicle_info/123" but only to "vehicle_info".

What am I missing?

A couple of things seem to be missing here. The main confusion seems to be around page callback which should be a function not a URL. The URL is the key to your $items array.

Your first menu item has no 'page callback'. This would be inherited from the parent item (keyed as $items['vehicle_info/%'] and a type of MENU_NORMAL_ITEM) if you had one, but you don't.
Your second item menu seems to be confusing URL with callback as well. If you want it handled by a view then your page display on your view should handle the URL path vehicle_info/%/history, i.e. it will have a contextual filter. Does your view work like this?


Master list of contrib modules? Does there exist an updated master list of contrib modules in some easily parsed format (csv, json, xml ... whatever) that I can use for quick reference to see active full projects (not sandbox)?

I'm particularly interested in a list of project names and their machine names. I'm working on a custom module that may turn into a contrib module and I'd like to make sure my project name and machine name aren't already in use.

I know I can search here:

https://www.drupal.org/project/project_module

But it'd save time if there was a list I could quickly reference. A quick Google search yielded no usable results in the first few pages.

It will be a pretty big list, you could get all packages known by composer which should contain pretty much everything

composer show drupal/* --all


how to store images into file_managed table from android to drupal I have tried calling Drupal file service from android and it is storing images in application/octet format and not in image/jpeg format in file_managed table.

$data['file'] ='encodedimage';
$fid = file_save_data($data);

So I thought I will call file_save_data($data) to store images where I pass the image as encoded string. But it is still storing in application/octet format and not in image/jpeg.

Can somebody help me to store as image/jpeg format into file_managed table?

The Services module provide an easy to use web services enpoint to create file which do all the heavy PHP work for you.

In file_save_data(), the mime type of the file is derived automatically, likely from its filename. You can set the filename of the saved file by using the $destination argument.


Look up nodes that reference a given node I'm using the references module (not grounded to it, but it seems to work well enough) however I don't know how in a custom PHP block/etc I would be able to do a query that can look up all the nodes of a given type that reference the current node.

What sort of query would accomplish this?

For just looking up by type I've used this previously:

<?php
    foreach(node_load_multiple(array(), array('type' => 'homepage_image')) as $node){
    //code
    }
 ?>

Well, you know, this is one of the problems that gave birth to relation. Nonetheless, an EntityFieldQuery with a fieldCondition('name_of_the_reference_field', 'nid', $nid) is what you want.


wysiwyg ckeditor inline styling not working I'm using wysiwyg api with ckeditor, but I can't make it to use inline styles like when I use indent from editor, it actually drops the style (which is margin-left) in output. it's not an override, it actually doesn't even appear in the code when I inspect it.

Verify the format used by the body field. If you are using Filtered HTML, filtering is done before rendering it on the page, where all inline styling is removed.

You could either set your format on Full HTML (which doesn't filter the body) or use the WYSIWYG Filter module which allows to enable certain inline styles on the Filtered HTML format.


How to copy a forum thread? I want to move a forum thread with all the posts from one server to another. What is the most convenient way to do so?

You can try using Bundle Copy Module...

  Has export/import support for:

  Node types
  Taxonomy
  User
  Field API fields
  Field groups

  You can find the export/import links for the supported entities on
  following paths:

  Nodes: admin/structure/types
  Taxonomy: admin/structure/taxonomy
  Users: admin/config/people/accounts


Using variable_set with associative array I use checkboxes in a form to capture a users selection as:

$form['mbo_block_config']['livembo_classes_details'] = array(
                '#type' => 'checkboxes',
                '#title' => t('Class Details'),
                '#description' => t('Choose class details to display.'),
                '#options' => $details,
                '#default_value' => variable_get('livembo_classes_details', array('c_id','c_cd_name')),
                '#required' => TRUE,
                );

The available options are stored in $details which is an associative array:

$details = array(
          'c_id' => t('Class ID'),
          'c_cd_name' => t('Class Name'),
          'c_cd_description' => t('Class Description'),
          'c_l_name' => t('Location: Name'),
          'c_l_city' => t('Location: City'),
          'c_l_full' => t('Location: Full Address'),
          'c_l_phone' => t('Location: Contact Number'),
          'c_s_FullName' => t('Staff: Name'),
          'c_start ' => t('Class Start Time'),
          'c_end' => t('Class End Time')
          );

I use variable set variable_set('livembo_classes_details', $edit['livembo_classes_details']); which works fine, however it flattens the array and changes the keys to values as per:

Array ( [0] => c_id [1] => c_l_phone [2] => c_l_name )

How can I retain the key/value format in the array as originally specified? For example:

Array ( [c_id] => t('Class ID') [c_l_phone] => t('Location: Contact Number') [c_l_name] => t('Location: Name') )

The problem is not variable_get()/set(). It stores whatever you pass to it as a serialized array.

However, what you are saving are the keys of your array, because that's what is passed from the browser when submitting the form. This is also what is expected in the #default_value so it needs to be like this.

When accessing the information, all you need to do is get the intersection of your $details and the selected keys like this:

$selected_details = array_intersect_key($details, array_flip(variable_get('livembo_classes_details', array('c_id','c_cd_name')));

I would recommend to add a helper function which returns $details if you haven't already, so you can re-use that definition and a second helper function which contains the above code.


How to allow OG admins to view private groups? The scenario I try to achieve:

Groups that are not public, are hidden for all users that are not member of the group.
Users with the permission "Administer Organic groups permissions (Administer all groups and permissions)" should be able to view it regardless.

The OG setting for "strict node access" is enabled to prevent other users from viewing content that belongs to foreign private groups.

The problem lies with 2.
Even though users with the "Admin OG permissions" permission can access /node/%/edit to modify the group entity, or even view the member list and add users to the group, viewing the group page itself is not possible nor is the group listed in the /groups view.

Is this a configuration issue or rather a bug?

After spending some time in the debugger, I would say this is a flaw in OG.

Users allowed to administer OG permissions should be granted access to view any group.
Solution: patched og_node_access() in og.module:490

patch format:

--- og.module
+++ og.module
@@ -490,6 +490,11 @@ function og_og_default_roles() {
 function og_node_access($node, $op, $account) {
   $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

+  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
+  if ($op == 'view' && user_access('administer group', $account)) {
+    return NODE_ACCESS_ALLOW;
+  }
+
   if ($op == 'create' && og_is_group_content_type('node', $type)) {
     // Save some legwork if the user has the core permission and strict node
     // access is not set.

The interesting bit is just this:

  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
  if ($op == 'view' && user_access('administer group', $account)) {
    return NODE_ACCESS_ALLOW;
  }

The above solved the issue with OG-Admins not being able to view private groups they did not belong to. There was another issue involving views. When for example creating a list of all groups with views, the same problem occurs. In this case, creating a separate view for admins and effectively disabling node access checks for it:

  In the Advanced tab of Views UI under Query settings, select the Disable SQL rewriting checkbox

Various approaches detailed here: https://drupal.org/node/677644


How to Execute a Specific Part of a Function I am building a function in a custom module, and I want to be able to execute only a specific part of that function.

I am starting with the hook_node_api to see if an event occurs, and if that event occurs, I want to execute a only a specific part of that custom function.

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {

    case 'presave'
    if (  $node->type == 'property' ){
        $old = node_load($node->nid);
        if($old->field_realtor_reference[0]['uid'] == NULL && $node->field_realtor_reference[0]['uid'] !== NULL){
               mymodule_tn_complete($node);
        }
      }

      break;
  }
}

function mymodule_tn_complete( $node)
{
  //Do something
  //Do Something Else

}

If I'm reading you right you're asking a basic program flow-control question.  In PHP, like most programming languages, you can use flow control statements like switch and if to only execute certain blocks of code, or move some blocks into separate functions.

Since it's your own function you're calling here it completely up to you how to handle it. As you gain experience you'll learn ways to determine what to separate out into unique functions and what to just use if statements to control.

To use an if statement, you'll probably need to add a parameter to your function to let you determine which pieces to execute.


Attaching existing server files to filefield How do you set an existing file path for a file field, in Drupal 7? The only option I see is to upload the file again.

In Drupal 6, FileField Sources seems to do this.

Does FileField Paths or IMCE along with file field allow assignment of server files?
Is there an API to programmatically manage file fields?

Edit
I just discovered that this can all be done with the media module. I also have mediaelement installed. However it is not completely intuitive, so here are the steps I took:

Import to media library: /admin/content/media/import

Create a mediafile asset field. This allows you to attach from the library.

Display formats (example for audio) are at /admin/config/media/types/manage/audio/display/, instead of content type "manage display" which only provides "large", "small", "preview", etc.

I would try Media and its associated modules. It's an evolution of FileField Sources, and provides most of the same kind of functionality although with Drupal 7 fields.


Custom Module Route run by External Cron Task I created a Drupal 8 module that cURL to a SFTP, grab a xml file and write it on the files folder. This module as a route (with _access: 'TRUE'), pointing to a controller that does the task.

While I'm connected as admin, and go to that route URL, the XML is downloaded as expected. When I do it as an anonymous user, it doesn't work, not throwing any error.
My goal is to have this route run by an external Cron task (every 5 minutes). However, when it runs, it's not recognized as admin, so it doesn't work.

What would be the best practice to have it working with a Cron Task but also secure enough so that not everybody could run it by going to that URL ?

I would make an API endpoint with authentication. Like:
mysite.com/api/crontasks?u=user&p=password

And then authenticate it via controller!


What is the reason behind the current menu structuring I'm not much of a Drupal Ninja; from what I saw at http://drupal.org/node/788972,
Drupal seems to have a menu structure like Joomla, in the sense that it allows menu items to be created under menu categories.
Why are we using this unlike a central menu items section, from which we can link an item to multiple menus, if needed?

This is what I can see in Wordpress. In the latter method, I can see reduced redundancy and a single point to change multiple occurrences of the same link.

I would like to understand the logic/reasoning behind the Drupal menu structuring, not understanding how Drupal compares to Joomla or WordPress.

You can create as many menu items as you want and have them point wherever you want. You can do this in code and in the UI.

Drupal menus have plenty of flexibility, especially with contrib.

More:

You can set up many different menus (and not just one overall hierarchy) because that way you can have more than one menu. You can put them wherever you want on the page. You can have a sidebar menu and a top-strip menu and whatever else.

Internally, the menu system is really a routing system. Drupal uses the same set of code for routing requests as it does for presenting menus in web pages. Each route/item can have its own permissions, so the list of items the user sees is determined by their role, automatically.

In short, to recap: The reasoning behind Drupal menu structuring is that it's flexible.


Productivity tool to help me add multiple fields at once Is there any Drupal productivity tool that will help me create multiple fields at the same time? I'm taking about about the actual creation of the fields under /admin/structure/types/manage/node_type/fields. I have a hundred of fields to create and it seems tedious to keep hitting the save button every time I create one.

Just wondering about the use case for hundreds of fields - this seems a bit bizarre. Maybe consider using Field Collections to group similar fields and combine with use multiple values per field on a field collection.

As for a possible solution (although not recommended since a lot of things could go wrong) - if you have many similar fields you could export some "base" fields using features and copy-paste inside the features' files the relevant fields. Clearing cache or feature-revert would create the relevant fields.


How to access a selected label instead of value I have a select list of states:

AL|Alabama
AK|Alaska
AZ|Arizona
AR|Arkansas

In code to access the selected state value I can run code like this:

...
$entity->get('field_state')->value;
...

I get the values like AL or AK.  How can I get the labels like Alabama or Alaska?

Not sure if there is a better way but I got the value by getting the allowed values first.

$allowed_values = $state->getFieldDefinition('field_state')->getFieldStorageDefinition()->getSetting('allowed_values');
$state_value = $state->get('field_state')->value;
$info['state_name'] = $allowed_values[$state_value];


How can I force Composer to install a dev branch over a stable release? I am experimenting with Bootstrap 3 in Drupal 8 and I want to stay on the dev branch of bootstrap.

In my composer.json, I wrote the following line based on Drupal Packagist:

"drupal/bootstrap": "8.3.*@dev",

However, when I run composer update, it downloads 8.3.0-beta2 (2015-Dec-19) instead of the latest dev release (2016-Feb-20).

Gathering patches for root package.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Gathering patches for root package.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/bootstrap (8.3.0-beta2)
    Downloading: 100%
    Downloading: 100%

To make sure it wasn't some caching issue, I ran:

composer selfupdate
composer clear-cache
composer update

But it did the same thing-- install beta2.

How do I force it to download the dev release instead?

While it will install the latest dev release of the Drupal module/theme to simply do the following:

composer require drupal/bootstrap:3.x-dev

I would argue a best practice when installing a dev version of a module is to make sure you are going to get the commit you want (which might not be the latest), so I would do the following:

composer require drupal/bootstrap:3.x-dev#5670922dea05fffb6506a6cd5d53546b9fae8df9

Or you can manually add it to your require in composer.json (as below) and then on the command line run composer install

"drupal/bootstrap": "3.x-dev#5670922dea05fffb6506a6cd5d53546b9fae8df9",

To get the commit you should go to http://cgit.drupalcode.org/bootstrap/log/ and find the commit you want (the commit hash is the id on the commit's page).
btw: the above hash is not a real commit on the Bootstrap project


how to run cron hook after a week i have created a module to hook Drupal cron system and the function in my module is being executed on every cron run, which is perfect.

I need this hooked cron function to run only once weekly without scheduling the default Drupal cron job .
Any help on this ?
Thanks

Check out the variety of cron modules that set intervals, like Elysia cron.

https://www.drupal.org/project/elysia_cron


how to export nodes and their referencing entities I have a site which has some content types which have custom entities which refer to them.

The exact example we are using is https://drupal.org/project/registration.  We have event nodes which have registrations. I need to export all the nodes and the entities which reference them. The Node Export module works fine for nodes but misses these entities. And of course, besides for actually exporting them, we need to maintain the node/registration relationship.

What is the best way of doing this?

My solution for this was to use the Migrate module. It is very powerful and you can create update classes for custom entities when one doesn't exist from the producer of the contrib module. I would highly recommend it.


Override default drupal_set_message() on node creation I am creating a simple basic module that alters the text of a submit button and should change the default creation message with drupal_set_message().

I've found an example about changing the message, and changed the code a little.

 function ask_admin_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "vragen_node_form") {
     $form['actions']['submit']['#value'] = 'Stel Uw Vraag';
     $form['buttons']['submit']['#submit'][0] = 'ask_admin_node_form_submit';
   }
 }

 function ask_admin_node_form_submit($form, &$form_state) {
   global $user;

   $node = node_form_submit_build_node($form, $form_state);
   $insert = empty($node->nid);
   node_save($node);
   $node_link = l(t('view'), 'node/'. $node->nid);
   $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
   $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

   if ($insert) {
     watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('Uw vraag is met succes ontvangen en zal zo spoedig mogelijk beantwoord worden.', $t_args));
   }
   else {
     watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('U heeft uw vraag met succes gewijzigd.', $t_args));
   }
   if ($node->nid) {
     unset($form_state['rebuild']);
     $form_state['nid'] = $node->nid;
     $form_state['redirect'] = 'node/'. $node->nid;
   }
   else {
     // In the unlikely case something went wrong on save, the node will be
     // rebuilt and node form redisplayed the same way as in preview.
     drupal_set_message(t('Er ging iets mis bij het verzenden van uw vraag.'), 'error');
  }
}

Although the form button is indeed changed to my own text, the message won't change when the node is created.

When I copy and paste the whole tutorial, my node messages won't change, but I also get no error messages.

Does anyone knows what is wrong, or how I can change the message using other code?

Change $form['buttons']['submit']['#submit'][0] to $form['actions']['submit']['#submit'][0] in your HOOK_form_alter().

I don't know why that tutorial has you modifying the $form['buttons'] array. Very few forms will put something as important as the primary Submit button outside of $form['actions'], and certainly not a core form.


Changing text-format for body field I've installed Drupal 8 in a minimal installation; I've enabled CKeditor and created a text-format called "Full". I've also created a role named as "Administrator" and gave it all permissions available whatsoever; After that, I've attached my user "Admin" to that role "Administrator" and associated it with my newly created text-format ("Full"). I than decided I'm good to keep on:

After I did all of this I went to my content type and clicked to edit it's body field... When I went in to the edit screen I didn't see any place to attach the new text format I created to it, so where is the right place to set the field for other text-format rather than the default "plain text"?

You're already using it, default text-only shows up when there is no other choice.

If you add another format: ie: "test", now you will see in the drop down CKEditor and test.

Also, you probably did not select CKeditor as your text editor. Did you enable the CKeditor module?

I highly recommend not using minimal installation. I just tried it and a lot of the modules are disabled, just figuring this stuff out it's quite the headache.

Normal installation is the way to go IMO.


How can I stop ckeditor from adding   in front of pasted word content? When I paste from word using the word clipboard button I get a blank paragraph inserted before the word content.

Can anyone tell me the way to prevent or fix this?

Upgrading to ckeditor 4 solved this issue for me. I am using wysiwyg 7.x-2.2 and CKEditor 4.0.0.769.


Views hook query alter, change the DatabaseCondition Object I am trying to alter views filters with hook_views_query_alter like

function custom_views_query_alter(&$view, &$query) {
     foreach($query->where[1]['conditions'] as $idx => $condition) {
      dpr($condition);
     }
}

And below is the output I get from DPR function

Array
(
    [field] => node.status
    [value] => 1
    [operator] => =
)
Array
(
    [field] => node.type
    [value] => Array
        (
            [0] => pricing
        )

    [operator] => in
)
Array
(
    [field] => DatabaseCondition Object
        (
            [conditions:protected] => Array
                (
                    [#conjunction] => AND
                    [0] => Array
                        (
                            [field] => field_data_field_zip_range.field_zip_range_from
                            [value] => 65000
                            [operator] => <=
                        )

                    [1] => Array
                        (
                            [field] => field_data_field_zip_range.field_zip_range_to
                            [value] => 65000
                            [operator] => >=
                        )

                )

            [arguments:protected] => Array
                (
                )

            [changed:protected] => 1
            [queryPlaceholderIdentifier:protected] =>
        )

    [value] =>
    [operator] =>
)

So the first 2 filters are not a problem, you just edit the field and you set new values. Problem is the DatabaseCondition Object  with this conditions:protected part. I just don't have a clue how to change values there.

There was similar questions here How to change the query value using hook_views_query_alter?  but it was not solved. It only solves problems for first 2 filters and doesn't do anything for DatabaseCondition Object.

The conditions may be altered by getting them by reference:

function custom_views_query_alter(&$view, &$query) {
   $conditions = &$query->conditions();
   foreach($conditions as $idx => $condition) {
     if ($condition['field'] == 'node.type') {
       $conditions[$idx]['value'] = array("Some other type");
     }
   }
}

Don't forget to modify the object/arrays by reference with the & character.


Entity Translation's Language Switcher (Content) is not showing Before using Entity Translation, I used the Language switcher (User interface text) to allow the users to switch between languages on the header.

On the 'Configure entity translation' page, under the heading 'Enable a different language switcher', it states:

  When the Entity translation module is installed, a second language switcher block is made available on the site called Language switcher (Content). Enabling this block rather than the default language switcher block, Language switcher (User interface text), will ensure that the language of the content is updated when the language switcher is used.

However, when I place the 'Language switcher (Content)' block in the header, it does not even show up. Switching back to 'Language switcher (user interface)' shows it again, but then it won't ensure the language of the content is updated using the languages switcher.

if you want to activate the Language switcher for User or for Content you have to go to:

../admin/config/regional/language

Use the second tab "Detection and selection" and activate for "Language switcher user" the first section:

User interface text language detection - Enabled: YES

After that, you will see the language switcher.

For your "Language switcher content" you have to activate the other section:

Content language detection - Enabled: YES


How can I create a friendship that must be approved with the Relation module? I'm trying to learn how to use the Relation module.  The Node One Screencasts are very helpful in showing how to set up a "User A and B are friends" type relation.  However, most SNS sites require friends to approve each other.

How would one go about setting up an approval mechanism?  The rules module?  What, roughly speaking, would such a set up look like?

Rules is just a handy "programmatic tool" (and API) to encapsulate things. Relation is a way to express -- well Relations.

In my opinion, using just relation and either Views or RelationQuery or EntityFieldQuery you can come up with what you need.

You just need more than 1 Relation.

Something like 1 relation of:
UserA <- are_friends -> UserB

to express a global "friends list" of users within your site. You could make another relation a_user <- has_friends -> user(s) which could be 1 users friends list.

Another relation:
UserA <- is_a_friend_request -> UserB (1-way relationship)

The is_a_friend_request relation could have an attached field of 'request_status' which is a "select list" field type for instance with "approved" and "denied" or "ignore" as options.

A view could be made to show to any user of their "friend_requests". Acting on a friend request adds a recipient user to a given user's "are_friends" relationship.

I'm not sure if this is a naive way of looking at your problem ... you could definately use rules in there somewhere ... but its not a necessity.


How can I attach a view for each row of another view? I may not have the correct terminology here but please allow me to explain what I am trying to do.

I have a view that shows pictures that users have uploaded and that require approval.  I am handling approval through the Flag module (administrators flag a node to approve it).

I have created a view that shows all the unflagged nodes containing pictures that are awaiting approval.

Now, on this view, for each picture that a user has uploaded, I would like to show all the other pictures that the author has uploaded (Users are limited to uploading five pictures, so this can't get too crazy.  Each picture is its own node.)

To do this, I tried creating a view display attachment that shows all the pictures uploaded by a user (limited by a Contextual filter of author: uid).  I then attached this to my main view, but the contextual filter's value is not added per row.  I may be misunderstanding how views attachments work; I've never used them before.

Am I configuring this wrong?  Is there a different approach that I should be taking?

In short, this is what I am trying to achieve:

The main view shows each picture (stored as an individual node) that needs to be approved.
Next to each picture that is pending approval, I would like to show all the pictures uploaded by that user (stored as individual nodes) that have already been approved.

1) Viewfield is a good solution.

Views attachment attach to a views display (Page, Block etc) not to each row.

So, first remove the Contextual filter uid.

Then add one more field, the flag of the node. Then you will have User_Name, Node Image, Flag and each row will represent a node.

2) Another option is to use the Views_Merge_Rows. In the Merge Rows settings you have to set the Merge Options for the User Name field as "Use the values of this field as filter" and uncheck the "Exclude this field from display". For the other fields select the "Use the first value of this field".

3) If you don't want to use a contributed module use the "Group results together" on the Format display settings. Group by user name and then Exclude from display the User Name field.


Get file field alt text value using entity_metadata_wrapper I'm trying to get the alt title of a picture using the entity_metadata_wrapper.

My code is as follows:

$file = file_load($image["fid"]);
$file_wrapper = entity_metadata_wrapper('file', $file);

The $image is one of the images i got by using

field_get_items("node", $node, "field_images")

If i try to get the alt text from the wrapper object, the result is null, although the alt text was set while creating the node.

var_dump($file_wrapper->field_file_image_alt_text);

outputs an EntityValueWrapper with type "text" and data "null".

var_dump($file_wrapper->field_file_image_alt_text->value());

returns null.

I don't understand why this is not working, is there any error in my thinking?

The file object does not contain the image metadata (Title, Alt,..). You must load the parent node to which the image is attached.

For example to get the Title of the 3rd image in the field "field_image" you would use:

$obj = entity_metadata_wrapper('node', $nid);
$obj->field_image[3]->title = $data;

Note 1: you do not have to load the node object first - the $nid variable can be the node id (entity_id)

Note 2: You should use the dpm() function to inspect the entity instead of var_dump. If you want to see also values of properties in the inspected entity, you can use a custom function. Google _wrapper_debug function to get it.


Interactive Drush Script I would like to write an interactive Drush script that potentially makes a change to all pages of a website.  Let's say we would would like to change "Foo" to "Baz" on each page.  We want to review each changed page before it is saved.  The code would look something like this:

foreach(website as node) {
  if node->body->value contains "Foo" {
    change "Foo" to "Baz" and display the changed version of body for the user
    Prompt User: Commit change? Yes or No
    if "Yes", save the node
    }
}

It appears Drush is buffering output so that I can not interact with the user in this way.  Is this possible?

Drush has built-in functions to handle I/O.

If you're using Drush <9.x, there's the procedural drush_confirm() that will prompt a user for a response to a given message. If you're using 9.x+, any custom command class extending the DrushCommands class will have access to the $this->io()->confirm method which does the same thing with Symphony's CLI components.

See the latest Drush docs for more info on I/O.


How to bulk update image alt and title? I have a content type with an image field. How do I update all my images to have the node title as the alt and title of the image?
I don't want to edit hundreds of nodes...

Thank you.
Daniel

The basic logic goes like this:

$nodes = entity_load('node', FALSE, array('type' => 'the_type'));

foreach ($nodes as $node) {
  $node->field_image[$node->language][0]['alt'] = $node->title;
  $node->field_image[$node->language][0]['title'] = $node->title;

  node_save($node);
}

You should probably split that up into a batch job if you have a lot of nodes.

I'm also pretty sure you could make a quicker solution using VBO and some custom PHP but I don't have time to flesh that out right now.


Change drupal standard messages like "You have just used your one time login link" I'm having trouble with changing drupal default messages.

Like for example when you register you get an email with a one time login link (I know how to change this email text) and when you click on the link you get the message

  This is a one-time login for username and will expire on ... .

  Click on this button to log in to the site and change your password.

  This login can be used only once.

But how can I change this text? Another example is:

  You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.

How can I change these texts?

Try the String Overrides module. If you have more strings to change.

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the
Locale module
Note that this is not a replacement to Locale as having thousands of
overrides can cause more pain then benefit. Use this only if you need
a few easy text changes.


How do I handle a dynamic domain i.e. www.(dynamic|.*).(com|org|ca|etc ...) So here is the deal, I recently started working on a site, actually three sites that have been split into three drupal installations.  These sites have the same function but different appearance.  So my thought was to merge them with different themes.  Now I have a new issue, two of the three sites are going to allow for others to use their own urls.  So www.hiya.com would point to my www.example.com.

Each of these new domains is in our db with what theme it is supposed to be.  My first impulse is to look up the site, and change theme in hook_theme().  There are some logic differences but worst case scenario I would just use a session variable to deal with those

I am new to drupal and wanted some thoughts, opinions, criticisms, wild accusations, etc...

I've seen this done three different ways. Here they are, from basic to advanced:

Use Drupal's built-in multisite support by setting up different sites in the sites/ folder. This is sort of the "standard" way, and you'll end up needing things like the Features module.
Use Domain Access and all of its modules. This allows you to do all kinds of sharing between multiple sites, and you can generally accomplish a lot with very little coding. Ken Rickard, the owner of that project, will bend over backwards to help you, and you can typically ping him in IRC #drupal-contribute.
A custom module that intercepts the request early in the process (hook_boot, hook_init, and other places in D7) can often give you a chance to initialize the theme layer (and sometimes other subsystems) in a request-specific way. This is how we do our mobile version of our site (in D6), which uses the same nodes and stuff, but has much different template logic.


Facebook Connect for Drupal The readme.txt of the Facebook Connect module is seriously out-dated! It really needs a review concerning the FB updates.

Now, the real problem:
I have installed the module, inserted my appID and all that, but when in /admin/config/people/fbconnect I click on 'appearance' I get this fatal error:

Fatal error: Call to a member function getUser() on a non-object in /customers/denotenbalkers.be/denotenbalkers.be/httpd.www/sites/all/modules/fbconnect/fbconnect.module on line 421

When I click on 'app settings' it shows me the notice: "Ensure that you entered valid api keys." but those keys ARE valid. Maybe I'm missing something from the readme? Ex.:

5. Enter the Connect URL on Connect settings tab (e.g. copy value from admin/settings/fbconnect field “Connect url”).
There is no such thing as a connect settings tab!

6. Add your server to the Server Whitelist on Advanced settings tab on Facebook or disable Session Secret Whitelist Exception.
What am I supposed to add here? Because only the url doesn't work. I suppose an IP-address but I wouldn't know which one.

I've done all the rest, so I'm guessing that that's the problem.

EDIT / SOLUTION:
The problem was that I followed the readme that was on Facebook Connect's project page. The information in there is OUT-DATED and insufficient. The readme that comes with the module itself is the one you should read!

Did you double check that you installed the Facebook PHP library correctly per the README?

2. Upload facebook-php-sdk library (http://github.com/facebook/php-sdk/) into the libraries folder so that it looks like 'sites/all/libraries/facebook-php-sdk/src/facebook.php'.

The error you are getting looks like it is coming from a library function not in memory.

You can confirm whether this is loaded or not on your admin 'status' page. You should also check the drupal logs to see if there is any more descriptive error to share.

If its in the right place but not loading, you might want to check this thread:

http://drupal.org/node/1318296

for advice on how to get it to work with the libraries API.


Drupal commerce price: allow null value I have an e-commerce site with drupal commerce kickstart and I added an additional field called "list price" and setted it as Price field (the same type of the default price).

Now I'm trying to update some of these prices via drupal views and VBO but I can't set them to NULL, I have an error:
"Integrity constraint violation: 1048 Column 'field_list_price_amount' cannot be null"

But if I change that price manually via the standard windows and leaving the field empty, drupal accepts the update, why?!

Via VBO I can update normal prices (increase, decrease and more other things) but I can't reset them to its default values...

This would be because an empty value and NULL are two different things to a database. Deleting the value in the UI is not the same as setting it to be NULL. That field is stored in the database with the setting that I cannot be NULL and so the VBO operation is failing.


handle the submit button Hello guys i am trying to add data to one of my tables... when the submit button is pressed.
I have the following script:

function review_m_admin_settings_form($node){
    $form = array();

    $form['overview'] = array(
        '#markup' => t('This interface allow adminss to manage general content types and vote them up!'),
    );
    $form['select'] = array(
        '#type' => 'select',
        '#title' => 'Choose a content type!',
        '#options' => node_get_types('names'),
    );
    $form['mark'] = array(
        '#type' => 'textfield',
        '#title' => 'Give a mark to the content type(1 to 10)!',
        '#size' => 60,
        '#maxlength' => 2,
    );
    $form['text'] = array(
        '#type' => 'textarea',
        '#title' => 'leave a feedback!',
        '#cols' => 60,
        '#resizable' => FALSE,
        '#rows' => 5,
    );
    $form['created'] = array(
        '#type' => 'textfield',
        '#title' => 'Enter the date!',
        '#size' => 60,
        '#maxlength' => 10,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Send review'),
        '#weight' => 10,
    );
    $form['action'] = $url;
    return $form;
}

this is my form.... i called the function with the _submit at the end .. but it doesn't work!

    function review_m_admin_settings_form_submit($form, &$form_state){
    if(!isset($node->text)){
        $node->text = '';
        }
        if(!isset($node->created)){
            $node->created = '';
        }
        db_query(
            'INSERT INTO {review_m} (rid, nid, uid, mark, text, created)'
            . "VALUES (%d, %d, %d, '%s', '%s')",
            $node->rid,
            $node->nid,
            $node->uid,
            $node->mark,
            $node->text,
            $node->created
        );
}

Help!

You're trying to assign a value to an object property without declaring the object.  Try this:

function review_m_admin_settings_form_submit($form, &$form_state){
    $node = new stdClass();

There's actually not any need to check if $node->text isset either because we know we haven't set it already.

You also need to pull your form values from the $form_state variable.  For example:

$node->text = $form_state['values']['text']


How do customize the HTML output around a specific field using field.tpl I in the middle of creating a content type with multiple fields. All the fields need to have all the extra markup removed, except for a specific 3 and I would like these to actually be wrapped in
 tags.

I've copied the field.tpl file into my theme and renamed to be used just for this specific content type, which is working fine with this code:

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

  <?php endif; ?>

  <?php foreach ($items as $delta => $item): ?>
  <?php print render($item); ?>    <?php endforeach; ?>

My trouble is that I have no idea the syntax I need to target a specific field. So I'm im guessing once I figure out how to target the specific field, I can just use:

  <?php foreach (something here to find the right field): ?>

<?php print render($item); ?></h2    <?php endforeach; ?>

What would that be if my field name was field_sizing_title?

I found the Field Wrappers Module, but it seem like overkill and I really like to learn more about how to work with the field.tpl file

You need identify the field machine name. For example if you have a field called Name and have a machine name field_name the field tpl name should be field--field-name.tpl.php.

See this thread as well as it provides a comprehensive guide on how to override field template using hook_theme and preprocess function.

One of the most handy helper I used is $conf['theme_debug'] = TRUE; in settings.php. It will show a template suggestion in HTML source.


Customise Title Mark Up from template.php On my site, I have several content types. They all use the same node--content_type.tpl.php file. However, the mark up applied to the node title has to change depending on the content type.

How can I modifying the title according to the content type from template.php?

(I don't want to use too many IF statements in my node.tpl.php file as you are supposed to keep those files clean, so I want the code to go in my template.php file).

(This question is for Drupal 7).

I found the solution to this

Create a field called Title
Your users use this new field to
    enter a title
Use Auto Node Title  to automatically title
    the node based on this field.

You can ow hide the original title in your theme and use the new title filed instead. The new title field can be customised like a regular field.


How to pass variable of paragraphs type to another preprocess function I want to override the fontawesomeicons.html.twig (Fontawesome Module). But I only want to do this for "my-very-special-paragraphs-type" and not in general. I think it is a good idea to declare a variable of "my-very-special-paragraphs-type" in a preprocess function and use the variable in the twig-file.

function mytheme_preprocess() {
  $var = my-very-special-paragraphs-type
}

the fontawesomeicons.html.twig:

{% if var == 'my-very-special-paragraphs-type' %}

    {{ icons }}

{% else %}

   {% if layers == '1' %}
      {{ icons }}
   {% else %}
      {{ icons }}
   {% endif %}

{% endif %}

But I do not know how to do this. Can anybody help?

This is the hook of fontawesome module:

This was quite a ride.

First of all: I didn't got this running in the theme. I needed to create a custom module AND move its implementation of the fontawesomeicons hook last.

Next thing was: hook_preprocess_fontawesomeicons doesn't contain a hint of the parent entity the icons are used in. So I used hook_preprocess_field first to pass the paragraph type over to drupal_static() and retrieved it back then in hook_preprocess_fontawesomeicons.

/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {

  if ($hook == 'fontawesomeicons') {

    // Run MYMODULE_preprocess_fontawesomeicons() last.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

/**
 * Implements hook_preprocess_field__FIELD_TYPE().
 */
function MYMODULE_preprocess_field__fontawesome_icon(&$variables) {

  if ($variables['element']['#entity_type'] == 'paragraph') {

    $paragraph = $variables['element']['#object'];

    $ptype = &drupal_static('paragraph_type', TRUE);
    $ptype = $paragraph->getType();
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_fontawesomeicons(&$variables) {

  $ptype = &drupal_static('paragraph_type', FALSE);

  if ($ptype) {
    $variables['paragraph_type'] = $ptype;
  }
}

Inside any variation of fontawesomeicons.html.twig you now can:

{% if paragraph_type == 'my-very-special-paragraphs-type' %}
  {# do your magic here #}
{% endif %}

I never heard of drupal_static() until today. Read more:

How do I pass data between hooks that don't interact?
Share a value between two different hooks


How to order a view by access control on files? I have a view that displays a series of nodes in a blog format.  Each node has a file attached to it.  How do I make the nodes with files that the user has to login to see come last in the list?

I've been looking through the options available in Views and have come up short there.  I was hoping I could create a relationship on the file, but I can't find any properties that relate to access control.

My other thought was that I could do this in a template, but I'm not sure if there is a template that will let me change the order of the rows in the view.  Are those variables passed to the template by reference?

Many thanks.

In views under the Advanced section when you select the Theme: Information link, you can select to override a specific field.

Choose the most appropriate naming convention as this will dictate the scope of your override. Copy the text given by views and copy this into a new file in your theme called the .tpl.php file name you chose.

Once there you can add a conditional statement before outputting your field with user_access to check if your user has the right permissions to view the downloads.

You might have to specify the permission in your own module with hook_permission.


Why is submit handler not called if $state['rebuild'] == true? I have a simple form that shows a form fields and after submitting shows just a download link:

function activit_report_download_file_form($form, &$state, $node) {

// check if form was already submitted
$submitted = false;
if(isset($state['triggering_element'])) {
  $submitted = true;

  if(!valid_email_address($state['values']['email'])) { $submitted = false; }
  if(strlen($state['values']['name'])<2) { $submitted = false; }
  if(strlen($state['values']['surname'])<2) { $submitted = false; }
}

if(!user_is_logged_in() && !$submitted) {

  $form['info'] = array(
      '#type' => 'markup',
      '#markup' => '
'.t('Po vyplnení Vaších údajov si budete môcť stiahnuť PDF report').'

'
  );

  $form['email'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váš email'))
  );

  $form['name'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váše meno'))
  );

  $form['surname'] = array(
      '#type' => 'textfield',
      '#attributes' => array('placeholder' => t('Váše priezvisko'))
  );

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Získať link na stiahnutie reportu'),
      '#attributes' => array('class' => array('button', 'btn-blue')),

  );

} else {

  $form['link'] = array(
      '#type' => 'markup',
      '#markup' => '

Report stiahnete kliknutím na toto tlačítko.

        '.t('Stiahnuť PDF report').''
  );

}

return $form;
}

In validation handler is $state['rebuild'] = true;

function activit_report_download_file_form_validate($form, &$state) {

  $state['rebuild'] = true;

}

In submit handler is:

function activit_report_download_file_form_submit($form, &$state) {

  db_insert('t_report_download')->fields(array(
      'email' => $state['values']['email'],
      'name' => $state['values']['name'],
      'surname' => $state['values']['surname'],
      'anonymous' => 1,
  ))->execute();

  dsm('submitted');
}

Problem is that submit handler is triggered only if $state['rebuild'] = true; in validation handler is commented. If it is not, submit handler will never be triggered.

What's the logic behind this behavior?

When form validation fails submit handler should not be executed because there are errors in the form.

In a similar way, when a form is mark as rebuild in the validation phase submit handlers should not be executed because the form is going to be rebuilt. This means that form is going to change and the user interaction with the form is not finished.

You can check the (complex) workflow of FAPI in this illustration:

(Illustration from https://www.drupal.org/node/165104)


How to store Ajax Return value into variable after clicking the Submit button I have created form with fields of State and City. After selecting the state appropriate city records will be loaded into city field till now working fine but after clicking the submit button I am not able to store city value into variable called $data1. Please guide me how to get it city value

function form_test_form($form,&$form_submit)
{
$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

}

Ajax Function

 function _ajaxfunction($form, $form_state)

    {

$key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record)
{
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
}

    $form['city_element_wrapper']['city']= array(
        '#type' => 'select',
        '#title' => t('District'),
        '#options' => $options_city,
        '#required' => TRUE,);

    return $form['city_element_wrapper'];
    }

Now I am trying to store the value of what I have selected in City into $data1 variable but I am not able to store it, Please guide me how to store

function form_test_custom_form_submit($form, $form_state){
    $data1 = $form_state['values']['city_element_wrapper']['city'];
}

You need to move the $form['city'] form input creation into your form_test_form function otherwise it's considered tampering with the form, so the values will get taken out.

function form_test_form($form,&$form_submit) {
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If there's a "State" value set, then we create the City dropdown
  if (isset($form_state['values']['state1']) && !empty($form_state['values']['state1'])) {
    $form['city_element_wrapper']['city'] = array(
      '#type' => 'select',
      '#title' => t('District'),
      '#options' => $options_city,
      '#required' => TRUE,
    );
  }

  return $form;
}

Now the callback becomes a simple return of the relevant element:

function _ajaxfunction($form, $form_state) {
  return $form['city_element_wrapper'];
}

Finally check the values of $form_state['values'] in your submit handler:

function form_test_custom_form_submit($form, $form_state){
  var_dump($form_state['values']);
  die();
}


User session and https I've got a few pages on my site that need to be accessed via https.
I need to pull some information about the current logged user on those pages.
The problem is, users log using http mode and the session is not kept when switching from http to https.
I've looked into secure login module but it brings some other issues (with facebook connect...)

Is there any way we can tell the cookie to persist ?
Thanks in advance

Add $conf['https'] = TRUE; to settings.php.

from here:
http://drupal.org/node/1037542
and
http://drupal.org/https-information

however, why not just run the whole site securely?


How to add input field in views fields? I have to store some hidden values in each views rows (To store Latitude and Longitude of Gmap Locations). How to add a input hidden field in Views Field. I tried bartik_preprocess_views_view_fields(&$variables) but it is not invoked.

I added the latitude and longitude in views fields and overwritten the global: Custom Text field with the replacement tokens and added "element-hidden" class so that value will be there in views in hidden. Any other Solutions?


Required field not being shown on password reset page We have a terms and conditions checkbox boolean which is required to create an account. It's created in the Manage Fields section under People.  We have set that checkbox to Required, and it works. But when a user goes to reset their password the form cannot be submitted because the field is required but it's hidden from the form. In the manage display for the boolean field it's set to display and shows for the user. Any idea why this field is hidden from users on password reset form but not account creation or their profile page?

Fields setup in the Account profiles only appear on the creation/edit forms for users and not the password reset form.

If you have existing users and just recently added the field, you could set the field for your existing user base with Views Bulk Operations; otherwise they won't be able to edit their accounts/reset passwords until the field has been assigned a value on their user account profiles.

This is also true of content types/nodes, when you add a new field with a default value- the default value will only appear for new nodes and not existing ones; likewise any required fields will prevent edits to the existing content until they are populated.


Hide a block when viewing own profile page - Show when viewing other people's profile? I have a "Feedback" form implemented on a block. This block displays only when viewing the user profile page.

To stop people rating themselves, I would like to hide this block when the logged in user is viewing their own profile page.

This block should only show when viewing other people's profile pages.

I am using Drupal 8.

How can I do this please?

Here is the code I am currently using:

The issue is a person should not see the block when viewing their own profile page. They should see the block only when viewing another person's profile.

/**
 * Hide feedback form to prevent self voting.
 */
 use \Drupal\block\Entity\Block;
 use \Drupal\Core\Session\AccountInterface;

function zup_hide_feedback_form_block_access($block, $account) {

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

    if ($operation == 'view' && $block->getPluginId() == 'block-webform-3') {
        if($account->id() != $uid){
            return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
            ->addCacheableDependency($block);
        }
    }
      // No opinion.
      return \Drupal\Core\Access\AccessResult::neutral();
}

You can use hook_block_access()

/**
 * Implements hook_block_access().
 */
 function mymodule_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if($operation == 'view' && $block->getPluginId() == 'block_id') {
    $uid_from_url = Drupal::requestStack()->getCurrentRequest()->get('user')->id();
    if($account->id() == $uid_from_url) {
      return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
        ->addCacheableDependency($block);
    }
  }
  // No opinion.
  return \Drupal\Core\Access\AccessResult::neutral();
}

See more document function hook_block_access


VBO showing error when using Drupal Commerce I am getting the following error on a white page after using VBO and Drupal Commerce -

  *Call to a member function aggregate() on a non-object in
  .../sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module
  on line 764*

I upgraded to Drupal Commerce 7.x-1.x-dev and am running the latest version VBO and Commerce Stock

Whenever I try to perform any Bulk operation, like deleting a bunch of products or changing the order status, I get the error

I have looked at the issue, which discusses an issue with Commerce Stock and empty fields, but the solution found doesn't apply because all the stock levels have values.

Does anybody have any suggestions?

PS: I am not sure if this is a red herring, but I also am occasionally getting this message on the module admin page:

  *Notice: Undefined index: step in
  views_bulk_operations_form_validate() (line 621 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: step in views_bulk_operations_form_submit()
  (line 664 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: select_all_pages in
  views_bulk_operations_form_submit() (line 711 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).
  Notice: Undefined index: operation in
  views_bulk_operations_form_submit() (line 713 of
  /var/www/html/nidadev/sites/all/modules/contrib/views_bulk_operations/views_bulk_operations.module).*

I flushed out the database, and started with a new fresh version of VBO.


Popular Content with statistics module incorrect So I wrote a custom module for displaying popular nodes, that is based on the buzzworthy module, but with a few tweaks. Buzzworthy has dependencies with the core statistics module.

The results are inaccurate, because when I compare with google analytics, GA yields different results. I know that GA has a latency issue, so it's like comparing apples and oranges, but another reason I know the list that my custom module displays is incorrect, is because it shows a blog post having waaaaaay more page views than it does normally.

Has anybody else had trouble with the accuracy produced by the statistics module? Is there a reason why my counts are incorrect?

There are many reasons the counts from different web counters are off (I had a former boss drive me nuts with that back in 1998 ...):

statistics module increments page counts on every reload
when a page is cached it might not increase the statistics counter, depending on the caching used. GA does increase because it's based on browser page loads
GA doesn't increase when bots are visiting your site (because they don't execute javascript)

I usually rely on GA for my business reports and just use statistics to show counts for my users.

You could also use the Google Analytics module to import GA numbers back into Drupal.


Show content added by current user In user permissions i let users with editor role "Access the content overview page". And this page showing them all added content. I can make a view with this user added content, but i want to achieve this with "Find content" page. How can i achieve that? I want users to show only the content they added.

I don't believe that's possible with the Find Content page. You may have to resort to making a View to accomplish the task. I've created several views for the same purpose, and actually prefer it as I can create my own admin links (edit, delete, view, publish, etc.) customized to what my goal for the page is.


How can I get the user ID from an order? How can I get the user ID from an Ubercart order?

use Drupal\uc_order\Entity\Order;
$order_load = Order::load($order_id); //Load Order
$ownerinfo = $order_load->getOwner(); //Fetch Owner Info
$ownerID = $order_load->getOwnerId(); //Fetch Owner ID
$ownerEmail = $order_load->getEmail(); //Fetch owner email


How can I color my taxonomy term How can I add color to my taxonomy terms. Example I have terms "Working" and "Under maintenance". I want to color them green and red respectively. How can I achieve this?

I would use CSS for that, and adjust CSS directives through the specific taxonomy vocabulary class, as appear in DOM.

I prefer CSS instead modularity as I think it would simplify the process and probably give you faster control over what vocabulary terms get what color, and on what circumstances.

Code example:

.field--name-field-categories .field-items {color: green}

Notes:

.field-label stands for the label.
.field-item stands for each vocabulary field-item.
.field__items stands for the whole row containing each vocabulary field-item.


Generate drupalSettings in Ajax Callback I'm returning a form with #ajax functionality in an Ajax response. The form is properly loaded into the page, however it is not #ajaxified, as the drupalSettings are not being returned. In D7, we could generate the JS settings AKA Drupal.settings using the following code:

$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
    $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
    $settings .= ');</script>';
}

I'm trying to find the D8 equivalent of this code, but not having much success. At the moment I'm returning a JsonResponse from my ajax callback, but I'm thinking I probably need to return an AjaxResponse. What I can't figure out is how to pass my generated form to the AjaxResponse, in order for it to return the settings along with the HTML for the form.

Well, I'm answering my own question. The secret is to use BubbleableMetadata. Here is my code explaining what I did and how it happened. Here is my entire controller response that generates the JSON for the response:

 public function ajax_callback($type)
 {
    // Retrieve the form
    $form = \Drupal::service('form_builder')->getForm('Drupal\path\to\Form');

    // Render the form
    $rendered_form = render($form);

    // Get the data from BubbleMetaData
    $data = BubbleableMetadata::createFromRenderArray($form);
    // Retrieve the attachments from the $data
    $attachments = $data->getAttachments();

    // Generate the settings to be sent back with the ajax response
    if(!empty($attachments['drupalSettings']))
    {
        $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
        $settings .= Json::encode($attachments['drupalSettings']);
        $settings .= ');</script>';
    }

    // Send back the rendered form along with the settings
    $response = [
        'content' => $rendered_form . $settings,
        'status' => TRUE,
        'type' => $type,
    ];

    // Return the data as a JsonResponse
    return new JsonResponse($response);
}


Display (and pass) a custom user field in php In Drupal 7, I've added some custom fields in Account Settings>Manage Fields.  One of them is field_company_name.  I'd like to be able to display this field and pass it to an external php function.

I can easily display the $user fields for the current user.  For example:

<?php
global $user;
echo 'Current User: ';
print_r($user->name);
echo '
User ID: ';
print_r($user->uid);
echo '
Email Address: ';
print_r($user->mail);
echo '
'
?>

How to I get at field_company_name for this same user?

You need to load the user object up fully with user_load(), so the fields get attached:

$account = user_load($GLOBALS['user']->uid);

Then use field_get_items() to extract the field data:

if ($items = field_get_items('user', $account, 'field_company_name')) {
  $company_name = $items[0]['value'];
}


Map does not show up I am creating a new custom block; when I put HTML into the body and select Full HTML as text format, it gives me only the source code back. What might be the problem? This is a full HTML link I get from http://maps-website.com/.

 embed a google map

EDIT: While looking at developer's tools console, I noticed there is 403 forbidden error.

Before paste the code you need to click on "Source" option.

See the screen shot


Rule to fire only on first time publish of node We are using workflow moderation for some content types and sent out emails to the author once a node has been published.

Sometimes we have the case that an author changes a node after he has been published. When this revision gets published we want to send out a different email.

I have tried many different things but I haven't been able to find a way how to determine if this was the first time the node is published or a subsequent publish. Can someone please point me in the right direction how this can be achieved?

Thanks

This is how I would try doing it:

create a field for the content type named first_publish, boolean, hidden, default value 0
create a Rule that when that content type is published, as a condition if first_publish is 0, first_publish becomes 1, add email output to user
create a second Rule that when the content type is published, as a condition if first_publish is 1, send out a different email

This will use a data field as a variable that follows the node - the rules will trigger appropriately depending on the conditions of whether or not the variable is set, giving different outcomes.


Uploading custom files, using CKFinder I installed CKFinder & CKEditor. They work well, and I uploaded the images. But I must give users the ability to upload pdf-s. When I try to do it through the image button uploading form, it says: "Invalid file extension.".

In /ckfinder/config.php I found this code:

$config['ResourceType'][] = Array(
        'name' => 'Files',              // Single quotes not allowed
        'url' => $baseUrl . 'files',
        'directory' => $baseDir . 'files',
        'maxSize' => 0,
        'allowedExtensions' => '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip',
        'deniedExtensions' => '');

I created the files dir under $baseDir, but it still doesn't work. What to do?

To upload a PDF or another arbitrary file, go through the generic Link dialog:

Then use the upload form:


Exporting my custom content tables for a module I've been working on a Drupal 7 module. As I've been going along, I have been adding content types in the database through the Drupal 7 admin.

I now want these content types to be created when my custom module is installed.

Rather than coding this manually in the module, is there any module available that can look at the content types on my site and create the code I need to put in the module install script?

You should look at the Features module. It will generate a module, which you can merge with your custom code.


unable to add configure field to drupal view I added a new field to an existing content type. But when I try to add same field or any other field to the view, I don't find it in the list except few.

Eg: I added image field to content type. Then I clicked on 'edit view' for which I want to add this image field. Then I click on add field under fields section. I don't find the fields of image body or anything, except title field others.

Can anybody help me sort out this issue?

Your view is not a Content view.  Create a "Content" relationship on the view, and all the content type fields configured on your site will become available to add to the view.


Error occurs every time I try to log in after updating I cloned a site locally, imported the database and run: "composer update --with-dependencies",

Got the following:

  [RuntimeException]
  Could not scan for classes inside
  "/home/www/sites/site/web/vendor/drexarj/disqus-php/disqusapi/" which
  does not appear to be      a file nor a folder

then I run "drush updb -y".

There were a couple warnings:

  The following module is missing from the file system: aspambot
  bootstrap.inc:268
  The following module is missing from the file system: phpmailer
  bootstrap.inc:268

Then I uninstalled recaptcha by typing:

"drush pm-uninstall recaptcha"

Tried to log in, but got the following unexpected error:

  The website encountered an unexpected error. Please try again later.
  Error: Call to undefined function Drupal\commerce_price\bcmul() in
  Drupal\commerce_price\Calculator::multiply() (line 75 of
  modules/contrib/commerce/modules/price/src/Calculator.php).
  Drupal\commerce_price\Calculator::multiply('107.000000', '1.00')
  (Line: 140) Drupal\commerce_price\Price->multiply('1.00') (Line: 259)
  Drupal\commerce_order\Entity\OrderItem->recalculateTotalPrice() (Line:
  133) Drupal\commerce_order\Entity\OrderItem->setUnitPrice(Object)
  (Line: 144) Drupal\commerce_order\OrderRefresh->refresh(Object) (Line:
  92) Drupal\commerce_order\OrderStorage->doPreSave(Object) (Line: 389)
  Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 820)
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line:
  391) Drupal\Core\Entity\Entity->save() (Line: 114)
  Drupal\commerce_order\OrderStorage->postLoad(Array) (Line: 249)
  Drupal\Core\Entity\EntityStorageBase->loadMultiple(Array) (Line: 231)
  Drupal\commerce_cart\CartProvider->loadCartData(Object) (Line: 184)
  Drupal\commerce_cart\CartProvider->getCartIds(NULL) (Line: 172)
  Drupal\commerce_cart\CartProvider->getCarts() (Line: 221)
  Drupal\commerce_cart\Plugin\Block\CartBlock->getCacheTags() (Line: 86)
  Drupal\block\BlockViewBuilder->viewMultiple(Array, 'full', NULL)
  (Line: 71) Drupal\block\BlockViewBuilder->view(Object) (Line: 151)
  Drupal\block\Plugin\DisplayVariant\BlockPageVariant->build() (Line:
  259) Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array,
  Object, Object) (Line: 117)
  Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array,
  Object, Object) (Line: 90)
  Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object,
  'kernel.view', Object) call_user_func(Array, Object, 'kernel.view',
  Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view',
  Object) (Line: 156)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line:
  68) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
  (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
  (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object,
  1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line:
  78) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
  (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1,
  1) (Line: 52)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1,
  1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line:
  666) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

My question is: what can I do about this? I've repeated the process two times and got the same error.

Call to undefined function Drupal\commerce_price\bcmul() in Drupal\commerce_price\Calculator::multiply()

Drupal Commerce requires the BC Math PHP extension - you don't have it in your current environment.

To fix, rebuild PHP with support for the BC Math extension.


Custom url theme for drupal We got site written on Drupal.

We want to make Nginx caching but there is one problem we met.

Nginx caching works perfect, but if user A will go to page http://domain.com and nginx cache it. User B use mobile theme http://domain.com/?theme=mobile and went to http://domain.com/ , he will see desktop version instead of mobile version.

I want to make something like http://domain.com/any/url/path for desktop version and http://domain.com/mobile/any/url/path

Is it possible? Where can I found information about how to do it?

If you are using Drupal6 Have a look at Mobile Tools module.

  The Mobile Tools module provides Drupal developers with some tools to
  assist in making adjustments to your site based on the visitor's
  device.

Once you install the module you can define different paths for desktop and mobile, then browser will detect the device and redirect to corresponding path.
For Drupal 7 Mobile Switch module is the alternative


Finding and display custom user variables I have create a series of user fields. Some of these fields reference taxonomy terms, require a mobile number or are just basic text fields. I used the below to print one of the fields (the number field) inside my page.tpl.php.

global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$number = $user->field_phone_number['und'][0]['value'];

if (isset($number) && !empty($number)) :
print 'Cell: ' . $number;
endif;

My question is how would I go about finding the information I need to print the other fields? The potion that reads ['und'][0]['value']; in particularly is where i'm stuck. I have used devel before to find this information for node variables but I cant find similar information for custom user variables.

It's easier to have Xdebug installed so that you can add breakpoints, pause execution and inspect surrounding variables. Alternatively, you can use Kint to print out variables.


Am I allowed to include a JQuery Plugin in my Drupal Module? I'm writing a Drupal module and I want to make use of a JQuery plugin, but I'm unsure if I'm a) breaking any rules and b) if there are any licensing considerations.

My question is can I use plugins and what is the best way to include them (i.e. in the libraries folder or as part of my module or via something third party).

Do you intend to publish your module as a contributed module on drupal.org? In that case: Probably not. The page 3rd party libraries on Drupal.org states:

  This is the policy for 3rd party code libraries in Drupal's contribution repositories.

  In general 3rd party libraries are forbidden, so do not commit any. Document for your users how to find and install it.

After that, it mentions some exceptions.

I understand that it's tempting to include the plugin in your module, but there are some good reasons not to. For instance:

If other modules use the same plugin, having it in the libraries folder will prevent collisions.
Users will always be able to get the latest version of the plugin.
You, as module maintainer, probably do not want to be bugged about releasing a new version every time the plugin is updated.


How to redirect user "back two pages" after login My users are only able to log in on the mysite.com/user page (I don't use any of the login blocks). How can I redirect those users to their location "two pages ago"? For example, they might visit the about us page, then click login (taking them to the /user page). After they complete their login, I would like for them to be redirected back to the about us page.

I currently have it set to redirect to the previous page after login, but that will always be the "user" page, which is not particularly useful in this instance.

Thanks!

Append

?destination=[PATH]

to your login link.

You can do this with the Menu Token Module


Is there a way to find internal links to a specific web page? For example, for a page called mysite.com/about can you determine any other pages that link directly to this web page? The goal is to determine all of the webpages that exist in mysite.com that have a link to the about page.

You may want to look at the Views module (pretty sure you already have that module enabled ...), which includes a Backlinks view. After you activate this view, a What links here-tab is shown on each node.
So on your about page, it'll list all of the pages that have a link to the about page (as in your question).


mark single form field as cause of error on form validation I've a custom field, and I'm trying to write the validation for the field values. however when a particular field causes the failure, the whole fielset is marked in red. I only want the specific field element to be highlighted, and in the case of Unlimited I only want the specific entry highlighted.

here is the code I have so far. but the whole fieldset is marked in red when ever a validation fails.

   function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langtype, $items, $delta, $element) {
      $base = $element;

      if ($instance['widget']['type'] == 'prodlist_text') {
        $element['#element_validate'] = array('_prodlist_text_validate');

        $element['prod_type'] = array(
          '#type' => 'select',
          '#title' => t('Product Type'),
          '#default_value' => isset($items[$delta]['prod_type']) ? $items[$delta]['prod_type'] : NULL,
          '#options' => type_options(),
          ) + $base;

        $element['prod_description'] = array(
          '#type' => 'select',
          '#title' => t('Description'),
          '#default_value' => isset($items[$delta]['prod_description']) ? $items[$delta]['prod_description'] : NULL,
          '#options' => description_options(),
          ) + $base;

        $element['order_amount'] = array(
          '#type' => 'textfield',
          '#title' => t('Amount'),
          '#default_value' => isset($items[$delta]['order_amount']) ? $items[$delta]['order_amount'] : NULL) + $base;
      }
      return $element;

    }

function _prodlist_text_validate($element, &$form_state) {

  if ($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') {
    return ;
  }

  $values = $form_state['values'];
  $language = $values['language'];
  $field_name = $element['#field_name'];
  $field_name_error_box = $field_name;

  foreach ($values[$field_name][$language] as $delta => $item) {

    if (isset($item['order_amount'])) {

      if (is_numeric($item['order_amount'])) {
        if($item['prod_description'] != 'no order' && $item['order_amount'] <= 0 ){
          form_set_error($field_name_error_box, t('Order amount has to be more then 0'));
        } else if ($item['prod_description'] == 'no order' && $item['order_amount'] > 0) {
          form_set_error($field_name_error_box, t('You have created an order amount without selecting a product.'));
        }

      } else {
        form_set_error($field_name_error_box, t('Order amount has to be numeric'));
      }
   }

  }

}

I'm trying to set the variable $field_name_error_box = $field_name; to the correct value but it either lights up the whole form section or nothing at all.

I've tried the following, and lots of other variants without luck.

$field_name_error_box = $field_name . 'order_amount';

You must use a field name like this:  'parent][element'

In your case,

$field_name_error_box = $field_name . '][order_amount';

should work.


Why does this code work for the current term but not the parent term? This code below displays the current taxonomy term on a taxonomy term page

$current = taxonomy_term_load(arg(2)); ?>
if ($current): ?>
echo $current->name; ?>
endif; ?>

The code below displays the error: "Notice: Trying to get property of non-object in eval() (line 9 of...)  Line 9 is "echo $parent->name;"

$parent = taxonomy_get_parents($current->tid);
if ($parent){
echo $parent->name;
}?>

I'm really confused as to why the first set of code works but the 2nd doesn't? "print_r($parent);" displays the info below, so the data is there.

Array ( [3218] => stdClass Object ( [tid] => 3218 [vid] => 12 [name] => NAME OF TAXONOMY TERM [description] => This is the description area [format] => full_html [weight] => 0 [vocabulary_machine_name] => mfr_model [field_displayed_view] => Array ( [und] => Array ( [0] => Array ( [vname] => final_term_pages|testing [vargs] => ) ) ) [metatags] => Array ( [und] => Array ( [title] => Array ( [value] => This is the meta page title ) [description] => Array ( [value] => This is the meta description ) ) ) ) )

If you check out the docs for taxonomy_get_parents() you can see that the return value is an array of parent terms.

So you might loop through the results like this:

$parents = taxonomy_get_parents($current->tid);
foreach ($parents as $parent) {
  echo $parent->name;
}

or use just the first one like this:

$parents = taxonomy_get_parents($current->tid);
if ($parents) {
  echo $parents[0]->name;
}


Deleting Aliases unchecks 'generate automatic alias' I'm sure this is a bug.

I have a bunch of alias paths set where page URLs are generated based on menu location. I'm testing to see if I restructure the site and move a lot of content around, can I use path-auto, bulk update to change all the URLs.

Obviously I can't update without deleting the existing ones first (tested).

So I went in and delete all the aliases via Admin > Config > Search > URL aliases > Delete aliases. All aliases deleted, great.

But Bulk update won't give me new aliases. After a bit of poking around it turns out that running Delete Aliases has caused the 'Generate Automatic Alias" checkbox to be turned OFF on all my content.

so...

Why did running Delete Aliases cause all my content to change to using custom aliases?
Can I (somehow) revert all pages to automatic aliases?

Note - I'm using the govCMS distribution, so adding modules like VBO is not an option. I have almost zero understanding of drush, but I'm willing to dive in with instructions.

Note again - I had pathauto persistant state enabled when this happened.

Okay, never mind. I spent over an hour with this repeatedly happening, dug through pages full of people having the same issue and the opposite issue, flicked persistant state on and off, and it suddenly started working in the time it took me to write this. Caching I guess