Mapping existing file against a new content type I am facing a situation here.

I have a content type A with an image field(field_upload_snaps) in it. There is another content type B which also contains an image field(field_valid_snaps).

Now user will upload the pics from A content type. So if user upload 3 pics via A then 3 FID and their corresponding URIs will be created in file_managed table in Drupal 7.

Now I have a requirement where I have to insert 2 images out of 3 programatically using Drupal code. Now there is no need to generate any new image copy in public URI as images already exist via A.

I tried two approaches:-

1) I have created a new node of Type B. I tried to fetch file URI,filesize,filemime and all relevant parameter from existing fid and associate with the node using this.

 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $file = (object) array(
  'uid' => $user->uid,
  'uri' => 'public://1.jpeg" ,
  'filemime' => 'image/jpeg',
  'status' => 1,
 );

 $node->field_upload_snaps['und'][] = (array)$file;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

But it gives me an error that "Cant insert duplicate value in file_managed". It will give because such value already exist in file_managed via A. So I am not able to save value.

2) I saved node first and then manually insert in the image field like this.

 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

 db_insert('field_data_field_valid_snaps')
    ->fields(array(
    'entity_type' => 'node',
    'bundle' => 'user_actualD_snaps',
    'deleted'=> 0,
    'entity_id'=>$node->nid,
    'delta'=>0,
    'field_valid_snaps_fid'=>517,
    'field_valid_snaps_alt'=>'',
    'field_valid_snaps_title'=>'',
    'field_valid_snaps_width'=>200,
    'field_valid_snaps_height'=>300,
    ))
    ->execute();

But the line after node_save() doesnt execute in this case. So I am not able to save it.

Are there any functions available which will map existing images into another table?

I think the File Field sources module will solve your problem.  (The D7 version works directly with the core Field module).  It will, among other things, allow you to re-use files by an auto-complete textfield.

Btw: Any file appearing in file_managed can only appear once in that table, so you should not be allowed to do what you try to do in your first approach.


Is it possible to use drush to save a theme setting? I need to set a theme setting via a scripting mechanism (specifically phing). Is it possible to use drush to set a very specific theme setting, without passing JSON?

drush vset {theme_setting} {specific_theme_setting}

I can use drush vget theme_{custom_theme}_settings --filter=json and get the JSON string, but I can't (at least I'm not aware of a way) set a specific key item of that array...?

Drush does not have any facilities for manipulating elements of arrays in the variable table; however, you can use drush php-eval to call variable_get() variable_set(), and include a bit of php to manipulate the json yourself.

It would also be pretty easy to make your own Drush command to manipulate the items you'd like to set regularly.  See the drushify tool for a fast way to get started.


7 - Views Filter where one field equals Logged in User's Email field On a custom content type I have created, there is a List(text) field called "Assigned to" that has a drop down selection of certain emails. (E.g user1@domain.com, user2@domain.com, user3@domain.com, etc.)

I have a separate view that displays fields from that content type.

I am looking for a way to filter results where the Logged in User's email field equals what is in the "Assigned to" field.

I thought of using a Contextual Filter, but that would require the user's email to be in the URL.

Could I use php code as a way to make the default contextual filter value equal the logged in user's email?

I have tried to use the following with no success:

global $user;
echo($user->mail);

Thank you.

Add your "Assigned to" field as contextual filter, and set "provide default value" to PHP code just like you were thinking, but change your php snippet to return a value instead of printing:

global $user;
return $user->mail;


How to add Drupal Commerce to an existing Drupal site? I wonder how to add the Drupal Commerce module to an existing Drupal installation.

I've had problems with the documentation about this topic that I have looked at so far:

A video about Adding Drupal Commerce to Existing Sites.
The Drupal Commerce User Guide.

I've also looked at the available Community documentation about Drupal commerce and I have installed the required modules. But when I try creating the products I'm having issues.

After following the aforementioned documentation and creating a custom product I get this error when trying to view the newly created product:

  EntityMetadataWrapperException: Unknown data property
  commerce_product. in EntityStructureWrapper->getPropertyInfo()

Any suggestions about how to resolve this error?

Option 1: Instructions from the community documentation
You saw the available community documentation about Drupal commerce, where it says (bold markup added here):

If you're installing Drupal Commerce on an existing Drupal site or on a new Drupal site without using Commerce Kickstart, you first need to install the latest packaged release of the following modules: ...

From my quote here, it sounds to me that it "has to be possible" to add Drupal commerce into an existing site.
I wonder however if it'd help to get your error resolved by taking into account this part of the community docu page:

Installing Drupal Commerce modules
When turning on the sub-modules of Commerce, you will notice that some modules are dependent on other modules. You may wish to turn them on one at a time so as to pinpoint any error messages. This is the order to satisfy dependencies:

Commerce and Commerce UI
Customer and Customer UI
Price
Line Item and Line Item UI
Order and Order UI
Checkout, Payment, Product
Product Reference
Cart and Product Pricing
Tax
Product UI
Tax UI
Payment UI

More specific: are you using all these modules? If not, could your error be caused by some dependency as mentioned in the quote above? Alse, does your error remain if you (temporarely) install/enable the modules in the list above that you don't use yet.
If you have all those modules enabled, what happens if (a) you disable them all and (b) re-enable them one at a time (as in the quote above also). It might help to pinpoint the real reason for your error message ...
Option 2: Use the Commerce Repair module
Other thoughts / approaches / attempts:

look at issue # 2312841, especially comment # 9 in it, and the suggested "Commerce Repair" module. Does this help to get your error resolved?

Could it be that you're experiencing the bug as described in the answer to Error When Create Drupal Commerce Product Display ? It refers to the same "Commerce Repair" module, a module that is "looking for a New maintainer", used in over 1.000 sites. To me it appears as your best possible alternative to consider, Unless you want to start from a fresh install.


Node permissions - administer content Can someone explain to me how node permissions are structured (or point me in the direction of a detailed list) - I'm trying to setup an editor role and want this to have full access to every content types.

It appears the only way is to tick 'Bypass content access control'?

Yet 'Administer Content' ("Promote, change ownership, edit revisions, and perform other tasks across all content types.") doesn't seem to do very much?

For example, I tick 'Administer Content' and untick 'Bypass Content Access Control', I don't seem to be able to "Promote" anything using the Actions dropdown, nor do I have an edit button next to anything on /admin/content, or any other way of accessing revisions or the ownership settings.

If I tick all the options for one content type, e.g. Basic Page, I get full access to those nodes, as expected.

I now understand how this works:

If you want a user to be able to edit all content types, regardless, you are supposed to use "Bypass Content Access Types".

"Administer Content" allows people without "Bypass Content Access Types" access to the Author and Promotion panels on the rhside of the node edit screen. i.e. they can change the Author (UID) and the creation date/time, and can either promote the content to the homepage or make it sticky.

"Administer Content" also gives access to the Revisions tab for all content types - but those permissions are duplicated - a user may already have them if type-specific revision permissions have been set, e.g:

Basic page: Delete revisions
Basic page: Revert revisions

(Note: Administer Content used to be called Administer Nodes and the latter name is still used internally.)


Detecting if site is inside iframe - loading custom CSS I would like to add an extra stylesheet for my site if it's being embedded inside an iframe on another site.

I found a JS method to try detecting an iframe embed over here: https://stackoverflow.com/questions/326069

Basically, you can run a script like:

if (top === self) { not in a frame } else { in a frame }

But I was wondering if it's possible to have that code add a stylesheet to the page in Drupal. Or maybe if there were some way to do it in Drupal, in hook_init() or something, that would be even better...

A final method I could think about is using the JS above to maybe add a URL parameter like ?embed=TRUE so I can detect that and add a stylesheet... but that would require a refresh inside the iframe :-/

You could...

munge the window.location object to add the additional param, but that will force the page to reload. From there you can access the param in Drupal and write server-side code to do a drupal_add_css().
Use jQuery (which comes with Drupal) to add the CSS directly.
Use jQuery to add a link to the remote stylesheet.

Example of the third method:

if (top !== self) {
  var cssURL = 'http://example.com/my/stylesheet.css';
  $('head').append('<link rel="stylesheet" href="' + cssURL + '"/>');
}

I would think that as long as you can predict the stylesheet name, the last option is going to be the most elegant.

Note that you would want to add the JavaScript to the document with drupal_add_js() in Drupal.


Adding Paypal Express Checkout for multiple domains I'm working with a multi-site setup (via Domain Access) and am having issues using Paypal Express Checkout on more than one domain.

What I have done so far:

Add a new Payment Method Rule with:

Event = Select available payment methods for an order
Rule = an existing component with a Domain Comparison element
Action = Enable Payment Method : Paypal Express Checkout

Edited the Action element to add in the updated Paypal payment settings (user, pass, Signature)
Ensure Rule is active

This does not add the Paypal Checkout button to /cart like I expected.

For testing, I edited the component for the domain that does have it and used the new domain for the Domain Comparison.  This did add the Paypal button to the second domain.  The only differences between these rules:

The component used in the rule has a different domain
The payment settings (user, pass, signature)
The original one has a status of Overridden whereas the new one has Custom

I appreciate any suggestions for troubleshooting the issue - let me know if you need more information!

Chris

This functionality is not currently in the Paypal EC module.  Please see https://www.drupal.org/node/2130605 for more information.

