Don't sanitize the more link in a view? Currently any HTML added to the "More link" output in a view is sanitized.  This is undesirable for me.  How can this be changed so that this field is not sanitized?

The most direct way would probably be to do something along the lines of...

function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && $display=='THE_DISPLAY_YOU_ARE_LOOKING_FOR') {

     $vars['more']= // the exact html you want to have in your more link

  }

}

If you would rather work with just templates, you can copy views-view.tpl.php to your theme and name it appropriately, eg, views-view--VIEW_NAME.tpl.php, and then modify the following in it:

<?php if ($more): ?>
  <?php print $more; ?>
<?php endif; ?>

to whatever you want $more to be.

Clear theme registry/caches and you should be all set in both cases.

ADDITION DUE TO COMMENTARY:

Gotcha.  However, the more link is generated from inside the view display plugin via render_more_link() and it eventually creates it by calling up a theme template via...

return theme($theme, $path, check_plain($this->use_more_text())); // D6

or

return theme($theme, array('more_url' => $path, 'link_text' => check_plain($this->use_more_text()), 'view' => $this->view)); // D7

...both implementations of which check_plain() the text entered via the UI.

So, in order for this to work via the UI, you will most probably need to craft up a new views display plugin without that check_plain() in there.

It also goes without saying that you will need to have implicit trust in the folks working with the UI to not enter any errant HTML in there.


Embed autocomplete textfield in a block I'm using the following code to embed an autocomplete field in a block. However the autocomplete process does not execute when I type in input:

function cse_block_info(){
    $blocks = array();
    $blocks['cse_search'] = array(
        'info' => t('CSE Search'),
    );

    return $blocks;
}

function cse_block_view($delta=''){
    switch ($delta) {
        case 'cse_search':
            // The subject is displayed at the top of the block. Note that it
              // should be passed through t() for translation. The title configured
              // for the block using Drupal UI supercedes this one.
              $block['subject'] = t('Title CSE block');
              // The content of the block is typically generated by calling a custom
              // function.
              $block['content'] = cse_block_content($delta);
            return $block;

        break;

        default:
        break;
    }

}

function cse_block_content($which_block){
    switch ($which_block) {
        case 'cse_search':
            $form['cse_search'] = array(
                '#title' => t('CSE Autocomplete TEST!'),
                '#type' => 'textfield',
                '#autocomplete_path' => 'cse/google/autocomplete',
            );

            // Adds a simple submit button that refreshes the form and clears its
            // contents. This is the default behavior for forms.
            $form['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Save',
            );

            return $form;
        break;

        default:
        break;
    }
}

I implement the same code as a stand alone system i:e not placed inside a block and the process works flawlessly.

Can anyone help with suggestions of why my attempt to place an autocomplete in a block does not work?

Your block content should look like this:

function cse_block_content($which_block){
  switch ($which_block) {
    case 'cse_search':
      drupal_render(drupal_get_form('my_custom_form'));
    break;

    default:
    break;
  }
}

function my_custom_form($form, &$form_state) {
  $form['cse_search'] = array(
      '#title' => t('CSE Autocomplete TEST!'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'cse/google/autocomplete',
  );

  // Adds a simple submit button that refreshes the form and clears its
  // contents. This is the default behavior for forms.
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Save',
  );

  return $form;
}


Add multiple user-roles in install profile I would like to create multiple roles with the same permissions in my install profile. To add one user in your install profile, it's quite simple. I use this snippet:

    // Make the new role
    $role = new stdClass;
    $role->name = 'User 1';
    $role->weight = 3;
    user_role_save($role);

    // Permissions to assign to the role.
    $perms = array(
    'access content',
    'access content overview',
    );

    // Grant the permissions. This function takes care of all necessary cache resets
    user_role_grant_permissions($role->rid, $perms);

I tried with an array, but it didn't work out. Drupal just ignored the array.

The Array didn't work out...:

    // Make the new role
    $role = new stdClass;
    $roles = array('Eindredacteur 1', 'Eindredacteur 2');
    $role->name = $roles;
    $role->weight = 3;
    user_role_save($role);

    // Permissions to assign to the role.
    $perms = array(
    'access content',
    );

    // Grant the permissions. This function takes care of all necessary cache resets
    user_role_grant_permissions($role->rid, $perms);

Anyone who can give me some advice?

This should work:

// Make the first role
$role = new stdClass;
$role->name = 'Eindredacteur 1';
$role->weight = 3;
user_role_save($role);
$roleid_1 = $role->rid;

// Make the second role
$role = new stdClass;
$role->name = 'Eindredacteur 2';
$role->weight = 3;
user_role_save($role);
$roleid_2 = $role->rid;

// Permissions to assign to the role.
$perms = array(
'access content',
);

// Grant the permissions. This function takes care of all necessary cache resets
user_role_grant_permissions($roleid_1, $perms);
user_role_grant_permissions($roleid_2, $perms);


How do I customise the header and footer using a page template for a particular content type? I have a content type.

I want to customise the node pages for this content type, I've used node--[content-type].tpl.php but I need to use a page template to customise the header and footer and page--[content-type].tpl.php doesn't work.

I've tried page--node.tpl.php, but this changes the home page as well, then i created page--node--[content-type].tpl.php which is not working.

Please help me.

Thanks

You can have page templates based on a content type, you just have to add some code so Drupal will recognise the template file: This link shows how to do this.

It depends on your Drupal version. You would think this would be default but for some reason, probably performance related, it is not.

For D7 add this to the template.php file in your theme directory.

<?php
function themeName_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}
?>

End now you can customize your footer header etc.


file_usage_add issue for compound field I have created a custom compound field which contains a managed_file element in the field widget form.

The issue I am having is not with saving the file, but with adding the file usage information.

I picked hook_field_presave based on some research, but this is not working for new content or translating the node.

function MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  switch($field['type']) {
    case 'FIELD_TYPE':
      foreach ($items as $delta => &$item) {

        // save file permenantly
        if ($item['IMAGE']) {
          $file = file_load($item['IMAGE']);
          $file->status = 1;
          file_save($file);
          file_usage_add($file, 'MODULE', 'FIELD_TYPE', $entity->nid);
        }
      }
      break;
  }
}

The issue here is that when I save a newly created node, at this point, $entity->nid has not been defined. This number is required by file_usage_add.

Is there another hook that I can use to do what I'm trying to do?

You could add the file usage by implementing hook_node_insert which gives you all node fields besides what you are looking for nid and the fid using file_load in that case you could add file usage


Views & Filter criteria I've got a filter criteria saying field xyz = NO. Old nodes meeting the criteria above do not get picked up by the filter. When I edit the node, and resave it, only then they appear in the view. Is there a reason for this?

Yes this is possible. You will have to create two or more filter groups which will be separated with an OR condition.

Click "And/Or, Rearrange Filter Criteria" from the drop down menu of the Filters section and then click "Create New Filter Group". After that drag the filters you want in the new filter group and change the condition separating the groups to OR from AND. I would do it as follows:

1st group

Content: Published Yes And

Content: Type = News And

Content: Xyz (xyz) = Yes

OR

2nd Group

Content: Published Yes And

Content: Type = News And

Content: abc (abc) = Yes


As a site builder, how can I learn when modules I use are (going to be) deprecated? I have a site that uses a relatively large number of modules (100+).  I do my best to keep up-to-date but recently I have become a little alarmed because I found that Heartbeat and Custom Breadcrumbs, two modules I use on my site, are likely to be deprecated in the near future.

I learned about Heartbeat's deprecation by visiting the module's page by chance when I was checking the documentation.  I learned about Custom Breadcrumbs possibly being deprecated from a comment here on Drupal Answers.

At the time I installed these modules (early last year), they were the most popular in their respective categories.  Heartbeat's maintainer was active and making releases every few weeks.

Now, a year later, they are being deprecated in favor of other modules.  I understand the reason for this, and I'm happy to migrate my site over to the replacement modules (well, maybe not happy, but I'll do it)-- however, I can't do this if I'm not informed that modules are going to be deprecated.  I only found out about these two by chance!

Is there any central resource that keeps track of deprecated modules?  Since I use so many, checking issue queues or even module's pages is not really a feasible option.

You could subscribe with RSS to tag data on projects such as:

Maintenance status: Unsupported
Development status: No further development

That can give you notice of deprecation assuming the relevant tag has been assigned to the project.


Changing the $from email in D6 contact_mail_user_submit() // Send the e-mail in the requested user language.
  drupal_mail('contact', 'user_mail', $to, user_preferred_language($account), $values, $**from**);

I wish to change the $from email to "do-not-reply@domain.com" to accommodate our email configuration.

$from is defined as $user->mail [here in the function][1] and I can't figure out how to override this via MODULE_form_contact_mail_user_alter.

You can implement hook_mail_alter() to do that, e.g.:

function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'contact_user_mail') {
    $message['from'] = 'do-not-reply@domain.com';
  }
}


How do I specify an image reference in a Drupal 8 REST POST request body? We have a content-type that includes a field of type Image.  There is also an image file that has been uploaded to Drupal.

We are trying to add new content via a Drupal 8 REST POST.  A new node is successfully created when the POST finishes, but the image field is never set.  Here is what we are trying:

