Pulling Possible Select Values From A Field (Drupal 7) I have been looking if there is a function that return all the possible values for a field. I have a select field that is a Node Ref. So, function list_allowed_values() is out of the question. Because, list_allowed_values() is not compatible with Node Ref. Does anyone know a function to get all the possible Node Ref for a field?

Or do have to code my own function?
Thanks,
Nate

Ok, I did some digger on google. ychaugule made a nice function for this problem. Here is the post.
Also, reference to the information here:

"But the above code will only work for select list, not for node reference or other types of references. _field_allowed_values() function is a custom function which returns allowed values of reference type field. The function returns allowed values for node reference and term reference field and can be extended to get allowed values of other reference fields as well. - See more at: http://yogeshchaugule.com/blog/2013/get-allowed-values-select-list-field#sthash.xnf89Cgn.dpuf"

<?php
function _field_allowed_values($field_name) {
      // retrieve field configurations from DB.
  $allowed_values = array();
  $query = db_select('field_config');
  $query->condition('field_name',$field_name)
  ->fields('field_config',array('type', 'data'));

  $result = $query->execute()->fetchAssoc();

// Allowed references type
  $ref_type = array(
    'node_reference',
    'taxonomy_term_reference',
    );

  $field_config = unserialize($result['data']);
  if (in_array($result['type'], $ref_type)) {
    if ($result['type'] == 'node_reference') {
      $node_types = array_filter($field_config['settings']['referenceable_types']);

      $query = db_select('node');
      $query->condition('type', $node_types, 'in')
      ->condition('status', 1)
      ->fields('node', array('nid', 'title'));
      $allowed_values = $query->execute()->fetchAllKeyed(0, 1);
    }
    elseif ($result['type'] == 'taxonomy_term_reference') {
      $allowed_values = taxonomy_allowed_values($field_config);
    }
  }
  else {
    $allowed_values_raw = unserialize($result['data']);
    $allowed_values = (!empty($allowed_values_raw['settings']['allowed_values']) ? $allowed_values_raw['settings']['allowed_values'] : array());
  }
  return

  $allowed_values;
}

$field = _field_allowed_values('FIELD_NAME');


Panel + views + taxonomy depth problem following this tutorial I create a Panel Page for the taxonomy term to display all the content related to the taxonomy term and it works.

But I need to have in all the nodes related to the taxonomy terms in the url and children.
So I sobstitute taxonomy term ID contex filter with taxonomy term ID (with depth) and do not work anymore -.-

This is the contex filter's setting

If I try this view block in view page [putting 'taxonomy-name' as argument] it works but not in the panel page.
Where is my mistake?

I don't know if this can help. This is the contex of panel page [I setup the view to take argument from URL.. but maybe it can help]

You should try to add a "Content pane" display on the view instead of using a page display (enable "Views content panes" module). "Content pane" allows to set the argument input from the views settings. On the "argument input" you can select "From context" as source, and the required term context.

EDIT: Like I've wrote on the following comments, the correct contextual filter settings is:

1) Content: Has taxonomy term ID (with depth). Provide a default value: Taxonomy term ID from URL (Load default filter from term page). Specify validation criteria: Taxonomy term, Filter value type: Term ID

2) Content: Has taxonomy term ID depth modifier


Deploying to multiple hosts using Webistrano We're using Webistrano to deploy our Drupal sites to testing and production.

The recipe we're using is as follows:

namespace :drupal do
  desc "symlink_files"
  task :symlink_files do
    invoke_command "ln -s #{deploy_to}/shared/files #{deploy_to}/current/drupal/sites/default/"
    invoke_command "ln -s #{deploy_to}/shared/settings.php #{deploy_to}/current/drupal/sites/default/"
  end

  desc "refresh_configuration"
  task :refresh_configuration do
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} -y fr-all"
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} -y updb"
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} cc all"
  end
end

after 'deploy:symlink','drupal:symlink_files','drupal:refresh_configuration'

This method is working great for single-host deployments, but fails for multi-host deployments. The reason is that the refresh_configuration task will run on each host, causing all kinds of race conditions and corruption on the central database server.

My question is, can anyone suggest a way to fix the Webistrano setup to only run refresh_configuration task on one server only?

PS. I'm not interested in changing the deployment system to Aegir or anything else.

As per this Capistrano Wiki page, you can restrict tasks and single commands to specific :roles and :only attributes:

task :migrate, :roles => :db, :only => { :master => true } do
  # ...
end

task :other do
  run "migrate", :roles => :db, :only => { :master => true }
end

Using this, I was able to run the refresh_configuration task to run on a server with a specific attribute.


'A' tags in Custom Blocks get removed I created a few regions for my footer. Inside of each region I've added a custom block with plain html code. One has the contact info, another has social media icons and the last one has a map.

The custom block dedicated for the social media icons has only an h2 heading and the a tags for the icons. I'm using font icons for the logos (I know probably not the best for accessibility), so the a tags don't have any text in between them. I am however using the title attribute along with the href attribute.

Everything gets saved and is rendered correctly, however, when I go back to the custom block to make edits all of the a tags are gone; the h2 tags are still there. As long as I don't hit the Save button again the site remains the same, but if I hit Save, obviously all of the icons are gone. I have Full HTML selected as the Text Format so I know that is not the issue. Is there a setting that I have to set to allow empty a tags or is this not allowed at all??

I don't want to hard-code these sections in my template as I want my site administrator to be able to edit each block if necessary.

Any help would be appreciated.

Thanx

I'm running Drupal 8.05 on Ubuntu 14.04

UPDATE

I double checked to make sure there aren't any missing tags. I also updated my code to:

Best Rate Guarantee

This time the a tag remains but the empty span tag is removed.

Just tested this on a fresh install of 8.0.6 and I think I see what is going on.

I saved a block using the Full HTML format with the following content:

&nbsp;

And had it display in my sidebar region. Everything worked fine, there are two links in this block, that can only really be seen if you inspect the html.

However, when going to edit the block again, with the default as-installed text format settings, ckeditor will wrap my first link with a P tag, and completely remove the second link.

So, you have a few options.

Enter an &nbsp; character inside your empty tag.
Disable the ckeditor for your format and just use the plain-text editor, with the Full HTML (or a custom filter of your creation) filter.

Ckeditor is doing the fixing of your html, so getting rid of it will solve your problem.


How do I update core in commerce 2.x distribution? I would like to update drupal core from 8.2.1 to 8.2.3 in a local environment. The normal procedure of deleting both the vendor and core folders along with the files in the site root won't apply. The commerce2.x disto installation puts the vendor folder outside of the site root and it contains more files than in a fresh drupal 8 downloaded vendor folder. I'm guessing there must be a slighty different process.

I run composer update drupal/commerce --with-dependencies.

The image attached shows the error.

If anyone can give me the steps I need to take, that would be great.

Simple solution found in the end. Before running a composer command I had to add paths in my Windows Environment path variable to both the Git.exe file and the ssh-agent file.

I then ran a slightly different composer command from the one above:
composer update drupal/core --with-dependencies
I did this from the root of my site.

I had to make sure that drupal/core is in the require part of the composer.json file and not the replace part.


#Ajax change the input wrapper i've made a form which update the price of a product. The user just need to select a duration by a select-list and it update the price by an Ajax callback. It update well the price but it change the structure of my select and then the select when is changed again does nothing...

The form inputs :

$key = array('field_friterie_suggest', 'MY-PRODUCT-SKU');

$form['content']['deals'][$key[0]]['purchase']['value'] = array(
            '#type' => 'select',
            '#name' => 'update-price-'.$key[0],
            '#options' => array(
                5 => t('- None -'),
                0 => t('1 month'),
                1 => t('3 month'),
                2 => t('6 month'),
                3 => t('1 year'),
            ),
            '#default_value' => $default_purchase_value,
            '#ajax' => array(
                'callback' => 'fritr_commerce_update_pricing_callback',
                'wrapper' => 'pricing-'.$key[0],
            ),
            '#attributes' => array(
                'data-update' => array(
                    'pricing-'.$key[0],
                ),
                'data-type' => array(
                    $key[1],
                ),
            ),
        );
        $form['content']['deals'][$key[0]]['purchase']['pricing'] = array (
            '#prefix' => '
',
            '#suffix' => '$
',
            '#markup' => 0,
        );

And my callback :

$month = $form_state['triggering_element']['#value'];
    $price = 0;
    if ($mont != 5) {
        $month_definition = array(1,3,6,12);
        // get the product by his SKU
        $product = commerce_product_load_by_sku($form_state['triggering_element']['#attributes']['data-type'][0]);
        // get the product price and reduction
        $product_base_price = ($product->commerce_price[LANGUAGE_NONE][0]['amount'] / 100) * $month_definition[$month];
        $reduction = $product->field_commerce_reductions[LANGUAGE_NONE][$month]['value'];
        // set the new price
        $price = $product_base_price - ($product_base_price * ($reduction/100));
    }
    return array (
        '#prefix' => '
',
        '#suffix' => '€
',
        '#markup' => $price,
    );

So my input become :

<select data-update="pricing-field_friterie_suggest" data-type="MY-PRODUCT-SKU" class="form-control form-select ajax-processed" id="edit-content-deals-field-friterie-suggest-purchase-value" name="update-price-field_friterie_suggest"></select>

to :

        <select data-update="pricing-field_friterie_suggest" data-type="MISE-EN-AVANT-SITE" class="form-control form-select ajax-processed" id="edit-content-deals-field-friterie-suggest-purchase-value" name="update-price-field_friterie_suggest"></select>

Then when i change the value of the select, it does nothing. Can you help me please ?

The solution proposed by Jaypan works well.
The solution was to not put the modifications of my field in the callback but in the form definition and set the value here by checking the $form_state fields.