Basically, the rule that is created by enabling the Paypal EC module is hard coded into the .module file, making it impossible to use more than one instance without patching the module.


Modifying Poll Template to have big buttons for voting I am re-skinning the poll module for an iPad/tablets.

How can I make the poll module vote page have large buttons/images instead of radio buttons.

The template has <?php print $choice; ?>

and thats it :(

What I ended up doing was overriding this theme function:

function media_preprocess_poll_vote(&$vars)
{
    $node = menu_get_object();
    $list = array();

    $vars['choice'] = '';
    $vars['vote'] = '';

    foreach ($node->choice as $i => $choice)
    {
        $vars['choice'].= '
        <div class="poll-choice-wrapper">
            <input type="button" data-choice="'.$i.'" id="choice-'.$i.'" name="choice-'.$i.'" value="'.$choice['chtext'].'" class="poll-choice" />
        </div>';
    }

    $vars['choice'].='<input type="hidden" name="choice" id="choice" value="-1" />';
}

Then adding a little js:

jQuery(document).ready(function()
{
    jQuery(".poll-choice").click(function()
    {
        jQuery("#choice").val(jQuery(this).data('choice'));
        jQuery("#poll-view-voting").submit();
    });
});


Is there a way to alter a form, implemented by another module, using a class? Is there a way to alter a form, implemented by another module, using a class, in the same way it is possible to build a form using a class?

Drupal core code still uses hook_form_alter() (or hook_form_BASE_FORM_ID_alter(), or hook_form_FORM_ID_alter()) for that purpose.
You could alter a route and change the form associated with that route, but this would mean that:

You would need to keep track of the form class that was associated to that route before you changed it; in this way, you would be able to let the previous class add its own form fields
You would need to alter all the routes using that form class, in order to make Drupal use your class

The closer I could see used from Drupal code, which means the code would be in a class, is what the Content moderation module does in content_moderation_form_alter().

function content_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(EntityTypeInfo::class)
    ->formAlter($form, $form_state, $form_id);
}

Using that, you have the pro of using object-oriented code, allow other modules to extend the same form without complicating your code, and without interfering with code used from other modules.

Since the Drupal API page doesn't link the EntityTypeInfo class, it's the class defined in core/modules/content_moderation/src/EntityTypeInfo.php.

The relevant code is the following one, which shows how a class method is used as form submission handler.

  /**
   * Alters bundle forms to enforce revision handling.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param string $form_id
   *   The form id.
   *
   * @see hook_form_alter()
   */
  public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof BundleEntityFormBase) {
      $type = $form_object->getEntity()->getEntityType();
      if ($this->moderationInfo->canModerateEntitiesOfEntityType($type)) {
        $this->entityTypeManager->getHandler($type->getBundleOf(), 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
      }
    }
    elseif ($form_object instanceof ContentEntityFormInterface) {
      $entity = $form_object->getEntity();
      if ($this->moderationInfo->isModeratedEntity($entity)) {
        $this->entityTypeManager
          ->getHandler($entity->getEntityTypeId(), 'moderation')
          ->enforceRevisionsEntityFormAlter($form, $form_state, $form_id);
        // Submit handler to redirect to the latest version, if available.
        $form['actions']['submit']['#submit'][] = [EntityTypeInfo::class, 'bundleFormRedirect'];
      }
    }
  }

This is the form submission handler that method is using.

  /**
   * Redirect content entity edit forms on save, if there is a forward revision.
   *
   * When saving their changes, editors should see those changes displayed on
   * the next page.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public static function bundleFormRedirect(array &$form, FormStateInterface $form_state) {
    /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state->getFormObject()->getEntity();

    $moderation_info = \Drupal::getContainer()->get('content_moderation.moderation_information');
    if ($moderation_info->hasForwardRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
      $entity_type_id = $entity->getEntityTypeId();
      $form_state->setRedirect("entity.$entity_type_id.latest_version", [$entity_type_id => $entity->id()]);
    }
  }

As you see, it's not the same as extending FormBase, but it's more OOP than using plain functions.


Supressing "Undefined variable: variables in module_block_view()" without hiding the notice I tried to create a simple custom block inside a custom module. there is a notice that inform me about undefined variable, but the block rendered properly. I am not sure where the mistake in the code is, but any nudge in the right direction would be highly appreciated.

I know I can hide the error message by accessing admin/config/development/logging or by modules such as Disable Message, but that isn't what I desire since it essentially just hiding the problem under the rug and hiding other notices that I might be interested to look at.

mymodule.module

<?php
/**
* Declare what blocks are provided by this module
* Implements hook_block_info().
*/

function mymodule_block_info() {
  $block = array();

  $block['myblock1'] = array(
    'info' => t('Block number 1'),
  );

  $block['myblock2'] = array(
    'info' => t('Block number 2'),
  );

  return $block;
}

/**
* Define what our block is going to look like.
* Implements hook_block_view().
*/

function mymodule_block_view($delta='') {
  $block = array();

  switch ($delta) {
    case 'myblock1':
      $block['content'] = theme('myblock1', $variables);
      break;

    case 'myblock2':
      $block['content'] = theme('myblock2', $variables);
      break;
  }

  return $block;
}

/**
* Implementation of hook_theme().
*/

function mymodule_theme() {
  return array(
    'myblock1' => array(
      'variables' => array(),
      'template' => 'templates/block--myblock1',
    ),

    'myblock2' => array(
      'variables' => array(),
      'template' => 'templates/block--myblock2',
    ),
  );
}

?>

The problem is with $block['content'] = theme('myblock1', $variables); and $block['content'] = theme('myblock2', $variables);: mymodule_block_view() doesn't define any $variables variable; just define it or use an array directly.

Since in mymodule_theme() you don't define any variable for your theme functions, just replace your mymodule_block_view() with the following one.

function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'myblock1':
      $block['content'] = theme('myblock1', array());
      break;

    case 'myblock2':
      $block['content'] = theme('myblock2', array());
      break;
  }

  return $block;
}

To make the question more complete: Drupal doesn't define any global $variables nor do hook_block_view() implementations receive any $variables as parameter. Therefore, $variables could just be a local variables for your function. That is why you are getting that error: You are using a variable without to first declare it.