POST to:   http:///entity/node?_format=hal_json
The normal 4 headers are set
POST Body:

{
    "_links": {
    "type": {
      "href": "http://localhost:8087/rest/type/node/product"
    }
  },
    "title": [{"value":"ProductC"}],
    "field_description": [{"value":"ProductC Description"}],
    "field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],
    "field_product_name": [{"value":"ProductCName"}],
    "field_product_n": [{"value":"prodC"}]
}

Any pointers on how to construct the "field_product_image" line in the payload to link the image to new content node?
Thanks

I tried again with just the image ID, and it worked perfectly. Thanks
  very much!

To elaborate...

After the image file has been created in Drupal, and you have the File ID you'll be ready to create/update Nodes. Instead of setting the src value on the image field you just need to set the target_id value.

Change this:

"field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],

To something like this:

"field_product_image": [{"target_id": 123}],

If you're using JavaScript this would typically be accomplished with 2 async calls. The first call would POST the binary file data to Drupal (or base 64 encoded string) to obtain the File ID, the second call (which takes places in the "success" callback of the first call) would then be used to create/update the node's image field with the new File ID.

The following d.o issue is an important one to follow and is very much related to the Question: https://www.drupal.org/node/1927648


Get select list Value in node template I have a integer selection list field in my content types with some key|Value options.

0|CEO
1|CTO
2|Manager

now in my template  I want get value. I try {{node.field_positon.value}} but it return me key value (it return 0 or 1 or 2 ).

My question is how can I get value of selection option in template file?

notice: I know I can paly with content.field_position ( but it put some markup wrappers around field),I want get it by node variable.

Just use the following, and you will obtain what you want to achieve.

{{ content.field_position[0]['#markup'] }}


I need to access individual elements of a node in my module I have the following query that fetches all the nodes of a certain type.

function shop_home_page() {
  $render = array();
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type AND n.status = :status';
  $result = db_query($sql,
    array(
      ':type' => 'music_albums',
      ':status' => 1,
    )
  );

  foreach ($result as $row) {
    $node = node_load($row->nid);
    $render['my_list'][] = node_view($node, 'teaser');
   }
  return $render;
}

How do I display in my page node elements such as $node-title, $node-body? I tried as $render['my_list'][] = node->title but it doesn't seem to work.
I also need to add a form with a buy button to each element. How do I attach it?

1) You can use code like the following:

$render['my_list'][] = array('#markup' => '<div>'.$node->title.'</div>');
$render['my_list'][] = array('#markup' => $node->body['und'][0]['value']);

2) Forms can be added similarly to node_view():

$render['my_list'][] = drupal_get_form('mymodule_buy_form_'.$node->nid, $node->nid);

I'm assuming you want the forms built with a single function, but with different id-s to work correctly (attached $node->nid for that). I also added an extra argument ($node->nid) since you may want to add it to every form in a hidden field to determine which form got submitted. Then you use hook_forms() to get the same builder function called for all the buying forms:

function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id, 'mymodule_buy_form_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_buy_form',
    );
  }
  return $forms;
}

The form builder function for this example:

function mymodule_buy_form($form, &$form_state, $nid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

And a submit handler:

function mymodule_buy_form_submit($form, &$form_state) {
  drupal_set_message('Form for node '.$form_state['values']['nid'].' submitted.');
}


computed field with product variation and content type Using Commerce Kickstart 2 distribution :

Question 1: Where should the computed field go to access fields from both the Content Type and Product Variation? Does the computed field belong to the content type or to the product variation?

Question 2: How do you reference one from the other?

ie - I thought...

$field_my_gauge = field_get_items($entity_type, $entity, 'field_needle_guage');
$field_my_type = field_get_items($entity_type, $entity, 'field_needle_type');
$field_my_st = field_get_items($entity_type, $entity, 'field_needle_style');
$field_my_len = field_get_items($entity_type, $entity, 'field_needle_length');
$vari_l = taxonomy_term_load($field_my_len[0]['tid']);
$vari_g = taxonomy_term_load($field_my_gauge[0]['tid']);
$vari_t = taxonomy_term_load($field_my_type[0]['tid']);
$vari_s = taxonomy_term_load($field_my_st[0]['tid']);
$vari_result =  $vari_l->name . $vari_g->name . $vari_t->name . $vari_s->name;
$vari_result = preg_replace('/[\s,.]{1,}/', '', $vari_result);
$entity_field[0]['value'] = $vari_result;

buuuut...

Notice: Trying to get property of non-object in eval() (line 9 of /Users/Robert/Sites/devdesktop/country_yarns/modules/computed_field/computed_field.module(468) : eval()'d code).

$vari_g is, or should, be based on the field_needle_guage field. But this is in the product variation of Needle, and not in the content type of Needle. All other fields are in the content type and work correctly.

So what's the right way to access members of a product variation in the content type - or is that even the right way around? (See Q1)

[EDIT]

Ok, so looking at the objects available in the wrapper:

$wrapper = entity_metadata_wrapper($entity_type, $entity);
// field_product_node is documented as the automatically created backreference to the content type.
$product = $wrapper->field_product_node;

// DrupalCommerce Kickstart 2 documentation says the below should work, but it does not - 'error: can't find getProduct function'. (WHY?)
$wrapper->getProduct();

// This comes out as an EntityDrupalWrapper
dpm($wrapper);
// This comes out as an EntityListWrapper
dpm($product);

// but below fails - can't find getIterator on object (WHY??)
$plist = $product->getIterator();
// and below returns an empty array!
$plitems = $product->value();

So all these auto-back-reference class things in DrupalContrib are not accessible in this manner, it seems. If they work, I'd love to find out how!

Looking at how the tables are set up: field_revision_field_product is the link table between 'commerce_product' 'commerce_product_revision' and 'node', and any particular field_data_field_XXX field data table.

So I guess I need to use a sql query to get the field_data_field_XXX value through an inner join. I guess I'll need to put that into a custom module and then make a field of that type that allows you to configure what field to grab from the CT

To clarify from the comment thread:

This is a question that is tough to answer on SE because it's just something you'll have to feel out. If you're doing 1:1 content types to product displays, it doesn't really matter where you put it (though it'd probably be easier to do it on the CT) in general I tend to put more on PV because it's data related to the product. If you're doing 1:N then you'll definitely want to put it on the PV and if you're doing M:N then you're going to have to do some customization.
You can put the computed field on the PV but you'll need something like Entity Backreference so that the PV has a link back to the content type so you can load it and grab it's fields.


How to override base url when creating links to public files? I need storage the upload into drupal file in another server and I need change public path to files to example http://server_with_image/image How I can do this?

You are basically describing the use case of a CDN (Content Delivery Network).
Check CDN module:

This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.
It provides two modes: "Origin Pull" and "File Conveyor".

In Origin Pull mode, only "Origin Pull" CDNs are supported. (These are CDNs that only require you to replace the domain name with another domain name.)
In File Conveyor mode, this module integrates with File Conveyor, which allows for much more advanced setups (e.g. optimize images, transcode videos, and so on, before syncing to the CDN).


Authentication to LDAP Server I'm using LDAP module to allow user login through a LDAP Server. This is server configuration:

Server Properties

sid = eng_ldap_server
numeric_sid = 1
name = Eng LDAP Server
status = 1
ldap_type = ad
address = 10.10.72.202
port = 389
tls = 0
followrefs = 0
bind_method = 2
basedn = Array ( [0] => dc=BMS,dc=ORVIETO )
binddn = admin
user_dn_expression = cn=%username,%basedn
user_attr =
account_name_attr =
mail_attr =
mail_template =
picture_attr =
unique_persistent_attr =
unique_persistent_attr_binary = 0
ldap_to_drupal_user =
testing_drupal_username =
testing_drupal_user_dn =
grp_unused = 0
grp_object_cat =
grp_nested = 0
grp_user_memb_attr_exists = 0
grp_user_memb_attr =
grp_memb_attr =
grp_memb_attr_match_user_attr =
grp_derive_from_dn = 0
grp_derive_from_dn_attr =
grp_test_grp_dn =
grp_test_grp_dn_writeable =
search_pagination = 0
search_page_size = 1000

Anything wrong?

I was having a lot of problems with the connection and authentication with the server until I change the bind dn format.

Maybe try something like this:

binddn = webwasher88@hnbwyo.com


Can I run the 'Toolbar' and 'Admin Menu' at the same time for different roles? I have three extra roles and I would like to use the Toolbar to use the menu for the Editor role, but the Admin Menu for the roles Adminstrator & SuperAdmin. The one problem I run into is that the higher level roles will inherit the permission to also display the Toolbar menu, which is redundant as the Admin Menu is already taking care of.

Thanks for your advice.

I recommend you to disable Toolbar module and use Administration Menu Source with Administration menu and enable Admin Menu Toolbar which will give you the same look as Drupal Toolbar.

Administration Menu Source:

  Use a different menu as the Administration Menu. Configurable per role.

Custom Solution:

Create a custom module add the following hook_page_alter function:

function mymodule_page_alter(&$page) {
  global $user;

  if(!in_array('editor', array_values(array_map('strtolower', $user->roles))) &&
     !empty($page['page_top']['toolbar'])) {
    $page['page_top']['toolbar']['#access'] = FALSE;
  }
}

The above code will check the role of current user and will hide toolbar if current user is not editor.

Note: make sure to replace editor to whatever editor role you named.


Rate content by the author's role I want a five-star content rating system, for example:
if a premium user creates a content this will be rated with five starts, if a simple user creates a content this will be rated with three starts etc. I dont wont users to rate the conten.
Is something like this possible ???

I'll assume your using Drupal 7, you want to look into hook_node_update() this will allow you to run code whenever a node is saved/created.

From there you'll have full access to the node object in which you can use user_load() to grab the user object and check it's roles. Then you need to add logic based on the role to modify the nodes fivestar rating.


How to import a Text File from feeds CSV and map it to a File upload field with multiple values? EDIT: This issue is directly related to how the Acquia hosting Platform handles private files, not webforms / feeds or feeds tamper.

I've got a site where I need to Migrate the users from a webform they were using, and convert those submissions into user accounts.

I am using Feeds (7.x-2.0-beta1+8-dev) and Webform (7.x-4.8) and feeds Tamper.

I've managed to map all the fields except the Attachment field which is of type File. The Attachment field has the ability to attach unlimited files. Here are the three options I have when using the Mapping section in Feeds importer:

When I export my CSV from webforms, my Attachment field becomes the parent of every field in my CSV, and won't run until I modify it by removing the Attachment key from the start of the CSV file. (This makes no sense to me.)

After removing the Attachments field I am left with:

  "Email","Name","Filesize (KB)"
  "testemail@example.com","http://dev.website.ca/system/files/webform/permits/genericfile.txt|http://dev.local488.evsite.ca/system/files/webform/permits/94ufos.txt","55"

In this CSV there is the Attachment field and the Email field. When the run the CSV import, the user is created but nothing is added to the file field. I've tried mapping the Name value to all the possible options and it doesn't seem to be outputting anything for me.

When there is multiple values in the Name field I am using the explode plugin, using | as a string separator.
 I'm just not sure if i'm suppose to pass in an array or values or am I missing a module or something? I've browsed several similar questions but they have to do with Image i'm just using text files.

I am just wondering how can I can use the Feeds User Importer to import a regular text file from a CSV file and have it uploaded to the File widget in the user's Account page?

Any tips in the right direction are highly appreciated.

It looks like you're on the right track from:
https://www.drupal.org/node/1116130#comment-6827626

I believe you to set it to use an array of values (that's what explode returns). The file type itself, image vs text file, is largely irrelevant as you simply want it to work with a multiple item field.


Access page.tpl.php variables from html.tpl.php I've got a well-established theme that's building a lot of variables for the page template, ie. $variables['page']['stripe_color'] = $some_node_data; However, now I'd like to apply this variable to the body tag; so, it needs to be communicated to html.tpl.php

I know there's a bunch of ways to this, store it in a global, reevaluate in the theme_preprocess_html, but I'm wondering if there's a simple variable somewhere that's available that I'm not finding.

Sounds like a perfect use case for the more generic hook_preprocess:

function MYTHEME_preprocess(&variables, $hook) {
  if ($hook == 'page' || $hook == 'html') {
    $variables['shared_var'] = 'foo';
  }
}

$shared_var will be available in both html.tpl.php and page.tpl.php. This will be processed twice, so if it's expensive to build the vars, make sure you statically cache them.


Multisite domain not working without symlink I used to have to work with my own custom *.conf file in order to get my multi-site to work off a non root install of drupal but now have moved it to root ,I don't need that file anymore as system reads the .htaccess.

So while my subdomains work fine in sites folder, my other domain name in sites folder refuses to work without symlink. Which I always thought was only necessary in tandem with *.conf file for virtualDocument hosts.

So my question is --

Why won't my other domain work like other sites in sites folder?

Why must it have a symlink to work?

And why do other sites have clean-urls working along with main install site but not other domain name?

My set up is

  mainsite.com/sites/

                  subdomain.mainsite.com
                  subdomain2.mainsite.com
                  otherdomain.com

If I symlink otherdomain.com while in www folder:

ln -s /var/www/html/ /var/www/html/otherdomain.com

It works but without clean-urls

I have the answer now.

The symlink is necessary so two separate domains can share the one IP along with your server's records. Obviously the subdomains share the same name and so are fine just listed in sites directory. The symlink links the other domain or any number of domains to the same html folder where the root installation of drupal resides.

The clean urls for the symlink multi-site domain on my Centos 6.4 linux system running httpd require the default httpd.conf file in etc/httpd/conf to change AllowOverride NONE to All for directories. Then the service must be restarted for changes to take effect service httpd restart


How to show a block only if a specific user is logged in? I have a block which act as a menu. And the block is created dynamically like that:

$menu_block = array(
    'module' => 'menu',
    'delta' => 'clientmenu' . $account->uid, // the id of the block
    'theme' => 'MYTHEME', // the current theme
    'title' => '<none>', // dispaly no title
    'visibility' => 1, // it is displayed only on those pages listed in $block->pages.
    'region' => 'menu',
    'status' => 1,
    'pages' => $onlythispages, // display the menu only for this client
);

drupal_write_record('block', $menu_block);

And content of the variable $onlythispages is:

// page to display the menu
$onlythispages = 'client/' . $account->name . '
client/' . $account->name . '/*' . '
all-products
product/*';

I created one menu for each created user. Each user has personal (only he can access) pages like:

client/' . $account->name
client/' . $account->name . '/*'

And each user has some common pages which share with all users, pages like:

all-products
product/*

So the problem is that when I go to common pages I see all the "menu blocks" from all the users. So is there a way to show a block only if a specific user id, which actually is the currently logged in user?

I use hook_node_access to handle the access to a node but, how can I do it handle the access to block?

If only a block needs to be shown for each user, then what I would do is to implement the block in a module that changes the content of the block basing on the currently logged-in user. The visibility settings are also used for blocks implemented by third-party modules.


How to use 2 twig template for for one field (or how to add a variable to a template from a template) Let say I have a node template which is calling twice the same field like the following:

...
{# First call #}
{{ content.my_field }}
...
{# Second call #}
{{ content.my_field }}
...

I also have a preprocessing function which is adding VAR1 and VAR2 to the 'my_field' array like the following:

function mymod_preprocess_field(&$vars) {
  if (isset($vars['element'])) {
    $fn=$element['#field_name'];
    if ($fn=='my_field'){
      $vars['VAR1'] = 'a value';
      $vars['VAR2'] = 'another value';
    }
  }
}

I would like that the first call of 'My_field' use the default twig template and the 'VAR1' value... As you can imagine, I could do it as this is the normal way Drupal is working.
But I didn't success to make use of an alternate twig template for the second call (and also, I would like this second template use 'VAR2')

My first idea was to put the following just before the first call:

{{ set content.my_field.is_first_call = true }}

and to use only the default template (I mean not 2 templates) with something like

{% if is_first_call %}
  ... code to print the first call
{% else %}
  ... code to print the second call
{% endif %}

But I couldn't succeed to transmit a value (is_first_call) from the node template to the default my_field template

Final note: I have added the 'VAR1/VAR2' story because I have also tested the {{ content.my_field | without ('a_check_var')}} filter: the idea was to remove a_check_var from the array to use a construct like {% if a_check_var %} in the default template.
Unfortunately, my preprocess function which is adding 'VAR1/VAR2' runs after the without filter

How to add a variable to the field template from the node template?

What you see in the node template from the field is before the field preprocess is run.

The global preprocess for fields starts like this:

function template_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];

  // Creating variables for the template.
  $variables['entity_type'] = $element['#entity_type'];
  $variables['field_name'] = $element['#field_name'];
  $variables['field_type'] = $element['#field_type'];
  $variables['label_display'] = $element['#label_display'];

Here can see, how the variables for the field template are built.

Example:

To add a variable in node set the variable with a '#' prefix:

function mytheme_preprocess_node(&$variables) {
  if (isset($variables['content']['my_field'])) {
    $variables['content']['my_field']['#var1'] = 'a value';
  }
}

And then in the field template:

function mytheme_preprocess_field(&$variables) {
  if (isset($variables['element']['#var1'])) {
    $variables['var1'] = $variables['element']['#var1'];
  }
}

The variable is then available in the field twig:

{{ var1 }}

To solve your specific problem I would suggest you copy the field in node preprocess and then set for both copies different variables.


How to create a single page application in Drupal? I know Drupal and now I am creating a website by Laravel framework. I know what are single page application and how better they are. I used Angular and Backbone as JavaScript framework/library to creating a single page application with Laravel.

I am not professional in Drupal, How can I use these libraries to create a single page application (SPA) using Drupal?

Is there any module to make a (SPA) or automatically make the website Full-Ajax?

You could use the Ajax Regions module.

It allows you to load specific regions via Ajax, thus load your whole website on one single page


Stream_flush in not being called while using stream wrapper I've created a stream wrapper foo:// and when I am using this wrapper and my file moved successfully but the flush_stream function is not called I don't why I also checked for the public:// stream wrapper and It calls the flush_stream function after moving file.

I backtracked the code while running for public:// stream wrapper I got this output

Array
(
[0] => Array
    (
        [function] => stream_flush
        [class] => DrupalLocalStreamWrapper
        [object] => DrupalPublicStreamWrapper Object
            (
                [context] =>
                [handle] => Resource id #11
                [uri:protected] => public://a1a1211127_aa_0.jpg
            )

        [type] => ->
        [args] => Array
            (
            )

    )

[1] => Array
    (
        [file] => /var/www/html/includes/file.inc
        [line] => 1633
        [function] => move_uploaded_file
        [args] => Array
            (
                [0] => /tmp/phpPaIdAn
                [1] => public://a1a1211127_aa_0.jpg
            )

    )
[2] => Array
    (
        [file] => /var/www/html/includes/file.inc
        [line] => 1585
        [function] => drupal_move_uploaded_file
        [args] => Array
            (
                [0] => /tmp/phpPaIdAn
                [1] => public://a1a1211127_aa_0.jpg
            )

    )

It means stream_flush is called after the move_uploaded_file function. But in my case the move_uploaded_file function is called but stream_flush is not.

Any idea why?

I Just changed the stream wrapper type to STREAM_WRAPPERS_LOCAL_NORMAL and implements the chmod function and it works seamlessly.


How can I have a custom module checked for deprecated functions? I created a custom module in Drupal 8 for a specific purpose.

How can I find out if it contains any deprecated functions?

Read Dries Buytaert's blog post on How to prepare for Drupal 9

drupal-check

  If you work on a Drupal site as a developer, run drupal-check. Matt
  Glaman (Centarro) developed a static PHP analysis tool called
  drupal-check, which you can run against your codebase to check for
  deprecated code. I recommend running drupal-check in an automated
  fashion as part of your development workflow.

Link: https://github.com/mglaman/drupal-check

Upgrade Status

  If you are a site owner, install the Upgrade Status module. This
  module was built by Acquia. The module provides a graphical user
  interface on top of drupal-check. The goal is to provide an
  easy-to-use readiness assessment for your site's migration to Drupal
  9.

Link: https://drupal.org/project/upgrade_status

Maybe also learn the background info of drupal-check reading Matt Glaman's blog post about Testing your Drupal code base for deprecated code usage with PHPStan.


Posting from Drupal to WordPress Basically I'm looking for a module/tool/mechanism that I could use to post to a WordPress install from my Drupal install. Ideally this would be filtered per post type and on/off per post. My scenario. I've got a custom post type in my Drupal site which I post to frequently. Sometimes (depending on the post) I'd like to to post to WordPress also, without the hassle of having to login to another platform. Apparently there was this module: https://drupal.org/project/wp_publish

But it seems is not ported to D7. Any knows anything else?

Many thanks

PS: Its not a migration. Some posts will only go to D7, and some will be posted on D7 and WP.
PPS: Both sites have very different objectives and only share some content, so no need for a joint solution/migration/etc.

Now nothing about wp, but in drupal you will have to fire the event when the node is saved and your form field,  "save into wp" is active.

Basically I'd do this with hook node api. Use case "save", check then the field and then fire the function or api which allows you to save the content into wp


How to pass a field value as contextual filter argument using Twig Tweak drupal_view? In Drupal 8, I'm using Twig Tweak to embed a view. I have a contextual filter set to one of the node's fields, field_project_id. If I use a literal for the third argument, it works. If I try to reference the value of the current node's project ID, no luck.

Works:

{{ drupal_view('my_view', 'block_1', '2011-40054-000') }}

Doesn't work:

{{ drupal_view('my_view', 'block_1', content.field_project_id) }},
{{ drupal_view('my_view', 'block_1', content.field_project_id.value) }},
{{ drupal_view('my_view', 'block_1', content.field_project_id.0) }},
{{ drupal_view('my_view', 'block_1', content.field_project_id.0.value) }},

etc.

What's the proper way to do this?

First of all check drupal_view implementation but I think that the arguments parameter (contextual filters) is an array, though the function wraps scalars into an array you should pass an array (robustness). Said that everything looks fine in your template perhaps you should do {{ vardumper(content) }}  to see what actually is getting to your template variable. In order to use the vardumper function you need to install the VarDumper module.


Register the user from the login form itself I want to create new accounts only if user name and password have matched with that of with Active Directory.

So if a completely new user tries to login and enters correct Active Directory login & password then I'm adding him/her using user_save in the form validator.

But at the same time I'm returning with error that "please re-login".

However I want a seamless login. That is if a new user tries to login -- I'll create a new user and at the same time he/she should also be logged in.

How can I do this?

I had a similar use case in the past and i am giving some snippet, hope will help you. The key was user_login_finalize and then redirecting internally to the same page.

Load the user if already present or create and then load him

$user = user_load_by_name_and_password($username, $password);
if ($user == FALSE) {
  $newuser = array(
    'name' => $username,
    'pass' => $password, // some password
    'mail' => $email, // some email
    'status' => 1,
    'init' => $email, // some email id
    'roles' => $roles, // some roles
  );
  // New user is saved and loaded
  $user = user_save(drupal_anonymous_user(), $newuser);
}
user_login_finalize();
drupal_goto(get_current_url_with_query_params());

http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_finalize/7
Finalize the login process. Must be called when logging in a user

drupal_goto must be called as user_login_finalize() bootstraps the currently logged in user too late and hence will throw 'access denied' even for the page for which the user has permission. drupal_goto() makes sure that the user is properly bootstrapped and then is made to access the page again.

It is equivalent to reloading the page after the user has logged in but this is the only way i got my external login work. Refer User login using a token or ID (no password)


How to add an html element (BODY) class based on taxonomy from logged in user? I'm building a website on Drupal 7 which will be accessible only to registered users. A taxonomy term is referenced to the user account. I need to add a body class based on that taxonomy term so I can personalize the theme's look depending on the logged in user.

In your custom module implement hook_preprocess_field().In the given code I am adding a taxonomy term field with uid as class,you can change to your requirement.

function mymodulename_preprocess_field(&$variables) {
  global $user
  if($variables['element']['#field_name'] == 'your_taxonomy_term_name') {
    dpm($variables);
    dpm($variables['classes_array']);
    $variables['classes_array'][] = $user->uid;
  }
}


Better exposed filters allows only one checkbox at a time Im using a exposed filter in views. That filter is displayed as a checkbox using the BEF module.
Im allowing multiple selection on that filter.

The problem is that when a user click on multiple checkboxes at once it only selects one. Its like refreshing after you check one selection and then it scrols up the list. You can select more then one option, but not at once.

And yea, Ajax is enebled.

Anyone else has this kind of a problem?

Follow the steps:

go to advanced tab.
Under exposed form section, go to exposed form style setting. (BEF settings).
Then under display option of your checkbox field, expand more options and check add select all/none option.
Uncheck autosubmit option if checked.


Display OR between two fileds in a content type I have two fields in a content type. one is file upload field. another one is link field.
Customer can either upload file or give the url to the field.

so I want to display "(OR)" between these two fields in content type.

How this can be achieved.

If you simply want to display "(OR)" between  two fields in content type, you can achieve this in form alter

function modulename_form_alter(&$form, &$form_state, $form_id) {

    if ($form['#id'] == 'page-node-form'){ //contenttype-node-form

   $form['field_test']['#prefix'] = '
 OR';
       $form['field_test']['#suffix'] = '
';
       //where field_test is your file upload field
    }
 }


Display full webform submission on submission page I'm using Drupal 7 and I'm learning PHP at the same time.

I'm using the webform module and when users submit a webform on my site, they can see their submission answers on the submission page but they can't see the whole webform with all the components.

I've read the THEMING.txt file in the webform module and I've copied webform-submission.tpl.php to my theme folder and have been trying to edit it but I can't figure out the code I need to use. I think it's probably quite a simple snippet but I'm not advanced enough yet to work it out.

Could someone help me out please?

It's the webform-confirmation.tpl.php that you'd want to edit.

There's an article here explaining exactly what you want to achieve. https://www.drupal.org/node/1515548


Drush backup of multisite platform Is there Drush command that can backup whole multisite platform:

database dump of each site
code of each site
backup of sites/all or complete core with sites/all
and all that in just ONE tar.gz

There is a archive-dump command which can backup whole platform code and database, but it does that for each site, and omitting other sites from its archive. And that is a problem because if you want to use that backup, and let's say you have 3 sites in platform, you would have to untar 3 backups of each site, and then merge those so your /sites folder has all three sites there, instead only one per archive.

Second, less annoying problem with that command is, if you provide it argument @sites, it will try to backup default site as well, which is not used on Aegir.

You can try drush archive-dump default,example.com,foo.com command to archive the DB and codebase. If it is not possibel through it, then you can create a shell script, which creates backup of the codebase and database.


Pre-populate a user reference field during drupal commerce checkout - buying a gift for a user without manual username entry I am creating a gift shop website where users can buy gifts for other users. So on every user profile i want to add a link "buy gift for this user" which takes you to the product page. After adding items to cart and checkout, a "gift recipient" (user-reference) field is already pre-filled with the name of the user from whose profile the shopping was initiated (not the name of the logged in user). Is this sort of thing possible in drupal 7? How can i achieve such? Thanks.

I don't know ready solution from the box for your use case but it's possible to implement it with Drupal Commerce and Line items functionality.

You can extend Line Item with the user reference field "gift recipient".
User value will be saved on line item but not a product.
Than everything is in your hands.
E.g. you can click on option "Include this field on "Add to Cart" form. Or you can prepopulate this field using special get parameter in the "buy gift for this user" link.

For more information about extending Line Items see the video: http://vimeo.com/31459435


Explanation of Content Types, Modules, and Views Attempting to structure a page within Drupal has led me down a convoluted path and I wanted to clarify the relationship between Drupal content types, modules and the views element before I ventured any further. My current understanding is that you can add content types via modules and with these various content types create a page that you can then format with views? What I am trying to do is create a basic page from various elements (pictures, tables, text, etc.) and format it through views. I realize this may be too generic to comment upon, but I would greatly appreciate any feedback!

Reading the Drupal documentation might be your best bet to get an in-depth explanation, but let me try to summarize each in my own words so you can hopefully get a basic foundation so you can understand better.

Content types - Content types are how you add any of your content to a website. For most of your general pages that have just regular text on them, nothing special, you would use the Basic Page content type to just create a basic web page, or node. However, say you were going to have an events feed on your website - you would want different fields for information that you would want to display. In this case, you would make a content type called Events (or whatever you would like), and then add fields to it (e.g., Event Title, Date, Time, Location, etc.). Now, Events would be listed as a content type you can use to add content. When you add content and choose Event to add, your fields will show up and you can add the information for an event, save that event, and repeat. Saving an event will bring you to the page for that event with all of that event's information (the formatting of which can be changed in the content type settings for that content type. Every event entry now has its own page displaying its information.

Views - Now, you have pages for events, but say you wanted to have a feed or list of events on a specific page. You would do this using a View. A view aggregates content (from one or more content types) into a display. So you would create a view, specify which fields from earlier you want to display (like maybe just event name and date) and then filter the content to just show content of type events. This view can be created as its own page, or you can create a block which you can then place in a region on another page. There is a lot of customization that Views allow you to do that isn't obvious in the beginning, but this is the gist of what views do.

Modules - Modules are jus "extras" for Drupal. Really, most of what you would need to create a basic site is already included. However, say you wanted to add some sort of fancy menu that Drupal can't already do. People have made modules to give you that capability. Say you wanted to create forms for people to fill out. There are modules for that.

If you want me to explain anything in more detail or if anything is not clear to you, feel free to ask and I can clarify or elaborate.


Views Contextual Filters - User Name in URL I have a view set up to function as a blog, and a contextual filter set up to filter by author of the blog post.

The point is to be able to click on the blog post author link and go to a page that lists all the blog posts by that person. This is facing anyone who visits the site, and any visitor (non-logged in) can view the blog listing of any of the authors.

The current set up is to have a Relationship to the author table, and filter by User: name. Then when visiting a url /blog/author/John Smith, you see all posts by John Smith. (I realise that's an invalid URL.)

The filter itself is working and the blog posts are being pulled through for all the authors, however, I'm having issues to transform spaces to dashes and to lowercase the URL.

When you visit /blog/author/John Smith, you are redirected to /blog/author/John%20Smith, and then the blog posts by John Smith are visible, but this isn't good enough for us in terms of URLs.

So instead of /blog/author/John%20Smith, I need the URL to be /blog/author/john-smith.

The problem is that the default checkboxes and options which work for taxonomy terms do not seem to work with Author names. Ticking transform spaces to dashes in URL and using case in path: lower does not affect the filter the way I want it to - it has no effect at all.

  I'm considering creating a new field in the user entity and then using that to filter instead. Like john-smith for the John Smith user. I'm not sure if that'll work, but I'll try it out right now.

The above has worked, and I do have the URL's I want and they query for the right items. I'm not sure if it's the cleanest solution though.

You should remove the "User: name" Relationship on the view and add a new relationship "User: uid". Then you can access the author view with /blog/author/123.

Then create a URL alias for "/blog/author/123" and set it to "/blog/author/john-smith". You will then be able to access the view with both the uid 123 or using john-smith.


xmlrpc function in another file I would like to put all my xmlrpc functions in a separate inc file and the problem is, how would we tell drupal it is in another file.  Right now, my hook_xmlrpc in my module file looks like this:

function mymodule_xmlrpc() {

  $methods['mymodule.get_myfunction'] = 'xmls_mymodule_get_myfunction';
  return $methods;
}

xmls_mymodule_get_myfunction resides in mymodule.xml-rpc.inc file.  How do we let drupal know that in this hook?

Unfortunately, I don't believe you can.

Many core hooks, such as hook_menu, let's you define a file and a file path which Drupal can use to find the actual callbacks for the menu.

However, I don't believe this functionality is supported by hook_xmlrpc.

Considering also that the module is likely to leave core soon, it's unlikely that there will be any large improvements to it.


Manage content type's different status for different users I want to know if there are any modules for the following situation:

I have a content type A with reference to user 1 to user N. Now that content type A will have different status for different users let's say for user 1 it has Status1, user 2 it has Status2. First thing is how can I achieve this functionality is there any module which will be useful for this situation ?

Other part of the scenario is when user1 logs in he should see content type A with status S1 and when user2 logs in he should see content type B with status S2.

Is this possible at all in Drupal? Please suggest me.

Thanks for reading!

Based on chat with @parth I realised the status field belongs more to relation of book and user rather than book. Here is my recommendation in that case.
Way 1:
The easiest way I could think of is

have a custom table as book_inventory with columns as book_entity_id, user_id,status,record_id

In order to allow admin to a UI in place to udpate status with fields as

autocomplete field for book
autocomplete field for user
status could be dropdown field

this UI will let admin to set status for any book against any user
down to your form UI, you can list what books are assigned to what users from your custom table with an edit link
when the admin clicks the edit button the same form UI will open but prepopulated with all the fields
now with help of this table
you always have information user and book status with you, you can query your database and get the status runtime
and in case you do not have a record agaisnt requested user and book, in that case you can have a default status, I believe 'not purchased' in your case
Way 2:
Other approach would be to try Relation module instead of entityReference, as relation module will allow fieldable relation between book and user.


Handling the 'default/' folder in Git I am running a legacy project with four developers on it. Occasionally I need to make changes to settings.php for remote server settings and/or a settings override example template in this directory. It seems like any time cache is cleared, the default folder permission is changed to not be writable, and the settings file changed to 644. Which I get.

However, the next time someone does a git pull and there are changes in that file, git says it does not have permission to touch it and the pull fails.

Is there any strategy to handling this? I tried searching but came up short.

Edit: this may sound like a Git question at a glance, but it’s due to how Drupal changes certain directories to be read only and not writeable which causes issues when those files update and are pushed to a repo for others. Therefore there must be some strategy to handle this.

The answer from @leymannx stops git from recognizing and pushing file permission changes to the repository.

Yet, it doesn't stop Drupal from denying write access to the configuration files after your cache cleared, and thus a git pull to fail if it can't write changes to these files.

As the permissions set automatically by Drupal still allow write access for the file owner, the easiest solution would be running git pull with the same user that is running the local webserver.

If that is no option, your developers may try to use access control lists (setfacl) for advanced write permissions to their local sites folders on Linux systems.

Another option would be to wrap the git executable with a custom shell script in their local binary paths, that ensures proper write permissions (unfortunately there's no pre-pull git hook).

As a last resort, you can patch the core. There is lots of discussion of whether and how to allow developers to circumvent file protection for setting files. None of the proposed solutions made it to core yet. But the patch from this issue for Drupal 7 allows a custom setting in your local development environment settings (e.g. in settings.local.php) to disable file permission changes.


How to redirect user after submitting an article? In Drupal 8 I would like to redirect users to the frontpage and display a status message after submitting an article?

How can I do that? form_alter and custom submit handler?

Yes, form_alter and a custom submit handler was the solution.

function _custom_admin_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = '_custom_admin_article_form_submit';
    }
  }
}

function _custom_admin_article_form_submit($form, FormStateInterface $form_state) {
  drupal_set_message(t('Thank you for submitting an article.'));

  $url = Url::fromRoute('<front>');
  $form_state->setRedirectUrl($url);
}


Adding attribute to menu - page specific Hi I know I can alter menu links classes/attributes using theme_menu_link() function.
But from what I can see, there is no way to determine what current page is being rendered from within the function.

i.e. I have a wep app that loads in 4 pages (ajax) and you can swipe to change page. I need to add an attribute on each menu link and they differ depending on the page.

Question being, how can I determine page from within theme_menu_link();

Regards

found it,

$page = arg(0);

cheers anyways


How do I show or hide a Views block based on a boolean field in the displayed node? I have searched and searched for an answer to this, so hopefully I'm not asking something that is answered elsewhere.

I have a content type with a boolean field that show or hide a form. On each of that content type node pages, I want to show a block if the boolean field is set to true.

So, in essence, the boolean on the content type tells whether or not to show the block.

Right now I have the form (via the Webform Module) displaying as a block using Views. I think I can set a contextual filter to determine if the block is shown or not, but I am having a ton of trouble getting it to do that.

So, how do I set up contextual filters to show the block if a boolean field is set in the content type to true and not if it's false?

Forget views.

Go to the visibility settings for the block (under /admin/structure/block) and set the Page Visibility to only show on "Pages on which this PHP code returns TRUE".

Then check your boolean field with the following code:

$node  = menu_get_object();

return (isset($node->field_boolean[LANGUAGE_NONE][0]['value'])) ? $node->field_boolean[LANGUAGE_NONE][0]['value'] : FALSE;

Then place the block on the page where you want it.


How can I make my entity controller class fetch the fields that have been programmatically attached? I've created a field, an instance of it, and attached it to a bundle that I've defined in hook_entity_info().

When I call up a new entity using entity_get_controller('module_content')->create($type), it doesn't have any field attached.

I've heard that I have to call field_attach_load(), but that requires an ID for the entity. I'm wondering how to fill out the data for the fields that I've attached to my bundle with a newly created instance of that bundle.

The create() method is the following one:

  /**
   * Create a default module_content.
   *
   * @param $type
   *   The machine-readable type of the module_content.
   *
   * @return
   *   A module_content object with all default fields initialized.
   */
  public function create($type = '') {
    return (object) array(
      'cid' => '',
      'type' => $type,
      'crc' => '',
      'class' => '',
      'conid' => '',
    );
  }

Fields are attached to instances of entities; that is the reason why field_attach_load() requires an entity ID.
Suppose you want to attach a field to a node; without knowing which node is, how do you know what value to use for the field?

DrupalEntityControllerInterface, the interface that all the entity controllers implement, doesn't define the DrupalEntityControllerInterface::create() method, but it defines the DrupalEntityControllerInterface::load() method, that is implemented by DrupalDefaultEntityController in DrupalDefaultEntityController::load(), which in turn calls DrupalDefaultEntityController::attachLoad(). The documentation for this method contains the following paragraph:

  Attaches data to entities upon loading. This will attach fields, if the entity is fieldable. It calls hook_entity_load() for modules which need to add data to all entities. It also calls hook_TYPE_load() on the loaded entities. For example hook_node_load() or hook_user_load(). If your hook_TYPE_load() expects special parameters apart from the queried entities, you can set $this->hookLoadArguments prior to calling the method. See NodeController::attachLoad() for an example.

If your entity controller extends DrupalDefaultEntityController, then the code for attaching fields to the entity instance is already implemented in that class, and you don't need to write extra code.

For the code to use when saving the entity, you can take node_save() as example. You will notice that the function contains the following code:

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

//...

// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

// Save fields.
$function = "field_attach_$op";
$function('node', $node);

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

The code calls field_attach_insert(), or field_attach_update(); those functions are responsible for saving the fields in the appropriate database tables.

The default implementation of an entity controller doesn't have support for saving an entity; there is a third-party module that implement the support for saving entities: the Entity API module.

  The module provides API functions allowing modules to create, save, delete, view or to determine access for any entity, i.e. entity_create(), entity_save(), entity_delete(), entity_view() and entity_access().
  The entity API introduces a unique place for metadata about entity relationships and entity properties: hook_entity_property_info(). This information about entity properties contains the data type and callbacks for how to get and set the data of a property. Modules may rely on this information in order to support any entity property, e.g. Rules and the Search API build upon that.
  Furthermore the module provides data wrappers that make use of the available information to provide a simple and unified access to entities and their properties. For usage examples have a look at the README or the provided tests.
  Beside that, the module helps you defining a new entity type. For that, it provides an entity controller, which implements full CRUD functionality for your entities. Optionally, entities may be created based on classes derived from the provided Entity class.


Allowed HTML tags in "Allowed value list" are not working I'm working on a select list content type which is essentially check boxes with words on one side. The issue appears to be that the html tags I put in that are allowed are stripped out when I go to save. I checked both text formats and it appears that all html is allowed, Any idea where I can look to see why the html is stripped out of the list?

Edit:
The allowed values list has  tags and I also am testing with a  tag, when I save the settings and refresh the view that has these check boxes and text, the text doesn't change according to the html assigned to it. I've looked and text formats (WYSIWYG, HTML, and plain text) do not have the  "limit allowed HTML tags" check box checked. So I am not sure why the tags are being filtered out any ideas? thank you.

According to your question comments, you are trying to create a form with an options list element using the core select element widget.

This widget is intended for creating select lists. Markup within select list options is considered invalid HTML. That's why the select options widget has a sanitizing function for its option labels, namely OptionsSelectWidget::sanitizeLabel(). This sanitizer is used on each widget settings form submit and cleans your labels from any HTML.

If you really require an options element with HTML in the option labels, you have three choices:

(1) Choose another widget type for the list field that supports HTML markup natively. Obviously you choose the select widget. Choosing checkboxes or radios as widget type in the "manage form view" tab will use the less restrictive satitizing function of the the abstract OptionsWidgetBase class.

(2) If you need an entirely unfiltered list, create a custom field widget for your list field. Make sure to also implement a form element different from select that supports HTML in its labels.

(3) Leave the sanitized labels in the Core widget configuration as is and use hook_field_widget_form_alter() to add your markup to the labels of the element you intend to replace the Core elements with.


Loop through node reference I want to send emails using email stored on node fields that are referenced twice by other two contents types. I have this content types relationship:

Content1
field1 (unlimited) - reference > Content2
                                 field2 (only 1) - reference > Content3
                                                               email

I want to send a email message to all itens on field1 using email field on Content3, after the node is created or updated.

I dont have experience with Rules looping. Ill appreciate any help.

Thanks!

The Rule will react on event "After updating existing content of type Content1".

The Rule will have to utilize a component in order to reach the email field in Content3.

In short: Rule loops through Content1 reference field (may contain multiple references) and then component will process each referenced node of type Content2 and return a variable back to the Rule. Returned variable contains an email that is taken from the field of the node of type Content3.

STEP 1 - Create Rules Component (export below)

{ "rules_process_content2_return_email" : {
    "LABEL" : "Process Referenced Content2 Entity and Return Email",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "content2" : { "label" : "Content2", "type" : "node" },
      "email_address" : { "label" : "Email Address", "type" : "text", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "content2" ], "field" : "field_content_reference_2" } },
      { "entity_has_field" : {
          "entity" : [ "content2:field-content-reference-2" ],
          "field" : "field_email"
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : [ "content2:field-content-reference-2:field-email" ]
          },
          "PROVIDE" : { "variable_added" : { "email_address" : "Email Address" } }
        }
      },
      { "data_set" : {
          "data" : [ "email-address" ],
          "value" : [ "content2:field-content-reference-2:field-email" ]
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "email_address" ]
  }
}

STEP 2 - Create the Rule that uses Component above (export below)

{ "rules_send_email" : {
    "LABEL" : "Send Email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--content1" : { "bundle" : "content1" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-content-reference" ] },
          "ITEM" : { "content2_item" : "Content2 item" },
          "DO" : [
            { "component_rules_process_content2_return_email" : {
                "USING" : { "content2" : [ "content2-item" ] },
                "PROVIDE" : { "email_address" : { "email_address" : "Email Address" } }
              }
            },
            { "mail" : {
                "to" : "[email-address:value]",
                "subject" : "Test Email on Content1 Update",
                "message" : "[node:title] was updated",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Replace "content1", "content2" and machine names of fields with your own content/fields machine names before importing. Modify to your liking.


Overriding Page Title with Contextual Links View Path:  team/member/%
Contextual Input:  Numeric User ID, single variable

The purpose of my view is to 1) use Views Responsive Grid to layout the page appropriately, which I have done, and 2) leverage the power of views to include future content / fields / etc.  After I finished building everything and themed it the way I wanted, I found that the page title was blank.

My question:  Is there a way to override the page title before the HTML is processed for this Views path?  Ideally, I would like the title to be:  "[first name] [last name] | Site Name"  The user's separated first and last names are available as fields.

I appreciate everyone's help with this! (view the bottom image in a new tab, it's pretty wide)

It can be done by placing the following code in your theme's template.php file (please note that my fields were named field_last_name and field_first_name, and my view was a page display with the view name 'user_stuff' - so please adjust your accordingly - you can inspect your values by installing devel and uncommenting the dpm statement).

function MYTHEME_views_pre_render(&$view){
  //dpm($view);
  if ($view->name == 'user_stuff' && $view->current_display == "page" && $view->total_rows > 0) {
    $first_name = $view->result[0]->field_field_first_name[0]['rendered']['#markup'];
    $last_name = $view->result[0]->field_field_last_name[0]['rendered']['#markup'];
    $site_name = variable_get('site_name', 'My Site Name');
    $view->build_info['title'] = "$first_name $last_name | $site_name";
  }
}

There is also no need for the pager and you should rather set your view to display 1 item only. Also note that you are outputting the rendered markup (as opposed to the raw value) so there is no need to sanitise the values.


How do I add divs to a sitemap? I have the Sitemap module installed and it creates an unordered list of my chosen menu's items.

Main Menu looks like this:

Home
 - submenuitem1
 - submenuitem2
 - submenuitemn

Services
 - submenuitem1
 - submenuitem2
 - submenuitemn

References
 - submenuitem1
 - submenuitem2
 - submenuitemn

Links
 - submenuitem1
 - submenuitem2
 - submenuitemn

How can I add DIVs to each main menu item with its subitems ( Home+subemenuitems, Service+submenuitems etc.) ?

I managed to override site_map_menu_link to give it some depth at least.

function MYTHEME_site_map_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';

    $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['plid'];
    $menu_id = 'menu-' . $element['#original_link']['plid'];
    $link_depth = 'depth-'. $element['#original_link']['depth'];

    if ($element['#below']) {
      $sub_menu = drupal_render($element['#below']);
    }

    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '

' . $output . $sub_menu . "
\n
";
}

You can use theme_site_map_box in your template.php!

I've done something similar before where I've changed the H2's to H3's:

Try something like the following in your template.php

function MYTHEME_site_map_box($variables) {
  $title = $variables['title'];
  $content = $variables['content'];
  $attributes = $variables['attributes'];

  $output = '';
  if (!empty($title) || !empty($content)) {
    $output .= '
';
    if (!empty($title)) {
      $output .= '
' . $title . '
';
    }
    if (!empty($content)) {
      $output .= '

' . $content . '

';
    }
    $output .= '
';
  }

  return $output;
}

I can't remember off the top of my head the structure of $content, but the above code should put an extra div around each section of the site map with the class of MYCLASS.

API Docs: theme_site_map_box()


How to display related data along with node I have a custom table that contains data related to certain nodes. I'm using EVA (Entity Views Attachment) to display some of this data along with the node, which works great.

However, I now want to display a single value from a related table when viewing a node.

I guess this could also be done using EVA, but creating a view to output a single value seems like the wrong approach(?)

In this case, the table does not contain entities. It is defined using hook_schema(), and made available to views with hook_views_data () in Drupal 7.

Thanks for any thoughts on the best way to proceed.

there is surprisingly many ways to acheive it :)
this is one that will require some work, but should be sane and scalable :

in a hook_node_load, load the data and attach it to the $node ($node->my-data)
[optionally] in hook_preprocess_node, create a variable for the template
in your template file, show the value aproprietly


One time change field + personal comments I'm not very familiar with all the modules for Drupal. Therefore, let me try to explain what I'm looking for.

1) The users shall be able to create nodes with some specific fields. Some of those fields shall be writable only one-time.

2) To this node only the author and users allowed by the author shall have access.

3) Additionally the users who have access to nodes of another user shall be able to make comments (including attachments). Something like a discussion forum to each node, but only the author of the node and the creator of the comment shall see their nodes.

