path alias for 'edit' not loading correct page under 'admin/' I have a content page that just editors need to see. So I set the pathauto to something like 'admin/page-title'. The edit-path is 'admin/page-title/edit' accordingly.

When trying to open the node in edit mode however, the first page of admin section is displayed instead of the edit form – as found under 'admin/'.

This basically is not really a problem – just took me some time to figure out that actually the 'admin' part of the URL is causing the problem. I would however really like to keep that URL structure since it would make the path consistent to the actual internal content structure.  Any suggestion how I could get this work? Any pointers would be gladly appreciated.

It happens because paths defined through hook_menu() implementations have the precedence over path aliases. The System module defines the admin menu item, which is a catch-them-all, since Drupal, for a non existing path like node/1/not-defined-from-any-module, will show node/1. This also happens for not existing path aliases that partially match a path defined from a module; if you try to access admin/not-existing-alias, Drupal will return the page at admin.
Notice that in the case of a non existing alias that partially matches an existing one (e.g. path-alias/sub-path-alias/not-existing-sub-path versus path-alias/sub-path-alias), Drupal will not show the page at the path for the existing alias (in my example, path-alias/sub-path-alias).

Also, the Pathauto module doesn't define path aliases for node/1/edit; for that, you need the Sub-pathauto (Sub-path URL Aliases) module.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.

  For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


How to sync configuration between multiple developers' environments D8 Configuration management is really awesome and easy to use when there's only one developer working on a project. We are running into challenges in keeping configuration synced between environments when more than one developer is introduced to a project at the same time.

Example:

Developer A is working on feature A. Exports configuration to their feature branch and pushes it to a shared develop branch.
At the same time, developer B is working on feature B and does the same thing - pushes feature configuration to the shared develop branch.

How do you import feature A and feature B concurrently?

Don't push to the develop branch directly. You should have a branch and merge strategy. If using GitHub or GitLab or similar, you would do a pull request of your branch to develop.

A common strategy (or one of) is the Git Flow workflow. Some links to explain Git Flow:

https://nvie.com/posts/a-successful-git-branching-model/
https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow

There are a handful of strategies, use whatever will fit for your team.

One of the few circumstances I ran into with merge conflicts was if someone was working on something touching the same configuration areas as another person.. we avoided this by just coordinating the work well.


Per entity settings storage (configuration / state / field) Background : #2833770 : Save user configs to states

Auto-logout saves the per-user settings using configuration API, which would obviously break with environment change and config deployment.

The suggested patch moves the storage from the config API to state API. My take on this and from the documentation of State API:

State API is a better alternative which will avoid the deployment issues, but isn't perfect as the state can anytime be reset.
The per-content configuration would get lost once that happens.

How often can a state API be reset? I would prefer some examples other than docs.

As an alternative, I think it would be safe to save the settings in a field on the user entity, but I would like to go this route only if state API is not a good option. I would really appreciate any input on the same.

Core provides a storage/API to store per-user information: the user.data service. It also provides a very simple example implementation in the Contact module: See contact_form_user_form_alter() and contact_user_profile_form_submit().

\Drupal::service('user.data')->set('contact', $account->id(), 'enabled', (int) $form_state->getValue('contact'));
$account_data = \Drupal::service('user.data')->get('contact', $account->id(), 'enabled');


How to get php error logging working properly in a production site OK, I'm clearly missing something about how error logging is supposed to work.  This is a D7 production site, so my goal is to get errors written into a log file, but not show up on the screen.  I've added the following to the end of my site's settings.php file:

error_reporting(E_ALL); // just to get going; I'll scale this back later
ini_set('display_errors', 0); // don't display errors on the screen
ini_set('log_errors', 1); // log errors...
ini_set('error_log', 'syslog'); // ...in the syslog (I'm running this on Fedora 15,
                                // so I think this should work (although I'd happy to
                                // have the logging happen somewhere else

My reading of all the docs makes me think that this should work, but when I put the following into a module file as a way of forcing some errors:

$x = 1 / 0;
$foo = $bar + $baz;

I still get the divide-by-zero warning and the undefined variable notices coming up on the screen via drupal_set_message, and comparable messages in watchdog.  If I instead do error_reporting(0), I get nothing on the screen, and nothing in watchdog.  In no case do I see any messages showing up anywhere in /var/log.

I'm clearly doing something wrong, no?  Can anyone see what it is?

Just to be sure that you are in the right path...

PHP.net says that:

  Note:

  Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

Also check http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors and http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log


Why 'Failed to start the session' when RedirectResponse is sent? When this code is executed, I have an error message logged.
The code is in shared_node_access(NodeInterface $node, $op, AccountInterface $account)

if ($node->get('nid')->value == 1) {
  if ($account->isAnonymous()) {
  }
  else {
    $path = Url::fromUserInput('/node/25')->toString();
    $response = new RedirectResponse($path);
    $response->send();
  }
}

The error message:

  RuntimeException : Failed to start the session because headers have
  already been sent by
  "/home/lejardindf/JdP8/vendor/symfony/http-foundation/Response.php" at
  line 377. dans
  Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start()
  (/home/lejardindf/JdP8/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php
  ligne 150)

There are two problems. First, you can't send a response from custom Drupal code. Second, you can't run non access code in an access hook, because access results are cached.

For redirects in Drupal 8 see these change records: drupal_goto() has been removed and hook_init() removed.

A different approach might be to let the 403 exception happen and then catch it in an exception event subscriber to do the redirect, see How to redirect an anonymous user to the login form after a 403 error?


How To Place One Forum Topic in Many Forums I have a forum system created with D6 and the Advanced Forum module. I would like to have a special forum topic posted in all the forum sections that describes the site rules and how to use the various forum features. It would be perfect if this could be done using a single node that appears in all forums at once because that way all the comments would be contained in a single discussion.

I've answered my own question. I used the Rules module (http://drupal.org/project/rules). That thing is GREAT!

First I created my topic that I wanted to show in all forums. Let's call it node/10.

Next I created a topic with the same title in all of the other forums, but the body content just reads, "REDIRECT". Let's call these nodes 11-16.

Then I created a new Triggered rule with one IF and one DO.

IF uses an "Execute custome PHP code" statement which checks the node id to see if it is one of the REDIRECT pages, like so...

return in_array($node->nid, array(11, 12, 13, 14, 15, 16));

When IF returns true, DO immediately executes a System > Page redirect to node/10.

So far, so good.


Hide node if user has viewed it I have a restaurant with a Drupal site and would like to post coupons for patrons to use.  They would have to create a user account to view it.  The coupon would be an image field and if a user wants to use it they would click use coupon and it would hide it from that user only.  Is this possible?

Thanks

You can with Flag + Rules

In /admin/structure/flags/add add flag of "Content" and call it something like "use coupon" flag.

I presume your Nodes teasers are listed in view. So in Views:

In Relationships add "Content flag"

Uncheck include only flagged content
Flag: Slect your flag
By: Current User

In Filter Criteria add "Flagging" and select not flagged.

To prevent from viewing node directly by typing the url, in Rules:

In /admin/config/workflow/rules create Rule with action of "Flagging is viewed".
Add Action of "Page redirect" and send them to some custom /url that says you already redeemed this coupon. (Create a basic page for this)


How to color cards (hearts and diamonds) red in Drupal 7 comments? I run a Drupal 7 website with Forum, Blog, Comment core modules enabled and a custom module (generates a block with Flash game and blocks with player rating) written by me.

The website is dedicated to a Russian card game and users often mention card colors in their comments when discussing some card riddle or a game:

Most users are older folks, who don't understand anything like HTML tags, so I have only enabled plain text comments for them.

My quesion is: in the plain text Comments - how to recognize the strings like K♥ or 7♦ and color them red?

The PHP code would be something like:

preg_replace(/(1?[0789JQKA][♥♦])/, '\1', $str);

(I can improve the regex later) - but where/how to apply it in Drupal 7?

If you need it to be configurable/re-usable then a custom filter is the way to go as Mołot said. The idea is that the raw data is always stored, and the filter is applied upon display. This is all well and good, but if you don't ever need the original text I find this method to be an unnecessary performance overhead (especially when you involve regexs, as most filters do).

The other way is to intercept the comment body before it's saved, and apply your filter then. For this you can use hook_comment_presave():

function MYMODULE_comment_presave($comment) {
  $comment->comment_body[$comment->language][0]['value'] = string_replacement_function($comment->comment_body[$comment->language][0]['value']);
}