Notice that if $variables were a global variable, you should still declare it as global $variables in your function, or use it as $GLOBALS['variables']. (Don't try it since it doesn't work because doesn't define any global variable with that name.)


Webform + reCaptcha - still lot of SPAM Few months ago I installed reCaptcha module to use with webform. It worked perfectly: I can't submit form if I didn't provide correct captcha code. It worked even if I disable JavaScript. Problem is that I still get a lot of SPAM submissions from this webform. How this can be possible?
Drupal version: 6.27.
Webform version: 3.18.

There is really no silver bullet that can be used to completely stop spam. Spam can only be minimized.

Spam entered by human beings will still always get through -- and there are more and more human being spam farms out there.

The best solution that I have found is to work with Mollom rather than ReCaptcha.

Just as @Bisonbleu mentioned in the comment. Another module you can make use of is the honeypot module

  Honeypot uses both the honeypot and timestamp methods of deterring
  spam bots from completing forms on your Drupal site (read more here).
  These methods are effective against many spam bots, and are not as
  intrusive as CAPTCHAs or other methods which punish the user.


Search API requirements I'm trying to get the Search API module to work on my Drupal 7 installation, but I get the following error when I go to Home » Administration » Configuration » Search and metadata » Search API » Default node index:

  The server this index currently lies on doesn't support facets. To use facets you will have to move this index to a server supporting this feature.

What steps should I follow, in order to make my server compatible with the Search API module?

You can't use facets on MySQL (for the moment), from the project page:

Search facets
This module provides the ability to create facets on any search executed anywhere in Drupal, be it a search page, a view or any other source. The feature isn't available for all servers, though, since it would be too complex to implement for some service classes. Right now only the Solr servers support this, facet support for the database-based searches might be done in the future.

This means that you can't use facets, but you can still use Search API to search your content.


Using mixed case shortened URLs I have a content type Advert, which have image and URL fields and I put it in a block to place it on the page.

All works fine EXCEPT when the advertiser provides a mixed case Bit.ly shortened link to their site, Drupal is converting it to lower case but Bit.ly is case sensitive and either does not find the link at all or it redirect to another . How can I force Drupal to retain the mixed case URL, at least for external URLs? The Bit.ly link is important as the advertiser uses it to track ad clicks and hence the performance of the advert on our site

Doh, what a dummy! I missed an option in rewrite results on the image field to set output as link with no transform!

Thanks everybody.


Print password confirm field in user register template file I'm trying to theme the user registration form in Drupal 8.
I have defined a custom template for user registration form and printing the fields with the following code.

{{ form.field_profile_title }}
{{ form.field_profile_first_name }}
{{ form.account.mail }}

When I try to print confirm password field it's not printing the field.

{{ form.account.pass}}

What could be the issue?

You can always debug your twig template by printing the present variables, with help of of the Kint module (part of Devel) for example:

{{ kint(form.account.pass) }}

Or you can also print all of them:

{{ dump() }}

Further information on this page.


How to make the Rules module perform a redirect to an URL that includes a query string? I have created Task nodes, and I want to redirect to the previous (source) page after creation of a new task. I don't want people to see the task node. That page includes a view of all tasks.

For that I have created a simple rule:

Event: After saving new content
Condition: Content is of type tasks
Actions: Page redirect to [site:current-page:url]

This works, but not for a page that includes a query string. The rules redirect action chops off the query string of the source page.

In my case, I have a source page that always includes ?og_group_ref=[node:og-group-ref] in the URL in order to create group tasks. After creating a group tasks, the redirect happens but the query string in the URL is gone.

I tried to change the Rules redirect using Rules Action "Page redirect to [site:current-page:url]?og_group_ref=[node:og-group-ref]". However, that gives an error:

  Input evaluation generated an invalid URI.

Is there a way to accomplish Rules redirect including the query string?

You may want to try the "Rules URL argument" module to get this to work. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.


Does "drush dl" allow to download a module from a site that is not drupal.org? I have created a Drupal test site on Openshift, and I got Drush 6.2.0 installed. Reading the online help for drush dl, I see the following:

  Download Drupal core or projects from drupal.org (Drupal core, modules, themes
  or profiles) and other sources.

Looking at the rest of the help text, I don't see any option to say to the command the module I want to install is not hosted on drupal.org.

Can drush dl really download a module from a site that is not drupal.org, e.g. my git repository on github.com?

It looks like the source url for project downloads is context-specific - so you can set, for example, cli.source to something other than the default Drupal server, and Drush will look there for new releases.

I can't see anything in the code that would suggest that this can be done per-project though, just globally/per context (it's in [drush]/commands/pm/downloads.pm.inc if you're interested).

It is possible per-module using core functionality, i.e. adding this to your module's install file:

project status url

which:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

But it looks like Drush is expecting the remote server to provide data in Drupal's update XML format regardless of the source, so I don't think you'll be able to integrate this with Github without implementing some middleware.


WSOD and Drush cc all fail after deleting a view of a long-time-ago deleted module Background

Drupal 7.40 site, all is up2date, the site itself worked, until the last hour, just fine.

The problem

I once had a module named Flexslider and have deleted it 5 months ago. One of it's views and/or content types stayed alive and I've deleted it in the last hour; Since then there is a WSOD in my site and each time I try to flush all caches with Drush I get the following error about the impossibility to access a Flexslider file.

Any ideas why would that happen?

Image update for user - Les Lim:

Since I happen to know from WSOD afte uninstalling the Memcache module and deleting it's folder that you just stopped using Memcache, then I know that your Drupal site has just reverted back to using the database cache.

You probably had entries in your database cache from before you switched to Memcache in the first place.  Those really old database cache entries are now back in use.

You're trying to clear caches, which is absolutely the correct thing to do. However, there's a nasty bug in CTools that prevents you from clearing the cache if a particular CTools cache entry is broken: https://www.drupal.org/node/1775612

In this case, though, the manual fix is pretty simple. You need to truncate the cache table in your database. That should allow the cache to rebuild itself normally.


Role that can set roles but not change its own In our sites, I have an Admin role (me) and Staff roles.  The Staff role needs to be able to create client user accounts and assign client specific roles to those accounts.  How can I give my staff the permission to set other's roles but not their own?  I don't want them changing themselves to an admin when they want to (and they have).

It really sounds like there should be a module that does this ... I'm not aware of 1 offhand.

You could use hook_form_alter on the user account form and simply check the role of the logged in user. If they are Staff allow them to set roles to all but the Admin role you've defined. You would simply unset() the admin value in the $options array for the Roles checkboxes.

For example:

function MYMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (array_search('Staff', $user->roles)) {
    // Any RIDs you want to remove.
    unset($form['account']['roles']['#options'][3]);
  }
}

You would also probably want to add a validator to this form to check that a Staff user does not try to get around this by setting this value for instance via Firefox's Firebug. I leave that exercise to you.


Enable rest resource resource when module installs I have a custom rest resource I have created within my module:

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "custom",
 *   label = @Translation("custom"),
 *   uri_paths = {
 *     "canonical" = "/rest/custom"
 *   }
 * )
 */
class custom extends ResourceBase {
public function get() {
    return new ResourceResponse("Response");
}

I have a rest.resource.custom.yml file in my module/custom/install folder to activate the end point when the module gets installed but it doesnt work:

id: module.custom
plugin_id: 'custom'
granularity: method
status: true
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie

How do you enable rest endpoints when module is installed?

The error was in the .yml file with the id: attribute. Dont need to include the module name with it:

id: custom
plugin_id: 'custom'
granularity: method
status: true
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie


Check if the user has read a node, if so give access to the next Is there a module which can check if an user has read a node? For example, I have this node:

Node order 1
Node order 2 (locked)
Node order 3 (locked)
Node order 4 (locked)

If the user read 'node order 1' or marked as read with a button, he has access to 'node order 2'. If 'node order 2' has marked as read, he has access to 'node order 3'.
It's all user based. It's similar to an e-learning structure, but I don't like heavy modules like: course or opigno for just this functionality.
Can I do something like this with rules or an other lightweight module? I saw the flag module, but I don't know if it possible to do something like this with that module?

I'd say you can use hook_ENTITY_TYPE_view to store the uid and the nid of the user into a custom table. That would solve the easy part, I believe.
You'd may start by something similar to
function yourmodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity,
        \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $bundle = $entity->bundle();
  if($bundle == 'your_content_type') {
    $uid = \Drupal::currentUser()->id(); // get current user's ID
    $nid = $entity->get('nid');
    [...] // insert into custom table, etc
  }
}

For the long-term, complex solution regarding performance, that's a huge discussion. If your node list is just a simple queue that unlocks next node if previous has been read, then maybe storing just the current nid would work for you. If you need the history per user, then, as mentioned, some different solutions could do the trick. Other approach could be to do database sharding, for instance creating 1 table per node so table_read_nid_1 would just contain the users who actually have read this node and can unlock the second. table_read_nid_2 would contain the next and so on. Don't be afraid of sharding, lots of big companies use it daily! :)


Create ubercart ordes for users I need to create ubercart orders for a bunch of users. Can this be done with views and VBO or do I need to make a custom module for that?

You would need to create a custom module for this as you want to create X number of orders for X number of users. Reason why you need a custom module is because each order is its own node with a bunch of references to other data on the site. Doing this in bulk would require you to know all the tables data that are updated and inserted when an order is created.


User proximity search? I'm running D7.  I'm trying to figure out how to a) tag users with a location (ZIP, address, city, state, etc.) when they register an account, and b) set up a search where the visitor inputs their location (via ZIP, address, etc.), and it returns a list of every registered user sorted by their proximity to the inputted location in the search.  I'm more interested in an answer to part b) since it seems more complicated, but honestly any help at this point would be very appreciated.  I've been stuck for a few weeks now.

Thanks,
Edward Sapp

There are two basic approaches for doing locations in D7:

the location and gmap modules
the addressfield, geocoder, and openlayers modules

According to Karen Stevenson's presentation at Do It With Drupal 2011, only location/gmap currently has location proximity search working in D7... but not very well.

Based on this presentation and the book Mapping with Drupal, I set up proximity search on my own site using the location module.  It works, but it's not terribly user friendly, it's a pain to theme, and it's still clearly under development.  However, it's a far better solution than I would have been able to arrive at rolling my own.


How to list duplicate nodes based on title with views I'm trying to list all duplicate nodes based on node title with views.

In views aggregation settings it's said that:

  If enabled, some fields may become unavailable. All fields that are
  selected for grouping will be collapsed to one record per distinct
  value. Other fields which are selected for aggregation will have the
  function run on them. For example, you can group nodes on title and
  count the number of nids in order to get a list of duplicate titles.

I enabled aggregation and added a node content title filter (aggregation: count) to count nodes and list if a title has more than one node (count:  Is greater than 1). But it doesn't work for me, it lists nodes with unique titles and duplicate titles (I mean no affect).

How can I list all nodes with duplicate titles by using views?

The filter should be on content:nid. Set it to aggregate on COUNT, and 'Is greater than' value 1.

Then check all of your fields that you have added. None of the fields for nodes with the same title should output a different value. Title for instance, can be unique, depending on how you output it. If you for instance output it as a link (the default), then for each title that is the same, but that belongs to another node, the link is unique, therefore you view won't perform the way you want it to. So deselect 'Link this field to the original piece of content' and it should work.


Add user name and content to user menu I'm very new to drupal, I've got a basic understanding of PHP and how it should be written but I think I'm still struggling with the concept of where to add code, at what point I need to jump in to edit things and make my own style do its thing

All I want to do is change my default user menu from:

User Menu

 - My Account
 - Log out

To

Logged in as:
[username]

My Account

Log Out (where both buttons have mybtn class applied to them rather than in a ul)

I've seen I can remove the ul function from the list that is outputted with the following code

function MYTHEME_menu_tree__user_menu(&$variables) {
 return $variables['tree'];
}

And I've also tried to add the username to the content of the username with this block

function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->content .= check_plain($user->name);
    }
  }

}

(this code was modified from someone explaining how to change the subject of the block to the username)

I'd really appreciate any help with where to go next

Kind regards

I ended up slowly working my way towards the result, my main issue was trying to get the dpm to show me what content I can change - but that's just because I'm, still slightly unfamiliar with how the whole process runs

function MYTHEME_menu_tree__user_menu(&$variables) {
 return '
'. $variables['tree'] .'
';
}

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

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

  $element['#localized_options']['attributes'] = array('class' => 'my-btn');

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