Hope it's somehow understandable.

Are there any kind of modules for any of the above requests?

If I understand the problem. You can write hook_form_alter() in custom module and disable needed fields when user edit node. And configure permissions on this page admin/people/permissions


How to retrieve value of hidden field in twig? How to retrieve value of hidden field in twig?

PFB screenshot:

I am able to retrieve value of "Partition Count" field when not disabled. But not able to retrieve it's value when disabled.

Exact requirement:
1) If "Partition Count" field is Disabled from Drupal Admin, then field should not be displayed. But this value needs to be retrieved in twig file as display of "Reference Paragraph" will vary according to the value of "Partition Count".

2) If "Partition Count" field is Enabled from Drupal Admin, then field should be displayed. In this case, I am able to retrieve "Partition Count" field value in twig file.

paragraph.html.twig:: https://github.com/WondrousLLC/paragraphs_starter_pack/blob/master/template/paragraph/paragraph.html.twig

The variables in a paragraph template contain the fully loaded paragraph entity:

paragraph.html.twig

{#
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

from which you can retrieve raw values of any field, not matter whether base field or configured field or displayed or not:

{% set value = paragraph.field_example.value %}

On the contrary {{ content }}

 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

contains only the fields configured to be displayed in "Manage Display".


Get radio field value in data selector in rules In content type form, I have a select list as radio with two values "Complaint" and "Feedback".

After content type save, I need to send email if "Complaint" is checked to complaint@web.com and if "Feedback" is checked then send email to feedback@web.com

I know how to do that with text field (e.g field-text-field is empty or not) but not yet found any solution with radio buttons.

Note: I have installed the Rules module, and also enabled its sub-modules Rules UI and Rules Scheduler.

Step 1

To get your rule to work like you want it to work, for the "Complaint"-part you should use these Rules Conditions (in the specified order):

Entity has field, for your "select list" field.
List contains item, whereas:

the list is also about that same "select list" field.
the item you want to check for (if it is contained in the list) is "Complaint".

With those 2 Rules Conditions, your Rules Action to be performed is to send the eMail to complaint@web.com.

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

Step 2

Create a similar rule by reepeating Step 1, but now for "Feedback".

Step 3 (optional)

If you'd be willing to also use the Conditional Rules module, you could merge the rules from Step 1 and 2 in a single rule, ie because this module allows you to include Rules Conditions as part of Rules Actions.


hook_theme with custom path I need choose different template based on the path (current_path()?)

user/register/* AND
user/register/recruiter/*

I started with hook function

function ohm_theme(){
    $hooks = array();
    $hooks['user_register_form'] = array (
        'render element' => 'form',
        'path' => drupal_get_path('theme','ohm')."/layouts/hero",
        'template' => 'user-register-form',
        'preprocess functions' => array('ohm_preprocess_user_register_form'),
    );
    return $hooks;
}

Which works fine only for user/register page

Then I would like to specify the new template suggestion user/register/recruiter/* using

function ohm_preprocess_user_register_form(&$vars) {
   dsm($vars);
}

but I can't figure out how to add condition using current_path() inside this.

Thank you

Is this Drupal 7? If so, you can do this:

function ohm_preprocess_user_register_form(&$vars) {
   $current_path = current_path()
   $variables['theme_hook_suggestions'][] = 'user_register_form__' . str_replace('/', '-', $current_path);
}

This should allow you to use user-register-form--user-register-recruiter.tpl.php


How to pass the Body field from a View to Rules? Context: using the Views Rules module to pass a number of items to an action-loop in a Rules component (Action Set).

In views (display: rules) I selected among others the Body-field to be used. This field appears to be an array of different things (value, summary, format), when I use the [body-from-view:value] in an action, it seems to be empty.

Question
I must have some settings wrong. What Data Type do I have to select in the Row Variables (Rules Settings) in the View for the Body-field? Or maybe I use a wrong Replacement Pattern in the Action?

Note: handling nid, email, title, date works very well, these have Data type like text, integer, date.

I assume you performed the steps similar to what is documented in my answer to "How to send out email based on matching taxonomy terms in user profiles?". And while doing so, you probably used a field name like body-from-view in the "Rules" display of your view. I'm not sure if it is the only way to get it to work, but below is a possible solution to answer your question ...

Part 1 - Getting it to work

Define the body field 3 times in your view

When adding the "body" as a field in your view, add that field 3 times. And when configuring these Views fields, make sure to use these field formatters:

Default (for the 1st "body" field).
Trimmed (for the 2nd "body" field).
Summary or trimmed (for the 3rd "body" field).

Select the 3 body fields 3 times in your view

When you edit the Rules settings of your view (by using the link that says "edit field info"), use 3 separate variables for each of the 3 body fields, e.g using machine names that look something like so:

body-default
body-trimmed
body-summary-or-trimmed

I'm not sure (yet) about the most appropriate "data type" to use for these 3 variables, but in my case I just used "text".

Create your Rules Component using appropriate tokens

Within the Rules Actions of your Rules Component, use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Within that Views loop add whatever Rules Action that fits your needs. E.g. to get started, just perform "Show a message on the site". At that point, you should have access to these token values that you're looking for (if you use the same machine names as suggested above):
[body-default:value]
[body-trimmed:value]
[body-summary-or-trimmed:value]

Part 2 - Showtime

Here is an example of the execution of a rules component, in which I implemented what's mentioned in "Part 1", using a Rules Action to show a message on the site, and which looks like so:

Details about node with id = [node-nid:value] and title = [node-title:value]:

- body-summary-or-trimmed = [body-summary-or-trimmed:value]

- body-trimmed = [body-trimmed:value]

- body-default = [body-default:value]

After executing it, and with 3 nodes that were included in my Views result, the result looks like so:

Details about node with id = 163 and title = Node with summary and separator line:

- body-summary-or-trimmed =
This is the summary of this node ... and there is really nothing else after this (in this summary) ...

- body-trimmed =
This is the body of this node, which does have a summary also ...

It has multiple lines, and the separator line is inserted right here ...

- body-default =
This is the body of this node, which does have a summary also ...

It has multiple lines, and the separator line is inserted right here ...

And from here on there is even more content (after the separator line ...)

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Details about node with id = 162 and title = Node without a summary but with a separator line:

- body-summary-or-trimmed =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

- body-trimmed =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

- body-default =
This is the body of a node which does not have a summary ...

It has multiple lines, and the separator line is inserted right here ...

And from here on there is even more content (after the separator line ...)

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Details about node with id = 161 and title = Node without a summary and without a separator line :

- body-summary-or-trimmed =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

- body-trimmed =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

- body-default =
This is the body of this node, which does NOT have a summary ...

It has multiple lines, but no separator line  ...

And there is even more content ...

Some more lines (1).

Some more lines (2).

Some more lines (3).

Some more lines (4).

Component rule: Views Rules demonstration has been executed.

Part 3 - Pieces of the puzzle

Exported View

Here is an export of the view I created (use the Views UI to import it in your own site, adapt the filter criteria to fit your needs):

$view = new view();
$view->name = 'details_about_nodes';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Details about nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Details about nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Body */
$handler->display->display_options['fields']['body_1']['id'] = 'body_1';
$handler->display->display_options['fields']['body_1']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_1']['field'] = 'body';
$handler->display->display_options['fields']['body_1']['label'] = 'Body - Summary or trimmed';
$handler->display->display_options['fields']['body_1']['type'] = 'text_summary_or_trimmed';
$handler->display->display_options['fields']['body_1']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body_2']['id'] = 'body_2';
$handler->display->display_options['fields']['body_2']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body_2']['field'] = 'body';
$handler->display->display_options['fields']['body_2']['label'] = 'Body - Trimmed';
$handler->display->display_options['fields']['body_2']['type'] = 'text_trimmed';
$handler->display->display_options['fields']['body_2']['settings'] = array(
  'trim_length' => '200',
);
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Body - Default';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['operator'] = '>';
$handler->display->display_options['filters']['nid']['value']['value'] = '10';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'details-about-nodes';

/* Display: ListToCreateRulesLoop */
$handler = $view->new_display('views_rules', 'ListToCreateRulesLoop', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['rules_variables'] = array(
  'title' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Content: Title',
    'name' => 'node_title',
  ),
  'nid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Nid',
    'name' => 'node_nid',
  ),
  'body_1' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Summary or trimmed',
    'name' => 'body_summary_or_trimmed',
  ),
  'body_2' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Trimmed',
    'name' => 'body_trimmed',
  ),
  'body' => array(
    'enabled' => 1,
    'rendered' => 1,
    'type' => 'text',
    'label' => 'Body - Default',
    'name' => 'body_default',
  ),
);