I know this method is 'frowned upon' (heaven forbid we alter someone's input, even if we want to control what goes in the database!), and I can think of at least 2 people who will downvote this if/when they see it.

I think the benefits/drawbacks of both methods are pretty clear, though, so I'd advise you make a decision based on your use-case. If the module you implement to do this isn't being released back into the wild, I see no benefit in taking the extra performance hit here.

But if you think you'll ever want to use this method to filter text elsewhere on the site (e.g. in node bodies), a custom filter would make more sense.


Setting up Drupal without a domain name A site's been developed on localhost and I want to move it to my new hosting, which uses Plesk.
This hosting doesn't have DNS pointing to it, although the domain is added. (The domain name is currently pointing to my old hosting.)

I have changed $base_url to the preview URL Plesk provides:

$base_url = 'https://the-url-pleskprovides:8443/sitepreview/http/myurl.com';

I can access the site and even browse, but I can't login because login redirects to https://the-url-pleskprovides:8443/user instead of https://the-url-pleskprovides:8443/sitepreview/http/myurl.com/admin/.

Is there any way to work with Plesk preview, or with Drupal without a domain?

Any help will be highly appreciated.

Ok, the answer is unfortunately Drupal can not handle this situation. What should be done is the following:

On Windows

Go to: C:\Windows\System32\drivers\etc

Open: hosts file

Add at the end:

100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

On Mac

Open Terminal (Applications -> Utilities -> Terminal)

Open hosts file: $ sudo nano /private/etc/hosts

Type your user password when prompted

Add at the end:

100.200.10.20 yourdomainname.com
109.200.10.20 www.yourdomainname.com

Save the file Flush the DNS cache: $ dscacheutil -flushcache

NOTE: The IP is the IP of your server. You can get it by logging into Plesk, Home>System Overview


How to make a calendar tab for every user showing user's events? I followed the tutorial Calendars for Organic Groups - A simple tutorial for D6, and successfully created a calendar for every group in my site showing its events. I also managed to show the calendar as a tab in every group homepage using the path node/%/calendar.

Now I want to create a second calendar page, shown as a tab in every user profile page, which will provide the user information about all the events that are registered in the groups the user is a member of. I created a second view, and configured it to show all the events of the site.

How can I limit this view to only show the events from all the groups? How can I add its page as a tab in every user profile? Is there a way to limit the access to this tab to only the user that owns the profile?

Clone the default view "OG all user group content" provided by Organic Groups. Filter content type based on events and thats it. This displays all the events from all the groups the user is subscribed to.

You can also change the display style to calendar and add a bunch of other settings.


Regarding MySQL and PHP versions MySQL Server version: 5.0.77 and Current PHP version: 5.1.6

Does Drupal 7 support them?

For Drupal 7 you'll need at least PHP 5.2.5. Have a look at http://drupal.org/requirements
One specific issue I had with PHP less than 5.2 was that I could not install http://drupal.org/project/drush so I had to upgrade. Probably I'd have more problems down the line if I hadn't.

The MySQL version you have is OK.


Override twig template file from classy theme I want to override file-upload-help.html.twig located in core\themes\classy\templates\content-edit. This template displays help text for file upload fields on node edit pages.

If I inspect the file upload help text on a page, above it I see (in debug mode):

BEGIN OUTPUT from 'core/themes/classy/templates/content-edit/file-upload-help.html.twig'

There is no FILE NAME SUGGESTIONS line before or after this line.

My site sub-themes the bootstrap theme.

I tried simply putting a file-upload-help.html.twig file in my sub-theme's templates folder, but it was ignored. Not surprising since I'm sub-theming bootstrap, not classy.

Is there a way to add more information to the theme.info.yml file to override classy templates as well? Or some other way to override the template? If I simply edit the file-upload-help.html.twig file within the classy theme folder, it works, but of course that's bad behavior.

As discovered through the comments discussion the answer in this case is to place the template into the admin subtheme (not the default theme).

When adding new templates to your subtheme it's important to be aware of the fact that there are usually two active themes in any Drupal site: the default one for "front-end" and an admin one for the "back-end" side.

There is also a part of the site that is ambiguous about whether it falls under "front-" or "back-end", and that is Editing content pages.

There is a setting under Appearance that controls which theme should be used for editing content. When adding a template for content-editing pages it's important to double-check which theme is chosen there to know which theme to add the template to.

As always, don't modify the contributed themes, instead add a subtheme that extends them and add the template there. Then adjust the Appearance settings to use the subtheme.


How can I validate required fields? I don't care about having custom error message or anything, but I just want AN error message.  Right now on my registration form I have a variety of supplemental fields listed as required but that has no affect on a user's ability to submit the form.  How can I prevent them from submitting if the field is null?  I don't care about crazy condiitionals or anything, simply if its null to not let them submit.  I have been unsuccessfuly trying to code a validation module and I can't figure out the code.  I really just need something to work ASAP.  I have tried the validation module but it doesn't work for me - no clue why.

Maybe there is something wrong with my theme, does anybody know where that validation would normally be found so I could check?  it seems other people do get the error message.

Any help would be SUPER appreciated.

There's definitely something wrong with your theme, or a custom/contrib module you've got installed. Required fields are always validated and checked for empty values; they just piggy-back off the FAPI #required property which I've never known not to work.

As far as debugging goes:

Check the context the registration form is being displayed in. If you're manually adding the registration form in your theme, and doing so in a template file, the problem is simply that the messages produced by the form builder are being built after $messages has already been outputted in page.tpl.php (ignore this one if the problem is happening on the main registration page).
Change the default theme back to Garland and see if the problem persists.
If it does, start methodically disabling contributed and custom modules to isolate the culprit. Start with custom modules, then dev/alpha/beta contrib modules (in that order), then the stable modules. Check the registration form each time you disable one.
To make sure there isn't some sort of conflict between your theme and a custom/contrib module, make sure you switch back to your custom theme before starting to disable modules.
If all else fails, install a fresh copy of Drupal as a test site, add a couple of required fields to the user entity, and check the registration form again. If it works, you know there's something definitely wrong with your main installation. If it doesn't (which is extremely unlikely), you know the problem is more sinister (i.e. it's a crazy problem with PHP/MySQL/your OS)


EntityFieldQuery with Workflow I need to filter an EntityFieldQuery with a given workflow state, let's say workflow it is state 21 (sid = 21). Below, the query I am using

$query_formularios_completos = new EntityFieldQuery();
  $query_formularios_completos
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array(
        'evento_agencia',
        'evento_energia'
      )
    )
    ->propertyCondition('workflow', 21)
    ->fieldCondition('field_e_expositor', 'target_id', $node_expositor_nid);
  $result_formularios_completos = $query_formularios_completos->execute();

When using DEVEL to inspect my node, I can see there is a property ->workflow, side by side with ordinary properties like ->title or ->created. Although I can see it there and I expected to filter only items with workflow state 21, I get a horrid database error when trying to execute the code above. Here is more or less the message I get:

  Column not found: 1054 Column 'node.workflow' unknown in 'where
  clause'

Any ideas on how I should filter an entity query using a workflow state as filter? Maybe what I am trying to do isn'tpossible and I have to actually run a query using db_query and applying the appropriate joins.

As described in EntityFieldQuery::propertyCondition(), you can use that method for every database field defined in the hook_schema() implementation for the base database table used from the entity.

  $column: A column defined in the hook_schema() of the base table of the entity.

The code that effectively handle that is in EntityFieldQuery::propertyQuery() which contains the following code.

  $entity_type = $this->entityConditions['entity_type']['value'];
  $entity_info = entity_get_info($entity_type);
  if (empty($entity_info['base table'])) {
    throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  }
  $base_table = $entity_info['base table'];
  $base_table_schema = drupal_get_schema($base_table);
  $select_query = db_select($base_table);
  $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  // Process the property conditions.
  foreach ($this->propertyConditions as $property_condition) {
    $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
  }

You could implement hook_entity_query_alter(), which is invoked before EntityFieldQuery::propertyQuery() is called, and which (by default) it's the EntityFieldQuery::executeCallback callback, the same callback hook_entity_query_alter() is suggested to change. Using your own callback, you could make a join with the tables the Workflow module is using.


Unable to upload files. Though the maximum file size limit is 80 MB, can't upload even 50 kb files I copied a site from localhost to AWS server. I can easily upload files in localhost but when I try uploading in the live site it gives me the error

"An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (80 MB) that this server supports."

In php.ini and .htaccess and settings.php I have changed upload_max_filesize to 80MB and post_max_size to 164 MB.

And according to this link, , I also disabled mod_security module in apache.

Here  it says, this could be AJAX/Jquery error.

Is there something else that could be the cause for this error?

Some things that can break file uploads:

upload_max_filesize and post_max_size ;
memory_limit ;
Unwritable tmp directory.


drupal 7.14,where to install a new module,it is different than 7.13 There is a  button in 7.13 on the top of the module menu,but it dispears in the new 7.14,I'm implementing a new drupal installation not upgrate from 7.13.Thanks!Where to find this button?

It's at http://mysite.com/admin/modules/install.

You can also get to it from the main modules page ( http://mysite.com/admin/modules ):


Add js with custom type How can i add a script file with type='module', like this :

<script src="site/test/test/index.js" type="module"></script>

I tried with :

  drupal_add_js(drupal_get_path('module', 'my_module') . '/assets/js/my_script.js', [
    'attributes' => ['type' => 'module'],
    'type' => 'module',
  ]);

But Drupal 7 only accept 'file', 'inline', 'external' or 'setting' as type.

Do you have any idea ?

Thanks.

You can do this in hook_preprocess_html():

function theme_preprocess_html(&$var) {
  $script = [
    '#tag' => 'script',
    '#attributes' => [
      'type' => 'module',
      'src' => 'path/to/script.js',
    ],
    '#value' => '',
  ];
  drupal_add_html_head($script, 'script');
}


limit exposed filter to top X taxonomy terms in drupal 7 basically I have an exposed filter that lets users use the filter to search the website.

Only the terms available are sometimes 20+ items so I want to limit the available exposed terms and show only the top X terms with the most related nodes and create a 'more' button to show the rest.

Is there already a module or something for this?

I think the closest I have seen to doing what you ask is http://drupal.org/project/better_exposed_filters which tries to at least make the exposed filters more manageable.

EDIT:

If you are prepared to switch the filtering to faceted search you could use search_api module in combination with its built in facets (through solr). Then you end up with being able to restrict the amount of terms you show in the facet.


Restricted nodes don't show up in search results On this Belgium version of the side users has to have the right permission to view specific nodes. I did this with Content Access module.

But now when you as anonymous user search any content the restricted nodes don't show up?

How do i manage the teasers show up always? But when you want to see full content it's restricted?

The default Drupal search respects the Drupal permission system, so if the user performing a search doesn't have permission to see a node, it won't appear in search results at all. To get around this, you'll need something that circumvents the permission system, either by altering the search function, or replacing it entirely.

You could take a look at the Custom Search module. It modifies Drupal's search, and gives you control over the default search options. However, I can't recall if it includes an option to show content you wouldn't otherwise have permission to see.

The other way you could do it is to create a custom view, add a filter for the field you want to search on, then under advanced, select "query options", and tick the "disable query rewriting" option. This will prevent the permissions from being applied to the view, so will allow users to see nodes they don't have access to. However, I'm not aware of any way of making a view search multiple fields from a single exposed filter, making it less than ideal for an alternative search box.


Is it possible to disable cache on certain fields? I am working on a site where i'm implementing my own cookie bar module.
For this module i have made it possible to write something in the CKeditor like:

Where everything between the {cookie} tags is only visible when cookies are accepted. This works fine on my dev environment, but when I deployed it to the test server where cache is enabled it won't show any change when you enable/disable cookies because the page is already cached.

Is there a way to disable cache on the text field or better yet, everything between the cookie tag?

You need to adjust the cache context of the node.

If the cookie is a drupal session, use the predefined cache context for this:

$build['#cache']['contexts'][] = 'session.exists';

If you target another cookie, that drupal is not aware of, you would need to create your own context, more info:

https://www.drupal.org/developing/api/8/cache/contexts


entitymetadawrapper with field collection multi value How can I save multiple values in a multi-value field collection using EntityMetadataWrapper ?

Here's some of my code

$field_collection = entity_create('field_collection_item', array('field_name' => 'MY_FIELD_COLLECTION'));
$field_collection->setHostEntity('commerce_line_item', $line_item);
$wrapper = entity_metadata_wrapper('field_collection_item', $field_collection);

for($delta=0; $delta<$max_delta; $delta++) {
  //MISSING something like $wrapper->setDelta($delta);
  $wrapper->field_example->set($new_value);
  $wrapper->other_field_example->set($new_value);
  $wrapper->save();

}

$field_collection->save();

I'm fighting with the field delta : I can't use $wrapper->field_example[$delta]->set($new_value) because the wrapper itself is the multi-value field, not its children fields.

So I need to find a way to perform something like

$wrapper[$delta]->field_example->set($new_value);

But this returns "Fatal error: Cannot use object of type EntityDrupalWrapper as array".

Summary : where can I set the delta of the wrapper in the loop ?

I've found this example in one of the bug reports on d.o, hopefully it will clear things up a bit:

// Load the entity and wrap it.
$entity = entity_load_single('my_entity', $entity_id);
$wrapper = entity_metadata_wrapper('my_entity', $entity);
// Create new field collection items.
$collections = array();
// This is a contrived example so assume $things contains some data that might be set on the collections.
foreach ($things as $thing) {
  $fc = entity_create('field_collection_item', array('field_name' => 'field_example_collections'));
  $fc->setHostEntity('my_entity', $entity, $entity->language, FALSE);
  // Skip saving the host entity since the order in which we are creating the items is not the order we want them saved.
  $fc->save(TRUE);
  $collections[] = $fc;
}
// Set the field collection items via the wrapper.
$wrapper->field_example_collections->set($collections);
// Save the entity.
$wrapper->save();

Just as @Clive commented, you need to first load the host entity that this field collection field is attached to (I'm assuming it's a commerce_line_item?), then loop through your data and create field collection entities. Then after you've done assigning values, collect them all in an array and set the array as the new value for the host entity's field collection field.


Check if a taxonomy term synonym exists I have a $category variable containing country names separated by comma. So I use the following code to save them as taxonomy terms:

$tids = array(); $ctids = array();
$category = explode(',',$category);
foreach($category as $cat) {
  insert_term_if_not_exists($cat, 'countries');
  $term_country = taxonomy_get_term_by_name($cat);
  $tid_country = key($term_country);
  $lang_country = field_language('node', $node, 'field_country');
  array_push($ctids, $tid_country);
}
foreach ($ctids as $index => $ctid) {
 $node->field_country[$lang_country][$index]['tid'] = $ctid;
}

As you see the above code uses the insert_term_if_not_exists() function which works perfectly well to check if a taxonomy term exists and to create it programmatically if it doesn't:

function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
  if(empty($matched_terms)) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $term_name;
    taxonomy_term_save($term);
  } else {
    $term = array_shift($matched_terms);
  }
return $term;
}