function MYTHEME_preprocess_block(&$variables){
  global $user;
  $block =& $variables['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $variables['content'] = check_plain($user->name) . $variables['content'];
    }
  }

}


.htaccess concatenating www + subdomain I'm running a new Drupal 7 site on Ubuntu 14 (so no httpd.conf file), and am trying to make a simple htaccess rule to redirect from no subdomain to www. Basic stuff, the Internet told me what to do, and I used this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Problem is that if I put in a subdomain - something.domain.com - it concatenates the URL to www.something.domain.com

How can I get around this? It's... quite annoying. Perhaps a module would be a better solution than an .htaccess update?

(Also Global Redirect Case Sensitive URL Checking isn't working, but that's another story...)

Thanks.

If I understand you correctly, you want to redirect everyone to the www version of the site.
How about this.

RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

It will redirect anything that isn't www.example.com to www.example.com and pass along the url.

http://httpd.apache.org/docs/2.4/rewrite/intro.html has more options you can use.


Cache error on file upload with media, multiform, and plupload Checkout the log entries for a site I am working on, I found multiple pairs of the following notice/error:

  Error: Form build-id mismatch detected while attempting to store a
  form in the cache. Notice: Undefined index: #build_id in
  form_set_cache() (line 564 of /dir/includes/form.inc).

I am using media-2.x with plupload and multiform. The above messages are always logged for all files uploaded through plupload at file/add. Any ideas what is going on here and how to fix it? There will be a lot of file uploads on this site, and I really don't want the database filling up with these log entries.

I am getting these messages with Pantheon and with my local environment, so going to assume it is not a server configuration issue, Core and all modules are up to date. Php is 5.4.

Any help would be very much appreciated!

There is a bug in multiform that was introduced by recent changes to Drupal Core. The bug has been reported in the module's issue queue and a patch has been provided: https://drupal.org/node/2247527

The patch fixed the issue for me, and hopefully will be included in the next release of the module.


How to add variable using mytheme_preprocess_field and print using twig template? We have a content type Article that has two custom fields: field_header and field_link. When field_header is not populated, we want to perform validation in twig template to add a CSS class. When we tried to set a custom variable using $variables['myVariable'] = TRUE and try to print the value in the twig template, it is returning a NULL value.

How can I create a custom variable using mytheme_preprocess_field() hook and use it in the twig template?

mytheme.theme

function mytheme_preprocess_field(&$variables) {
  $element = $variables['element'];
  if($element['#field_name'] == 'field_header') {
    if($element['#items']->first()->isEmpty()) {
      $variables['myVariable'] = TRUE;
    }
  }
}

node--article.html.twig

<div>
  {{ kint(myVariable) }} // Returns NULL everytime.

  {% if myVariable %}
    // If not empty, do something.
  {% else %}
    // If empty, do something else.
  {% endif %}
</div>

Variables in a template are scoped - what you add in hook_preprocess_field will only be available in field.html.twig and its derivatives, not node.html.twig etc.

You can implement the same logic in the node preprocess:

function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->hasField('field_header') && $variables['node']->field_header->isEmpty()) {
    $variables['myVariable'] = TRUE;
  }
}


Ajax textfield in hook_form_alter I'm attaching ajax on textfield value. One enter value in textfield and ajax callback returns form element.

Below code is showing ajax 500 error. Can anyone tell what is mistake in this code?

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    $form['field_base_price']['widget'][0]['value']['#ajax'] = array(
            'event' => 'change',
            'wrapper' => 'final-price-wrapper',
            'callback' => 'final_price_ajax_callback',
            'method' => 'replace',
          );

    $form['field_final_price']['#prefix'] = '
';
        $form['field_final_price']['#suffix'] = '
';
          $form['final_price_label'] = array(
            '#weight' => 11,
            '#prefix' => '
',
            '#suffix' => '
',
          );
          $form['final_price_label']['title'] = array(
            '#type' => 'markup',
            '#markup' => '' . $form['field_final_price']['widget'][0]['value']['#title'] . '',
          );

    }

    /**
     * Final price AJAX callback.
     */
    function final_price_ajax_callback($form, $form_state) {
      return $form['final_price_label'];
    }

You can use simple jQuery to achieve this then. Try putting the following code in your JS file:

$("#fname").blur(function(){
  var fname = $("#fname").val();
$("#lname").val(fname);
});


Add a CSS basing on the author of the comment This node has a comment by the user #1, who is the node author, and a comment by an anonymous user. I want to add an extra CSS class to comments by the node author.

The variables in Bartik's comment.tpl.php include $author and $comment-by-node-author.