Drupal views get field info from node within another field I'm attempting to create a view which will show Photo Galleries that have a reference to a project. The project has a reference to a category. It is on the category page I want to show these galleries.

So I am on the category page, and would like to show the latest galleries posted within the projects in this category.

When creating the view for photo galleries I can display the project field, so I know what project they are in. However the category field is within the project node, so how can I find out what category the project has referenced?

I need to look at the node referenced in the project field, then take the category field from that to determine if it is associated to the current category. Is this possible within the fields module or should I look at something else?

Hopefully this question makes sense, if not please ask questions or edit the question. Thanks!

Edit: This is using Drupal 7 and I assume views 3.

I assume that you are using the References module to provide a Node Reference field to Photo Gallery nodes which reference Projects, and then provide another Node Reference field, or Term Reference field to Project nodes which reference Categories?

In Views:

Expand the Advanced column
Add a Relationship
In the Add Relationships dialog, select the Photo Gallery: Project Node Reference field from the list
In the Configure Relationship dialog, Click Apply
Add another Relationship
This time in the Add Relationships dialog, select the Project: Category Node/Term Reference field from the list.
In the Configure Relationship dialog, there is a field labelled Relationship with a drop-down menu, which lets you choose other compatible relationships you've added previously, from which you should select the Photo Gallery: Project relationship (I'm not entirely certain what text to expect here). Then click Apply.
Now when you add new Fields to the View, you'll have the option to select a Relationship for each individual field, which allows you to pull data from the entity (Node/Term) that is referenced by the selected Relationship


Table in custom form + empty values in form_state In a custom form I created a table element:

  // Table results.
  $form['table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => ['id' => 'table-results'],
    '#empty' => t('No results.'),
    '#prefix' => '
',
    '#suffix' => '
'
  ];

This table is ajaxified and updated when I click on a specific button.

I need to get the output HTML of this table in another function. If I use a dpm($form_state->getValue('table')); I get an empty array. Yet, the other values (of other fields) are accessible in the $form_state.

// My second function
public function secondfunction(array $form, FormStateInterface $form_state) {
  dpm($form_state->getValue('table')); // -> empty value...
  dpm($form_state->getValue('textfield')); // I get a value
}

What do I change in my code to solve this problem?

When you want to get the HTML of the table you must use the renderer service.

In Drupal 8:

$html = \Drupal::service('renderer')->render($form['table']);

Or better, use dependency injection :)

In Drupal 7:

$html = drupal_render($form['table']);


Populate fields when a checkbox is clicked on a form I have a regular drupal 7 form (based on a content type called guests) where I need a "Bring my partner" checkbox. When the checkbox is clicked, a field collection field (first name/last name/address) needs to be prefilled basing on the details for the currently logged-in user. (Partner details are in my user account details.)

Can this be done in hook_form_alter()? Is there any other way to achieve this?

You could do this with hook_form_alter and add a state to the field that needs to be hidden.

$form["first_name"] = array(
    "#states" => array(
        "invisible" => array(
            ":input[name='bring_parter']" => array(
                "checked" => FALSE,
            )
        )
    ),
);

What this does is hides the "first_name" unless "bring_partner" is checked. More info here


How do I create an uncacheable field plugin base? I created a custom field plugin base for show an additional data column in a  view.

In my FieldPluginBase Class, I define the value of my additional data column for each row of my view (one row equal one node). The datas depends some node parameter.

My problem is users can often changes nodes parameters, but when the user access to my view after change a parameter of a node, the additional column show old data.

I notice when I clear website cache, the view show the new value.

This is the code of my class, can you tell me what must I do for the view shows all the time the newest value of the node in my field plugin base ?

class MyFieldPluginBaseCustom extends FieldPluginBase {

    ...
    public function render(ResultRow $values) {
        //do some work with the current node (the current row view)
        if(node_parameter_test_isOK() == true)
            return "string A";
        }
        else{
            return "string B";
        }
    }

    // 0 : the view shows a list of node
    // the view ;
    // (nodeid - mycustom Field Plugind)
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string B"
    ...
    // nodeN - "string B"

    // 1 : a user change the parameter of the node3

    // (2) : then, when the user access to the view page, the view must show
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string A"
    ...
    // nodeN - "string B"

    // 2 : However, the view hasn't been updated and show again (unless I clear caches via drush cr by example)
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string B" // row not updated
    ...
    // nodeN - "string B"
    ...
}

May be you can try :

use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;

class MyFieldPluginBaseCustom extends FieldPluginBase implements CacheableDependencyInterface  {

    ...
    public function render(ResultRow $values) {
        //do some work with the current node (the current row view)
        if(node_parameter_test_isOK() == true)
            return "string A";
        }
        else{
            return "string B";
        }
    }
  public function getCacheMaxAge() {
    return 0;
  }
  public function getCacheContexts() {
    return [];
  }
  public function getCacheTags() {
    return [];
      }
}


How do I install core on Windows 10 with Nginx server? I Want to install Drupal 8 on Windows 10 with nginx server.
I do know how to install with Apache using XAMPP.
I use PHP 7.2, Microsoft SQL as the db.
I installed nginx 1.18.0 and PHP in C:/
I connected them with php-cgi -b 127.0.0.1:9000
my root file for the server is  C:/nginx/html.
I copied the extracted drupal file to the C:/nginx/html/ folder.
In the internet explorer i try to run the installation of drupal, 403 forbiden appear.
So how do I install Drupal 8 on Windows 10 with nginx server.??
my nginx configuration is:
#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
worker_connections  1024;
}
http {
include       mime.types;
default_type  application/octet-stream;
#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#    listen       8000;
#    listen       somename:8080;
#    server_name  somename  alias  another.alias;

#    location / {
#        root   html/ltts;
#        index  index.html index.htm;
#    }
#}

# HTTPS server
#
#server {
#    listen       443 ssl;
#    server_name  localhost;

#    ssl_certificate      cert.pem;
#    ssl_certificate_key  cert.key;

#    ssl_session_cache    shared:SSL:1m;
#    ssl_session_timeout  5m;

#    ssl_ciphers  HIGH:!aNULL:!MD5;
#    ssl_prefer_server_ciphers  on;

#    location / {
#        root   html/ltts;
#        index  index.html index.htm;
#    }
#}

}

You can use Laragon https://laragon.org it's a dead-simple configuration and you can install a blank drupal 8 projects (+ tons of other options).
If you are more advanced user you can use Docker or Vagrant. I would prefer Docker-based (Lando, Docksal...)


Taxonomy Access Control Change Default Behavior From Taxonomy Access Control Documentation

  Users with multiple user roles: Allow/Ignore/Deny options are
  interpreted only within one user role. When a user belongs to multiple
  user roles, then the user gets access if any of his/her user roles
  have the access granted.
  In this case, permissions for the given user
  are calculated so that the permissions of ALL of his user roles are
  "OR-ed" together, which means that Allow in one role will take
  precedence over Deny in the other. This is different from how node
  access permissions (for multi-category nodes) are handled within one
  user role, as noted above.

This is a default behavior of the TAC. But is there a way to change this behavior so that the it is AND-ed instead of OR-ed or in other words a Deny in any of the roles would deny access to the content even if the other role has Allow permission.

The use case is as follows. Let us Assume there are Two Taxonomy called Grade and Subject. And all the contents are tagged with with both the terms.

A student logged in with a role of Grade 1 and Science should only be able to see the contents tagged with both Grade 1 and Science

The way to go about it should ideally be set allow permission to the Grade 1 role to access all with the grade 1 Term and deny for rest of the roles in the grade category such as grade 2 grade 3 etc.

Similarly Set allow permission for Science and Deny for the rest of the subjects.

With the current setup if you give the role Grade 1 and Science. the student would be able to see all the subjects in Grade 1 and all Grades in science.

Is there a way to accomplish this.

One option I found was to use the hook_node_access this function has three inputs

$node The Node object on which the operation is done
$op The Operation being done on the Node could have three values view, update or delete
$account the user object.

The taxonomy access control stores the access information in taxonomy_access_term which has the following fields tid - taxonomy term ID, rid - the role ID, grant_view, grant_update, grant_delete, grant_delete, grant_create, grant_list

All the grant columns can have the following values

0=>Ignore
1=>Allow
2=>Deny.

Used the following function to override the hook_node_access

    function custom_node_access($node, $op, $account) {

        if ($op == 'view')
        {
        // Get all the tids into the $tids array
            $tids = array();
            $tids[] = $node->field_class[$node->language][0]['tid'];
            $tids[] = $node->field_subject[$node->language][0]['tid'];

        // Get all the role ids into the $roles variable
            $roles = array_keys($account->roles);

        // Create the query to get the `grant_view` with a value 1 if all the
        // roles have grant permission then the result would have 2 records.

            $query = db_select('taxonomy_access_term' , 't');
            $query->condition('t.tid', $tids, 'IN');
            $query->condition('t.rid', $roles, 'IN');
            $query->condition('t.grant_view', 1);
            $query->fields('t', array('grant_view'));
            $result = $query->execute();

        // if the result is less than two then we deny access other wise we
        // ignore it so that let the node_access control take over.

        if ($result->rowCount() < 2)
        {
                return NODE_ACCESS_DENY;
            }
      }
      return NODE_ACCESS_IGNORE;
    }

This works well node displays. But the problem would be that since the hook_node_access is bypassed by the list queries this will not work, Might have to add the node_access tag to all the queries which would become a performance issue.

The second method was to use the hook_node_access_records_alter and hook_node_grants_alter

the hook_node_access_records_alter edits the grant realms before writing it to the node_access table when creating or editing a node.