Exported Rules Component

Here is an export of the Rules Component I created (use the Rules UI to import it in your own site, adapt the Rules Conditions to fit your needs):

{ "rules_views_rules_demonstration" : {
    "LABEL" : "Views Rules demonstration",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "details_about_nodes",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "node_title" : { "node_title" : "Content: Title" },
            "node_nid" : { "node_nid" : "Nid" },
            "body_summary_or_trimmed" : { "body_summary_or_trimmed" : "Body - Summary or trimmed" },
            "body_trimmed" : { "body_trimmed" : "Body - Trimmed" },
            "body_default" : { "body_default" : "Body - Default" }
          },
          "DO" : [
            { "drupal_message" : { "message" : "\u003Chr \/\u003E\r\nDetails about node with id = [node-nid:value] and title = [node-title:value]:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-summary-or-trimmed\u003C\/strong\u003E = [body-summary-or-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-trimmed\u003C\/strong\u003E = [body-trimmed:value]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003Ebody-default\u003C\/strong\u003E = [body-default:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}


How do I extend an existing entity? I would like to add some custom fields to the taxonomy_term_data table.

How do I programmatically extend the Term entity?

There is a hook for that hook_entity_base_field_info(). The code could look something like this

/**
 * Implements hook_entity_base_field_info().
 */
function module_name_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'taxonomy_term') {
    $fields['new_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Label'));

    // You can add more options about visibility configuration etc.

    return $fields;
  }
}

The above could add "hidden" field, (not visible in display or edit mode and not configurable). You need to do the same thing as when creating base fields in a custom entity.


In Drupal 7 Views how do you set permissions via roles for an attachment display? I am trying to set roles permissions for my attachment view, but every time i set the roles permissions it affects the master display aswell. I want my attachment display only viewable to admin's of the site. Am i missing something or should is there another alternative to this issue?

From you screenshot you gave permission to anonymous user, authenticated users and instructor. So the attachment will be visible to all users. Choose only admin for the attachment and for the page it is attached you do not need to set permissions. You settings should look something like the image below

Make sure you always apply permissions to the current display and not to all display.


Why is my content showing up below other blocks? I did some work on my site and now i realize that even though my main page content block is weighted to be at the top, it shows below everything else within that area.

Is there any way someone can take a look and help me figure out why this is happening?

Using
- drupal 7
- omega3 main theme with a custom subtheme

example of my issue: http://www.destinationsound.net/contact

The two blocks "Buy Beats Front Page" and "Banner Ad Top" blocks are the two located above the contact form on the contact page (and other pages)

Try hiding the row weights and dragging the items around. Change them any way you want - then save configuration then go back in and change them to the way you want them to be and save again. Dont forget to clear your caches.


Taxonomy with adjacent cities I have a content type 'company' with a related tax-term: 'city'.
With a view I can search for companies based on 'city' with autocomplete.

Is there a way I can relate adjacent cities into the same tax-term 'city'?
If not, I would have to create a new tax-term into the content type 'company' and select for each company the adjacent cities. That is a lof of work.

Geo lookup is not an option, because we want te select which adjacent cities belongs to a specific city.

For example:
Tax-term: city

City A
-- City B // adjacent city of 'city a'
-- City C // adjacent city of 'city a'
-- City D // adjacent city of 'city a'
City B
City C
City D

As you can see, City B, C and D exists in the tax-term but also are children of 'city A'. It should be an alias, because otherwise the children will have all a different ID, so that won't work.

Hope it is clear ...

I would like to share my own working solution. If you see any improvements, please correct me. That would be helpful. If not I hope this script can be helpful for someone else...

I've created my own module and used this function to alter the query:

<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\taxonomy\Entity\Term;

function search_cities_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // machine_name of view
    if ($view->id() == 'zoek_een_bedrijf') {
        foreach ($query->where as &$condition_group) {
            foreach ($condition_group['conditions'] as &$condition) {
                // check which field must be changed
                if ($condition['field'] == 'node__field_stad.field_stad_target_id = :node__field_stad_field_stad_target_id') {
                    $value = $condition['value'];
                    // get ID from taxonomy term
                    $city_id = $value[':node__field_stad_field_stad_target_id'];
                    // load taxonomy term info
                    $term = Term::load($city_id);
                    // load reference field with taxonomy term ID's
                    $term_field = $term->get('field_aangrenzende_gemeenten')->getValue();
                    $cities = array();
                    // add ID from parent taxonmy term
                    array_push($cities, $city_id);
                    // add taxonomy terms from reference field (children)
                    //print_r($term_field);
                    foreach ($term_field as $key => $value) {
                        array_push($cities, $value['target_id']);
                    }
                    // update the condition before sending query to database
                    $condition = array(
                        'field' => 'node__field_stad.field_stad_target_id',
                        'value' => $cities,
                        'operator' => 'IN',
                    );
                }
            }
        }
    }
}