What is the correct syntax for an if statement saying if this comment is by the node author (or by user #1) apply the class example and just print the comment as usual when the author is somebody else?

If (what I'm not sure) understand your question correctly, you want to add an extra class if the comment was posted by the node author.

As explained in Bartik documentation:

 /*   - $classes: String of classes that can be used to style contextually through
  *   CSS. It can be manipulated through the variable $classes_array from
  *   preprocess functions. The default values can be one or more of the following:
  *   - comment: The current template type, i.e., "theming hook".
  *   - comment-by-anonymous: Comment by an unregistered user.
  *   - comment-by-node-author: Comment by the author of the parent node.
  */

There are already specific classes for comments posted :

by node author : .comment-by-node-author
by anonymous : .comment-by-anonymous

And you can see that in your node markup :

/* ... */


How to create a block to remind special dates as stored in user profiles? I'm looking for a way to remind special dates per user profile. I mean remember birthdays, marry dates, graduations.

The idea is to display in the home page a block with all those reminders for all the users.

Any suggestions?

Step 1: Flag appropriate users/nodes

I assume you want to show a Block with such reminders (not "sending eMails" ...). To do so, use the Flag module to create a global flag, say you name it "Show Reminder", and then use the Views module to create a block of all "flagged content" (using this flag), similar to what is explained in Creating global flags and listing flagged content in Views.

Step 2: Use Rules to automate the flagging

You don't want to manually flag (and unflag) all such content every day, right? But that's what the Rules module is for: create a (1st) rule to "flag" whatever node, user, etc fits your criteria for "current day", and a similar (2nd) rule to later on "unflag" them again.

Step 3: Trigger both rules once a day

Use the Rules Once per Day module to schedule both rules described in Step 2.

Bonus Features

Handling invalid or missing dates

In case any node or user that "should" show up, doesn't show up on a specific date (since its date is missing or wrong), it's a matter of just flagging such node or user to have it also appear in the block.

Spotlights

For some node or user you for which you don't have a date, but which for some reason you also want to be shown, just flag it and it shows up also.

Creating reminders does not require edit permission

Flagging a node or user can be configured in such a way that you can separate its required permission from editor permissions. That opens possibilities for having various types of users contribute to producing such reminders (if that is what you'd want).


User registration email translation I am working on an English/Arabic website, the user can switch between the two languages using the language switch block, I wanted to translate the email sent to the user after registration. So after some digging, I figured out I could do this using the account setting (translate tab), I added the Arabic translation of the email; then, after testing, I found out that the registration email is still sent in English.

Shouldn't a user registered in the Arabic language get an Arabic registration email?

I also found out that the user's preferred language is English, even after registering in the Arabic language.

These are my language detection settings.

As you said you have configured the translations correctly.
On the account settings page you will be able to see the Translate Settings tab here /admin/config/people/accounts

After clicking on the link here you will find the enabled languages with options in front of them

Click on edit and then you will be able to see all the Account settings to be translated including mail where you can write / modify the text in mail like in following screenshot.


Custom field widget: hook_field_is_empty() I'm creating a custom module that has implemented these hooks:

<?php
/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_hook_info() {
  return array(
    'CUSTOM_field' => array(
      'label' => t('Custom Text Area'),
      'field_types' => array('text_long'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch($instance['widget']['type']) {
    case 'CUSTOM_field':
      $element['MYFIELD_field'] = array(
        '#type' => 'textarea',
        '#attributes' => array('id' => 'MYFIELD', 'rows' => '5', 'cols' => '3'),
        '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
      );
      break;
  }
  return array('value' => $element);
}

All it is supposed to do is provide a custom widget to the Long Text field type that enables some custom functionality. My custom widget appears in manage fields and I can enable it and use it on a node edit form. However, when I save the node with text in the field, nothing saves to the database the data saves to the database, but doesn't display in the field when the node is edited again.

After some searching, I found some posts that said hook_field_is_empty() is mandatory and is a common problem for values not saving. I attempted to implement the hook exactly as the API said:

<?php
/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {
  if (empty($item['value']) && (string) $item['value'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

This immediately started throwing an error in Drupal:

  Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1573 of /includes/bootstrap.inc).

So I looked around some more on here and Google and changed the hook based on this answer:

<?php
/**
 * Implements hook_field_is_empty().
 */
function MYMODULE_field_is_empty($item, $field) {
  if ($field['type'] == 'text_long') {
    if (empty($item[$field['type']]['CUSTOM_field'])) {
      return TRUE;
    }
  }
  return FALSE;
}

This returns the same error and it also doesn't save the value of the field into the database display the field data from the database. Do I have to create a custom field with a MYMODULE.install and the appropriate hooks, or can I just use an existing field type like I'm doing. Why is the data not saving to pulling from the database?

I think you want to change your default values to variable_get('yourmodule_variable') so that it displays the value that was saved previously.


Prevent cache when updating with field_attach_update I have a problem with caching. I've set up a menu hook for an URL like /user/USER_ID/some_info, which automatically receives the entire user object because of the way I set up my menu hook (see below).

The problem I'm facing is that I have all caching modules enabled in Drupal (including EntityCache) and the $usr variable gets passed from the cache. So naturally if I update a field and save it using field_attach_update, the data is saved into the DB, but the old data is shown on the form, confusing the admins (the checkbox is checked, even though I just unchecked it, and it's value in the DB is in fact 0).

Is there a way I can disable caching for this particular object ($usr) in this particular function?

Note: on my local machine where caching is pretty much disabled, it works fine, both the UI and DB get updated.

My menu hook:

$items['user/%user/some_info'] = array(
    'title' => 'Some Info',
    'description' => 'Edit',
    'page callback' => 'mymodule_edit_user',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'file' => 'mymodule.pages.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 8
);

The function that gets executed:

function mymodule_edit_user($usr){
    // check if POST and validation here
    if(isset($_POST['somefield'])) //checkbox
        $usr->field_somefield[LANGUAGE_NONE][0]['value'] = 1;
    else
        $usr->field_somefield[LANGUAGE_NONE][0]['value'] = 0;

    field_attach_update('user', $usr);
}

Sorry I didn't do more digging before asking this, but going to answer my own question in case someone else finds this.

I've taken a look inside the user_save function, and seen that it does some invoking, so I did it too. Surprise: it worked (EntityCache was the bad guy who was caching everything BTW).

Here's my code for reference:

$usr->field_somefield[LANGUAGE_NONE][0]['value'] = 0;
field_attach_presave('user', $usr);
module_invoke_all('entity_presave', $usr, 'user');
module_invoke_all('entity_update', $usr, 'user');
field_attach_update('user', $usr);


Which is more performant: entity_metadata_wrapper or field_get_items? To get values from entities, there are two ways:

Use field_get_items and get the value of a field
Use entity_metadata_wrapper and get the value of a field

Although entity_metadata_wrapper abstracts away the language differences, its API is still awkward sometimes, especially when using PHP 5.3. For example, getting the value of a long text field usually goes this route:

$field = $wrapper->field->value();
print $field['safe_value'];

Fortunately, PHP 5.4 supports this syntax: print $wrapper->field->value()['safe_value'];.

But my question is more concerned about performance. How do they both work? Do they query the database every time they request a value? Does entity_metadata_wrapper requests everything at once? (Making field_get_item more suited to single-value-retrievals.)

I'm not brave enough to dive deep into Drupal source.

The short answer: field_get_items() is more performant than entity_metadata_wrapper().

Check out the code for these functions:

field_get_items()
entity_metadata_wrapper()

Both require that you pass along the entity, which has already been loaded from the database. For example:

$node = node_load(123);
$items = field_get_items('node', $node, 'field_my_field_name');
print $items[0]['value'];

or, as you've already suggested:

$wrapper = entity_metadata_wrapper('node', $node);
$field = $wrapper->field_my_field_name->value();
print $field['safe_value'];

Both of these instances kind of bother me because of the silly logic in trying to get a value that's already available to you, but they are certainly useful in lots of cases.

You could just do print $node->field_my_field_name[LANGUAGE_NONE][0]['value']; but that would throw PHP notice errors if the field doesn't have a value, since you're trying to access arrays that may not exist (i.e. [LANGUAGE_NONE][0]['value']). I find myself doing this quite often lately:

if ($field = field_get_items('node', $node, 'field_my_field_name')) {
  print $field[0]['value'];
}

which is a lot cleaner than doing:

if (isset($node->field_my_field_name[LANGUAGE_NONE]) && isset($node->field_my_field_name[LANGUAGE_NONE][0])) {
  print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];
}

If you look at the code for field_get_items()) you'll see that it's doing nothing more then ensuring that the field's array has data in the curent language and then returns it. So, the overhead of running such a tiny function is negligible, but if you are really concerned with performance you can just do your own check if the data exists and then print it.

Edit: Since field_get_items() runs field_language() there would actually be a bigger performance hit than just checking the language, so, if you already know that $entity->language exists, you could just write your own super-performant function:

function my_super_performant_field_value_getter($entity, $field_name) {
  return isset($entity->{$field_name}[{$entity->language}]) ? $entity->{$field_name}[{$entity->language}] : FALSE;
}


How to load library only on one twig template? We have a custom theme, mytheme where we have the following library for the header-fix. I have also added {{ attach_library('mytheme/header-fix') }} to only one twig template block--myblock.html.twig that is for my custom block myblock.

The goal is to only add the library to myblock when myblock is rendered on the page.

The problem we are having is that the library is being added to all pages even ones where the block is not present (loaded on the page). How can we load a single library only on one block and not all the twig templates?

myblock configuration:

restricted to only Article content type (so do not load on basic content type)

block--myblock.html.twig

{{ attach_library('mytheme/header-fix') }}

Continually fashion turnkey sources without web-enabled alignments. Some more content.

mytheme.libraries.yml

...
header-fix:
  version: 1.x
  js:
    /path/to/header-fix.js: { preproces: false, attributes: { defer: true } }
...

mytheme.info.yml

...
libraries:
  - mytheme/header-fix
...

Just remove the reference from mytheme.info.yml.

That's adding it any time the theme is loaded (every page), whereas attach_library will add it only when that specific template is used.

You'll need to rebuild cache for the change to take effect.


How to manage ajax in nested forms? As implied in this question, I'm adding a list of similar child forms to my parent form with the following code:

foreach ($form_state['items'] as $key => $item) {

    $existing = NULL;
    if (isset($form['item_holder'][$key])) {
        $existing = $form['item_holder'][$key];
    }

    $state = NULL;
    if (isset($form_state['item_holder'][$key])) {
        $state = $form_state['item_holder'][$key];
    }

    $el = item_form_edit($existing, $state, $item);

    $form['item_holder'][$key] = $el;
}

I am calling the form function directly because drupal_get_form() was causing errors due to confusion about which form was being submitted.

My child form type has ajax callbacks that return parts of it $form object. But  the child's callback function is receiving the parent form's object and causing an error trying to return parts of the child form.

How do I sort out ajax calls between parent and child $form contexts? Do I need to go back and add the child forms with drupal_get_form()? If so, how do I avoid confusing which form has been submitted?

It turns out Drupal will distinguish ajax for subforms automatically if you work within the system - which I was not.

Instead of calling the form builder function directly (bad), I use drupal_get_form() so the code above becomes:

foreach ($form_state['items'] as $key => $item) {

    $form['item_holder'][$key] = drupal_get_form('item_form_edit', $item);

}

I was previously loading the subitem's code with module_load_include(). I now load the sub-item's code with form_load_include() which should make a cached version of this form load correctly.

Since I am building a list of similar subforms, the subform needs to make sure it gets a unique wrapper:

function item_form_edit($form, &$form_state, $edit = NULL) {

    $id_string = 'sub-item-form';
    $unique_id = drupal_html_id($id_string);

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    ...

    return $form;
}

Now, an AJAX element on the subform can replace that subform with

    '#ajax' => array(
        'wrapper' => $unique_id,
        'callback' => 'subform_callback',
        ...

In this example, the entire subform is being replaced by the callback:

function subform_callback($form, &$form_state) {
    return $form;
}

My subform builder function is in a separate file, so hook_init() needs to make Drupal aware of the subform code during AJAX requests:

if ($_GET['q'] == 'system/ajax' || strstr($_GET['q'], 'file/ajax/')) {
    if (preg_match('/item_form_edit/', $_POST['form_id'])) {
        module_load_include('inc', 'mymodule', 'file_with_item_form');
    }
}


Alter login form in block by id I have a small problem on D7, I need to alter the login form inside block (add class to inputs, placeholder and submit button text, custom pass reset and login links) im using hook_form_FORM_ID_alter. I don't need to use custom module.

block id = block-user-login, form id = user_login_block

My theme.php code

function themename_form_user_login_block_alter(&$form, &$form_state) {

    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );

   // custom register link
    $form['actions']['signup'] = array(
        '#markup' => l(t('Register'), 'user/register', array(
            'attributes' => array(
                'class' => 'top-user-block-link register',
                'title' => t('Create a new user account.')
            )
        )),
    );

    // custom reset password link
    $form['actions']['request_password'] = array(
        '#markup' => l(t('Forgot my password'), 'user/password', array(
            'attributes' => array(
                'class' => 'top-user-block-link new-password',
                'title' => t('Request new password.'),
            )
        )),
    );
}

Links for password reset and login links renders fine, but i can't make the placeholders or class add to work.

i've tried to use

function theme_form_alter(&$form, &$form_state, $form_id){
  if ($form_id === 'user_login_block') {
$form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
}

but i works only on /login page.

If I recall correctly, you need $form['account']['name']['#attributes'].


How to use the Webform Serial in a Webform Rule? Is there a way to use the Webform Serial (not the SID) be used in a webform rule?

I've tried the following with no success:

[data:serial]
[webform:serial]
[node:serial]

I do have Webform Rules & Webform Tokens installed.

Have a look at comment #2 in issue #2572067, which states this:

The correct token for that is [submission:serial], but some module is going to have to make that token available to the rules module. Webform itself doesn't do that. I haven't tried it, but the Webform Rules modules would be the place to start.
The serial number is a relatively new feature, but I would have though it would work without an update to the Webform Rules module. If not, you might file an issue in that module's queue.


Form alteration is not working from within my form class I am following https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api for my hello world module.

Below is my code

namespace Drupal\hello_world\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an hello_world form.
 */
class HelloWorldForm extends FormBase {

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

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

        $form['phone_number'] = array(
            '#type' => 'tel',
            '#title' => $this->t('Your phone number'),
        );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
            '#button_type' => 'primary',
        );
        return $form;
    }

    function hello_world_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
        if ($form_id == 'hello_world_form') {
            $form['phone_number']['#description'] = t('Start with + and your country code.');
        }
    }

}

I also cleated cache. Not sure why form is not altering.

Use your hello_world_form_alter in your module file. I guess should be hello_world.module. I guess you already have a folder hello_world where you placed the file above. In this folder you should also have an .info.yml file at the same folder place your hello_world.module file.

Please check https://www.drupal.org/docs/8/creating-custom-modules. You will find a lot of tutorials about how to create a custom module. Just google it!


How to force D8 "Configuration synchronization" to send HTTPS download URL I have a Drupal 8 site hosted on an Apache Server.
There are 2 virtuals hosts :

one listening on port 80, which redirects everything to HTTPS
one listening on port 443 which serves the htdocs directory where the Drupal site is located

Everything works well, except for the "Configuration synchronization" full export. When I click the "Export" button, I'm redirected to the home page, without any message or log.

Enabling the console on my web browser, I saw these calls :

POST https://my.domain.fr/admin/config/development/configuration/full/export
[HTTP/1.1 303 See Other 86 ms]
GET http://my.domain.fr/admin/config/development/configuration/full/export-download
[HTTP/1.1 301 Moved Permanently 101 ms]
GET https://my.domain.fr/
[HTTP/1.1 200 OK 183 ms]

The download process of the config file seems to be killed by the redirection.

The second URL (GET http) is sent by Drupal in the response to the first call, in the "Location" header.

How can I force Drupal to send only HTTPS url, even in the Location header in this precise case ?

Edit: Potentially linked post

Edit2: I'm having the same trouble with the RSS link on the site : on the page returned by https://my.domain.fr, the RSS link is http://my.domain.fr/rss.xml

Edit3: Found the solution for the export problem (see answer below). Still not a solution for the RSS link, but it's not the main subject of this post.

I forgot the SSLEngine On Apache directive in the configuration of the VHost listening on port 443.

With it, the Location header sent by Drupal contains now https scheme.


Taxonomy term custom view page for all sub terms I have taxonomy called Sections and it has several terms,their children and grand children.
How can i set same display page or display format for all the sub section pages irrespective of their depth.

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

This module will help you for sure :)

Read the documentation at https://www.drupal.org/node/577646


Use Checkboxes with Drupal Better Exposed filter Better Exposed Filters is not showing the option for Radio buttons and Check boxes. How do I enable it?

Better Exposed Filter working well and good until I enable the Auto Submit option. My Check boxes are gone and shows simply the list. So I uncheck the auto submit, but still i don't get the options to choose.

The filter criteria are set to "Content: Has taxonomy term"; the selection type is "Dropdown."

This also tripped me up. The settings weren't where I expected them to be and there were a couple of prerequisites. Maybe this is your issue too?

Create a View and expose a filter
Under Advanced > Exposed form > Exposed form style select Better Exposed Filters
Under BEF Settings roll down to the bottom where there are the Exposed Filter settings and select Checkboxes/Radio Buttons from the drop down menu.

Note: You can't select these settings for filters that don't have a limited number of options. (A title won't work, but a term will.) The documentation says:

  BEF only operates on fields that have a limited number of options such as Node:Type or Taxonomy:TermID. Open-ended fields, such as Node:Title, do not work with BEF. Entity References do work, however, if you Enable Render Views filters as select list (a checkbox) in the Entity's entityreference field.

I had utilized the entity reference field pattern. You need to edit the field you are referencing in the Content types > [content type] > manage fields > [field name] > edit. field settings. There, at the bottom of the page under Additional Behaviours you will find a checkbox for Render Views filters. That will allow the aforementioned select box (in BEF settings) to properly display the Checkbox/Radio option.


Ubercart 3: Skip review, single page checkout I am using Drupal 7.12 and Ubercart 3.0. I created a custom module in order to enable a single page checkout by skipping the checkout review page.

The Code

/**
 * Implementation of hook_form_submit().
 *
 * Change Ubercart review pages to instant order submissions.
 */
function uc_onepagecheckout_form_submit($form, &$form_state) {
    // check for order submit
    if(isset($form_state['storage']['order'])) {
        $order_id = $form_state['storage']['order']->order_id;
        $reviewRequested = $_SESSION['uc_checkout'][$order_id]['do_review'];
    }

    // If the normal submit handler set do_review then call the review
    // form submit function.
    if ($reviewRequested && $form_state['redirect'] == 'cart/checkout/review') {
        // Clear the previous redirect because we're going to override it anyway.
        unset($form_state['redirect']);

        // Cause the review form to be loaded because some modules may
        // do some of their processing here.
        uc_cart_checkout_review();

        $order = uc_order_load($_SESSION['cart_order']);
        if ($order->payment_method == 'paypal_wps') {
            $wps_form = uc_paypal_wps_form($form, $form_state, $order);
            $wps_url = $wps_form['#action'] . '?';
            foreach (element_children($wps_form) as $key) {
                $wps_url .= urlencode($key) . '=' . urlencode($wps_form[$key]['#value']) . '&';
            }
            $wps_url = trim($wps_url, '&');
            drupal_goto($wps_url);
        }
        else {
            // Now submit the form.  Obviously the $form_state isn't actually
            // correct... hopefully nothing will care.
            uc_cart_checkout_review_form_submit($form, $form_state);

            // And check for an error.
            if ($form_state['redirect'] == 'cart/checkout/review') {
                // There's an error, so pretend the user clicked back.
                uc_cart_checkout_review_form_back($form, $form_state);
            }
        }

        // Ultimately the $form_state changes made by functions above are used.
    }
    elseif ($form_state['redirect'] != 'cart/checkout') {
        // Log any unexpected URLs in 'redirect'.
        watchdog('uc_cart', 'Checkout returned unexpected destination url: %url',
            array('%url' => $form_state['redirect']), WATCHDOG_DEBUG);
    }
}

/**
 * Implementation of hook_form_alter().
 *
 * Changes text on review order button to submit order and adds our custom submit function.
 * Adds a "Skip checkout review" option to checkout settings form.
 */
function uc_onepagecheckout_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id) {
        case 'uc_cart_checkout_form':
            // Change the submit button label.
            $form['actions']['continue']['#value'] = variable_get('uc_checkout_submit_button', t('Submit order'));

            // Add our submit handler.
            $form['#submit'][] = 'uc_onepagecheckout_form_submit';
            // And add our JavaScript file to handle this submit button.
            drupal_add_js(drupal_get_path('module', 'uc_optional_checkout_review') .'/uc_onepagecheckout_checkout_form.js');
            // Add the uc_cart css, since it contains the throbber styles that we are using in the JavaScript.
            drupal_add_css(drupal_get_path('module', 'uc_cart') .'/uc_cart.css');

            break;
    }
}

This code is based on this module: Ubercart Optional Checkout Review

The Problem

Submitted orders are getting stuck in the "in_checkout" state instead of having the "pending" state. Also, no emails are sent to the customers. Probably, the invocation of uc_cart_checkout_review_form_submit($form, $form_state) does not work properly.

Can you help me to solve this issue?

I found it myself. The problem was a non-intended change in the ubercart core file uc_cart.pages.inc, so that the function uc_cart_checkout_complete() instantly returned without completing the order. This should not occur in normal cases, so that the code in my question should work.


Custom image style conversion - how to read back from a file? I'm making a custom image style in Drupal 8.

It takes various parameters and passes the image to an external service for processing, and it now needs to read back the processed image from a file.

However, in applyEffect I'm expected to work with the Image $image object passed in.

The site is using the standard GD2 toolkit, which provides a load() method, but alas it's protected (presumably because the Image object that owns it would need updating).

Previously (porting this effect from D7) I was able to create a new Image object from the new image and replace the original object's resource and info properties, thus moving the altered image data into the image object. But this is no longer possible.

To summarise I want to:

public function applyEffect(ImageInterface $image) {
    $image->save('/some/path');
    $new_image_filename = call_some_external_process('/some/path');
    $image->load($new_image_filename); // ← this does not work :-)
    return TRUE;
}

Here's how I did it.

public function applyEffect(ImageInterface $image) {

    // Save the image and process it externally...
    $some_tempoaray_filename = '/tmp/foo';
    $image->save($some_tempoaray_filename);
    call_some_external_process($some_tempoaray_filename);

    $toolkit = \Drupal::service('image.toolkit.manager')->getDefaultToolkit();
    // Re-call the existing Image object's constructor with the name of the
    // new file.
    $image->__construct($toolkit, $some_tempoaray_filename);
    // Next we have to make sure it loads the file into memory
    // because $image->save() requires it to be loaded, but this
    // happens outside of this function and we want to delete
    // the $some_tempoaray_filename so as not to leave temp files.
    $toolkit->getResource(); // forces a load.
    // Now we can lose our temporary file.
    unlink($some_tempoaray_filename);

    return TRUE;
}


How to troubleshoot entity error How can I tell which entity is throwing this error (on all pages)?

  TypeError: Argument 4 passed to Drupal\views\Plugin\views\display\Block::__construct() must implement interface Drupal\Core\Entity\EntityManagerInterface, instance of Drupal\Core\Entity\EntityTypeManager given, called in /usr/local/var/www/hifldlive/web/modules/contrib/ctools/modules/ctools_views/src/Plugin/Display/Block.php on line 54 in Drupal\views\Plugin\views\display\Block->__construct() (line 69 of core/modules/views/src/Plugin/views/display/Block.php).

I have run composer update on an un-familiar site.
Composer update, drush updb and drush cr all run without errors.
There are about 20 migration tables generated.

I'm guessing I need to roll back the composer update (since it trashes the site), fix the data, then re-run the composer update.
I stuck on how to identify what to fix.
It is no problem to roll back.

I can't where entities are stored in the database.
I also don't see entities in the admin pages.

I can use Drupal Entity API in a custom module, but the site won't load on any page.

This is not a problem with entities stored in the database, it is is a version conflict between the module Ctools and Drupal core.

When you install the current version of Ctools with composer require 'drupal/ctools:^3.4' you see that __construct() is calling the parent constructor providing a parameter EntityTypeManagerInterface.

modules/contrib/ctools/modules/ctools_views/src/Plugin/Display/Block.php

  /**
   * Constructs a new Block instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
   *   The block manager.
   * @param \Drupal\views\Plugin\ViewsHandlerManager $filter_manager
   *   The views filter plugin manager.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, BlockManagerInterface $block_manager, ViewsHandlerManager $filter_manager, Request $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $block_manager);

    $this->filterManager = $filter_manager;
    $this->request = $request;
  }

This requires that your core version has this code change:

https://git.drupalcode.org/project/drupal/-/commit/12d7ed53087a469ef8f87476c2849f7b24bfbbb7#140e79af0797f7f25fd1f20e2ebc697be118fea6

So you have to make sure you are using a current core version 8.8.x or you have to downgrade Ctools to a version not having this change.


How to create a contextual filter to be used as the first character for a field? I create a view listing a field called authors the page path miSite.com/authors

Then if I load this page I get the results:

Bach
Vivaldi
Vaccaro
Babbitt

This view page has the path: miSite.com/authors

I need to create a contextual filter to filter the result for the first character of the author field. I should work in this way:

1) If I load:

miSite.com/authors/b

I get the results:

Bach
Babbitt

2) If I load:

miSite.com/authors/v

I get the results:

Vivaldi
Vaccaro

You can create a contextual filter for the node title and configure it in "glossary mode". Provide a fixed value "a" and check the glossary mode settings at the bottom of the settings page.


Editor Persons Who Copy/Paste From Word We have many editors that are going to submit documents for appearance on our website. Most documents come in the form of a .doc etc. What would be the best method of importing the text into a content node?

WYSIWYG + CKeditor provides a "Paste from word" option; it doesn't do any automated importing, but does provide a popup window containing a textarea for the user to paste from word. The pasted content is then cleaned up and converted to HTML, and finally placed in the WYSIWYG as normal content.


Redirecting Pages from Standard Node page to views page How can I redirect all of my nodes created by a content type to a views page with a different url? For example, I created content types for publications and then have pathalias creating a url for a created node:

publications/form-one

I am then using views to reformat that look and feel of the node fields and also add in some other data from other content types via Relationships and Context. In the end my new url is:

publications/001

Now, my search results will find the /form-one url and bring the user to that page, but I'd like to only return the user to the /001 page that I have compiled in views with the additional data.

Some thoughts I have had, but not sure how to implement:

If I take all the url alias away from publications and reset it back to node/nid and then .... not sure here? Some Context Redirect?
Redirects? I have a TON of pages.
hook_node_view()?

Thanks for any thoughts and please ask for clarification if needed.

Chaos tool suite (ctools) has a sub-module called Page Manager.

  Page manager is a critical tool for Drupal development. It's a
  sub-module of Chaos Tools that enables you to change the paths of
  pages, even some of those defined by Drupal core. While it won't
  change the appearance of a node, it can change the context of it. With
  Page Manager you can control who has access to pages, and how they get
  to the pages, including nodes that are part of other pages. Working
  hand-in-hand with other modules like Panels, Page Manager can help
  give you great control over the user experience.

Using it you can do redirects on a specific content type to your view and pass along the context such as the nid. No need to worry about aliases.

You do it as follows:

Activate Page Manager
Go to admin/structure/pages
Enable /node/%node to override it.
Create a variant with a 301 redirect
Create a selection rule on Node Type = Your node type
Set the redirect destination to your-view-path/%node:nid


how to know if the page i am on is a node or not with a custom module, in drupal 8, how can I test whether I am on a node entity or not, when i browse to that page?

If I do this  $node = \Drupal::routeMatch()->getParameter('node');  I get an error if i'm not on a node.

You can do:

if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
 //Do what you want.
}


Use theme_image_style twice I am trying to add different html class attributes to images based on what view they are being output with. I have created two image styles using the administrative interface, here are the two machine names.
1. front_page_recent_blogs
2. blog_page_view

I have assigned each of these to the image field in the two different views. I have successfully added classes to the front_page_recent_blogs images using the following code:

function mythemename_image_style($variables) {

  $variables['attributes'] = array(
    'class' => 'img-responsive center-block',
  );

  $variables['path'] = image_style_url('front_page_recent_blogs', $variables['path']);
  return theme('image', $variables);

}

How do I add classes to the blog_page_view image style, and to any future image styles? Calling the function twice breaks the entire site. If there is a better way to add classes to multiple image styles than overriding theme_image_style, please let me know.

For this situation overwriting the image_style theme function seems a bit heavy-handed, and as best I can tell your overwritten version omits some logic that it probably should not (see the core theme_image_style()). This could explain why things "break".

You would probably be better off implementing a preprocessing function that simply alters that 'attributes' variable that your site's exiting image_style theme function uses, something like:

function mytheme_preprocess_image_style(&$vars) {
  if ($vars['style_name'] == 'front_page_recent_blogs' || $vars['style_name'] == 'blog_page_view') {
    $vars['attributes']['class'][] = 'img-responsive';
    // etc... add other var adjustments as needed
  }
}

You may also be able to avoid custom theme changes altogether if you have enough flexibly in your CSS. It sounds like you need to add some CSS rules only to images in specific fields within specific views, so CSS like this may work too:

.view-id-my_view_name .views-field-field-my-field img {
  // Add your CSS for .img-responsive here
}

Of course this may require duplicating the CSS for .img-responsive if it's used all over the place already (probably likely), which may only be realistic if you are using a CSS preprocessor. I assume you ruled this out already for good reason, but I figured I'd mention it anyway.


How do I separately get label and field? For form fields, we have label and field (Text/Select/...).

How do I get the field title and its value separately in a template file?

{{ form.title }}

I need both separately, so I can properly style.

To access separately labels and values for fields in twig template (example in node twig template: node.html.twig) I propose to loop all the node variable.

My example:
Instead of print all content with this line {{ content }} loop the content object

    {% for item in node %}
        {# Print the label of the field #}
        {{ item.fieldDefinition.label }}

        {# Print the value of a field text/simple field #}
        {{ item.fieldDefinition.value }}

        {# Print the value of a field reference  #}
        {{ item.value[0]['target_id'] }}
    {% endfor %}

Other way is to use this module: https://www.drupal.org/project/twig_field_value


Custom edit user page I'm trying to build an edit form for specific users.
For one type of user I want to hide password field for example

What I did is to create a module called profilechange.

Into profilechange.module I wrote this code :

function profilechange_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'user-profile-form') {
       hide($form['account']['pass']);
       hide($form['account']['current_pass_required_values']);
       hide($form['account']['current_pass']);
    }
}

So I enable the module and into my page--user--edit.tpl.php I've this code :

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

It displays the default edit form. But password fields are not hidden.

That's why I need your help, I don't know why it does not work even if I clear the cache

You also might try the user readonly module. It allows to disable or hide certain form fields for certain users.


How do I display content on slideshows? I am using the Jssor Slider module. My slider works, but the content type Jssor slider, where text is displayed on images, is not working on Drupal 8.

I want to display content on slideshows like shown on
http://www.jssor.com/demos/content-slider.slider. How can I do this?

I've tested the module and tested.It works. Seems you missed the pre-configured view provided by this module.

You can find it at http://www.example.com/jssor_jssor. Find the jssor views in the view list. You can do slider settings in the view itself.

Seems you've selected 'Content' instead of Jssor in view. If you select 'content' it display normal slider. So in order to display text on slider make sure to add Jssor in show under FORMAT options.


Issue Tracker for Open Atrium 2.0 I just installed Open Atrium 2.0 and noticed, as many people have, that the Issue Tracker functionality is not included. I understand why they didn't want to include it in version 2: to make way for a better solution that fits in with Drupal Core.

However, this functionality is pretty killer for what I use Open Atrium for.

So, other than https://drupal.org/project/oa_worktracker, are there other alternatives to implementing issue tracking within Open Atrium. I guess I'm unaware of a standard issue tracker for D7.

I dont know whats OA2 friendly but Case Tracker, and Project Management are both D7 friendly.

From the project page of Case Tracker:

  Actually, the 7.x-1.x-dev version has the content types for Project
  and Cases working without problems. The Notifications, Actions and
  View integration that needs to be tested.

  The development is active and we're working toward a release. Check
  out the 7.x-1.x branch and post your patches!

From the project page for Project Management:

  Project management software, allowing you to manage:

  Organizations, Teams, People, Projects, Tasks, Tickets, Timetrackings,
  Notes, Invoices, and Expenses. Each of these features is managed as a
  separate module within the suite.


How to show pager in terms of views of tags? I've lists of tags suppose good and bad, now when I click to good tag it lists all good posts ( full posts ). But I wanted to show good posts only upto 5 items then all other should be there while I navigate.

So, how can I show the pager for the clicked tags. I tried it with views module, but nowhere I could see it to do this.

I've setup my views like this:

Create a view of content ( as a page with pager ) and add a contextual filter named Content: Has taxonomy term ID. Refer the images below.

Once you have configured this then you can acces this view using a url like mysite.com/view-path/tag-name.


Getting only the login field i got a user-login-block.tpl.php to customize user login block of Drupal 7. here is that code:user-login-block.tpl.php:

<?php print $name; // Display username field ?>
<?php print $pass; // Display Password field ?>
<?php print $submit; // Display submit button ?>
<?php print $rendered; // Display hidden elements (required for successful login) ?>

Create an Account | Forgot Password

this works; here is the screenshot:

but i want to print only the username field, password field and the submit button so i can easily position them, using css, adding custom label etc.. Also delete the blue marked default drupal 7 links..  any idea? thanks..

In your theme's template.php file:

/**
 * Implements hook_form_FORM_ID_alter().
 */

function YOURTHEMENAME_form_user_login_block_alter(&$form) {

    unset($form['links']);
    return;

}

In this function you have access to the form as an array. Usually I enable devel module and do a dsm($form) . In your case dsm() will not work because you need to be logged in to be able to see the output. I used var_dump($form) to see the form and used unset() function to remove the links.


Drupal 7 - views blocks not displaying page field content I have a page where a view is creating a block which loads a field.

Other blocks loaded into the region are showing up just fine but that particular one will not show.  It is not because the field is empty or otherwise, I can creae labels and tables and empty conditions etc that do not get picked up at all

Is there something that has to be done to template files or otherwise to enable blocks created by views?

A block created by view shows up as any other view, unless you have permission control for the block at views level or at block level.

Permission at views

Permission at block

Visibility settings - By various ways block visibility can be controlled, ensure you have appropriate configurations for this.

Region Settings - Ensure you are putting the block in the region of right theme you are expecting the block to see.

Few things to debug.

Login with super admin(user id 1) see if you can see the block, if yes it will ensure you have permission issues.


View does not display attached file without Display field checked I've got a view that exposes a list of nodes with fields: Title, Publishing date, Attached files.

If an attached file has checked the "Display" flag it is visible on the view result, but if the "Display" field is not checked the file is not visible.

Is it possible to show all attached files?

There are three files attached to node, but only two with "Display" checked, I'll want to show all files attached to node.

Under advanced > query settings > check "Disable SQL rewriting" - it should prevent any access or visibility checks for nodes and fields. Don't forget to add the ones you need directly to a view if you do this.


8 - Is It Possible To Create Routes Through The Admin Question: Is there a way for users to create routes in the admin?

Issue: I have a bunch of nodes and tax terms that are being used in Views but no where else. They shouldn't be accessible to the public either. Changing their path to /admin didn't give me the result I wanted, where in D7, that would automatically set them to the admin theme and I could set the permissions that way. I haven't found a decent entity module to create them like I want either.

Solution: Created a module that used a wildcard route. Then create a service that uses RouteSubscriberBase and alterRoutes to block any access to it without X permission.

I think there is some potential for others to use this but cannot find a way to set the routes to be blocked through the admin.  x

You may want to check out the Rabbit Hole module.

  Rabbit Hole is a module that adds the ability to control what should
  happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its
  own page, like an image content type that's displayed in a carousel.
  Rabbit Hole can prevent this node from being accessible on its own
  page, through node/xxx.


Send email after term is selected in checkbox in a node form with rules I have created a node form which has taxonomy vocabulary Application Status with three terms  represented as check boxes

Approve Masters
Approve Honours
Rejected

What I am trying to achieve is when you select one of the terms a unique rule for each term sends an email for the term that has been selected in the check box.
I have tried numerous setups but cannot get it to work properly. My current approach is

Event:

After updating existing content of type Online Application Form

After saving a new field collection item

Conditions :

Entity is new

Actions:

Send HTML e-mail

If anybody can give me some good advice on how to achieve this I would be most grateful.

You need:

An "Entity has field" condition to check for the existence of the taxonomy field, and then
A "Data comparison" condition to match the value of the taxonomy field to the one of the three terms on which you want the rule to operate.

You have two Events in your rule. It seems if you put the Field Collection condition first, then the node fields aren't available in Rules, and vice-versa. So list the "After updating existing content of type Online Application Form" event first so that you can access the taxonomy field in the conditions.


"Fatal error: Call to a member function setFormClass()" I am trying to load the node in an external script, and shows me the following error.

Fatal error: Call to a member function setFormClass() in field_ui_entity_type_build()

The code causing the error is the following one.
define('DRUPAL_DIR', dirname(realpath(dirname(__FILE__))));
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\node\Entity\Node;

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
$kernel->preHandle($request);

$nid = 123;
$node = Node::load($nid);
$node->set('field_number', 222);
$node->save();

Any help?

The code shown in the question doesn't correctly bootstrap Drupal. An external script needs to do that, differently from a module. While loading the autoloader allows PHP to find the Node class, that isn't sufficient to bootstrap Drupal correctly.
I usually use the authenticate.php file as guideline for writing code for an external script file that needs to bootstrap Drupal.
use Drupal\Core\DrupalKernel;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Route;

// Change the directory to the Drupal root.
// Edit the following line to make it point to the directory containing the autoload.php file.
chdir('.');
$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();

  // A route is required for route matching.
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);

  // Ensure our request includes the session if appropriate.
  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('node', 'core/modules/node');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('node');