function custom_node_access_records_alter(&$grants, $node) {

  // Store the grants to a temp variable

  // create a new varible to store the new gid
  $gid = "";

  // Loop through the grants
  foreach ($temp as $key => $grant)
  {
    if ($grant['grant_view'])
    {
        // if the grant_view is set to 1 then append the gid
        // after adding a padding 0 to the left so that we get
        // a 2 digit number
        $gid .= str_pad($grant['gid'], 2, "0", STR_PAD_LEFT);

    }

  }

  // After completing this loop the new gid would look something like 040506
  // which means the role id 4, 5, and 6 has access to the page. and since we have
  // added it together we can make sure that it is individualy not valid
  // has to work together.

  // Rewrite the grant values with the new gid.
  if($gid_view != "")
  {
    $grants = array();
    $grants[0] = array();
    $grants[0]['realm'] = 'taxonomy_access_role';
    $grants[0]['gid'] = (int)$gid;
    $grants[0]['grant_view'] = 1;
    $grants[0]['grant_update'] = 0;
    $grants[0]['grant_delete'] = 0;
    $grants[0]['priority'] = 1;

  }

}

The next step would be to override the hook_node_grants_alter function.

function custom_node_grants_alter(&$grants, $account, $op) {

  // we only want it to work with the view.
  if($op == 'view')
  {
    $gid = '';

    // loop through the roles of the user
    foreach($account->roles as $rid => $role)
    {
        // we do not want the role id 2 as it is the id of the authenticated user.
        if ($rid >2)
        {
            // generate the gid we created in the hook_node_access_records_alter
            // so if the user has all the roles we set to the node then we would
            // get the same gid other wise the gid would be different and access
            // would be denied
            $gid .= str_pad($rid, 2, "0", STR_PAD_LEFT);
        }
    }

    // Over write the grants array.
    $grants = array();

    $grants['taxonomy_access_role'][0] = (int)$gid;

  }
}

Note : There are few assumptions made here

We only have the taxonomy access control module as access control module other than the core access control system. If there are more then we have to check and make changes to the function accordingly.
We are only checking for the view grants and not bothered about the rest of the grants.
Maximum number of roles that a user would have is 5. The gid is of the type int so it can accommodate a maximum value of 10 digit.
Each role would have only one allow per taxonomy term and rest of it would be deny.


Can't seem to make use of new user account field in display suite I need to be able to display a particular user field in my node display.

The user field is a new, custom field I created, here: /admin/config/people/accounts and it's called 'organization role'. I was able to successfully add values for this field to my users. So the field itself works just fine in the user account settings. When you look at a user it shows their organization role. All that is fine.

However, in my node display I show the photo and name of the author of the node. These fields were made available to me when I installed display suite module and made a custom layout using that module, for my node page(s). However, no matter how many times I flush the cache my new user field 'organization role' is not available to me in my node's 'manage display' tab.

So my question is: how can I make that field available to my node display so I can display it with the rest of the node fields? (and once I make it available how do I actually display it?)

Display Suite only shows user fields Author and User Picture by default. However, there is a way to do this by defining a Code Field with Display Suite

Go to admin/structure/ds/fieldsand create a Code Field

Select Entities: Node (make this field available to nodes). You can do some additional filtering in Limit field if you want

Use the following code (be sure to select Display Suite code en Text format and use the php tags)

 $author = $entity->uid;
 $u = user_load($author);
 if (isset($u->field_special_field[LANGUAGE_NONE][0]['value'])) {
   return $u->field_special_field[LANGUAGE_NONE][0]['value'];
 }

(Replace field_special_field with the name of your field,e.g. field_organization_role). Then go to your Content type Manage display and add the new field.

Another way:

This is really easy to do with Views, though. Create a View of your content type, select Unformatted list of fields. Add all the fields you want from your Content Type. Go to Advanced and create a Relationship to Content: Author. This will expose ALL the User fields in the list of Fields. You can add them at your heart's content. If you want to show only one node (rather than a list of all nodes) you can use Content: Nid in the Contextual filter area and pass the nid at the end of the url, as in www.example.com/view_name/[nid]


Custom subdomains with htaccess I have page structures like:

example.com/aaa
example.com/aaa/a1
example.com/aaa/a2
example.com/bbb
example.com/bbb/b1
example.com/bbb/b2
example/com/ccc
........

What I need is instead example.com/xxx/x1, I want users to see xxx.example.com/x1

How can I achieve this with a rewrite rule? Or any other suggestions?

Subdomains module does not work for me because it doesnt allow custom subdomains.

I ended up creating a multisite structure.

Under sites folder I created a folder for each subdomain like: "aaa", "bbb",...
I created a settings.php inside each folder (starting with php tags, do not close it though):

include_once(dirname(dirname(__FILE__)) . "/default/settings.php");
$conf['site_frontpage'] = "aaa";

(It inherits the general settings.php file since I dont need very different settings per domain)

Created a sites.php file inside sites folder (again starting with php tags):

  $sites['aaa.example.com'] = 'aaa';

  $sites['bbb.example.com'] = 'bbb';

  .......


One submit button posting to multiple functions I am displaying a form inside a block and I want it to submit to multiple functions, namely the original submit functions and in addition my own pm_form_submit. Yet I can't get it to work... you can submit to multiple functions right?

In the case bellow only "Test Form Submit" (the original submit function) is displayed.

Submit button of my test form:

function test_form_form ($form,&$form_state){
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

My code for displaying the form in a block:

$form = drupal_get_form ('test_form_form');

//add our submit function (both are here just to test)
$form ['#submit'][] = 'pm_form_submit';
$form ['submit']['#submit'][] = 'pm_form_submit';

$output .= drupal_render ($form);
return $output;

My submit functions: (the pm_form submit is in the same file where I alter the form and the test_form_form_submit is in the file where the form is generated)

function pm_form_submit ($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}

function test_form_form_submit(&$form, &$form_state) {
  drupal_set_message('Test Form Submit');
}

when I print_r the $form array I can see the following:

[submit] => Array
    (
        [#type] => submit
        [#value] => Submit
        [#input] => 1
        [#name] => op
        [#button_type] => submit
        [#executes_submit_callback] => 1
        [#limit_validation_errors] =>
        [#process] => Array
            (
                [0] => ajax_process_form
            )

        [#theme_wrappers] => Array
            (
                [0] => button
            )

        [#defaults_loaded] => 1
        [#tree] =>
        [#parents] => Array
            (
                [0] => submit
            )

        [#weight] => 0.001
        [#processed] => 1
        [#required] =>
        [#attributes] => Array
            (
            )

        [#title_display] => before
        [#id] => edit-submit
        [#ajax_processed] =>
        [#sorted] => 1
        [#submit] => Array
            (
                [0] => pm_form_submit
            )

    )

...
[#submit] => Array
    (
        [0] => test_form_form_submit
        [1] => pm_form_submit
    )

You can't add submit handlers to form after drupal_get_form() is called, because they will not be processed.

You need to add submit handler in hook_form_alter(). If you want add this handler only in specific cases, you can add cutom parameter to drupal_get_form()

Code in block:

$form = drupal_get_form('test_form_form', 'add_pm');
$output .= drupal_render($form);
return $output;

Code in custom module:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'test_form_form') && ($form_state['build_info']['args'][0] == 'add_pm')) {
     // add custom submit only if form was called with parameter.
     $form ['#submit'][] = 'pm_form_submit';
   }
}

function pm_form_submit($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}


How to make one view with different taxonomy terms in different rows? I want to make a view with 3 rows of lets say fruits, with 6 fruits max for each row. Spring, Summer and Autumn fruits.

And I don't want them to be mixed in one array so I could style them in view-template. How can I do it correctly?

I wanted to post this as a comment but my rep is not high enough. I had asked a similar question and received an answer here: Separate grid rows by field value


How to use arguments, defined in a custom event, for an action I've just defined this event with the two arguments: number and message. I want to use them to verify the message and send a response back to the number. I have an action for that but I don't know how to pass the arguments.

function sms_rules_rules_event_info() {
  return array(
      'sms_rules_sms_received' => array(
         'label' => t('SMS received'),
         'module' => 'sms_rules',
         'arguments' => array(
            'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
            'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
         ),
      ),
  );
}

In your action you might have something like

function mymodule_rules_action_info() {
  return array(
    'my_action' => array(
      'label' => t('Label'),
      'module' => t('My module'),
      'arguments' => array(
        'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
        'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
      ),
      'base' => 'mymodule_my_action',
    ),
  );
}

The 'base' property indicates the callback for the action. You can also use the key of your action as the callback if you choose not to set a 'base'. In this case it would be function my_action(). The arguments defined in the action will automatically be passed to that function. Now, whether the action is available is dependent upon which arguments your event makes available and which arguments your action requires. So, if I had an event that passes a 'type' => 'user' and 'type' => 'node' then only actions that have arguments 'user' and 'node' would be available. This is how Rules 1 works. Alternatively, by using a simple 'text' data type the actions will always be available because the data type is not unique. You can specify your own data types by implementing hook_rules_data_type_info().

Anyways, I got off track. So, with your base being mymodule_my_action:

function mymodule_my_action($number, $message) {
  // Do stuff here.
  return $number;
}

Another addition you can make if necessary is adding a settings form to your action.

function mymodule_my_action_form($settings, &$form) {
  $form['settings']['my_options'] = array(
    '#type' => 'select',
    '#title' => t('Select an option'),
    '#options' => array(
      'this' => t('this'),
      'that' => t('that'),
      'also' => t('also'),
    ),
    '#default_value' => $settings['my_options'],
    '#required' => TRUE,
  );
}

In this case, you would just add the settings array to your action callback as the last argument:

function mymodule_my_action($number, $message, $settings) {
  if ($settings['my_options'] == 'this') {
    // Do stuff.
  }
}

Hmm... I don't even know if I answered your question, but I tried to provide as much info as possible. If I completely missed it please give me some guidance. I maintain three Rules modules, so I've been around that module for a while and I'm glad to help.


What properties does a custom cck_phone form field need to work? I am struggling to get a working custom implementation of a cck_phone field from the cck_phone module. I have included my partially working code at the bottom.

What seems to be not working is that the function cck_phone_phone_number_process expects to be able to retrieve information about the widget with

$instance = field_widget_instance($element, $form_state);
$settings = $instance['settings'];

However in my implementation, field_widget_instance($element, $form_state) returns NULL, resulting in both $instance and $settings being NULL and problems further on in the cck_phone_phone_number_process function.

What does work is that the code below does render a properly populated country code dropdown and phone number entry textfield.

My code to create the custom cck_phone field:

$form_section['phone']['field_phone_home'] = array(
    '#type' => 'phone_number',
    '#field_parents' => array(
        'profile_personal_information'
    ),
    '#field_name' => 'field_phone_home',
    '#language' => 'und',
    '#delta' => 0,
);

I was unable to find an exact answer to this question, but I was able to find a work around to get the extensions to load.

using form_alter, after the field is partially built in a form function

//set value for office extension
  if(
    isset($form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE])
    &&
    $form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE][0]['extension'] != NULL
  ){
    $field_phone_office_ext_value = $form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE][0]['extension'];
  }
  else{
    $field_phone_office_ext_value = '';
  }

  $form['user-information']['user-information-fieldset']['profile']['phone']['field_phone_office']['extension'] = array(
    '#type' => 'textfield',
    '#title' => t('Ext.'),
    '#default_value' => $field_phone_office_ext_value,
    '#value' => $field_phone_office_ext_value,
    '#size' => 10,
    '#maxlength' => 10,
    '#weight' => 2,
    '#attributes' => array(
      'class' => array(
        'phone-extension'
      )
    )
  );


How to render specific block from template without rendering entire region I'm attempting to render a specific block on a page without rendering the region. I'm assuming the machine name of the block is 23 based on the URL I get when configuring the block.

example.org/admin/structure/block/manage/block/23/configure

I'm attempting to grab the block using the information I've found here

https://www.drupal.org/node/26502

My attempt at it is

$block = module_invoke('block','blockview',23);
print render($block['content']);

But I'm not having any luck.

Almost there it's block_view not blockview

$block = module_invoke('user', 'block_view', '2');
print render($block['content']);


Naming conventions for fields machine name in Drupal There is a naming convention for the fields machine name such as:

entity_name_field_name

for not shared fields

or

field_name

for shared fields.

When I go to start a project, what should be the naming convention I must use on it?

TL;DR Always use a short succinct but entity agnostic machine name for your fields because requirements will change.

I would never put the entity name in the field name. While today you might think that a field will only ever be used on a node. Requirements change over time. Today's assumptions will bite you tomorrow.

For example you might have a "Hero image" field and decide to use "node_hero_image" (or worse "node_blog_hero_image") because it is only used for nodes.  Later someone decides that they want to use hero images on another entity type - say taxonomy terms to create nice "category landing pages".  You have hard coded the entity type into the field. You have 2 choices, either keep the poorly named field or create a new one - both options are less than idea an increase the technical debt in your project.

If you had've used "hero" as the machine name for your field it would remain flexible. The purpose of the field is clear to anyone who sees it in the UI. You don't need "_image" in the name either as most places in the UI will tell you it is an image field.


Duplicate Entry for Video Embed Field which not allow to save node Content Type : VideoDisplay

  Fields : Name of Video(Type: String), Video(Type: Video Embed Field), Artist(Type : Node Reference Field)

User already created a record of type VideoDisplay. Now as per requirement I can add more

  Artist to Existing Video.

So I take this approach:-

$node_vids = node_load($videoId);
$node_vids->field_artist[LANGUAGE_NONE] = array(
               0 => array('nid' => $form_state['values']['nid']));
$node = node_submit($node_vids);
node_save($node);

But it gives me error saying:

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  'node-143-0-0-und' for key 'PRIMARY'

This error comes up while inserting data in Video(Type:Video Embed Field). But here I want to save Artist(Type : Node Reference Field) field only. I get to know that node_save actually saves all the attributes of Content Type.

After searching net I try to use field_attach_update() but again it is throwing
same exception. Please let me know any solution to  get out of this problem.

field_sql_storage_field_storage_write() function exposed by Drupal helps to update desired single field only. Calling this will not invoke any hooks.


Upgraded to 7.31 but getting "no pending updates" message After copying over the files for 7.31 (was 7.26), minus the /sites folder, and running update.php, the result is "no pending updates." I followed the instructions at https://www.drupal.org/node/1494290 properly - any thoughts about what to do next? Thanks.

Go to '[your-website]/admin/reports/status' and if there you see that Drupal version is 7.31 (which you probably will see), if there is no some other errors and everything works fine on website you successfully did update.

It is not necessary to always have database update if you are updating some module or Drupal itself.


How do you disable Cron on a staging / dev server? I have a staging and dev setup, but I wonder if I can disable cron on these as I don't want cron firing. It's mainly because I have backup migrate module scheduled to backup my site everyday, but I don't want this executing every time.

Yes, you can do this in your settings.php file (as you have mentioned that is the only difference between versions).

You would do it like this (in your settings.php file):

// Disable drupal's built in cron trigger.
$conf['cron_safe_threshold'] = 0;

For more information see Defining variables in a site's settings.php $conf array.

Edit
How this works is:

Variables are loaded from the database (or the cache if they have already been cached).
If those variables were not already in the cache they are saved to the cache.
The $conf variables from the settings file are added to the variables and take precedence over variables from the database.

So variables from the database are cached, but variables from settings.php are not.


Views block that shows all references to current node (cross references) I'm confused with views filters and relations...
In my articles I have a field (field_article_reference_nodes) that references other nodes and shows these as a link.
Now I want to attach a view to other nodes that lists all articles referencing them.
So this is kind of a cross reference.
How do I have to set the filters/relations for this view to list all articles that are referencing the current node?
Thanks for your support!
Mathias

After knowing that this approach is called "reverse entity reference".
I found this tutorial:
https://mushtaq.ch/blog/4/drupal-8-reverse-entity-reference-in-view
But in step 3 I needed to use "Content USING field_myfield" instead of "Content referenced from field_myfield".
Thanks for your help!


Copying multiple components from another webform? I have a bunch of webforms, threre are a lot of repeating fields just in different order or with different conditionals / labels. I want some plugin that would allow me to copy elements from existing webform to new one.

Is there such thing?

You can use Webform Template:

This module allows to easily copy webform configuration from one node to another (including all webform fields). If I remember well it copies all fields, you can't select wich fields to copy.

I've used it and worked fine.

EDIT: Adding more info:

The module doesn't allow you select which fields are going to be copied. Anyway, the module's code not long and it may be easy to add this funcionality. The module also triggers some cusom hook to modify webform (hook_webform_template_insert and hook_webform_template_update).

I think this would be a good starting point.

The heavy lifting seems to be done in the webform_template_node_update (hook_node_update).

// Insert the components into the database.
if (isset($node->webform['components']) && !empty($node->webform['components'])) {
  foreach ($node->webform['components'] as $cid => $component) {
    $component['nid'] = $node->nid;
    webform_component_insert($component);
  }
}

// Insert emails.
if (isset($node->webform['emails']) && !empty($node->webform['emails'])) {
  foreach ($node->webform['emails'] as $eid => $email) {
    $email['nid'] = $node->nid;
    webform_email_insert($email);
  }
}


Migrate rows of files for nodes I've got a CSV where every row contains details about a node and then a URL to a file.

Each of the nodes rows has an id number associated representing each specific node.

So eg:

id, node name, file url
1, farfitnugen, /documents/foo.pdf
1, farfitnugen, /documents/bar.pdf
2, farfitnugen, /documents/2foo.pdf
2, farfitnugen, /documents/2bar.pdf

Using the example above, I've got the migration working such that it creates one record for each node, and downloads and links the appropriate file, but it does not cycle all the entries.

I'm currently mapping by the id, can anyone provide a suggestion of how to get Migrate to import all the documents per node?

I coded two imports; one for the files and one for the nodes.  The nodes import then references the files using the oncomplete callback that the migration api provides.
Thank you to the Drupal irc channel for pointing out the oncomplete function.

Special thanks to stack exchange for the most depressing achievement ever, the tumbleweed.


Drupal 7 - Node Clone Alternatives just want to ask if there are any other suggested alternatives for cloning a node for drupal 7. Now I know most of you will answer "Node Clone Module", but is there any other module out there that can do the same thing? Thanks.

"Drupal way" is to collaborate, not compete. It means that anyone wanting to write his own cloning solution will be asked to cooperate with author of existing one to provide what he finds lacking. Only if that's not possible, and some basic differences in approach or expected results are found, community will welcome new module. Otherwise it'll just die silently, unloved.

That said, you can use node exporting and importing tools to export nodes, edit them or not and import again, possibly under new nid. Node export is example of modules that can do that. Probably there are other ways to get content duplicated, and if you can think of basically different scenario, there is a big chance someone got that implemented.


Views Php how to select actual term name not term ID How to select term reference field with variables in views global PHP field?  I need to not Term ID, but actual term name. My views is fields of a content type that contains term reference field. And php field selects term reference fields as term ID. But I need actual term name.

You can either create a relationship with taxonomy in order for the term name to be available in views as a field, or use taxonomy_term_load().


Is there is any module which creates new users by reading a spreadsheet/excel file? Could anyone tell me if there is any module which creates new users by reading a spreadsheet/excel file? I have added few more fields to the user registration form, and that might make this a bit tricky! Any suggestions would be helpful.

Try out the user import module

  Import users into Drupal, or update existing users, with data from a
  CSV file (comma separated file). Provides a wide range of features out
  of the box, and a comprehensive API to customise imports.


How do I set a node/page's background image to that content's image? I've installed both 'Background Image' and 'Dynamic Background' but am having trouble trying to configure them for my situation. In the website I am trying to edit, there are content types of 'Performer,' 'Venue' among others. Now each content type has an image as one of their fields and I would like to have that image as the background image for that content's page.

Background Image only gives me option to do this for 1 content type, and when I tried setting it up, nothing appears.

I'm pretty sure I could do this with Dynamic Background, but the process would be really inefficient; I would have to add the pictures again to Dynamic Background's library.

So is there another way to do this? Or what can I do with Background Image to make it work?

This can be done without installing extra modules:

Add an image field in the content types you want to enable a dynamic background image.
Use this code:
template.php:

function THEME_preprocess_page(&$vars) {
    if (!empty($vars['node'])) {
        $node = $vars['node'];
        if (!empty($node->field_background_image)) {
            $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
            $vars['background_image_css'] = 'style="background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC;"';
        }
}
}

Add this in your div#content in page.tpl.php:

print (!empty($background_image_css)) ? $background_image_css : ''; ?>

Updated version: template.php:

function THEME_preprocess_page(&$vars) {
 $node = menu_get_object('node');
 if (!empty($node) && !empty($node->field_background_image)) {
        $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
        drupal_add_css('div#content {background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC; }', array('type' => 'inline'));
 }
}


Views with filter on "main" and "additional" taxonomy terms My articles are organised in a taxonomy, where each article has multiple taxonomy terms. I now want to build views for my front page, where each view represents a part of the taxonomy.

However articles can have tags from multiple parts of the taxonomy, but here, each article should only appear in one view. Is there a simple way to somehow in the admin interface mark one taxonomy term as "main term", such that in the front page views, the article only shows up for the view which shows this "main term"?

What I have tried so far is to have two taxonomy fields for my article, one for "main term" and one for "additional terms". However when building the view with the filter "has taxonomy terms (with depth)", there seems to be no way of specifying that I only want it to look in the "main term" field. Is this approach viable and how would I build the view?

You should use the Representative Node pattern. That is that your View on the taxonomy refers to another View that collects a Node based on a particular filter (a checkbox in your example but just as easily a flag like "Sticky" or "Promoted").
There are two representative node patterns in Drupal 7. The first, which is builtin to Views, is a little less flexible (you can only sort on one parameter and you can only get one result). The second is the contrib module Views Field View which has fewer limitations but is a little harder to set up (you have to pass the contextual filter yourself).
Views 3

Firstly create a View on Content (filtering on Articles) with a contextual filter on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
Next create a View on your Taxonomy and have it list out the terms.
Add a Relationship (Advanced > Relationship) using Taxonomy term: Representative node
Sort on your specifier (your checkbox field or sticky/promoted)
Select your first View on Articles and apply.
Add a field Title and use the Representative node relationship. Continue adding fields using the relationship.

Views Field View

Firstly create a View on Content (filtering on Articles) with a contextual filter on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
Then limit the number of results. Possibly 1 in your case. Turn off paging.
Lastly filter on how you want to select your Representative node. The checkbox, or stick/promoted.
Next create a View on your Taxonomy and have it list out the terms.
Add a hidden tid (term ID) field
Optionally add Title and other fields.
Then add a field of type Global:View
Select your View previously created. Pass in the term ID.


How do I use webform tokens in my PHP code for the form submission page? I see this in webforms, but I don't know how to use these in my result page, as print_r(%value) doesn't print anything.

  Submission tokens

  %sid - The unique submission ID.
  %value[key] - A value without additional formatting. Elements may be accessed such as %value[fieldset_a][key_b]. Do not include quotes.

These won't show up in the results page.  I think these are only useable when the form is submitted.  One thing that confused me for a while was the [fieldset].  If the value you are trying to access is not in a fieldset it is [Root].

Name:  __

%value[Root][name]  would be most likely way to access that value after the form is submitted by the user.

(%email works also if you are going to send an email, but that also shows the label)

Hope this helps and is actually what you need help with.

-Marc


File Framework for Drupal 7? File Framework is a collection of modules which allow uploading, converting and displaying different media type files as Drupal nodes.

  Metadata is extracted from uploaded files using EXIF, getID3, pdfinfo
  and stored as Resource Description Framework (RDF).

  A node of type file is created for each uploaded file. This gives a
  revision control and will integrate with views.

  Each file is converted to number of other MIME formats using available
  open source converters. For example a MS Word file can be
  automatically converted to PDF, OpenDocument Text (using OpenOffice
  daemon / LibreOffice + JODConverter), Plain text (using catdoc), Flash
  video (using SWFTools), JPEG (using GhostScript) and Zip (using gzip).
  Converted (derived) files are saved in the Bitcache and their metadata
  is extracted and saved in the RDF along with the relation to the
  original file. All derived files are listed and can be downloaded.

Unfortunatelly the module is available for Drupal 6 only.

Is there any similar solution available for Drupal 7 ?

Please follow http://drupal.org/node/1827110 if you are interested in File Framework port for Drupal 7.

I would suggest using Media as your starting point, and improving it if needed. That's the D7 solution aiming to solve similar problems to the File Framework (and other D6 modules).


Crumbs not adding home link to beginning I have installed Crumbs on the site I am currently working on and for some reason I can't get it to display the "Home" link.

I have tried debugging some of the nodes and according to the results the home link should be displayed.

The home link is definitely enabled and there isn't any CSS or anything like that which may be interfering with it, am I missing something?

How to find out why not seeing the home link in bredcrums Drupal 8.

Check your theme (admin/appearance/settings/THEMENAME)

Some themes like bootstrap can set to show or not.
Check modules for any 'hook_system_breadcrumb_alter'

These can alter how bredcrums work.
Check modules for any services tagged with - "{ name: breadcrumb_builder" (same as above)
Check theme templates for any templates overriding core bredcrums or .theme overrides
Check if the block is enabled (admin/structure/block)
Cry


Programmatically change logo I tried two versions:
1.

$form_state = array();
form_load_include($form_state, 'inc', 'system', 'system.admin');
$form_state['values']['var'] = 'theme_settings';
$form_state['values']['logo_upload'] = file_save_upload('/path/to/logo.jpg');

drupal_form_submit('system_theme_settings_submit', $form_state);

2.

 variable_set('logo_path', '/path/to/my/uploaded/logo.jpg');

but none of them worked.

That setting is part of the theme settings variable; each setting is put in an array and that array is serialised as the value of the main theme settings variable.

You can set this value programmatically like so:

$theme_name = 'garland';
$var_name = 'theme_' . $theme_name . '_settings';

$settings = variable_get($var_name, array());

$settings['logo_path'] = $new_path;

variable_set($var_name, $settings);


Bulk action on views only works for the administrator role? I have a view with a VBO field to execute a bulk operation over nodes.

The bulk operation for this VBO field is a rule component (which I have created) Get Voucher

This component execute some actions.

Now in the view I can execute the VBO only if I'm logged as a administrator. But not with any other role.

I make sure that the permission of all action are enabled. But the action for the component Get Voucher is not listed here.

The button for the bulk operation is shown but when I click it nothing happens.

Which other permission do I need to enable?

UPDATE 1: I know that the problem is related to the actions executed in the compoment. Here is the exported component

UPDATE 2: trying with a more simple component (just one action to show a message)

{ "rules_test_registered_user" : {
    "LABEL" : "test registered user",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "DO" : [ { "drupal_message" : { "message" : " Hello" } } ],
          "LABEL" : "first rule"
        }
      }
    ]
  }
}

If using Action Permissions, under Admin > People > Permissions, double check the "Execute action name" permission is enabled for the role(s).

It may also be that the user role needs permission to eval that php code in the Rule as well as possibly a userpoints grant points permission required.

Lastly, check the Rules module user permissions and also in edit form for the actions on the rule itself.


What is public static function create() in plugins for? Sometimes I encounter a function public static function create with arguments in plugin classes.

For example, here https://www.sitepoint.com/tutorial-on-using-drupal-8-plugin-derivatives-effectively/
we can see it.

public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity.manager')->getStorage('node')
    );
  }

Could you clarify me, what is the function for? What should it do and where is it used?

create() is a factory method for dependency injection.

Plugins which implement ContainerFactoryPluginInterface are instantiated by create() of the plugin class:

ContainerFactory::createInstance

public function createInstance($plugin_id, array $configuration = []) {
  ...
  // If the plugin provides a factory method, pass the container to it.
  if (is_subclass_of($plugin_class, 'Drupal\Core\Plugin\ContainerFactoryPluginInterface')) {
    return $plugin_class::create(\Drupal::getContainer(), $configuration, $plugin_id, $plugin_definition);
  }

  // Otherwise, create the plugin directly.
  return new $plugin_class($configuration, $plugin_id, $plugin_definition);
}


Tokens in blocks configuration for List only pages I want to set a block to visible only for a certain path, with the logged in user id, like my-path/[user:uid].  I feel like I should be able to just do that.

How can I do this?

1) Enable the core PHP filter module

2) Use php in the visibility setting of your block. Notice that the path 'mypath' must be registered somehow before using this code. I mean that if the path 'mypath' does not exist at all any code here will not work.

<?php
global $user;
$uid = $user->uid; // Get the logged in user id
// If the path is 'mypath/myarg' then arg(0) is 'mypath' and arg(1) is 'myarg'.
$show = (arg(0) == 'mypath') && (arg(1) == $uid); // It must return both TRUE

return $show;
?>

Alternative, use the Context module.


webform2pdf blank page I am using webform2pdf. I'm having an issue with the download PDF button; it goes to a blank page when it goes to a path like /node/3/webform-results/downloadpdf. Does anyone have a fix for this?

what PHP errors do you get when errors are set to be shown on the website from your php.ini or htaccess file. webform2pdf has a dependency on TCPDF library and they often become out-of-sync with one another. So as a developer you need to be sure you're using the recommended versions of the required dependencies.


I can't remove comma after currency in commerce price In my project I had to change currency code from USD to IRR (Iranian Rial)

but in Persian language after currency, there is always a "," character in rendered price (in price component or formatted amount).

Anyone knows how can we get rid from this comma.

In commerce.currency.inc the currency is defined as:

'IRR' => array(
  'code' => 'IRR',
  'numeric_code' => '364',
  'symbol' => 'REMOVED_DUE_TO_SE_ERROR',
  'name' => t('Iranian Rial'),
  'symbol_placement' => 'before',
  'symbol_spacer' => ',',
  'code_placement' => 'hidden',
  'minor_unit' => t('Rial'),
  'major_unit' => t('Toman'),
  'decimals' => 0,
),

If you wanted to override this and set the thousands_separator (not present) to and empty string. You can do this in hook_commerce_currency_info, documented here http://cgit.drupalcode.org/commerce/tree/commerce.api.php?h=7.x-1.x#n11

You need to set it as, let's say '' because the defaults are the following for missing properties:

  $defaults = array(
    'symbol' => '',
    'minor_unit' => '',
    'decimals' => 2,
    'rounding_step' => 0,
    'thousands_separator' => ',',
    'decimal_separator' => '.',
    'symbol_placement' => 'hidden',
    'symbol_spacer' => ' ',
    'code_placement' => 'after',
    'code_spacer' => ' ',
    'format_callback' => '',
    'conversion_callback' => '',
    'conversion_rate' => 1,
  );


Attach file to post using C# RestSharp and Drupal Services I'm writing a C# app that posts to Drupal using Rest calls to the Services module, I can connect and create new nodes easily but I cannot figure out how to attach files to the nodes.
Using the RestSharp library for C#, this is the code:

var request = new RestRequest("...node/12/attach_file.json", Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddCookie(my_session_name, my_sessid);
request.AddHeader("X-CSRF-Token", restResponse.Data.token);
request.AddParameter("field_name", "field_done");
request.AddFile("file", @"C:\pathtomyfile.png");
var response = client.Execute(request);

No errors are returned, status is 200 but the response is empty and nothing is uploaded in Drupal! And by the way the node date looks like modified, so something worked...!

The AddFile method of RestSharp is multipart and so the attach_file of Drupal:

  Upload and attach file(s) to a node. POST multipart/form-data to node/123/attach_file

Any help?

I have figured it out this way, sorry for late posting the answer:

// FIRST LOGIN
var client = new RestClient("http://....../");
var request = new RestRequest("user/login.json", Method.POST);
request.AddHeader("Content-Type", "x-www-form-urlencoded");
request.AddParameter("username", username);
request.AddParameter("password", password);
var restResponse = client.Execute<Login>(request);

Now upload a picture:

public string UploadPic(string path, Login login)
{
    var request = new RestRequest("file.json", Method.POST);
    request.RequestFormat = RestSharp.DataFormat.Json;
    request.AddCookie(login.session_name, login.sessid);
    request.AddHeader("X-CSRF-Token", login.token);
    request.AddParameter("uid", login.user.uid);
    string filevalue = System.Convert.ToBase64String(file_get_byte_contents(path));
    request.AddParameter("file", filevalue);
    request.AddParameter("filename", path.Split(new Char[] { '\\', '/' }).Last());
    var response = client.Execute<DFile>(request);

    return response.Data.fid;
}

static byte[] file_get_byte_contents(string fileName)
{
    byte[] sContents;
    if (fileName.ToLower().IndexOf("http:") > -1)
    {
        // URL
        System.Net.WebClient wc = new System.Net.WebClient();
        sContents = wc.DownloadData(fileName);
    }
    else
    {
        // Get file size
        FileInfo fi = new FileInfo(fileName);

        // Disk
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        sContents = br.ReadBytes((int)fi.Length);
        br.Close();
        fs.Close();
    }

    return sContents;
}

Where the class Login and DFile are the following:

public class DFile
{
    public string fid { get; set; }
    public string uid { get; set; }
    public string filename { get; set; }
    public string uri { get; set; }
    public string filemime { get; set; }
    public string filesize { get; set; }
    public string status { get; set; }
    public string timestamp { get; set; }
}
public class Login
{
    public string sessid { get; set; }
    public string session_name { get; set; }
    public string token { get; set; }
    public User user { get; set; }
}


Invalid response object from API: (HTTP response code was 0) I am using Ubercart and stripe and enabled  this module its working great for my dev version which is HTTP but when I use similar at live site having HTTPS I get below error.

Please suggest what I am doing wrong or what i need to resolve it, I tried searching it tried support but not able to find any solution.

Please suggest!

  Payment failed for order 32: Stripe Customer Creation Failed for order
  32: Invalid response object from API: (HTTP response code was 0)

Thanks!

I downloaded the stripe api and ran all it's unit tests. That way I could find that curl was disabled. By enabling following functions in php, all unit tests succeeded and it got working:

shell_exec
proc_open
curl_exec


Ubercart 2.x drupal 6 combo attributes price Is it possible to set a different price for each combination of attributes in Drupal? For example when A and C, the price is $10; when I select B and C, the price is $12; when I select B and D, the price is $13.
I see http://drupal.org/project/uc_custom_price; it works, but I have too much combination for each product. There is a module, http://www.ubercart.org/project/attr_combo_price, but it is for Drupal 5.

Are there any other solutions?

Would Ubercart Attribute Tokens help you out here?


How get empty record on date field with entityQuery? I am on a custom entity with custom fields and i try to get all empty record on date field :

Field was create with CCK, so the field storage has a table.

  $query = \Drupal::entityQuery('test_entity');
        $query->condition('field_date',NULL,'=');
        $ids=$query->execute();

This doesn't work for date field.

Since the field is stored in a single table, this is how i get all empty record from my entity where my custom field is empty :

 $query = \Drupal::entityQuery('test_entity');
        $query->notExists('field_date');
        $ids=$query->execute();


Cache not clearing on expiry Using the steps explained here: http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 I'm storing an array with specified expiry time.

But what is happening is that even after expiry of time, the cache_get is returning the stale cache. Even Cron run is not deleting the cache entry(I've checked the cache_block table).

This is the code:

     $out = &drupal_static(__FUNCTION__);

        if ( !isset($out)) {
            if ( ( $cache = cache_get(__FUNCTION__,'cache_block'))) {
                $out = $cache->data;
                dsm("cache returned");
            } else {

//do something
//...........
  $out = '
' . $out . "
";
            cache_set(__FUNCTION__, $out, 'cache_block', strtotime("23:59:59")+2);
        }//else ends
    }//!isset ends

    return $out;
}//function ends

Only cache clear all in the Performance tab is clearing this cache entry in the cache table.

I'm confused how this expired cache will be deleted.

In that article I can read this statement:

  Expired entries will be automatically discarded as they pass that
  date.

But does not seem to be happening. Also I've verified that "expire" value in the cache table is beyond current time.

I can clear the cache myself but then cache_get function does not return the "expire" time in the table.

Anything I'm missing here?

As you can see in the documentation:

  $expire: One of the following values:

  CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
  CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
  A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.

Please note - it's not "at most". It's "at least". So your code works just the way it is to be expected. If you want to force-expire it, use cache_clear_all( __FUNCTION__ , 'cache_block'), for example in hook_cron() or at the beginning of your code.

Also note that it looks like you are re-saving cache at each use. That's not an usual thing, saving data is CPU and HDD expensive. It costs more than not caching at all. So consider only setting cache if it was not found in the first place, and needs to be regenerated. If cache is already set, let it expire and don't set it again.


Exposed Filter not shown in view which has a Custom Filter Handler I have a view and I programmatically created a filter for this view. (I pasted the code below).

This filter works fine but I had other Exposed Filter created inside the view (created by clicking add filter in the view).

Now the filter added programmatically is working fine but the other one is not shown at all.

If I disable the filter added programmatically then the other one is shown correctly. So the problem is in the code I guess.

I need both filter working together.

here is the code which adds the filter:

/**
 * Implements hook_views_pre_view().
 */
function vouchers_views_pre_view(&$view, &$display_id, &$args) {

   if ($view->name == 'vouchers') {
    $info = array(
      'table' => 'field_data_field_labpoints',
      'field' => 'field_labpoints_value', // name of value field in that table.
      'value' => array('value' => userpoints_get_current_points()), // dynamic part.
      'operator' => '<',
      'id' => 'field_data_field_labpoints_vouchers', // unique id.
      'group' => 100, // new group.
    );
    $handler = views_get_handler($info['table'], $info['field'], 'filter');

    $handler->init($view, $info);
    $view->display_handler->handlers['filter'][$info['id']] = &$handler;

    unset($handler);
  }
}

I would do this by adding a contextual filter, previously called an argument in D6 Views. You can set contextual filters / arguments in code when you embed a view. So, you could add a contextual filter for field_labpoints (not sure what kind of field this is) and pass along the argument you want to filter for when you embed the View in a .tpl file or a panel or whatever:

print views_embed_view('my_view_name', 'block_1', $labpoints_value);

This allows you to make the View more dynamic without tinkering with the existing filters.


Additional old_XXXXXXtaxonomy_term__field_XXX Tables after upgrading After Upgrading from Drupal 8.6 to 8.7 I have tons of new (garbage?) tables in the database. The naming schema for the tables is old_XXXXXXtaxonomy_term__field_XXX

Is there a drush command to remove them or can i just drop dem directly?

I tried drush eval "field_purge_batch(5000)" and drush entity-updates without success.

Not sure there is an automatic way to do this, a manual way would be to use:

echo "Show tables;" | drush @alias sql-cli | grep old > drop_tables.sql

Edit the tables.txt file and add drop table and a ; after each table name.  Each line should look like:

drop table old_XXXXXXXtaxonomy_term__field_XXXX;

Backup you database in case Murphy come's around and do:

drush @alias sql-cli < drop_tables.sql

That will remove them from the DB.

Alternative way to do it via a GUI would be to use MySQL Workbench and drop them thru the interface.


How can I query and order nodes with multiple date field values within a specific range? I'm trying to get nodes that have date fields (multiple instances in some cases) and display them sorted ascending by start time for a given date. For illustrative purposes, here are some events and their date field values (start time).

Event A

4/2/17 8:00AM
4/3/17 2:00PM

Event B

4/3/17 11:00AM
4/3/17 5:00PM

Event C

4/3/17 6:00PM

Event D

4/4/17 4:00AM

I'm using EntityFieldQuery to gather the events with dates on 4/3/17 and order them using this code;

$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1)
->fieldCondition('field_datetime', 'value', array('2017-04-03/T00:00:00', '2017-04-04/T00:00:00'), 'BETWEEN')
->fieldOrderBy('field_datetime', 'value', 'ASC');

I get the nodes ordered like this;

A, B, C

but I want them ordered like this;

B, A, C

I guess the fieldOrderBy method is looking at all the date field values and ordering that way, which includes dates other than my target (4/3/17).

Anyone know how to accomplish this (with EntityFieldQuery or without)?

Are the date/time values stored as a varchar in your database? If I'm not mistaken, in that case the ordering is performed by comparing the String values (which is inline with the outcome of your example, i.e., A:2, B:5, C:6).

You could alter your query, using hook_query_alter(), and cast/convert the datatype to datetime (not sure whether every database supports this).

The easiest solution would be to sort the query result afterwards, using the usort() function and in your comparison function you can use PHP's DateTime object or the strtotime() to compare the values.


Can't add column to renamed table When I first developed this module internally (not on Druple.com) the module_schema function created a table with the same name of the module (it was the only table, so it made sense. Short sighted.).

But I now need a 2nd table, so the first table should have a more sensible name. There is also a requirement for an additional field in the original table.

 function afd_pce_update_dependencies(){
   // update_7201 needs to run after update_7200.
   $dependencies['mymodule_field_mappings'][7201] = array(
     'mymodule_field_mappings' => 7200,
   );

   return $dependencies;
 }

 function mymodule_update_7200(){
      db_rename_table('mymodule', 'mymodule_field_mappings');
    }

 function mymodule_update_7201(){
   $spec = array(
     'type' => 'varchar',
     'description' => "The fieldset that this mapping belongs to",
     'length' => 15,
     'not null' => FALSE,
   );
   db_add_field('fieldset_type','mymodule_field_mappings',$spec);
 }

When I run update.php I get the error

Update #7201
Failed: DatabaseSchemaObjectDoesNotExistException:
Cannot add field fieldset_type.
mymodule_field_mappings: table doesn't exist.
in DatabaseSchema_mysql->addField() (line 325 of
{filepath}\includes\database\mysql\schema.inc).

I think your mixing up table names and module names in hook_update_dependencies().

First of all, you don't need hook_update_dependencies() to declare dependencies inside your own module. The updates will always be run sequentially, so that mymodule_update_7200() will always run before mymodule_update_7201().

Then, if you want to use hook_update_dependencies(), you would use it to declare inter-module depenencies like this:

function mymodule_update_dependencies(){
  $dependencies['mymodule'][7201] = array(
    'other_module' => 7203,
  );
  return $dependencies;
}

Now to your error. Can you check in the system table record for your module what the current schema version is? From the code and the error message I would suppose, that the database is already at schema 7200 (at least officially) but that somehow the renaming has not been done. Is it maybe possible that you have altered the database manually?

Edit: You are mixing up the arguments to db_add_field. It must be db_add_field('mymodule_field_mappings', 'fieldset_type', $spec);


How to set alias pattern of node's source alias? When I translate a node I want that node's path alias to be like it's source node's path alias.

So in the url pattern for the translation nodes I use the token:

  [node:source:url:path]

which according to this thread should be fine. But, it actually generates the alias "/node-402-0", although the source node has a path like "/welcome".

I have the feeling that in the token module the wrong language is being looked into.

Am I missing something?

I think you can set the alias to not be translated in the the content language settings (Admin->Config->Regional->content language.

Under each content type there should be a url alias option. Unchecking this should make the alias the same for all languages.


Adding a specific field of a content type in the display of another content type Sorry I didn't know how to put my question easily, so I detail my problem here.

I use Entity Reference to reference various fields in my contents, and it works good.

Now, I have a "Fruits" content type, with a field named "Picture".

I have another content type, which contains a reference to the fruit "Name", but I want to display the picture and not only the name.

How can I do ?

With entity reference there are a couple ways to go about this.

You can select the view mode to display (i.e 'teaser') on the display ui of the other content type and then on the 'Fruits' field display ui for the view mode teaser show only the picture. If you use the title module, you'll be able to hide the title on the teaser. If you don't want to use the title module there are other approaches to hide the title.
You can create a view using entity views attach and set up a relationship and then display only those fields. This is more complicated and not as maintainable, I recommend going with #1.

Hope that helps


Add taxonomy terms into submenu I'm currently using drupal 7. I want to create an album gallery with different category. I wish to put "Albums" in the main menu, with the categories as sub menu under "Albums".

I had created a content type "Album", and plan to use taxonomy to creating vocabulary and terms as category.

However, I wish to make it automated. Once I create a album category, it will automatically appear in the sub menu under "albums". And each category will link to the list of albums under the category.

Anyone knows how to achieve the effect?

For an action that is caused by an event I would use the Rules module.

Create new rule

Set rule name, etc.

Set event to act on - saving new term

Set a condition - term is in vocabulary album

Set action - add menu item

These options may not all appear with just Rules.  You may need additional rules modules to get some of these events, conditions, or actions to be available (I think there is one for menus and one for taxonomy, but they may be built in to rules i can't remember.).

Take what I said as a starting point to put you in the right direction.  Definitely sounds like what you want can be done with Rules.


Can webform conditionals require filling one of two fields? The snippet below is one of the ways I attempted to require that the user fill out at least one of phone no. and/or email using webform conditionals. This one came closest to working. The logic is both fields default to required but that requirement clears when the other field is filled out. It fails because webform interprets it as a circular reference.

Any suggestions? I don't have the technical wherewithal to attempt the answer to question 87889 so looking for a way to do this using webform conditionals. Question 63912 looked promising until I realized it dealt with Drupal fields and not Webform fields.

The Webform Validation module has what you are looking for (Require at least one of two fields).

  The following validation rules are currently included:
  Numeric values (optionally specify min and/or max value)
  Minimum length Maximum length Minimum number of
  words Maximum number of words Equal values on
  multiple fields Unique values on multiple fields
  Specific value Require at least one of two fields
  Require at least one of several fields Minimum number of
  selections required Maximum number of selections allowed
  Exact number of selections required Plain text (disallow
  tags) Regular expression Must be empty (anti-spam:
  Hide with CSS) Words blacklist Must match a
  username


How do I change the value of a Hidden element? I would like to change the value of a hidden element and, depending of this value, to show some elements in the form or not. I'm trying to implement hook_yamlform_element_info_alter(array &$elements) and I do $elements['hidden_element_name']['#value'] = 'New value of the hidden element' but it doesn't work.

Do you have any idea?

Based on @mradcliffe suggestion, I've implemented hook_form_FORM_ID_alter() and I do:

$form['elements']['hidden_element_name']['#value'] = 'New value of the hidden element';

It works for me! I hope it helps someone!


Continually adding fields to a form each time a button is pressed using AJAX I'm attempting to add fields dynamically to a form using AJAX in a block plugin however no action occurs when clicking on the button that is meant to add a field.
The code I'm currently is below

   class Standard extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $form_state->setCached(FALSE);
        $form['actions'] = array(
            '#type' => 'actions',
        );
        $form['column']['columnNum'] = array(
            '#type'          => 'value',
            '#default_value' => $this->configuration['columns_submit'],
        );

        $form['column_wrapper'] = array(
            '#type'       => 'container',
            '#attributes' => array(
                'id'         => 'column_wrapper',
            ),
        );
        for ($i = 1; $i <= $this->configuration['columns_submit']; $i += 1) {
            $form['column'][$i] = array(
                '#type'           => 'details',
                '#title'          => t('Column '.$i),
                '#open'           => FALSE,
                'group'           => 'Content',
                'body_text'       => array(
                    '#type'          => 'text_format',
                    '#title'         => $this->t('Body'),
                    '#default_value' => $this->configuration['column'][$i]['body_text_submit']['value'],
                ),
                'class'           => array(
                    '#type'          => 'textfield',
                    '#title'         => $this->t('Class'),
                    '#default_value' => $this->configuration['column'][$i]['class_submit'],
                ),

            );
        }
        $form['addcolumn'] = array(
            '#type'     => 'button',
            '#name'     => 'Add Column',
            '#value'    => t('Add column'),
            '#submit'   => array($this, 'addColumnSubmit'),
            '#ajax'     => array(
                'callback' => [$this, 'addColumnCallback'],
                'effect'   => 'fade',
                'wrapper'  => 'column_wrapper',
            ),
        );
        return $form;
    }
    public function addColumnSubmit(array&$form, FormStateInterface $form_state) {
        $this->configuration['columns_submit'] += 1;
        $form_state->setRebuild(TRUE);
    }
    public function addColumnCallback(array&$form, FormStateInterface $form_state) {

        return $form['column'];
    }

Nothing occurs when clicking the $form['addcolumn'] button. I've based my attempts on examples such as this one https://www.drupal.org/node/2723033. (I understand that is an example of it not working, but based on the comments it seemed like an error that was easily fixed)
I'd like to be able to continually add fields each time the button is pressed. Is there something wrong with my code? Is there a proper way to continually add fields when a button is pressed to a form using AJAX?

Update: I made another attempt which failed as well.

I used

    if (empty($form_state->getValue('columnNum'))) {
        $form_state->setValue('columnNum', 1);
    }
    $columnNum = $form_state->getValue('columnNum');

in BlockForm()

and

    $numColumns = $form_state->getValue('numColumns');
    $numColumns += 1;
    $form_state->setValue('numColumns', $numColumns);
    $form_state->setRebuild(TRUE);

in addColumnSubmit()

Assuming all your logic for $form[‘column’][$i] is correct, you can try replacing '#attributes'

$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#attributes' => array(
            'id'         => 'column_wrapper',
        ),
    );

With '#prefix' and '#suffix'

$form['column_wrapper'] = array(
        '#type'       => 'container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

And then in the callback get the values from the complete form.

public function addColumnCallback(array $form, FormStateInterface &$form_state) {
    $form = $form_state->getCompleteForm();
    return $form['column'];
}

I had a similar problem, Ajax does rebuild the form, but using “old” values, so after the $form[‘column’][$i] is completed and calculated, Ajax then just overrides it with the previous $form[‘column’][$i].
If that makes sense.


Drush not selecting database I'm using a Vagrant environment generated from https://puphpet.com/ for a Drupal project & it is all going well except for Drush which gives me an error any time I try running "drush cc -all", see the error below.

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected: SELECT 1 FROM {blocked_ips} WHERE ip = :ip; Array
(
[:ip] =&amp;gt; 127.0.0.1
)
in drupal_is_denied() (line 1933 of /var/www/includes/bootstrap.inc).

Additional

PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected: SELECT * FROM {system} WHERE type = &amp;#039;theme&amp;#039; OR (type = &amp;#039;module&amp;#039; AND status = 1) ORDER BY weight ASC, name ASC; Array
(
)
in system_list() (line 165 of /var/www/includes/module.inc).

Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]

From what I gather the problem is that it isn't selecting a database. Does anyone know where the details for this would be stored? The Drupal site itself is connecting & using the database fine.

I'm not sure if this would cause and issue but the database details for the Drupal site are stored as an Apache environmental variable.

What you are seeing above is a bug in Drush where Drush cannot bootstrap the database of a Drupal site if the database credentials are correct, but the database itself is empty.  To fix this problem:

If your database is empty, run "drush site-install" to create a database.
If your database is not empty, check the settings of your database prefix, and make sure that it is correct.

This was recently fixed in https://github.com/drush-ops/drush/pull/1442.


How to update fields of a new node created using Rules? I have created a content type called Tasks that helps me track things I need to do on my site. I am trying to create a rule that when some content is published, a new task item is created reminding me to do some follow up work.

I created a rule that when the new content is published, a new task item is created.  I did this by adding Create a new entity to the Actions section.  I can give the item a title and set the author, but I can't figure out how to update the other fields in the new Tasks item.

Can this be done using rules or do I have to write PHP code to accomplish this?

In Rules you have to add those fields as conditions - "Entity has x,y,z field" - then they will become available for your actions


When term is not selected, output specific text I have a content type, Article with a field 'Category' as term reference to 'category' taxonomy.

Category taxonomy has 2 terms, 'Live' and 'Outdoor'

Field's widget type is 'Check Boxes'.

When Live is checked, it should say 'Program is Live'
When Live is NOT checked, it should say 'Program is NOT Live'

When Outdoor is checked, it should say 'Program is outdoor'
When Outdoor is NOT checked, it should say 'Program is indoor'

Creating a terms view and using conditional field in view, I can check either value is empty or not, and can out put the desire result if there is only ONE term. But cant be done using multiple terms in the vocab.

When both are selected or not, every time both conditions are called for each term. And the output is true or false every time.

You can use DDF module to implement this.
Module url is https://www.drupal.org/project/ddf


How can I POST x-www-form-urlencoded data from REST API plugin? In Drupal 8, the REST API plugin can have a serialization format, such as xml or json. This affects the accepted "request formats" for a resource.

Is it possible to add a format for application/x-www-form-urlencoded handling for the REST plugin? or does this need to be handled in a form controller instead?

While looking into this, I found this solution to accept form encoded POST data and respond with JSON:

<?php

namespace Drupal\example\Encoder;

use Drupal\serialization\Encoder\JsonEncoder as SerializationJsonEncoder;

/**
 * Decodes form data and returns JSON.
 *
 * Simply respond to form format requests using the JSON encoder.
 */
class FormJsonEncoder extends SerializationJsonEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['form'];

  /**
   * {@inheritdoc}
   */
  public function decode($data, $format, array $context = array()) {
    parse_str($data, $result);
    return $result;
  }

}

and then add the encoder to the example.services.yml

services:
  serializer.encoder.form:
    class: Drupal\example\Encoder\FormJsonEncoder
    tags:
      - { name: encoder, format: form }

After that, the "Accepted request format" can be selected on the rest plugin config page:

admin/config/services/rest/resource/example_rest_plugin/edit


How to perform a comparison in a rule to check all values of a multi-select list? I'm stuck with a simple problem, maybe someone can point me in the right direction...

I have a ContentType with a field, let's say it's a list of hobbies. It's a Checkboxlist, multi-select.

Users have an additional account field to select their favourite hobby (a single-select selectbox)...

Now, when a new content of that type is generated I wan't to send an email to all users who have a selected hobby from the list, selected as favourite in their profile.

--

I used "Fetch entity by property" to get the users with one of the selected hobbies.

I configured it that way:

Entity type - Value: User
Property - Value: Hobby (this is a single value, cause a user can only select one hobby)
Value - Data selector: node:hobbies:0 (and there is the problem: I can only compare it with the first value of the multi-select hobbies list)

Result: It triggers only correctly for the first selected hobby.

--

How can I configure it to take every selected value?

There is a switch to direct input mode button in the Value - Data selector section, after clicking it you'll see a select box with all the values of that field which now you can select.


Built in cache system doesn't work in Drupal 6 Recently, I have selected "Normal" (recommended for production sites, no side effects) of the Caching mode at admin/settings/performance; I can see the CPU usage is drop from 60-70 to 6-8 by accessing the Drupal site on the same PC. However, when I use another PC to access the Drupal site, the CPU usage is risen to 60-70 again. So is there any mis-configure on my Drupal site?

Drupal generates cache when a node, block, or view is rendered the first time. How much cache is served versus how much is generated on that request can depend on both that visitor's role and specific user account.

If two anonymous users hit the same page, the first anonymous user will trigger the cache to be generated for elements on that page, then the second anonymous user will receive those cached elements and the page will load faster for them.

However, if one authenticated user hits a page, then an anonymous user hits the same page, two different versions of a selection of elements on that page will be cached (for instance, if authenticated users are allowed to see a block, but anonymous users aren't).

Therefore, Drupal's caching mechanism works best when there are lots of visitors with the same permissions hitting the same non-personalized pages. If it's a site with users who sign in, and there are lots of permissions (especially field-level permissions) at play, Drupal's cache will be fairly ineffective for anything but static content nodes and blocks.


Create an Entity (Beginner) beginner here,

I am trying to follow the typical entity example and create my own entity in Drupal 7. So I basically changed the name from typical_entity_example_1 to source_entity and the test fails (see picture below). I'm not sure what I'm doing incorrectly, any advice would be much appreciated.

install file:

function source_entity_schema() {
  $schema = array();
  $schema['source_entity'] = array(
    'description' => 'The base table for source_entity.',
    'fields' => array(
      'teid' => array(
        'description' => 'The primary identifier.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'Entity title.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'Entity description.',
        'type' => 'text',
      ),
    ),
    'primary key' => array('teid'),
  );
  return $schema;
}

Module file:

<?php

function source_entity_info() {
  $info = array(
    'source_entity' => array(
      'label' => t('Source Entity 1'),
      'base table' => 'source_entity',
      'entity keys' => array(
        'id' => 'teid',
      ),
    ),
  );
  return $info;
}

Test file

class SourceEntityUnitTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Source Entity Test 1',
      'description' => 'Check existence and possibilities of source_entity.',
      'group' => 'Source Entity',
    );
  }

  public function setUp() {
    parent::setUp('source_entity');
  }

  public function testSourceEntity1() {
    $entity_description = entity_get_info('source_entity');
    $this->assertEqual($entity_description['base table'], 'source_entity', t("Entity type 'source_entity' exists."));

    $new_entity = entity_create('source_entity', array());
    $this->assertFalse($new_entity, t("Can't create an instance of source_entity because 'source_entity' entity type has not create callback."));
  }

}

Module file:
Hook name is source_entity_info()  insted of source_entity_entity_info()

    <?php

    function source_entity_entity_info() {
      $info = array(
        'source_entity' => array(
          'label' => t('Source Entity 1'),
          'base table' => 'source_entity',
          'entity keys' => array(
            'id' => 'teid',
          ),
        ),
      );
      return $info;

}


Hook or rules event to identify payment failure in Drupal commerce Is there any hook or rules event that will help to catch the payment failure in Drupal Commerce?

Thank you

There is no direct hook or event, but essential to payment transactions in Drupal Commerce is that they should be created for every attempted transaction, not just complete ones. This means when a payment fails, a payment transaction will still be created for your order. Thus you can hook into the payment transaction creation process (or use Rules on the related event) to look for failed transactions based on the transaction status.