Image field: Force at least/exactly two images per field I can easily set the maximum number of elements per field, but is there an easy way to specify the minimum value?
For now, I have an Image field, and I want at least two images.

This question has already answer here

You can do it by using Field validation Module.

The following validators are listed:

  Regular expression
  Numeric values (optionally specify min and / or max value)
  length (optionally specify min and / or max length)
  number of words (optionally specify min and / or max words )
  Plain text (disallow tags)
  Must be empty (Anti-Spam: Hide with CSS)
  Words blacklist
  number of selections (optionally specify min and / or max selections
  )
  Unique
  Match against a field
  Match against a property
  Specific value(s)
  Require at least one of several fields
  Equal values on multiple fields
  Unique values on multiple fields
  PHP Code (powerfull but dangerous)
  URL (support internal path and external url validation)
  Email
  Pattern (Regular expression lite)
  Date range2

Hope this will help you


Calculate sum in View of ISO-style timestamps I have a text field on a node type, which the user fills out with a video duration in ISO format (no validation or anything). So, '4:33' or '04:33' would be likely values for this field.

The client now needs a View which shows all these videos' titles and durations, and adds up the durations. I've looked at solutions like Views Calc and have had no real success. I've also have bad luck formatting the duration as  a datestamp and trying to manipulate it that way. I need a way to show something like this:

+----------+--------------+
|TITLE     | Duration     |
+----------+--------------+
|Swimming  | 4:33         |
|Diving    | 2:42         |
|Running   | 1:27         |
+----------+--------------+
|TOTAL     | 8:42         |
+----------+--------------+

Imho your two best bets would be to either create a custom formatter, or to use hook_field_attach_view_alter() to modify the display (this answer might help if you go down that road). I'd be happy to expand on either of those methods.

Is there any reason you're using a text field? I would've thought a dedicated duration field would've been the way to go. I've never used any myself, but Google suggests: HMS Field, Time Period. Have you had a look at them? They might already have a formatter that supports what you want (a longshot, perhaps!).


Fast method to locate occurrences of SQL queries via code? I'm reviewing some SQL queries made throughout a few modules, but to do that, I've been reading every line of code manually, which is time consuming.

Is there a term or phrase I could CTRL+F for to find out where the queries are occurring directly? Any packages I should be on the look for?

Try CTRL+F-ing for these:

db_query
->query(
\Drupal\Core\Database\Connection::query()
\Drupal\Core\Database\Connection::defaultOptions()