$node = Node::load(123);
$node->set('field_number', 222);
$node->save();

Actually, $kernel->preHandle($request) should be sufficient to load all the modules, since it contains the following code.
// Load all enabled modules.
$this->container->get('module_handler')->loadAll();

The code that explicitly loads the modules isn't necessary. At the same time, not explicitly loading the modules makes the code dependent from the installation profile, as the previous code line only loads the modules the installation profile enabled.


Content display errors - Missing styling and content I have a local Drupal 7.2.6 installation that I am experiencing a strange issue with.  If I log in and go to Find Content the it displays my content as expected.  Clicking on an item takes me to the relevant page and everything looks ok,

However a few of the content items take me to a page that looks like this....

Anyone any ideas?

Seems to be related to a PHP error, see which are the the resources (images, css, js, ...) that are returning 500 HTTP error.

Check if the issue only happens with a specific content type.

Check the Drupal log (admin/reports/dblog) and the Apache log to find more info about this issue.


Retriving nodes by content type using Drupal::entityQuery I created a content type named product. How can I retrive all node of such content type using the entityQuery method?

I tried with this, but it doesn't works:

$ids = \Drupal::entityQuery('product')
  ->execute();

$products = \Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($ids);

This is how we do this:

$ids = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->execute();

$products = \Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($ids);