However, I also need to check and avoid creating a new taxonomy term if it is a synonym of already existing another taxonomy term. So I modified the above code in the following way:

function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);

    if(empty($matched_terms)) {
      $matched_synonym = synonyms_get_term_by_synonym($term_name, $vocabulary);
      if (empty($matched_synonym)) {
        $term = new stdClass();
        $term->vid = $vocabulary->vid;
        $term->name = $term_name;
        taxonomy_term_save($term);
      } else {
        /*
        * Here I need to do something, but don't know what exactly. Using
        * $term = taxonomy_term_load($matched_synonym);
        * here doesn't work.
        */
        }
    } else {
        $term = array_shift($matched_terms);
    }
  return $term;
}

Having troubles to make it work properly.

Edited my answer since my original answer referred to dev code.

The following simple module works with Drupal 7.34 and the current stable version of synonyms (7.x-1.2) and successfully matches a synonym to a taxonomy term.

synonyms_test.module:

function synonyms_test_menu() {
  $menu['test-synonyms'] = array(
    'page callback' => 'synonyms_test_page',
    'access callback' => TRUE,
  );

  return $menu;
}

function synonyms_test_page() {
  $vocabulary_name = 'tags';
  $output = '
Assuming you have a taxonomy with machine name "tags" and that '
            . 'taxonomy has a term named "first term" and that term has a '
            . 'synonym "syn one", this test will produce these results:
';
  $test_terms = array('first term', 'bogus term', 'syn one');
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  foreach($test_terms as $test_term) {
    $output .= 'Testing "' . $test_term . '"
';
    $matched_terms = taxonomy_get_term_by_name($test_term, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $output .= 'Not an existing taxonomy term.';
    } else {
      $output .= 'Is an existing taxonomy term.';
    }
    $output .= '

';
    $matched_synonym = synonyms_get_term_by_synonym($test_term, $vocabulary);
    if(empty($matched_synonym)) {
      $output .= 'Not an existing synonym.';
    }
    else {
      $output .= 'Is an existing synonym, for tid ' . $matched_synonym;
    }
    $output .= '
=========

';
  }
  return $output;
}

* Original answer below *

This is the function you're looking for (from synonyms.module):

/**
 * Returns the term objects that have the given string as a synonym.
 *
 * @param $synonym
 *  A string containing the synonym to search for.
 * @param $vocabulary
 *  (optional) The machine name of the vocabulary in which to search for.

 * @return
 *  An array of term objects containing that synonym.
 */
function synonyms_root_terms_get($synonym, $vocabulary = NULL) {
  $tids = synonyms_root_tids_get($synonym, $vocabulary);

  return taxonomy_term_load_multiple($tids);
}

So if your $matched_terms is empty, try something like:

$matched_synonyms = synonyms_root_terms_get($term_name, $vocabulary->machine_name);
if(empty($matched_synonyms)) {
  // ...now create your new term
}
else {
  $term = array_shift($matched_synonyms);
}


403 error in files while hosting drupal site in hostgator I'm trying to host my drupal site in Hostgator. Here what i've done so far:
a. uploaded files to server, created db and user and imported too.
b. Change settings.php database content.

My site is up and running although my css and files are not being loaded..when i check my browser console it shows 403 error, even i can't access my backend whenever i try to access it shows 404 error,although it seems to be working fine on my localhost.. i know it's permission problem but i don't know how to deal with it is there any steps i leftover which i need to follow, is there any step by step documentation on hosting drupal site on cpanel any help would be great.Thanks in advance.

P.S.-i'm using nginx, and linux system for my development environment.
And new to drupal :)

Read up on the basics of linux permissions. Figure out which user nginx is running under. Make sure that user has read access on files and read/execute access on directories.


CKEditor and attributes I wish to enforce a site-wide set of attributes to content produced via CKEditor.

For example, if someone inserts a table, I want the class 'myclass' automatically added as follows:

...

I want to do this for a large number of tags.

I have tried achieving this by modifying twig templates like table.html.twig, however CK editor content does not appear to apply any template, it only renders the entire post with field.html.twig.

What is the best - or generally accepted- way to accomplish this?
I could modify the CKEditor Module directly but that would be modifying core which is not ideal.

This is a drupal 8 site.

You can tackle this problem from both sides, with a ckeditor plugin as @Sssweat suggested and on the drupal side with a filter plugin.

This is an example from core which adds classes to tags. This code looks for the attribute 'data-align', but you can also look for tags:

namespace Drupal\filter\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
 * Provides a filter to align elements.
 *
 * @Filter(
 *   id = "filter_align",
 *   title = @Translation("Align images"),
 *   description = @Translation("Uses a data-align attribute on &lt;img&gt; tags to align images."),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
 * )
 */
class FilterAlign extends FilterBase {
  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $result = new FilterProcessResult($text);
    if (stristr($text, 'data-align') !== FALSE) {
      $dom = Html::load($text);
      $xpath = new \DOMXPath($dom);
      foreach ($xpath->query('//*[@data-align]') as $node) {
        // Read the data-align attribute's value, then delete it.
        $align = $node->getAttribute('data-align');
        $node->removeAttribute('data-align');
        // If one of the allowed alignments, add the corresponding class.
        if (in_array($align, array('left', 'center', 'right'))) {
          $classes = $node->getAttribute('class');
          $classes = (strlen($classes) > 0) ? explode(' ', $classes) : array();
          $classes[] = 'align-' . $align;
          $node->setAttribute('class', implode(' ', $classes));
        }
      }
      $result->setProcessedText(Html::serialize($dom));
    }
    return $result;
  }
}

The scaffolding of a custom filter module is very simple. See the tutorial:

https://www.lullabot.com/articles/creating-a-custom-filter-in-drupal-8


How to know, if on taxonomy page? Possible Duplicate:
  Check if current page is taxonomy term

For now, I use something like this to decide, if I'm on a taxonomy page.

if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
   $tid = intval(arg(2));
   $parents = taxonomy_get_parents($tid);
   $term = $parents[0];

   ...
}

Is there a more elegant way to decide, if I'm on a taxonomy page than this arg(0), arg(1), arg(2) thing?
Same would apply to a node page if (arg(0) == 'node' && is_numeric(arg(1))).

I didn't find any reference in the net. But maybe I ask the wrong questions.

You could try menu_get_object(), it's slightly cleaner:

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // You're on a term page and have the loaded object in $term
}


Hook to render all active Facet Is there a possible hook or something else that can be written to display all the current active facet link i.e the selected facet. i want to display to the user in breadcrumb format  all the facet they have selected and give them the option to remove it
thanks

There is a bock for this.

You can create/configure the block from Configuration->Search and Metadata->Current Search block (admin/config/search/current_search)

Create a new Search Block and choose a type: Active Items. In pattern enter from tokens below: [facetapi_active:active-value]
Then go to your blocks page and activate your new block.

See the screenshot how my settings look like.


Filter Taxonomy Widget Options by Entity Reference I have two content types, Lesson Plan and Course. When creating a Lesson Plan, users select a Course (Entity Reference). Later, they choose course goals (Term Reference) that the Lesson Plan meets. I'd like to filter the list of course goals by the earlier selection, Course. Each Course has a number of course goals (Term Reference).

Is this possible? I've tried using Term / Entity Reference Views, but can't figure out how to pass the selected Course as an argument and have the term list update (AJAX).

It is possible and can be implemented using Simple Hierarchical Select. From the modules page-

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Expose the view filters (course and course goals) in your case after you set the field type to simple hierarchical select. This guide might be helpful.


Views Slideshow only shows one static image and doesn't cycle in IE8 I have a slideshow that runs through numerous images on the homepage of a site. The slideshow works perfectly in Chrome and Firefox, but simply shows a static image in IE8. On IE8, a Javascript error is returned as follows:

Message: Object doesn't support this property or method
Line: 160
Char: 5
Code: 0
URI: /sites/all/modules/views_slideshow/contrib/views_slideshow_singleframe/views_slideshow.js

The Drupal settings JS is as follows:
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "basePath": "/", "admin_menu": { "margin_top": 1 },
"admin_menu_dropdown": { "key": "`", "default": 1 }, "colorbox": { "transition":
"elastic", "speed": 350, "opacity": "0.85", "slideshow": false, "slideshowAuto":
false, "slideshowSpeed": 2500, "slideshowStart": "", "slideshowStop": "", "current":
"{current} of {total}", "previous": "« Prev", "next": "Next »", "close": "Close",
"overlayClose": true, "maxWidth": "100%", "maxHeight": "100%" }, "CTools": {
"pageId": "page-4d858fb47100047beb7ca4246959a972" }, "extlink": { "extTarget":
"_blank", "extClass": "ext", "extSubdomains": 1, "extExclude": "", "extInclude": "",
 "extAlert": 0, "extAlertText": "This link will take you to an external web site. We
are not responsible for their content.", "mailtoClass": "mailto" },
"viewsSlideshowSingleFrame": { "#views_slideshow_singleframe_main_main_panel-block_1": {
"num_divs": 7, "id_prefix": "#views_slideshow_singleframe_main_",
"div_prefix": "#views_slideshow_singleframe_div_", "vss_id": "main_panel-block_1"
, "timeout": "5000", "sort": 1, "effect": "fade", "speed": "700", "start_paused":
null, "delay": "0", "fixed_height": "1", "random": "0", "pause": "2",
"pause_on_click": "0", "pause_when_hidden": 0, "pause_when_hidden_type": "full",
"amount_allowed_visible": "", "remember_slide": 0, "remember_slide_days": 1,
"controls": "0", "items_per_slide": 1, "pager": "0", "pager_type": "Numbered",
"pager_hover": "1", "pager_click_to_page": 0, "image_count": "0", "nowrap": "0",
"sync": "1", "advanced": "", "ie": { "cleartype": "true", "cleartypenobg": "false" }
} } });
//--><!]]>

It turns out that this was caused by something in the template.  The developer had called the JQuery library from the page.tpl file when it was already being called by core, so it caused the error in IE.  See this page on drupal.org for more information.


Drupal Error log services Can I create views for error logs, or directly expose them to services? How can I maintain my own error logs and expose them in services?

Can I create views for error logs?

Yep, you can create Views for pretty much any type of data. There are a couple of existing modules that already do this:

Views Watchdog
Better Watchdog UI

Or you could of course write your own.

To expose Views as services, you can use the Services Views module, or, again, you can write your own resources for the Services module if it doesn't do exactly what you want.


Fetch Customer Profile from Line Items In a webshop I’ve build I want to send  individual e-mails to owners of a prodruct in the shop after a product is sold. To do this I got this as a solution: Send mail to product owner with Rules

But with this I’m only able to send the product owner an e-mail about the product. I am not able to add a shipping/billing address or mailadres form the customer profile to it.

When I try to add the customer profile as a parameter to the component the rules breaks and doesn't work anymore.

This is an export of my component:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "USES VARIABLES" : {
      "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
      "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" },
      "commerce_customer" : { "label" : "Commerce Customer", "type" : "commerce_customer_profile" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "entity_fetch" : {
          "USING" : { "type" : "commerce_customer_profile", "id" : [ "commerce-order:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched user" } }
        }
      },
      { "drupal_message" : { "message" : "Product Mail = [product-fetched:field-e-mailadres-product]" } },
      { "mimemail" : {
          "key" : "[commerce-order:order-id]",
          "to" : "[product-fetched:field-e-mailadres-product]",
          "subject" : "Product order",
          "body" : "OUTPUT PRODUCT INFORMATION AND USER INFORMATION HERE",
          "language" : [ "" ]
        }
      }
    ]
  }
}

This is the export of my rule to loop trough the line-items:

{ "rules_send_mail_to_product_owner" : {
    "LABEL" : "Send mail to product owner",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Custom" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_presave" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_items" : "Commerce Line Items" },
          "DO" : [
            { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-items" ] } }
          ]
        }
      }
    ]
  }
}

I set the rules action to order presave as this is the easiest way testing the rule, in the end it should run on when payment is first payed in full.

The rule isn't running because of my fault in the parameter settings the parameter commerce_customer is giving problems, I get an error that says: "Missing configuration for parameter commerce_customer".

How can I get to this information in my component?

The rule isn't running because of my fault in the parameter settings the parameter commerce_customer is giving problems, I get an error that says: "Missing configuration for parameter commerce_customer".
How can I get to this information in my component?

It looks like you have a mismatch in the variables of your rules component (which has 3 of them) and the rule which invokes that rules component (which only passes a value for the first variable selected_line_item).
Here is what I suggest you try to get the 2 remaining variables for your rules component fixed:

commerce_order: in your rule (which invokes the rules component), add the value of it as your 2nd variable (to actually pass that value to your rules component). For sure you have a token available to actually pass it (= commerce-order), since your rule already refers to commerce-order:commerce-line-items also (which you would not be able to do if you wouldn't have commerce-order).

commerce_customer: just remove (delete) that as your 3rd variable in your rules component. It seems you don't need to "pass" that as a variable, as per the (2nd) entity_fetch included in your rules component. Whereas this (2nd) entity_fetch will return you that entity_fetched (BTW, a terribly bad name IMO, consider changing that to something more meaningful like fetched_user, or even better fetched_customer).
Whatever you end up using (i.e. entity_fetched, fetched_user, or fetched_customer) that's what you can then use within the body of your eMail (any of the tokens related to it).


Error in Pager of a Ajax View I am getting the following error in Ajax Enabled View, which uses Load More Pager.

I am not sure if its, entirely because of OG, as the error doesn't appear in Views Preview but only in the actual view rendering in a page.

I was able to figure out the issue. Its a bug in the views which doesn't handle the nested views. More about this issue can be found in https://www.drupal.org/node/1016602

I had to override a javascript function in views to fix it. But since it was very use-case specific, I am not sharing the details of the same.


How to get BundleKey in EntityManager after getting storage of entity? I want to get bundleKey of any entity type after is loading from

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

After getStorage I am getting bundleKey Value as "type", but how to render that, as it is saying that is a protected value.
Tried to fetch like:

-> $node->get('bundleKey')->Value();
-> $node->getField('bundleKey')->getValue();
-> $node->bundleKey;

All above methods i tried to fetch Values but still no luck.

Anyone Knows how to fetch bundleKey.

You can get bundleKey of your entity type by this way:

$type = 'commerce_product';
$bundle_key = \Drupal::entityTypeManager()->getDefinition($type)->getKey('bundle');


Drupal Views page into a menu subitem Somehow I cannot get the result I want. I have a view that produces a page and I am offered to have this as a menu item in menu of my choice. But what I actually want to achieve is to nest it as a menu item of a MENU ITEM of main menu, such as in:

[main menu] > Downloads > PDF Diagrams

Is that possible at all?

Artur

As far as I understand your question,
after creating menu item entry within Views UI
you can go to chosen menu configuration (admin/structure/menu for D7) and set parent for your new entry as you would like.


Naming convention for field type templates? It seems that the naming convention for field types is undocumented. Looking at the classy theme shows a seemingly arbitrary convention. For example, the Text (formatted, long, with summary) type as displayed in the UI is apparently named field--text-with-summary.html.twig as a template file.

What are the naming conventions for field types and how could I have determined them myself?

The naming convention for field templates is documented here, Twig Template naming conventions

  field--node--[field-name]--[content-type].html.twig
  field--node--[field-name].html.twig
  field--node--[content-type].html.twig
  field--[field-name].html.twig
  field--[field-type].html.twig field.html.twig

But field--text-with-summary.html.twig is one of those that is harder/trickier to figure out from just looking at the Field Type.

To make Drupal life easy for this, you can enable Twig Debug. See Locating Template Files with Debugging

Now when you inspect element with browser, you can see which template file is being used (the one with the "x") and what other available template file names (the ones with "*") you could use.


How to add behavior-based onclick to ajax-enabled Form API button? I have a form with a button:

$form['categories_update'] = array(
  '#type' => 'button',
  '#value' => t('Load category-related properties'),
  '#ajax' => array(
    'callback' => '_mymodule_categories_callback',
    'wrapper' => 'categories_properties',
    'method' => 'replace',
    'effect' => 'fade',
    'prevent' => 'submit',
  ),
  '#limit_validation_errors' => array(),
);

Now, in Behavior I'm using:

(function($) {
  var initialised = false;

  Drupal.behaviors.mymoduleTag = {
    attach: function (context, settings) {

      // Unrelated code

      $('#edit-categories-update', context).on('click', function(){
        console.log('Load category-related prperties clicked');
      });
    }
  };
})(jQuery);

And it simply fails to work - no errors in console, but no code executed either.

It works all right when I comment out '#ajax' part of a button's definition. Is there a way to have both behavior JS and Form API Ajax working for one button?

I'm using jQuery update module in it's dev version, and I have it set to jQuery 1.8. The button is not inside the wrapper, so it's ID is not affected by AJAX call (verified in browser).

Form API #ajax effectively disables behaviors on elements. I can't see this documented, but that's how it works, consistently. So the solution was to change the line:

$('#edit-categories-update', context).on('click', function(){

and make it

$('#edit-categories-update').ajaxSuccess(function() {

That way code was not executed on click, but after processing of AJAX triggered by the button succeeded. It's not useful if you want to perform JavaScript before AJAX call, but if you need it to happen after, or if you don't care, it is a sufficient solution. If you need things to happen before AJAX call, use this instead:

$('#edit-categories-update').ajaxStart(function() {


How do I deploy a local site? I've been getting mixed messages and there is practically no solid up-to-date documentation, I just want to know the standard procedure for moving a locally developed Drupal 8 site to an online server.

Some say it's as easy as FTP'ing your files over and exporting your local database SQL code over and then connecting to the db via the settings.php, others say to put a fresh installation of Drupal 8 online and then move certain files over while exporting the database using the backup module and then importing it online, others still say I also need to export the local configuration and import it online, still others say I need to update the URL's in some parts of the SQL or configuration exports, etc.

I'm developing with the latest Drupal 8.4 with a custom theme in Windows 10 on XAMPP (I have drush) and migrating to a server subdirectory that my domain points to with php 5.6+ (no drush options online because there's no SSH access).

TLDR: What are the steps to move a locally developed Drupal 8.4 site and database to an online server and get it configured, up and running normally?

There are many ways to migrate a local site to a server. Here are a few of the most common.

SFTP/FTP is one way, you can "manually" move all the files up to the
server and use PHPMyAdmin to import the database. Many hosts will
also have automatic Drupal installs, in which case you can use that,
only upload your theme, files, and modules, and then import database. If you upload via FTP you will need to update settings.php to include the servers SQL log/pass as well as domain url
Set up a git repo which you can pull/push to from your local machine
and the server is likely a better solution if you plan on making
changes. This allows you to more easily manage the files and is a
"safer" solution. Set settings.php to .gitignore
There are also managed solutions such as Acquia Dev Desktop which
will allow you to push/pull files, code, and database simultaneously
using a UI.


How do I examine an entity's update SQL statement in order to write a unit test? I have a core patch (https://www.drupal.org/node/2342699) which ensures that SQL updates do not include the primary key in the field list. I need to write a unit test for this issue and EntityApiTest.php looks like the ideal place for this. This test class has a section

$entities = array_values($storage->loadByProperties(['name' => 'test']));
$entities[0]->name->value = 'test3';
$entities[0]->save();

The way I see it, I will need to examine the entity schema to find the database column name of the 'id' entity key, and then examine the SQL update object to ensure that the entity key is not in the field list. Any advice on how to do either of these steps?

Just write a test that attempts to update a primary key, and assert that it fails to do so.

There's no need to test the SQL generation mechanism of the storage class.


og_members block & og_nodes block won't display content OG Version: 7.x-1.x-dev

My problem is that I can't get the og_members block & og_nodes block to show up under a group page.

Breakdown of my process:

A fresh install of D7, necessary modules
Created a new Content Type: Country: Specified as "Group type", "Not a group content type".
Add a new country: "England".
Createt a new Content Type: News: Specified as "Not a group type", "Group content type".
Add a News, title "Hello World", select England in "Group audience".
In Views page, I add block display for og_members, og_nodes. (All use default setting, no modification to the Views)
Assign og_members block, og_nodes block to sidebar left. (Bartik)
I go to "England" page, og_members block not show up, og_nodes block shows me "There is no content in this group."

I am pretty sure that the views setup correctly, as I pass the gid into the live preview, it does show the result. (See screent shot)

But the block just can't show up in a group page. I am guessing in the page, gid not passed to the block or what?

Am I missing any steps?

Thanks in advanced!!

Update: I found the solution by enabling the OG context module.

og_nodes and og_members did not exist prior to views 3 beta 3's release.  The user must have been using a dev version at this time because I was unable to reproduce this until views beta 3 came out today.


Alter a form based on where it is called from I am using something on the lines of

  $view = views_get_current_view();
  $build = drupal_get_form("comment_node_contenttype_form",
  (object) array('nid' => $view-> args[0]));
  print render($build);

to print a comment form in my views.

My challenge is I am using the same code in two different displays. I need to make a few fields in the comment form required only when it is getting called from a particular display.

The following worked for me.

  if ($form_id == 'comment_node_CONTENT_TYPE_form') {
    $view = views_get_current_view();
    if ($view->current_display == 'block_1') {
      //Alter my form
    }
  }

I checked views_get_current_view function. Since it is using caching there is no harm in calling it again.


how to get date filter settings I want to exposed date filter option
but am getting just textbox instaed of datepicker
I have installed date module still am not getting following options:

installed modules are as shown bellow:

Please guide me how to set datepicker and add search option using that?

You can use Date picker Module for popup date on exposed filter.

It includes the date popup. You can use this module to easily add an exposed filter with the date popup.


Log Message - Page Not Found: includes/database/sqlite/log/login When I check "Recent Log Messages", I keep finding a large number of "Page Not Found" errors with the message "includes/database/sqlite/log/login".
I've checked the site and the directory does not exist.

My questions:

Should this directory exist? If so, how do I create it?
How do I determine what is calling for this directory?

This is most likely somebody trying an automated script to gain malicious access to your site. There's no action required.


Node content in panels vs. configuration in code I am trying to keep most of the configuration in code (and separating content and configuration). When I have a panel that is supposed to contain a content from for example a node, I would like to be able to export that setup somehow so that I can be sure it would work also on the other page. So it shouldnt be a node id, not either node title (so from my point of view, this help doesnt qualify).

The way I did it is somewhat complicated, but allows me to keep all config in code while happily creating the content separately. I am posting a writeup my colleague did to convince me i am doing it too much complicated. Yet, I cant think of a better way.

Create taxonomy vocabulary with terms: top, middle, bottom.
Create custom node-type called panel content to which you assign terms from vocabulary from pt 1
Create a view that takes term from vocab from pt 1 as an argument.
Place this view inside frontpage panel and hardcode the argument depending on region.

Am I missing some point here? Would there be a better way to it?
Thanks.

One could

Use Fieldable panels panes, which can replace the custom entity you use, and put content directly into the pane.
Configure the view to find nodes with a certain tag. Tag the node that should show up. Require the tag to be uniquely applied if only a single node is allowed.


Controlling the active menu item I'm having problems understanding the menu system. I have an hosting node that has 3 pages:
https://beta.ulyssis.be/hosting/

Menu Hook

function packages_menu() {
  $item['hosting']= array(
    'title' => 'Start',
    'type' => MENU_NORMAL_ITEM,
    'description' => 'Dit maakt ons ULYSSIS!',
    'page callback' => '_hosting_page_main',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  $item['hosting/bekijk']= array(
    'title' => 'Features',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
  );

  $item['hosting/kortingen']= array(
    'title' => 'Kortingen',
    'type' => MENU_LOCAL_TASK,
    'description' => 'Deze groepen krijgen kortingen',
    'page callback' => '_hosting_page_discount',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'weight' => 3,
  );

  $item['hosting/pakketten']= array(
    'title' => 'Vergelijk',
    'type' => MENU_LOCAL_TASK,
    'description' => 'Vergelijk onze pakketten met elkaar!',
    'page callback' => '_hosting_page_compare',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'weight' => 4,
  );

  $item['hosting/bestellen']= array(
    'title' => 'Bestel Nu!',
    'type' => MENU_LOCAL_TASK,
    'page callback' => '_hosting_page_order',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'weight' => 5,
  );

  return $item;
}

Problem
When navigating trough these pages, you'll notice that the top hosting menu item doesn't stay as 'active' menu item.

I'm having the same problem with other things, like when reading documentation, that the documentation menu item isn't active to. So I guess I'm not using the menu system as it should or that I'm missing some kind of knowledge about this.

Does anybody know what I'm doing wrong?

The "Hosting" li item is only active if you're on the Hosting page.  If you're on a child page of "Hosting" won't be the "active" item, it will be the "active-trail".

You can change your navigation CSS to make the link look properly by changing .active to .active-trail:

.navigation li a:hover, .navigation .active a {
    background: none repeat scroll 0 0 #FFFFFF;
    border-color: #E99719;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

to

.navigation li a:hover, .navigation .active-trail a {
    background: none repeat scroll 0 0 #FFFFFF;
    border-color: #E99719;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

What might have confused you is that the link itself has a class of active, but its li wrapper does not.


Customize the default search block In the .theme file of my custom Drupal 8 theme, how do I customize the default search block so that I can add custom classes and also alter the input label to remove the word "search" but instead have a search icon from fontawesome?

Pretty much, I'd like the final output code to look like this:

<div class="infoBar-search">
  <form action="#!" class="searchForm">
    <input type="search" name="sitesearch" placeholder="Search...">
    <input type="submit" class="searchForm-submit fa" value="&#xf002;">
  </form>
</div>

Would the .theme approach be the best way to go about this? I tried altering a few template files but noticed this would affect the other forms on the site as well.

I'm sure this can be done more elegantly , but I was able to do this with a #icon_variable from the form[] to change the input suggestion. I just added side that I want the icon on the button and an extra option to ...-icon-class.html.twig etc.

1) Add a suggestion to the input

function MODULE_theme_suggestions_input_alter(array &$suggestions, array $variables, $hook) {

   if (isset($variables['element']['#icon']) || isset($variables['element']['#icon-left']) || isset($variables['element']['#icon-right'])) {
         $suggestions[] = 'input__submit_icon';
         if (isset($variables['element']['#icon'])) {
           $suggestions[] = 'input__submit_icon_' . $variables['element']['#icon'];
         }
      }
   }

Then I can add/alter this on the form:

   $form['actions']['submit']['#icon-left'] = 'icon-class';

With a template like input__submit_icon.html.twig :

<button {{ attributes }} >
    {% if element['#icon-left'] %}

    {% endif %}
    {{ attributes.value }}
    {% if element['#icon-right'] %}

    {% endif %}
</button>


How to disable context from URL in Views I use D7.
I have a view which I want to show only current user. Those fields, in the view, are related to the current user via relationship of Profile. So, I can also say that the current user can view their own profile's fields.

So, I set 'User: Uid' as 'User ID from logged in user' on contextual filer. But, if I write non-current user's uid after page's path(Let's say '/test-user') like '/test-user/100', it outputs that user's(uid=100) fields.Even if I set 'global $user; return $user->uid;' with PHP Code for User: Uid instead, I got the same result.

For some reason,  with Field Permission module, I set those fields as 'View anyone's value for field_name'. So, I have to control the visibility in this view somehow.

Can anybody give me some advice?
Thank you.

Found the solution. Actually this doesn't disable a context from URL. But it worked for my demand.

Click 'add' under Filter criteria.
->Select 'User: Current'.
->Select 'Is the logged in user' as 'Yes'.

That's all.


Drupal entity from different database I have an existing database (which is not under my control) that i want to use as base database for my entity. However I'm stuck at getting the data from the database. There already exists a question about this problem. However that question is only about installing the module and that doesn't apply to loading an entity.

Hope I stated my problem clear enough.

I think your talking about remote entity.

Remote Entity API provides a system for treating data from remote sites as local, Drupal entities. Remote data is stored locally in an entity base table, and can be periodically refreshed with data from the remote source.

Once a custom entity type is defined, entities can be manipulated just as normal Drupal entities: they can be loaded and saved to the local database, and have fields added to them. Remote Entity API provides ways to load an entity remotely, query the remote source for multiple entities, and save back to the remote source.

From the Remote Entity Documentation page:

  Creating a connection

  TODO.

  Creating a resource

  The Clients Resource for the remote entity type is composed of two
  parts, and as such can't be created in the UI:

  hook_entity_info() defines the remote entity type. See remote_entity_hook_entity_info() for the additional keys that must/can
  be defined here.
  The Clients resource itself must be defined with hook_clients_default_resources():

/**
 * Implements hook_clients_default_resources().
 *
 * Define our remote entity resource.
 */
function example_clients_default_resources() {
  $items['my_entity_type'] = entity_import('clients_resource', '{
    "component" : "my_entity_type",
    "connection" : "my_connection_name",
    "name" : "my_entity_type",
    "label" : "My Entity Type",
    "type" : "remote_entity", // do not change @see function remote_entity_load_by_remote_id
    "configuration" : null,
    "rdf_mapping" : []
  }');
  return $items;
}


user empties cart how do I redirect that user to originating page I have a rule

  Redirect to cart after adding a registration

this rule works exactly as planned.

New scenario and new rule, If the user empties their cart of all products, I want to redirect to previous page (the sending page).

New rule

  Redirect user to originating page after removing all items from cart

I have the Event and the Conditions but I don't see how to massage the originating address that was used to get to the cart. The originating form action is <input type="submit" id="edit-submit" name="op" value="Add to cart" class="form-submit">.

{ "rules_redirect_user_to_originating_page_after_removing_all_items" : {
    "LABEL" : "Redirect user to originating page after removing all items from cart",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Cart" ],
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_remove" : [] },
    "IF" : [ { "data_is_empty" : { "data" : [ "quantity" ] } } ],
    "DO" : []
  }
}

Can anyone help?

In your first rule "Redirect to cart after adding a registration" you probably are using a "Page redirect" action. If so you can do the following.

Edit this action and set "APPEND DESTINATION PARAMETER" to true (see screenshot).
This will add the referring page as a query parameter to your url e.g. example.com/cart?destination=node/3

Then in your second rule you can retrieve this destination parameter by using the function drupal_get_destination. Use the return value of that function in the drupal_goto function and the user will be redirected to the url they were coming from.

{ "rules_redirect_user_to_originating_page_after_removing_all_items" : {
    "LABEL" : "Redirect user to originating page after removing all items from cart",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Cart" ],
    "REQUIRES" : [ "php", "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_remove" : [] },
    "DO" : [
      { "php_eval" : { "code" : "drupal_goto (drupal_get_destination());" } }
    ]
  }
}


What is the right way of installing Drush? The http://docs.drush.org/en/master/install page states:

  Drush 9 only supports one install method. It requires that your Drupal
  8 site be built with Composer and Drush be listed as a dependency.

and if you go to https://github.com/drupal-composer/drupal-project and follow the given steps, in particular run the composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction command, then:

You will have to create an empty directory (otherwise it will complain the given directory is not empty);
It will create Composer structure with Drupal 8 located in web sub-directory;
It will also create vendor sub-directory with lot's of other sub-directories as:

alchemy       composer           doctrine         fabpot          league       phar-io        sebastian    theseer
asm89         consolidation      drupal           grasmash        masterminds  phpdocumentor  squizlabs    twig
autoload.php  container-interop  drupal-composer  guzzlehttp      mikey179     phpspec        stack        vlucas
behat         cweagans           drush            instaclick      myclabs      phpunit        stecman      webflo
bin           dflydev            easyrdf          jakub-onderka   nikic        psr            symfony      webmozart
chi-teck      dnoegel            egulias          jcalderonzumba  paragonie    psy            symfony-cmf  zendframework

Now with regard the new way of isntalling Drupal 8 I have two questions:

Previously we would install Drupal 8 in document root set by control panel. Different control panel have different document roots, ours default them in /home/username/public_html.

Now, with the new way of installing Drupal 8 we end up with document root located in /home/username/some-dir/web, which does not play nice with our control panel's defaults. So I wonder what is the best recommended practice here?

Creating symbolic links between the old and new document roots also have its issues. For example, if you switch to /home/username/public_html (which is a symbolic link to /home/username/some-dir/web) and run the composer update command then it will give:

No composer.json in current directory, do you want to use the one at /home/username/some-dir? [Y,n]?

and we would really like to avoid this kind of extra steps, but at the same time respecting our control panel's default settings.

Changing the default setting for document roots in control panel is also not a good option as there could be lot's of old and non-Drupal websites on servers, so the old document root must be kept.

Do we have to have Composer structure with lot's of sub-directories like ones in vendor in every website's home directory? Please note that in my test setup Composer is installed globally. But when you run the composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction command it creates all those directories within a website's home directory.

You do not necessarily have to run composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction to create a new Drupal 8 site using the drupal-project composer package.

You can also just download the composer.json of that project and place it into your future Drupal 8 base folder. Then you can alter the installer paths within that composer.json to your liking. So if you prefer public over web as your Drupal root, then rename that part of the installer paths. You may also wish to alter the project name or other details of the composer.json file.

After your customization, you can then run composer update to generate an according composer.lock file. Assuming you did so on a local development environment, you can then use composer install --no-dev on your production system after uploading your composer and custom files/checking them out if you use a code versioning system.

Coming to the folder structure: It is advisable to keep the folder above the Drupal 8 root as base folder of your root package (project), location for the composer dependencies (vendor folder), Drush site settings, and auxillary files that should not be directly accessible from your web URLs (e.g. exported configuration files, private files, temporary files, Node.js packages, ...).

Therefore you should consider pointing your virtual hosts' root directories for example to /home/username/public_html/web (or /home/username/public_html/public, if you customized your composer.json like that) while using the regular root directories of your hosting panel /home/username/public_html as composer root package folder.

Depending on your hosting panel, you may have the ability to alter the vhost root directory by overriding the web server settings (e.g. defining a DocumentRoot for Apache, or a root for Nginx). How to do this depends heavily on your used hosting solution and is therefore off-topic in Drupal Answers.

And yes, you will have this folder structure on every of your projects. As every project may require a different version of dependencies, different modules (which may add dependencies with certain version restrictions to the vendor folder as well), binary tools for the shell, probably applied patches and so on. These dependencies and their version requirements are project specific, even when you use a global Composer installation.


Storing data / session for anonymous user I am working on a shop, and for the cart, i need to store items before payment.

  $tempstore = \Drupal::service('user.private_tempstore')->get('boutique');
  $tempstore->set('poids', $form_state->getValue('poids'));

I take a look on the user service for :

  pivate_tempstore and shared_tempstore

But that work only for authenticates users.

What can I use for store data ? $_SESSION ? or Drupal 8 has a service for that ?

Late answering, but it's worth mentioning that you can use private tempstore for anonymous users, as long as the tempstore has access to an active session. To do so, you need to inject your class with services for the temp store, session, and current user, like so:

public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;

    $this->store = $this->tempStoreFactory->get('myclass.storename');
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('user.private_tempstore'),
        $container->get('session_manager'),
        $container->get('current_user')
    );
}

Then you just need to ensure you start the session manager if the user is anonymous, before you need to put anything in the temp store:

if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
    $_SESSION['session_started'] = true;
    $this->sessionManager->start();
}

You might find this approach preferable because it means that you can use a single system for temporary storage, regardless of whether a user is logged in.

(My code examples are lifted more-or-less verbatim from this excellent tutorial on building multi-step forms.)


How to Override Views Field Handler Is it possible to overwrite a Views Field hander without creating a new field?

For example, I am trying to overwrite the Geolocation ProximityField field handler.

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\geolocation\Plugin\views\field\ProximityField;
use Drupal\Core\Form\FormStateInterface;

/**
 * Field handler for geolocation field.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("geolocation_field_proximity")
 */
class RangeProximityField extends ProximityField {

  /**
   * Form constructor for the user input form.
   *
   * @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 function viewsForm(array &$form, FormStateInterface $form_state) {
    $this->viewsForm($form, $form_state);
    // Add custom logic here.
  }

}

I tried using hook_views_data_alter() but had no luck (I renamed in above annotation to mymodule_field_range_proximity):

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(array &$data) {
  $data['node__field_latlong']['field_latlong']['field']['id'] = 'mymodule_field_range_proximity';
}

You don't need to create a new field handler. You can replace the class of the existing field plugin. The plugin manager provides a hook to alter the plugin definitions:

/**
 * Implements hook_views_plugins_field_alter().
 */
function mymodule_views_plugins_field_alter(array &$plugins) {
  $plugins['geolocation_field_proximity']['class'] = 'Drupal\mymodule\Plugin\views\field\RangeProximityField';
}


How do I sort or filter a View by proximity using Search API location? I am trying to set up a Solr Search View with Search API Solr and Search API location, witch is sorted by proximity an can be filtered by proximity.
To achieve that,

I created an search index, which indexes a geofield as latitude/longitude (under admin/config/search/search_api/index/INDEX_NAME/fields):
I created a View for the mentioned Search index and was able to add a proximity filter as contextual filter:

It is also possible to add the indexed Lat/Lon field to the field section of the View and set up a formatter showing the distance to a certain geolocation:

But there wasn't any field I could add to the sort section or the filter section of the View, that filters or sorts by proximity.
What do I have to do, to filter and sort a Search API Solr View by proximity?

If you want to filter based on some user selection, you can have PHP code which gets the value and filters result based on that.

Please check this http://murtuza88.blogspot.in/2014/11/use-drupal-location-module-to-filter.html for detail steps on how to filter view based on user selection.


Why is my alias "NULL" in a test? I am using Drupal 7, I have Pathauto enabled, and my user has permissions to create new aliases.

When I manually create a node, uncheck the checkbox for automatic alias generation, and enter a custom alias (e.g. 'qwerty'), I can use drupal_lookup_path() to return the alias. So

$path = drupal_lookup_path('node/' . $node->nid);

gives $path a value of 'qwerty'.

However, when I create a node in simpletest with the code

$edit = array(
  'title' => 'asdf',
  'path[alias]' => 'qwerty',
);
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));

and then

$path = drupal_lookup_path('node/' . $node->nid);

$path has a value of 'NULL', even when the alias is functioning, e.g. when

$this->drupalGet('qwerty');

returns a 200 status.

Why is drupal_lookup_path() failing to find my alias only when called from a test?

I tracked this down to the fact that current_path(), which returns path/to/content in the browser, instead returns batch when called from within Simpletest.

Since drupal_lookup_path() uses the output of current_path() to generate the $cache[map] variable that it uses to find and store the path alias, this prevents drupal_lookup_path() from working in tests.

I have filed this as an issue on d.o.


Solr can't find lib files I have been trying to install the search_api_solr module.  I installed tomcat and Solr according to the instructions on the module's project site and the INSTALL instruction in the module.  However, I am stuck.

According to the INSTALL.txt instructions:

  NOTE: The Solr 4.3+ example application is currently not completely
  supported with the configuration files included in this module, due to
  a slight change in the directory structure. To fix this, simply copy, move
  or symlink the contrib/ directory from the top level of the extracted
  Solr package one level down to example/.

  (For other directory structures: the contrib/ directory has to be in the directory two levels up from the one which includes the conf/
  directory. For help, just start the Solr server and check the log
  files for WARN messages – they should state in which place Solr
  expects the directory to be.)

I checked an sure enough Solr is reporting the following warnings:

  00:15:45  WARN    SolrResourceLoader  Can't find (or read) directory to
  add to classloader: ../../../contrib/extraction/lib (resolved as:
  /usr/local/tomcat/solr/drupal/../../../contrib/extraction/lib).

  00:15:45  WARN    SolrResourceLoader  Can't find (or read) directory to
  add to classloader: ../../../contrib/clustering/lib/ (resolved as:
  /usr/local/tomcat/solr/drupal/../../../contrib/clustering/lib).

The question is how to resolve this? I am using SolrL ver 4.6.1

I was having the same issue.

I ended up copying the contrib folder into: /usr/local/tomcat
So I had: /usr/local/tomcat/contrib/
and: /usr/local/tomcat/solr/drupal/

That error about contrib/extract/lib went away, but now I'm getting:
"Failed to load file /usr/local/tomcat/solr/drupal/solrconfig.xml"

As seen on the logging screen: http://screencast.com/t/MqtSNpqUljI

UPDATE: I went to the admin section on Solr and tried to add the core called drupal. So it tried to process the solrconfig.xml and found an error: http://screencast.com/t/EEmU4P9M
I had the useCompoundFile twice. I fixed it and added the core. After that, it was working fine.
I hope this helps out someone. I installed solr on centos by following the lullabot guide: http://www.lullabot.com/blog/article/installing-solr-use-drupal


Process a token from panel context in a ctools content type plugin I have a ctools content type plugin. It has a simple text field settings form. In there I am putting a token from the panel content e.g. %vn_subject:vn-subject-facebook-link. I am then rendering this into a template. However, it is just rendering out the token as above without processing it. How can I process the token if possible to retrieve the required field value?
Thanks

The magic function is ctools_context_keyword_substitute

The key to getting this working is to make sure that you use the all contexts flag in your plugin configuration.

$plugin = array(
  'single' => TRUE,
  'title' => t('Instagram'),
  'category' => t('Content'),
  'all contexts' => TRUE,
);

/**
 * Render the custom content type.
 */
function MODULE_PANE_content_type_render($subtype, $conf, $panel_args, $context) {

  ....

  $replaced = ctools_context_keyword_substitute('your_string_with_%keywords', array(), $context);

  ....
}


Blocking IP Address In Drupal 7 Via Code I want to know is there any function in DRUPAL 7 that I can send it an IP address as a parameter and it adds this ip to blacked_ips table ??

Indeed I have a rule that contains a Execution PHP action . In my action I want to add an IP to black list.

There isn't in core; system_block_ip_action() is about as close it you'll get, but that blocks the current IP.

Such a function would be trivial to implement though:

function block_ip($ip) {
  if (!(bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField()) {
    db_insert('blocked_ips')->fields(array('ip' => $ip))->execute();
  }
}


rendering node $content but not all $content is there node $content variable does not contain all node elements

On my local test site the $content variable contains around 10 elements which I used to build my custom node template.

but now on the live site I only have 2 elements in the $content array.

I can't figure out why and looked everywhere but can't find where $content is set and or why the the other 'elements' of my node are not loaded in the $content variable.

using the normal 'view' all content is available.
using my node--teaser.tpl.php not on the live site.

Both sites have the same modules enabled and are using similar node types.

Check your display options for that content type to make sure that those fields are set to display in teaser mode.

Drupal 6: admin/content/node-type/NAME-OF-CONTENT-TYPE/display

Drupal 7: admin/structure/types/manage/NAME-OF-CONTENT-TYPE/display


Send email when entity field value is changed I have used Rules module for notification when node is created, edited or deleted.

My site is in three languages and I use Entity Translation for translating node's field.

Now I want notification when node's or entity field is changed/updated. Can I achieve it with Rules module?

Yes, you can use Rules to achieve this.

Here's how:

Create new rule that will react on "After updating existing content" event.
Use the following conditions: data comparison: node:field-your-field and node-unchanged:field-your-field and select "Negate: FALSE"
Create whichever actions you want, e.g. send mail, show message, etc.


Using Drush on shared hosting without `curl` and `wget` I have a Drupal 7 site installed on shared hosting.

And installed Drush:8.1.17 with composer and cgr all is working well except drush up because hosting provider does not support curl or wget on shared accounts.

When I ask them they said that there is no plans for giving permissions on shared account users to curl or wget when I run:

$ drush up
$ wget nor curl executable found.

$ curl
-jailshell: /usr/bin/curl: Permission denied

Is there another way of using drush up?

Your use case is not supported. You'll have to update locally and then push to your provider.


How do you add an incrementing primary key to an existing table? I'm working on the contributed Login History module which has an existing table that does not have a primary key. I'd like to add a primary key to the table, but am struggle with the db_add_field syntax for upgrades. The existing table is:

/**
 * Implements hook_schema().
 */
function login_history_schema() {
  $schema['login_history'] = array(
    'fields' => array(
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'uid of user.',
      ),
      'login' => array(
        'type' => 'int',
        'not null' => TRUE,
        'description' => "Timestamp for user's login.",
      ),
      'hostname' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => "The user's host name.",
      ),
      'one_time' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'Indicates whether the login was from a one-time login link (e.g. password reset).',
      ),
      'user_agent' => array(
        'type' => 'varchar',
        'length' => 256,
        'not null' => TRUE,
        'default' => '',
        'description' => 'User agent (i.e. browser) of the device used during the login.',
      ),
    ),
    'indexes' => array(
      'login_history_uid' => array('uid'),
      'login_history_onetime' => array('one_time'),
      'login_history_uid_host' => array('uid', 'hostname'),
    ),
  );
  return $schema;
}

And what I think should work to add a primary key is a hook_update like this:

/**
 * Add device_id and login_id columns.
 */
function login_history_update_7106() {
  if (!db_field_exists('login_history', 'login_id')) {
    db_add_field(
      'login_history',
      'login_id',
      array(
        'description' => 'The primary identifier for a login.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      array('primary key' => array('login_id')));
  }
}

However, that results in this error:

SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead                                                                                [error]

I've tried:

Reading and re-reading the docs for db_add_field and db_change_field
Using db_add_field to add an empty int field and then using db_change_field to make it a serial primary key.
Using db_add_field without the 4th parameter that sets the new primary keys and then trying to use db_add_primary_key('login_history', array('login_id')) but that gives an error before the field is even added saying that auto_increment fields have to be part of a unique key.

I've grepped core and some contrib looking for instances of adding an auto increment primary key and can't find any for Drupal 7.

This actually seems to be an issue in Drupal Core where creating a serial field on an existing table is not possible in MySQL 5.7+ without first creating an int field and converting that to autoincrement (this issue does not show up in MySQL 5.6 and below). Please see https://www.drupal.org/node/2615496 for a patch that fixes this issue for new releases of MySQL. It might be worthwhile to update that patch to be rolled into 8.x so it will allow us to patch 7.x.


Create a dynamic user registration form using Profiles So, I need to create a user registration form for a website that has numerous types of users that are distinctly different from one another. I've already found the profiles module, and I'm using that. But I want to streamline the user registration process.

We don't want to create a large form that pushes everyone through the same questions, even if that question isn't applicable to that user. Nor do we want to compromise and only not ask certain questions that are important to that particular type of user.

I'd also prefer the form to be dynamically updated, rather than a multi-step form.

How can I do this?

Bascially, we create an Ajax callback on the form element used to update the form, and we create an additional form element which is simply a container to display the the relevant profile form.

I used the Profile 2 Registration Path module to add the Profiles Forms to the User Registration form. I then use hide();  and show(); to display them if appropriate.

The Devel module was also invaluable doing this.

function rego_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'user_register_form'){
        dpm($form);

        //First, hide all the other profiles
        hide($form['profile_designer']);

        //User selects what type of profile is most appropriate
        $form['profile_main']['field_profile_type']['und']['#ajax'] = array(
            'callback' => 'rego_update_profile_type',
            'wrapper' => 'profiles_container',
        );

        //Create a container to the relevant profile
        $form['profiles_container'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#weight' => '500',
        );
    }
}

//Callback
function rego_update_profile_type($form, $form_state){
    // Switch based on the user input
    switch($form_state['values']['profile_main']...['tid']){
    case '82':
        $form['profiles_container'] = $form['profile_designer'];
        break;
        // --Other cases here --
    }
    //Put back the div id so that the container can be updated again
    $form['profiles_container']['#prefix'] = '
';
    $form['profiles_container']['#suffix'] = '
';

    show($form['profiles_container']);
    return $form['profiles_container'];
}


Background Image not shown I use the Bluemaster theme for my site. Since I installed this theme, it worked well, but
a few days ago the background image was not shown.

I think this is because there are a large photo in background.
How do I fix this problem?

Your css is the problem.   There is no images/bg.gif.  There is an image/bg.png file.

Change

body {
    background: url("images/bg.gif") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}

to:

body {
    background: url("images/bg.png") repeat scroll 0 0 transparent;
    color: #666666;
    font-family: Tahoma;
    font-size: 12px;
    padding: 0;
    text-align: center;
}


Can I add text to a form file upload field? Is it possible to add text/markup to a file upload field similar to the image below?

I thought that something like

$form['actions']['edit-field-upload']['#prefix'] = 'First';

in a hook_form_alter would work, but don't see anything.

You can add a #prefix to a file upload field using hook_form_alter, but I don't think it will give you what you're looking for

function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {  //custom content type of 'test'
    //custom field in the content type called 'field_test_upload'
    $form['field_test_upload']['#prefix'] = '
test prefix
';
  }
}

With the above code I have a custom content type of "test" and a custom field called "field_test_upload"

When adding a #prefix to the field I get the following results:


How to use multiple text fields in widget "image" in content type I'm new in Drupal and I'm working on a website built in Drupal. I want to use multiple text fields like title, medium, photo credits with image widget in content type. I have attached two screen-shots to make clear what I really want to do.

Please help to find out the way to do this. I'll be thankful to you.

You can take a look on Image Field Caption module.

Adds an extra text area for captions on image fields.

Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

Media module also work for you.


drupal /?q=user is working but /user not working I have recently moved my files from dev server to test server. same setting and db of dev server were copied to test server. In dev server all is working fine but when I have am checking in test sever /user not working but /?q=user is working

I have checked with mod_rewrite in test server apache setting and it is enabled.
I also checked my clean url drupal setting it is also enabled

/user throws 404 error for me

Not Found

The requested URL /user was not found on this server.

Can someone help me find the issue

As you have checked mod_rewrite settings for your server and .htaccess both it sems that you may have mis-configured  RewriteBase in your .htaccess file.

Please check comments in .htaccess file

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
   VirtualDocumentRoot and the rewrite rules are not working properly.
   For example if your site is at http://example.com/drupal then its value should be:

RewriteBase /drupal

If your site is running in a VirtualDocumentRoot at http://example.com/,
   then its value should be:

RewriteBase /

Try and see if you have something wrong here.


hook_theme() in a custom file of my module I'm facing an issue for a few hours now. I created a new module that must render an admin page with some settings and another one with analytics data. The second one must use a custom template file that I created for the occasion.

I added a hook_theme() in my .module file and everything worked fine for a while.

When refactoring my code I wanted to move the hook_theme() in a subfile.inc of my module. Even though I cleared the caches, I always get the issue Theme hook "my_custom_template" not found..

After moving back the hook in the .module file everything work again.

Are they some hooks that must be in the .module file only. As the hook_install() and hook_uninstall() must be in the .install file?

Just to clarify, you mean the actual hook_theme() implementation, correct? Not a theme hook you are defining in hook_theme(). If so, by default, all hooks must be in the .module file. Hooks are meant to be callable at any time, and only .module files are loaded by default on every page load. However you can tell Drupal that a hook is in a different file by implementing hook_hook_info():

function hook_hook_info()
{
   $hooks['theme'] = ['group' => 'theme'];

   return $hooks;
}

With this code, Drupal will look for the hook (the array key 'theme') in the file MODULENAME.GROUPNAME.inc. In this case your GROUPNAME is defined as 'theme' in hook_hook_info(), so Drupal will load MODULENAME.theme.inc, whenever hook_theme() is invoked.

Now, if you meant that you want to put a theme hook that you define inside hook_theme() in another file, then you need to declare the file for that theme hook:

function hook_theme()
{
  return array
  (
    'some_theme_key' => array
    (
      'variables' => array(),
      'file' => 'path/to/file.inc', // relative to module root
    ),
  );
}

In this case, when the system tries to load the theme some_theme_key, it will load the file [MODULEFOLDER]/path/to/file.inc.