Module: Extend "Authoring information"-tab and adding new field to it I'm looking for a way to attach a custom field of my module to "Authoring information"-tab.

Thanks for any hint

Use hook_form_alter(), add your form item to $form['author'] fieldset (see node_form() function), add your own submit function to $form['actions']['submit']['#submit'] array (or $form['#submit']) and you're good to go! And always remember, Form API Reference is one of your best friends!


Specifying the default database to store new field tables in I have a few Drupal 7 sites running on a multisite setup. They each have their own database, and there's a "shared" database used by all of them, which contains user data, date formats, filters and some other data that is shared across all of the sites.

Nodes and taxonomy are not shared, but I am looking at changing that so they are, and using a taxonomy vocab as a means of specifying which site each node is associated with.

I don't have a problem setting that up as I have a nice little database include that handles database credentials and prefixing, but there is one drawback with this setup and that is controlling which database any given module should create new tables in. I know that in order to have all sites use a single node table, I should also share the content types and fields - but I am going to run into issues when creating new fields on content types, as their respective tables will naturally be created in the site's default database and not the shared one.

So, I suppose my question is: how can I specify what the default database should be on a per-module basis?

P.S. I did consider using Domain Access to achieve this, but that doesn't seem to be suitable in this case as each site uses a separate database already, and I'm not looking to share themes, site config, blocks, views, panel data, paths, etc.

Unfortunately, Drupal was not designed to work this way.  The only way to figure out where to put each table would be to carefully inspect each new module and adjust your settings in advance of enabling the module. Even if you manage to do this, you are likely to run into problems with modules that stores critical information in the variables table.  Clearly you cannot share the entire variables table, so you would instead need to figure out how to synchronize individual values that must be shared, avoid race conditions, etc.

You should strongly consider using domain access or subdomain to share node content between different sites.  You will have some work ahead of you in converting from your current site format to one that will work for you; the migrate module may help with this task.