Syncing Development Site with Production Site I recently built my first Drupal 8 site. I've updated the production site since it's been launched, and I wanted to sync it with the development site before I create another content type.

Could someone point me in the right direction?

You simply need to sync the database and the whole complete Drupal folder. Every single file except for .htaccess and settings.php as they may be different in every environment.

And from now on you start to do things just the other way around.

git init a Git repo on your local machine. Then you do every update, every UI change, every site building task on your local machine first.

When you are done locally you do drush cex to export the new configuration into YAML files. I think you can do that from the UI as well.

Then you deploy (upload) these YAML files to your live site and start the configuration import, drush cim or UI.

Similar with updating Drupal. Wether Composer or manually, you do that on your local machine first. Then deploy the resulting composer.lock file or the updated files to your live site and start the database updates once again, drush updb or from the UI.

From now and then you get a database dump from your live site and import that locally. Maybe you download or rsync the whole sites/default/files folder to your local machine as well. This one and your settings.php are going to be ignored from Git.

That's how things are supposed to go. File changes always upstream, database dumps downstream.

After you've set up Git correctly you may start to use Git Flow. Which expects you to work in different Git branches, master and develop. And feature/* branches when developing new features locally.

Basically when you're done with a feature you merge the feature branch into the develop branch and push the changes to your Dev server. Once in a while you start a new release where the develop branch gets merged into the master branch. And the master branch would be the one that pushes stuff to the Live server.


BOA Aegir Octopus, APC disabled: Module's php files seem to be cached, changes are not reflected. Why? I installed BOA on a VPS and everything seems quite alright except the fact that when I change a module's php file, the changes are not reflected in the website.

When I change something in drupal's index.php I can see the changes.

My first thought was APC which I disabled globally in php.ini for testing but that didn't help.

It looks like the file is never called, though I double checked that I'm working in the right directory and drupal setup.

Obviously I'm missing something and even Google didn't shed light no this.

Do you know what this could be?

Clearing Drupal cache may be not enough in this case.

Since Redis is active by default, it may still cache some include paths, or there can be old paths still present in your system table, so you need to run the "Rebuild registry" task followed by "Flush all caches" task (the second is the same as running drush cc all on command line).

If this still doesn't help, upgrade to latest BOA-2.0.6-dev (head), which includes recent APC 3.1.14 version to avoid this known APC bug.


Ultimate Cron installation Table 'db_name.ultimate_cron_log' doesn't exist After installing the ultimate cron module version 8.x-2.0-alpha4,
When I navigate to (/admin/config/system/cron/jobs), I get the following error meassage -
Base table or view not found: 1146 Table 'db_name.ultimate_cron_log' doesn't exist: SELECT l. FROM {ultimate_cron_log}* l WHERE (l.name = :db_condition_placeholder_0) AND (l.log_type IN (:db_condition_placeholder_1)) ORDER BY l.start_time DESC, l.end_time DESC LIMIT 1 OFFSET 0; Array ( [:db_condition_placeholder_0] => system_cron [:db_condition_placeholder_1] => 0 ) in Drupal\ultimate_cron\Entity\CronJob->loadLatestLogEntry() (line 526 of modules\ultimate_cron\src\Entity\CronJob.php).
Drupal\Core\Database\Statement->execute(Array, Array) (Line: 640)
I have tried uninstalling and installing it again, but the error persists.
Kindly help.

I ran the following to fix the issue.  Manually create tables.
CREATE TABLE 'ultimate_cron_log' (
  `lid` varchar(176) NOT NULL COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `log_type` int(11) NOT NULL DEFAULT '0' COMMENT 'Log type',
  `start_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution start',
  `end_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution end',
  `uid` int(11) NOT NULL DEFAULT '0' COMMENT 'User ID',
  `init_message` text COMMENT 'Initial message',
  `message` text COMMENT 'Message',
  `severity` int(11) DEFAULT '-1' COMMENT 'Max severity level of the execution',
  PRIMARY KEY (`lid`),
  KEY `idx_last` (`name`(80),`start_time`,`end_time`,`log_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Logs';
CREATE TABLE 'ultimate_cron_lock' (
  `lid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `current` bigint(20) NOT NULL DEFAULT '0' COMMENT 'Current lock',
  `expire` double NOT NULL DEFAULT '0' COMMENT 'Expiration time of lock',
  PRIMARY KEY (`lid`),
  UNIQUE KEY `idx_name` (`name`,`current`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Locks';
CREATE TABLE 'ultimate_cron_signal' (
  `job_name` varchar(166) NOT NULL COMMENT 'Name of job',
  `signal_name` varchar(166) NOT NULL COMMENT 'Name of signal',
  `claimed` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Is signal claimed',
  PRIMARY KEY (`job_name`,`signal_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Signals';


How to show snippet of an event when clicked in the calendar in Drupal 7 with the Calendar Module I created a calendar with the Calendar Module, but I don't know what to do to show a snippet of the event when clicked. This calender is a perfect example of what I mean https://hutchinscenter.fas.harvard.edu/calendar. Thanks!

There are probably many different ways of doing it.

One possibility is the Calendar Tooltips module.

Another is using Colorbox module to control the popup, you construct the Views output yourself so that the Colorbox library displays it as a popup: Does Calendar Popup Module exist in D7?, using-colorbox-display-event-details-popup


How do I model content (types) from a database-centric point of view? How can I model content from a "database-centric" point of view?

For example to show Appartments in a District in a City, as in this example:

Table Cities:
CityID (int) primary key
City (string)

Table District:
DistrictID primary key
CityID foreign key
District (string)

Table Appartment:
AppartmentID primary
DistrictID foreign
AppartmentName
NrOfRooms
.....etc....

How would I create content types (?) to do this?

I'm assuming this question is about Drupal 7 ... Only using Site Building features (no custom module development yet) should get you pretty far (if not far enough ...).
The Relativity Data Model for Drupal
Have a look at the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handful of modules (cfr. the last bullet) is like so (apart from Drupal core):

https://www.drupal.org/project/ctools
https://www.drupal.org/project/date
https://www.drupal.org/project/entity
https://www.drupal.org/project/entityreference
https://www.drupal.org/project/entityconnect
https://www.drupal.org/project/field_group
https://www.drupal.org/project/token
https://www.drupal.org/project/pathauto
https://www.drupal.org/project/views

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".
Typical add-on modules
Even though that small handful of modules above can get you already extremely far, I often add a subset of other contributed modules to it also, as further detailed below.
Tables, Columns and Foreign keys

Tables: Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...). In your case that would be entities like Cities, District and Appartment.
Columns: For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
Foreign keys: For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node_reference' and 'user_reference' as contained in CCK for D6).

Business logic
Using the Rules and Flag module, it is possible to implement all sorts of business logic (= rules), simply using the typical Drupal admin UI for those modules.
Queries, custom reports and charts

To perform queries (listings, etc), use the views module, possibly further extended with modules such as Views Slideshow: Galleria (there are dozens of modules to further enhance views).
The Forena module can be used as a supplement / alternative (e.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc).
Create charts using the views integration of the Charts module to visualize a lot of data in a way that can be quickly digested.

Page Layout
Modules like Display Suite and/or Panels can help to enhance the look and feel of it all also.
Many more modules

Group (a pretty new alternative to Organic groups, to create arbitrary collections of your content and users and grant access control permissions on them).
Workflow (to create arbitrary workflows, and assign them to entities).
IP Geolocation Views & Maps, a mapping engine to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet)
Or, or  ... on and on goes the list.

Disclosure: I'm a (co-)maintainer of Forena and Charts.


How to reference existing Paragraph entity? I'm trying to create an entity reference field for existing paragraph, but can't seem to figure it out.

I've tried creating a normal entity reference field (content) but that only gives me the options to select from content types.

I've tried creating a paragraph field and using a entity reference view to display the results. (this displays a list of paragraph entity ids but when referencing one in a node it comes up with There are no entities matching "(21)".

How do I reference existing paragraph entities in a node?

Re-using paragraphs is not supported/allowed. Each paragraph has a reference to the host entity it is being used in and only supports one such reference.

If you need re-usable content in paragraphs, you need to have another entity type or bundle that you reference from a paragraph type.


How do I create and set fields in multiple nodes using a rules loop I have created a RULES loop.  It loops over a set of flagged nodes (using the action 'Fetch Node flagged by user') and attempts to create a new node for each flagged node.  Finally, the new node is linked to its related 'loop' node via entity reference.

My problem is:  The action that creates the new node ('Create a new entity', which is called within the loop) assigns the new node to a static variable name (mine is: entity_created).  Because of this, the loop only creates one new node and only saves data from the final loop node into it.

Is there a way to either create this variable dynamically or is there a way to reset the value of entity_created so that it can be used to create multiple nodes?

Create a sub-rule which does the node creation and call it from within the loop.  This should provide enough separation to keep the nodes from interfering with each other.  Also, use "Save entity" action to lock the new nodes in place during the loop, instead of at the end of the rule.


How to override form element templates from custom module I have a custom field with some radio inputs and the following (widget-)output right now:

  <input />

For every radio single radio input(In my case 5 times - back 2 back). Can I remove the outer
 without actually touching any themes (neither the stable theme nor my custom theme) ?

Got it working. First you have to copy the default form element template into your module's /templates folder. For example:

$ mkdir -p modules/custom/MYMODULE/templates
$ cp core/themes/stable/templates/form/form-element.html.twig modules/custom/MYMODULE/templates/form-element.html.twig

Now rename it to something you want. For example:

$ mv modules/custom/MYMODULE/templates/form-element.html.twig modules/custom/MYMODULE/templates/form-element--foo.html.twig

Edit the file to match your needs. For example remove or change the

 tags. Finally in your module's MYMODULE.module file add the following two hooks.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * This hook adds a new theme suggestion for all radio form elements.
 */
function MYMODULE_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {

  if ($variables['element']['#type'] == 'radio') {
    $suggestions[] = 'form_element__foo';
  }
}

/**
 * Implements hook_theme().
 *
 * This hook registers a new theme in your module. It will
 * automatically look for the template in your module's /templates folder.
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'form_element__foo' => [
      // base_hook is important!
      // Otherwise your template won't know what to render.
      'base hook' => 'form_element',
    ],
  ];
}

Only thing left, I find, is to have the form ID added to the template suggestion as well, so that we could target only this one form's elements. As now this template will be taken into account for all radio form element wrappers. Independent from what form they are in. But unfortunately I couldn't find the form ID inside the form_element's $variables.

Hah, you simply could add a class to your radios and identify them by that later.

$form['radios'] = [
  '#type' => 'radios',
  // ...
  '#attributes' => ['class' => ['foo']],
];

And then the hook_theme_suggestions_HOOK_alter could look like that:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMOUDLE_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {

  if ($variables['element']['#type'] == 'radio' && in_array('foo', $variables['element']['#attributes']['class'])) {
    $suggestions[] = 'form_element__foo';
  }
}

Now the custom template would only be taken into account for your specific radios.


How to change form submit button value after form submission? I want to change the value of the submit button after the the form is submitted successfully without any validation errors.

And then when the page is reloaded the button's value will be changed to its original value?

I think its not possible with any javascript or jquery but I can't find a value in the $form_state array to set a js variable.

Edit:
The form is submitted without ajax. The button should be replaced with that text after the form is submitted. And then when the user comes back to page again or reload it again then the text should be reverted.

You can do this with two steps. The first is to check whether $form_state['values'] has been set, and change the value accordingly:

if(!isset($form_state['values'])) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
}
else {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit Again'),
  );
}

The next step is in your submit function, where you have to tell Drupal to rebuild the form (rather than build it from scratch)

$form_state['rebuild'] = TRUE;


How to set a mini panel to display node fields? I want to load node fields into a mini panel, but when I do what I think that I need to do, the mini panel (= MP) is invisible (because the fields aren't displayed, I guess).

So far I have:

Added a Content Type
Added fields to that Content Type
Created a Minipanel with Required Context = Node
Added my various Node Fields to that MP: Add Content > Node > Field: ___
Moved the MP into my Content range in the Blocks Editor

I don't see my MP anywhere. This user seems to have a similar issue, and solved it with the Context settings but doesn't answer the question at all, just closed it.  Other people seem to have this issue as well:

Can't get a mini panel containing node form fields into a panel page
Node fields and node tokens not showing up in a mini-panel

Can anyone clarify for me how to make my MPs show up with information populated from the node?

As per Beebee comment, you should first try removing the "Node" required context and see if that renders the block. Make it work at the most basic level possible and then add various customisations and contexts.


Integrate simplenews and rules I have a website developed in Drupal 6. I am using Simplenews for my newsletter. When a user subscribe to the newsletter I would like to redirect him to a new thank page. In order to do this, I need integrate simplenews module with rules.

In this link https://drupal.org/node/620498 there are several patchs, #40 it works. The point is that I´m not a developer and I don´t know how I do not know how to implement it. I understand I have to create multiple files with these lines of code. I do not know in which folder I have to save the files. Could anyone help me?

Thank you very much!

It seems like you don't really understand what a patch is and how you can use them. You can read about the basics at https://drupal.org/node/620014. Basically, this is a general definition of a patch:

  A "patch file" is a specific kind of file that contains code that is
  used to modify one or more existing files for a Drupal module.

You can use a special program to apply a patch, but I prefer applying them manually. You can find some more detailed information at https://drupal.org/node/534548.

In the patch you refer to, you find for example

+++ simplenews_rules/simplenews_rules.info
@@ -0,0 +1,7 @@
+; $Id$
+name = Simplenews rules
+description = Provides integration with Rules module for Simplenews.
+dependencies[] = simplenews
+dependencies[] = rules
+package = Mail
+core = 6.x

That means you should add the code (without the "+" signs) after @@ -0,0 +1,7 @@ at the top (after the "0th" line) of the simplenews_rules/simplenews_rules.info file. If the file doesn't exist yet, simply create it with your favourite code editor at the mentioned directory. I'm using Notepad++, for example.


Override Taxonomy Node content for different terms without using views I have taxonomy-term.tpl.php page in my theme folder which shows the standard layout of a taxonomy term page like : Title, Description and content listing corresponding to the taxonomy term. Now I wish override this standard layout for a particular term and I create another term file namely : taxonomy-term--32.tpl.php. For this I haven't added any function in the template.php file in my theme.

My problem is that for the term page with tid / term id = 32, does not entirely override the content block. Precisely, the listing of the contents related to that taxonomy term remains in the overridden web page as well, which is not what I want.

N.B : I have disabled the Taxonomy Term View from the admin end of the site as I am not absolutely sure about its functionality.

Change your node.tpl.php file so that it only returns the parts of the node you want, if the current path of the page being viewed is taxonomy/term. Using the Bartik node.tpl.php file as an example, and assuming you only want the title (linked to the node) to be displayed, you could do something like this:

Original ("before"):

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>

      <?php print $user_picture; ?>
      <?php print $submitted; ?>

  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

  <?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>

      <?php print $links; ?>

  <?php endif; ?>

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

Altered ("after"):

<?php if (!$page && arg(0) == 'taxonomy' && arg(1) == 'term'): ?>
<?php
 // Note:
 // If you want to see all the values available to you at this point, uncomment
 // the next line (not safe for production environments):
 // print '
' . check_plain(print_r($node, 1)) . '
';
?>
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

<?php else: ?>

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>

      <?php print $user_picture; ?>
      <?php print $submitted; ?>

  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

  <?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>

      <?php print $links; ?>

  <?php endif; ?>

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

<?php endif; ?>

Hope that helps...

:)


Getting translations programmatically from non-default language Scenario: I have the original string: "Perro", which has its translations: EN => "Dog", FR => "Chien".
Mission: In my custom module, I have the string "Chien" and I need to get its English translation, "Dog".

This will work for a node that has a field_animal with translation (in Drupal 8).
First we found the french translation then we compare with the string, second we fetch the english translation.

$myString = 'Chien';
$translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'fr');
$animalFr = $translation->get('field_animal')->value;
if ($myString == $animalFr){
  $translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'en');
  $animalEn = $translation->get('field_animal')->value;
}


How do I send an email notification to a user who flagged another user using rules? I have the Flag module set up so that the users can flag each other; there is a link shown on the user profile page. I would like to have those users who flagged another user to receive a notification by email when the flagged user post new content.

How can a user who is 'following' another user to disable email notification on new content?

I am using Drupal 7.

Solution: I created FLAG users, so that users can flag each other.

RULES is set up as follows: New event, node new content.

Elements (3 items)
1st  : Fetch users who have flagged a user
Parameter: Flag: Flagname..., user: [node:author]
Provides variables: Users who flagged (usersflagged) Add another

2nd : Add Loop
Parameter: Lijst: [usersflagged]
List item: Current list item (list_item)

3rd : Send E-mail
Parameter: To: [list-item:mail], Subject: Sitename | [node:author]..., Message: Dear [list-item:name], ..., From: no-reply@sitename.com

Next step to discover is how to digest the mail. And I am wondering how much impact this rule will have on a busy site.


Cannot Find property after adding it with hook_entity_property_info_alter (callback not firing) I'm very new to drupal, so forgive me if this is a simple question, but I have been working on this for a few days and have not yet found a solution.

I have an entity, to which I've added the property "hour_created" via the hook_entity_property_info_alter() function. The property has a getter_callback function that simply returns an integer for now. I can see that this property has been added by calling watchdog("normal", print_r($info, true)) after adding the property in the same hook_entity_property_info_alter() function.

The problem is that it does not appear this property is ever actual added to the entity when I try to look at it through Drupal. I added a watchdog("normal", print_r($item, true)); call in the callback, but the watchdog is never called, and never appears in the logs. To try and get the callback to fire, I have tried the following:

node-load through drush
loading the node through the site directly
directly attempting to access the property with php

Unfortunately, I have had no success with any of my above attempts. I suppose what we can boil this question down to is 'How can I make my entity property getter_callback fire, and why isn't it fired when I load the node?' I apologize if any of this is a little muddled, please let me know if any of this is unclear or if you need more information.

Thanks!

EDIT:
Here's the code for my callback:

function mymodule_test_property_getter_callback($item) {
  watchdog("normal", print_r($item, true));
  return 10;
}

And here's my hook_entity_property_info_alter() function:

function mymodule_entity_property_info_alter(&$info) {
  $info['node']['bundles']['mynode']['properties']['test_property'] = array(
    'label' => t('Just a test!'),
    'type' => 'integer',
    'computed' => TRUE,
    'required' => TRUE,
    'getter callback' => 'mymodule_test_property_getter_callback'
  );
  watchdog("normal", print_r($info, true));
}

I think this is what's going on...

With your current code you've described the property to the entity API module; if you want to access it via that you already can:

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
print $wrapper->test_property->value(); // Prints '10'

But the core entity system has no knowledge of test_property, so it doesn't show up on a node object from node_load(). To get it there, you'll need to implement hook_node_load():

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    if ($type == 'mynode') {
      $node->test_property = mymodule_test_property_getter_callback($node);
    }
  }
}

There's also the outside chance that your getter callback will rely on something having been added to the node object already, by another module's implementation of hook_node_load(). You can get past that by moving your implementation to last in the queue, with hook_module_implements_alter().

If you want Views support, I think you'll also need to implement hook_views_data_alter() to add the property to the node table. But maybe the entity module will magic that up for you, it's a good'un.


Ckeditor Stripping all attributes, when re-editing content Ckeditor is stripping out all attributes from the source code.

This is the case I'm going through:
When I add html code to the source of the Ckeditor, and then want to preview the changes by selecting source again, I find that no styling was taken. When I go back to check the source all styling attributes are removed and some HTML tags.

I found a way to save the content, without stripping by directly saving after pasting the html code in the source. But if I try to re-edit the content it strips all styling attributes and some html tags.

I am using Full HTML Text format, and did try previous versions of the ckeditor module. Also tried to modify the config.js file by adding "config.allowedContent = true;" as referred by the following post

  About

    Biography

    Timeline

    Quotations

    Philosophy

CKeditor Stripped HTMl:

About

Biography

Timeline

Quotations

Philosophy

Intellectual Legacy

Any way to resolve the following?

You shouldn't really hack the config.js file. You can pass any custom configuration values through the admin:

Go to /admin/config/content/ckeditor.
Click on the "Edit" link next to the profile you are working with.
Expand the "Advanced options" fieldset.
Enter the following code in the "Custom JavaScript configuration":

// Instruct CKEditor to disable the filter. You can also limit this to specific tags.
config.allowedContent = true;
// Allow p, div, li and ul tags to have any attributes attached to them.
config.extraAllowedContent = 'p(*)[*]{*};div(*)[*]{*};li(*)[*]{*};ul(*)[*]{*}';

See docs for CKEDITOR.config.allowedContent and CKEDITOR.config.extraAllowedContent. If you are insterested in having this in every Drupal installation, check out my Drupal 7 installation profile.
The file in question is here.

Hope this helps.


Add more info to entityreference autocomplete widgets I'm using a simple entityreference field with "autocomplete" widget on a content type.

When I start to search something, the autocomplete function returns me only the title of the node. Is there a way to add some information? I would like to add created time, or nid.

I tried to create an "entityreference" view as widget, but It useful only to select contents with filter or others configurations.

How can I do?

Maybe take a look at the Entity Browser module: https://www.drupal.org/project/entity_browser

Or Content Browser, which is specifically designed for nodes:
https://www.drupal.org/project/content_browser

I haven't used it yet, but it's on my want-to-learn list. I think it does what you want.


removing stylesheet from base theme In our Drupal 8 theme we are using the classy base theme. themes/mytheme/mytheme.info.yml:

base theme: classy

Using the information from drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme I am trying to remove some stylesheets from the base theme - but I cannot figure out the right way to do so. For instance, I want to remove the css/components/form.css stylesheet from the base theme. So far I tried:

libraries-override:
  base:
    css:
      component:
        css/components/form.css: false

libraries-override:
  core/base:
    css:
      component:
        css/components/form.css: false

libraries-override:
  core/classy:
    css:
      component:
        css/components/form.css: false

None of which is working. Removing the stylesheet with stylesheets-remove would work fine - but this is deprecated and I would rather use the new intended way for Drupal 8+.

What is the correct way of removing/addressing/extending a library from the base theme?

It's classy/base:

libraries-override:
  classy/base:
    css:
      component:
        css/components/form.css: false

Which is defined in the classy.info.yml.


How to create custom 403 page for a particular content type? For a particular content type in my Drupal 6 web site, I do not want the users to see the "access denied" message when viewing an unpublished node. Instead I want to show a more meaningful message.
I have tried various modules like http://drupal.org/project/customerror, but I can't find a way to restrict the message for only a single content type.
There is a similar question here http://drupal.org/node/888312.

Do you have any suggestion on how this could be achieved?

Try looking at the Custom 403 module, or the Teaser 403 module .

  Custom 403

  This module provides helpful messages to users when they encounter a 403 (Access Denied) page. Depending on different role(s) permissions set on the specific node or content type, the administrator can specify messages accordingly. The user who encounters the 403 will obtain more specific information on how to obtain the role(s) required to access the node.

  Teaser 403

  This module is designed to expose teaser content for sites which normally require users to login to view nodes.


Drupal 6 site not sending password reset emails The password reset emails for a Drupal 6 site I'm working on aren't getting to our users' inboxes. The emails aren't being blocked by spam filters, and according to the site logs at admin/reports/dblog the emails are being sent. How can I go about debugging this?

Are other kinds of mails correctly sent, or are ALL mails from the senong site discarded ?

If other mails are sent from the same server/site, then something's wrong with the Drupal installation.

If they're not and the sending server's logs are indicating a correct sending, then I'd check the destination server logs to see what's happening here. Sometimes mails got discarded for voodoo reasons, like blacklisting (which is not the same as spam detection) etc.


RewriteRule doesn't work Due to request, every page (except the front page) needs to be prefixed with "training"; if the path was first /aboutus, now it needs to be /training/aboutus.

I edited almost every page I needed by rewriting mypage.tpl.php, so to change all path would be troublesome.

I tried to edit the .htaccess file, for example using the following rewrites.

RewriteRule ^/training/about$ /about

RewriteRule ^(.*)/training/about$ $1/about

Neither of them works.

Could someone point me to the right direction?

Using rewrite in .htaccess may change how external URLs are handled by Apache, but it won't change how Drupal generates URLs itself. For that you need to change the base URL. Take a look at https://stackoverflow.com/questions/5879190/how-to-set-the-base-url-in-drupal


Is there any Russification of the Simple MCQ Drupal 7 module? Is there any Russification of the Simple MCQ Drupal 7 module? How to translate it?

It looks like it is partially translated: Translate Simple MCQ to Russian.

To import the translation that exists into your own site, enable the core Locale module and add Localization update.  You can now use the standard Drupal translation site interface to translate the bits that are not translated.

Please help the community by adding your own translations to Localize.Drupal.org


Is it possible to alphabetize a sorted view? Drupal 7.18 w/ Views 7.x-3.8 user here.

I have a view set up that consists of rows of objects, which have names and 'yes/no' properties. By default, it is sorted alphabetically by object name. I want to allow the user to be able to sort through the view using the various properties, but to then have those sorted results be alphabetized for them post-hoc. Currently, when the user sorts through the view using property X (with either 'yes' or 'no' content), the objects seem to be retrieved based on their location in the database table, or some other factor. Either way, they are in no way alphabetical which means that this view of 500+ results is impractical to sort in this fashion.

So, is it possible to set up a sort mechanism where the results are (1) sorted by property into their respective 'yes'/'no' groups (or any other groups with identical content for that matter) and then (2) alphabetized?

To demonstrate what I mean, I currently have something like this:

NAME    PROPERTYX
Alpha   yes
Beta    no
Delta   yes
Epsilon no
Gamma   yes

Which when sorted using PROPERTYX (let's say descending), might return something like:

NAME    PROPERTYX
Delta   yes
Alpha   yes
Gamma   yes
Epsilon no
Beta    no

(As I said, I suppose this random order is based on the object's actual location in the database table.)

When the desired output would be:

NAME    PROPERTYX
Alpha   yes
Delta   yes
Gamma   yes
Beta    no
Epsilon no

Can this be accomplished somehow?

It is definitely be possible to add a second sort to the query which will give the desired effect, but you will have to write some custom code.

There are several hooks that Views provides that you can use in a custom module.  I suggest looking at hook_views_query_alter().  The example code on the API page actually shows it altering a WHERE clause, but creative use of dsm()'s will help you figure out what you need to change.

I'm sorry that I can't give you code (because this kind of modification is highly specific to your installation), but this is definitely the way to go.


Find target bundle(s) for a specific entityreference field I am creating a simple administration page that shows all content types and some details about each content type field.

I am getting the list of content types with node_type_get_types()
I am getting the list of fields with field_info_instances()

When the widget module is entityreference I'd like to display the target bundle(s) of that entity reference field.

foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
    }
  }
}

Thanks in advance for any help on that!

Drupal 8 version:

$bundles = \Drupal::entityManager()
->getAllBundleInfo()['node'];
 foreach ($bundles as $id => $value) {
 $node_fields = \Drupal::entityManager()
  ->getFieldDefinitions('node', $id);
   foreach ($node_fields as $field) {
      if ($field instanceof \Drupal\field\Entity\FieldConfig) {
        if ($field->getType() == 'entity_reference') {
          $target_bundle = $field->getSettings()['handler_settings']['target_bundles'];
          kint($target_bundle);
        }
      }
    }
  }

With $target_bundle, You can do something like this as well to filter out a specific bundle:

if ($target_bundle != null && key($target_bundle) == 'mybundle'){
  kint($field->id());
}


File/image upload via CCK and Nginx + FastCGI I am using the ImageField module with Pressflow, Nginx, and FastCGI. When I go to add a file via the standard ImageField CCK upload widget on a node, the Upload "throbber" does its thing, Drupal does not report any problem. The upload completes fine, but no thumbnail is generated in imagefield_thumbnails, and no ImageCache presets are generated.

I can see the file in the right place on the server. It feels for all the world like a file permissions problem, but I'm getting no such warnings from Drupal or PHP and the file is chmod 664 and belongs to www-data (which is the user Nginx is running as). So I can see no reason why PHP would not be able to read the image.

Furthermore, all the ImageField and ImageCache target directories are chmod 777 and owned by www-data, so again, no reason why the application would not be able to write there. And anyway, no errors suggest that is the problem, in either /var/log/messages or in /var/log/nginx/error.log. It makes no sense!

Can anyone shed some light? Is there any simple step I need to follow (or a missing package I need) to make Drupal work, or am I doing something stupid?

Ok, turns out unbeknownst to me someone had added rules in the .htaccess file pointing image loading to another server, which, of course, did not have the created presets and thumbnails. Gah!

Another gotcha in this was the $base_url variable was set in settings.php to force Drupal to load a from a specific site, regardless of the one requested.

Hopefully this will help someone in the future.


How to get an instance of a plugin I am attempting to use a pre-configured instance of a plugin.  The plugin is of type @CommercePaymentGateway.

I am currently trying to use something like:

/** @var PaymentGatewayManager $manager */
$manager = \Drupal::service('plugin.manager.commerce_payment_gateway');
$manager->getInstance(['module' => 'commerce_paypal']);

But I'm getting the error Error: Call to a member function getInstance() on null.  However, using kint(), $manager is clearly an instance of Drupal\commerce_payment\PaymentGatewayManager.

I see what I think is the instance configuration in the config table under commerce_payment.commerce_payment_gateway.paypal_ec.  But that paypal_ec part is specific to my site.

How do I get an instance of a plugin?

It turns out, in my case, I'm asking the wrong question.  All that I need is the parent config entity (@bojanz pointed this out in slack), so I was over-complicating the issue:

$gateway = \Drupal::entityTypeManager()
  ->getStorage('commerce_payment_gateway')->loadByProperties([
    'plugin' => 'paypal_express_checkout',
]);

This will return an array of gateways, get a specific one:

// Get the first one
$plugin = reset($gateway);
$plugin = $plugin->getPlugin();

Now you have the $plugin to be used elsewhere.


Limit access to subsite I googled for it but couldn't find anything about that.
Is it possible to create drupal website (example.com) with subsites (example.com/subsite1 and example.com/subsite2) where access to them are limited to:

2 users on example.com/subsite1
users on example.com/subsite2
no limits on example.com/"

I want to share some digital content on those subsites to not more than X users at time.

There's no built-in way to do this, afaik. Are the sites truly separate sites? Drupal multi-site?

You could build a custom module that uses one of the hook_preprocess_XXX functions.  In that function you could do a mysql query with the "sessions" table.  If there are 2 active sessions, block/redirect the user.  Session management would be tricky though.  You'd want to change the session timeout length for that site, and also encourage your users to logout when they're done browsing to make room for the next guy.

edit: process for the content type,  or you could look in to hook_menu functions which might be cleaner, though I am not sure it will work.


Change a multiple value field to use divs instead of a table in node/add? I have the # of values set to 10, which I want to put in 2 columns of 5 each, but I don't know how to change the table structure to accomplish this, or perhaps preferably, just change it to use divs so I do it with css.

You can override theme_field_multiple_value_form(), e.g.

function MYTHEME_field_multiple_value_form($vars) {
  // Copy code from theme_field_multiple_value_form() and change as appropriate
}

It's not a short function, and you'll probably be reproducing a bunch of code, but it uses theme_table() directly so it can't be solved with a preprocess function.


Set allowed value of a list field depending on the URL In the list field php code I want to set the value of a field:

first do a call to parse the URL.
take the [3] element (nid of the organic group) and use it to do a call to the db to get the node type for that nid.
set the value of the field depending on the node type.

I had all this working in D6, now have to redo for D7.  Not having any luck getting it working yet.

function custom_pathnoder() {
    $pathnoder = array();
    $pathnoder = check_plain(drupal_get_path_alias($_GET['q']));
    $pathnoder = explode('/', $pathnoder);
  return $pathnoder;
}

$node = menu_get_object();
$pathnoder = custom_pathnoder();

$group_id = $pathnoder[3];

$query = db_select('node');
 $query->condition('nid', '$group_id', '=')
              ->fields('type');
$og_type = $query->execute();

if ($og_type) {
if ($og_type == 'square_group')  {
$def_value = array( 0 => array('value' => square) );
}

elseif ($og_type == 'west_group')  {
$def_value = array( 0 => array('value' => west) );
}
elseif ($og_type == 'east_group')  {
$def_value = array( 0 => array('value' => east) );
}
elseif ($og_type == 'circle_group')  {
$def_value = array( 0 => array('value' => circle) );
}
elseif ($og_type == 'north_group')  {
$def_value = array( 0 => array('value' => north) );
}
elseif ($og_type == 'south_group')  {
$def_value = array( 0 => array('value' => south) );
}
}

if (isset($def_value)) {
  return $def_value;
}
else {
  return array(0 => array('value' => null));
}
}

@Shawn Conn

I changed the code to reflect the suggestions above but it's still not setting the value.  Can you see the reason?

def_value = array();
$pathnoder = array();

$pathnoder = check_plain(drupal_get_path_alias($_GET['q']));
$pathnoder = explode('/', $pathnoder);

$og_type = db_select('node','n')
    ->fields('n', array('type'))
    ->condition('nid', arg(3), '=')
    ->execute()->fetchField();

switch ($og_type) {
    case square_group:
         $def_value = array( 0 => array('value' => square) );
         break;
    case west_group:
         $def_value = array( 0 => array('value' => west) );
         break;
    case east_group:
       $def_value = array( 0 => array('value' => east) );
       break;
    case circle_group:
       $def_value = array( 0 => array('value' => circle) );
       break;
    case north_group:
       $def_value = array( 0 => array('value' => north) );
       break;
    case south_group:
       $def_value = array( 0 => array('value' => south) );
       break;
}
if (isset($def_value)) {
  return $def_value;
}
else {
  return array(0 => array('value' => null));
}

You're making this a little more convoluted than it needs be; the core arg() function can parse out the path and get the 4th element; the query is also broke (condition() is passed a string literal instead of variable & it's missing aliasing argument); lastly you could help readability with a switch control.

  //fields() needs an alias argument $group_id can be pulled from arg()
  $og_type = db_select('node','n')
    ->fields('n', array('type'))
    ->condition('nid', arg(3), '=')
    ->execute()->fetchField();


Views: Table rows containing multiple nodes by taxonomy tag How do I build a staff directory table that displays everyone assigned to a particular assignment? I'm using taxonomy for staff titles and staff assignments.

So in a simple example:

Staff1
- Title1
- Assignment1,Assignment2

Staff2
- Title2
- Assignment1

Staff3
- Title3
- Assignment1,Assignment2

Staff4
- Title2
- Assignment2

Table should be:

| Assignment  | Title1 | Title2 | Title3 |
------------------------------------------
| Assignment1 | Staff1 | Staff2 | Staff3 |
| Assignment2 | Staff1 | Staff4 | Staff3 |

I ended up using Views Field View, which allows you to implement a separate view's output per row based on a particular field. Definitely resource intensive. Definitely less than ideal, but it works.


entityCondition check if a field is not empty My user table has an init field in it, it maybe empty or not.
I want to find all rows that are not empty
I tried

  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');

function mymodule_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', ['administrator', 'contributor', 'publisher'], 'IN');
  $query-> isNotNull(ur.init); // I ALSO TRIED a != '' condition
}

What I am doing now that works is:

  $results = $query->execute();

  $users_node_list = entity_load('user', array_keys($results['user']));

  $return_results = array();

  foreach ($users_node_list as $key => $value) {
        if ($value->init != ''){

but that is post query.

and read https://www.drupal.org/node/1157006

but this is not working (I don't get any results when I add this)

Ideas?

You can do this by

$query->condition('field', '', '<>');

See: https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3Acondition/7.x

If this doesn't answer your question you need to. Be more specific.


Place custom block on particular content type pages and home page I have a custom block which I want to place on all the pages of one content type AND on the home page. The home page is a custom twig file that pulls in the region where the block is placed. Right now I have the custom block limited to the content type I want but of course that precludes being able to put it on the home page. Is there an elegant way to get it in both places? I'm also using Twig Tweak if that will help.
(Worst case I'll duplicate the block content and put it right into the twig file but I'm trying to avoid that.)
Thanks!

You can create two instances of the block on the manage blocks page. One instance can be limited to the content types on which you want it shown, and the other instance can be limited by path, which you will then set to <front>.


Why am I getting a PDO Exception error when I try to run Drupal Console inside the root directory? I've installed Drupal Console and can confirm it is in the proper directory, etc.

I run the command "Drupal" from my home directory and I see a Drupal Console help list of commands, but when I run it inside my site root directory, I get a PDO Exception error. I can't figure this one out. Should I move Drupal Console into my Drupal site directory? Thanks for the help.

Try to update below in your php.ini. You need to define php for correct location for .sock file.

mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock

OR

If you will not getting result then try to replace below in your settings.php file.

Replace 'host' => 'localhost',

With 'host' => '127.0.0.1',


How to convert the Title field on Image type to multi-line text box I have a Basic Page content type with a Gallery field that lets the user upload images to that page.

when I active the Title field for the user to input a title, it shows as a single text box.

But is there a way to convert this to a multi-line text box?

Using the Media module, you can add fields to images, such as description or caption.

OR
Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.


How do I add a custom field token to a default value? I want to add node-field data into the web from block via tokes as with Webform 7.x-4.1 this should work.

But tokens from custom fields are not available in a webform(block) ?

[node:title] and [node:author] work but [node:field_mycustumfield] or [node:field-mycustumfield] does not work .

Any help appreciated!

I know this was asked years ago, but if someone comes across this, here's the solution:

https://www.drupal.org/node/919760#comment-9973163

Node tokens in a Webform block refer to the Webform node, not the current node which the block is placed on. Currently, the Token module does not expose node tokens to the Webform block.

There is a patch in this thread which exposes tokens to the Webform block, and should do just what you need. Hopefully it will get committed to the Token module soon. :-)

As an alternative, you could also use https://www.drupal.org/project/token_custom and create a custom token that exposes the field you need.


Changing TABS into CONTEXTUAL LINKS I'm making a module that changes the output from the tabs (View, Edit, ...) into contextual links. The name of my module is "testmodule" and the name of the theme I'm using is "Bartik".

When I place this into my test module, it works, but only when I use the Bartik theme:

function bartik_menu_local_tasks($variables) {...}

This doesn't work

function testmodule_menu_local_tasks($variables) {...}

Any idea's?

I was also wondering if I could easily change the html made by template.php, for achieving the change of tabs to contextual links I have to change this line in template.php:

change into :

I want to do this within my module...

I found a sollution to overwrite the "theme_menu_local_tasks" function.

function MODULENAME_theme_registry_alter(&$theme_registry) {
    if (!empty($theme_registry['form_element'])) {
        // Menu local tasks
        $theme_registry['menu_local_tasks']['function'] = 'MODULENAME_menu_local_tasks';
    }
}


AWS SDK installation problem I used Drush to install Amazon S3 module. AWS SDK was installed as part of the process. No error was thrown

[root@ip-10-128-146-179 zencoder]# drush dl amazons3
Project amazons3 (7.x-1.0-beta7) downloaded to                         [success]
/var/www/html/drupal/sites/all/modules/amazons3.
[root@ip-10-128-146-179 zencoder]# drush en amazons3
The following projects have unmet dependencies:
amazons3 requires awssdk
Would you like to download them? (y/n): y
Project awssdk (7.x-5.4) downloaded to                                 [success]
/var/www/html/drupal/sites/all/modules/awssdk.
Project awssdk contains 2 modules: awssdk_ui, awssdk.
The following extensions will be enabled: amazons3, awssdk
Do you really want to continue? (y/n): y
amazons3 was enabled successfully.                                     [ok]
awssdk was enabled successfully.                                       [ok]

Now I see an error in my Drupal admin dashboard:

Failed to load the AWSSDK
Please make sure the AWSSDK library is installed in the libraries directory. Use the drush make file for easy installation.

What shoud I do?

This is my drush status:

Drupal version                  :  7.22
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  drupal
 Database name                   :  drupal
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  bartik
 Administration theme            :  seven
 PHP configuration               :  /etc/php.ini
 Drush version                   :  5.9
 Drush configuration             :
 Drupal root                     :  /var/www/html/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp

Using the AWS PHP SDK version 1.6.2 instead of the latest solved the problem. sites/all/libraries/awssdk/sdk.class.php does not apply for at least version 2.1.1.


Prevent page creation for a published custom content type I have a Drupal 8 custom content type that is used in views only.  I would like to prevent this type from creating a web page for content that is published.

One easy method would be to add Rabbit Hole module and set it to "Page Not Found" when that content types view route is accessed.


Custom page with form i am new to drupal i want to make custom page with form , i googled and was able to built custom form using guide at Link

but i need form as part of my page content not just form so basically i need custom page with form ,please guide me with this .

Have i to recode it or can use buildForm at certain place in my html, please help me with suitable link or guide

You need to create a route, and a controller that builds the response on that route - in your case a form.


Problem with home page misaligned on website The site in question is http://johannabolhoven.co.uk/.

As you can no doubt see, the home page seems to be misaligned from the other pages.
I've got the disable breadcrumbs module installed and I'm wondering if the problem is that the space is still being left for the disabled breadcrumbs, but it could also be something else.

I've tried (to the best of my ability) to disable the breadcrumb div in the template files, but that didn't seem to help either.

Found it.  You have a custom content pane when you have an image that is inside of a p tag.  That p tag has a margin of 12px on the top and bottom and the image has 10px border on all sides.  Remove that and you should be good to go.

I got this from http://johannabolhoven.co.uk/personal_shopping.

Let me know if there were other issues that you had, but the home page being higher than the other pages was the only thing I could find.


How to add Jquery plugin to Drupal? Should I just paste the code in the main template file, or is there any other recommended way of attaching new Jquery plugins in Drupal 7?

The easiest way is just to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

The only exception is if you are adding an external resource (CDN/hosted script), in which case you should use drupal_add_js(), as explained by Jamie Hollern


Adding classes to block title I have a block which template I'm overriding with my own.

The title in it is displayed by the following code:

    <h2<?php print $title_attributes;?>><?php print $title; ?>

I just want to add some custom classes to the h2, but I can't figure out how to format it. I want to keep $title_attributes but I can't seem to be able to add my own classes if I do.

I tried:

    <h2 class="a-class" <?php print $title_attributes;?>><?php print $title; ?>

and:

    <h2<?php print $title_attributes .'a-class';?>><?php print $title; ?>

But neither did anything. My PHP is scrappy at best so it's probably just me who don't know how to write what I want. Can anyone help me?

The way to do this is by overriding variables in the template. Put the following code in your themes 'template.php' file, replacing YOURTHEME, YOURBLOCK, YOURCLASS with the obvious.

/**
 * Override or insert variables into the block template
 */
function YOURTHEME_preprocess_block(&$vars) {

  // var_dump($vars);

  $block = $vars['block'];

  if ($block->delta == 'YOURBLOCK') {
    $vars['title_attributes_array']['class'][] = 'YOURCLASS';
  }

}

You can determine what the $block->delta is for example by doing a var_dump($vars) in the function. If you have the DEVEL module installed you can use dsm($vars) which gives the dump some presentation.


Updated site now URL is not working I updated my site and now the site only shows up in Firefox.  I believe it has something to do with the redirect since if I type in mysite.com/mysite then it shows up.  I've tried updating the .htaccess file and the default/settings.php files and can't get it to work correctly.  Any ideas?  Thanks!

Check that the following rule is not commented out in your .htaccess file:

RewriteBase /

If you have installed Drupal in a folder inside your root it should be:

RewriteBase /my_folder


Adding the category for a custom entity reference field add other fields to the same category I have a custom entity reference field working well, but once I added the category to it the other entity reference fields appeared in the same category.

Here is my code:
/**
 * Plugin implementation of the 'region_token' field type.
 *
 * @FieldType(
 *   id = "region_token",
 *   label = @Translation("Region Token"),
 *   description = @Translation("Region custom token."),
 *   category = @Translation("Tokens"),
 *   default_widget = "region_select_widget",
 *   default_formatter = "region_formatter",
 * )
 */
class RegionToken extends EntityReferenceItem {

Any idea about how to fix this?

I fixed the problem by adding the following code to the class
  /**
   * {@inheritdoc}
   */
  public static function getPreconfiguredOptions() {
    return [];
  }


Form isn't sending POST parameters? I want to have a single email field form on my page to suscribe to a newsletter and when the user submit this form, to redirect to a complete form (with name, surname...)

The complete form is designed with Webforms module and this single field form with the Form API in a custom module.

I'm using Drupal 6.25.

The problem is when I submit this form; I feel it don't send any POST parameters. I get them in Webform by setting a default value for the E-mail field at %post[newsletter_mail] and it doesn't work.

This is my code.

function block_contact_newsletter_form() {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Suscribe to Newsletter !')
  );

  $form['newsletter_mail'] = array(
    '#type' => 'textfield',
    '#default_value' => t('Your E-mail')
  );

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

  return $form;
}

function theme_block_contact_newsletter_form($form) {
  $output = '';
  $output .= drupal_render($form['description']);
  $output .= drupal_render($form['newsletter_mail']);
  $output .= drupal_render($form['submit']);
  $output .= drupal_render($form);

  return $output;
}

function block_contact_newsletter_form_theme() {
  $themes = array();

  $themes['newsletter_form'] = array(
    'arguments' => array(),
  );

  return $themes;
}

function block_contact_newsletter_form_submit($form, &$form_state) {
  $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), $language->language);
  if (strstr($path_newsletter, 'node/') !== FALSE) {
    $link_newsletter = drupal_get_path_alias('node/'.variable_get('webform_newsletter_default_nid', ''), 'fr');
  }

  $form_state['redirect'] = $link_newsletter;
}

function block_contact_default() {
  $content = array();
  $content[] = '
My.Sitwe
';

  $items[] = array('class' => 'mail', 'data' => l(t("By mail"), 'node/'.variable_get('webform_contact_default_nid', FALSE)));
  $chat = variable_get('default_chat', "");
  if (!empty($chat)) {
    $items[] = array('class' => 'chat', 'data' => l(t("By chat"), variable_get('default_chat', "")));
  }

  $facebook = variable_get('default_facebook', "");
  if (!empty($facebook)) {
    $items[] = array('class' => 'facebook', 'data' => l("Facebook", $facebook));
  }

  $twitter = variable_get('default_twitter', "");
  if (!empty($twitter)) {
    $items[] = array('class' => 'twitter', 'data' => l("Twitter", 'http://twitter.com/'. $twitter));
  }

// The interesting part for this function begins here.
  $items[] = array('class' => 'newsletter_form', 'data' => drupal_get_form('block_contact_newsletter_form'));

  $content[] = theme('item_list', $items);

  return array(
    'subject' => t("Contacts"),
    'content' => implode('', $content),
    'classes' => array('block-ot-contact')
  );
}

Do you have any advice?

You're telling the form to submit via POST, and then once it's done submitting, to redirect to the webform. I think what you intended to do was to make the form submit its data straight to the webform, which you could do with the #action key in the $form array. See http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#action

However, this isn't really a very robust approach. A better approach would be to put together your own webform, and then put that webform into a block. If you need to do any custom processing on the webform, the webform module has its own API and hooks that you can use.


Help getting the values from user profile fields from currently logged in user As the title says, I am trying to get the values from a custom field I added to the user profile. I am using this code from a previously asked question regarding this.

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

This seemed to work for the person that previously asked this question but the problem I am running into is that it is only returning values of an anonymous user regardless of who I am logged in as. For example if I replace custom_field with uid it will return a value of '0'. Any idea where I could be going wrong?

You're missing a $ in your second line.. Should be $user->

I always use the below.

global $user;
$user = user_load($user->uid)

And then get the field like your last line. If someone else could confirm if that is a waste and there's a better way to load the field, that'd be great.


How do I select a page using views_embed_view? I am writing a rather intensive ajax interface that requires me to manhandle views quite a bit. I am retrieving the results of the ajax triggers using

views_embed_view($view, $display, $arg1, $arg2);

Everything works great except the default pager ajax drops the custom info I'm dumping into views_embed_view

How can I use views_embed_view to select which pager page to return?

drupal 7, views 3

I found the answer after a good deal of research and testing.

views_embed_view() does not have a way to do this. However, we can use the same method that views_embed_view() used.

1  $view_args = array($terms); //, $search_text
2  $view_object = views_get_view($view_name);
3  $view_object->set_current_page($offset);
4  $html = $view_object->preview($view_display, $view_args);

Line 1,2, and 3 are a simplified version of views_embed_view(). I'm bypassing permissions here so check out the function code to see how to do that part.

Line 3 is the part that sets the pager offset and solves my problem.

Note: their are two functions for setting the page offset and I used the wrong one the first time and it caused a log of confusion. The first function view->set_offset does not seem to work. I think it sets the correct value in the view object but without doing the theme and query work. so view->set_current_page is the one you want to use. I think it goes through the pager plugin to set the query and theme implications as well as set the offset.


500 Internal Error Drupal 7.26 - Can't access forums last night my site (Drupal 7.26 core) was working fine and then all of a sudden after creating a new forum topic with some excel graphs included (copy paste from excel) the forums completely shut down. All other pages and content are available except the forums. I can't remember the exact error that was coming up at the time but I was getting an error due to the PHP memory limit not being enough. I contacted the hosting company and got them to change it from 32mb to 128mb and also created a php.ini file with the following code:

php_value memory_limit = "128M"

and placed that in the root folder. The PHP memory limit error stopped coming up but the forums are still inaccessible and I'm now getting the following error when trying to access the forums:

  The server encountered an internal error or misconfiguration and was
  unable to complete your request. Please contact the server
  administrator, webmaster@mysite.co.za and inform them of the time the
  error occurred, and anything you might have done that may have caused
  the error. More information about this error may be available in the
  server error log. Additionally, a 500 Internal Server Error error was
  encountered while trying to use an ErrorDocument to handle the
  request.

Could someone please help me with this? It is a community site which is pretty useless without the forums.

The "500 internal server" error message just means: "Your web server just crashed". There are many different things that can have gone wrong.

To determine the cause, you need examine your web server logs (your hosting provider can tell you where these are if you don't know where to find them).

Below is a list of some of the most frequent causes of a "500" error on a Drupal web site (I am trying to make this generic - for future reference - I know you've covered the PHP memory limit already):

The setting for PHP memory_limit is too low.  Note that if you're on shared hosting, you can't change this yourself.  You need to get it increased by your hosting provider.
Your hosting provider has set restrictions on what php_values or php_flags you can put in .htaccess that is violated by one of the .htaccess-files created by Drupal or by directives added to these by you.
Your have syntax errors in one of the .htaccess-files in your configuration. (In particular if you've edited the default .htaccess.)
There exists permissions on files or folders that is outlawed by a security measure your hosting provider uses.

As the message says: "The server encountered an internal error or misconfiguration". To gather information about what type of error this was, you need to examine the server (error) logs. There is no way we can help you with this without seeing the relevant error messages from your logs. We don't have access to your server or your logs.

You may also increase the level of error reporting from PHP to get better diagnostics. You'll get full runtime error reporting by adding this to the start of settings.php on your site (just below <?php):

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

In addition, navigate to: Administration → Configuration → Development → Logging and errors and select the radio button "All messages". This sets $conf['error_level'] = 2;.

When you examine the logs and diagnostics from PHP error reporting, you may find out more about what made your server crash.  If you do not fully understand what those messages means, you can update the question with the specific error messages, and hope that someone here shall be able to shed more light on the cause of the problem.

If everything else fails, make a backup of your database (you may use the Backup and Migrate module or some DB tool that works independent of Drupal (e.g. phpMyAdmin).  Then disable and uninstall the module that you thinks is the cause of your problems (sound like it is the Advanced Forum in your case.  Make sure you not only disable, but also uninstall (these are two separate steps).

Verify that your site is now stable.

If it is stable, re-install the module (e.g. Advanced Forum) that caused the problem from scratch.

Re-assess the status of your site. Is it still stable?  Is any content missing?

If it is not stable, then the problem is not solved, and you need to reconsider the use of module that causes grief (i.e. ditch it and find a better module).

However, if content is missing, you should be able to restore that back from the back-up yiu made (perhaps after looking through your backup files for anything problematic, and deleting it from the backup before restoring).


View is not working the intended way I created a view and set it as in the following screenshots.

  [

If (under the Format section) I select Show:Content or any other setting, I can see the view being displayed on page and on the preview like I want it to show; if I select Show:Fields, the view doesn't show on page, but it does show on the preview.

To clarify the it shows on page part:

The theme is the right one
The region is defined on that particular theme, and I can display content on that region besides the one I really want to show, which also dismisses block settings preventing it from showing

Why is this happening? What can I do to make the view show on page when selecting the Show:Fields option?

Since I am a Drupal beginner, I don't know if the issue is merely caused from a wrong value I set for one or more settings.

Sometimes a clear cache solves the issue.  Don't know if yours is the same issue but it happened to me and i cleared cache and it resolved the issue.


Service Userpoints : Missing required argument points My environment : Drupal 7 & service 3.x

I use userpoints and service-userpoints. I want to CRUD userpoints.

So i create a xmlrpc server and test it by Postman from Chrome store.

The xml code is belowed:

<?xml version='1.0' ?>
<methodCall>
  <methodName>pointss.add</methodName>
  <params>
    <param>
      <value>
        <struct>
          <member>
            <name>uid</name>
            <value>
              <int>1</int>
            </value>
          </member>
          <member>
            <name>points</name>
            <value>
              <int>150</int>
            </value>
          </member>
          <member>
            <name>description</name>
            <value>
              <string>test for xmlrpc service</string>
            </value>
          </member>
        </struct>
      </value>
    </param>
  </params>
</methodCall>

"pointss" is my userpoints-api's alias

i connect successful but got the message belowed.

<?xml version="1.0"?>

                    faultCode

                        401

                    faultString

                        Missing required argument points

How can i fix my xml body?
Does anybody have experience?
Thanks a lot.

I finally get it.

The XMLRPC format is belowed:

<?xml version="1.0"?>
<methodCall>
   <methodName>pointss.addpoints</methodName>
   <params>
     <param>
           <name>uid</name>
           <value><int>1</int></value>
           <name>points</name>
           <value><int>150</int></value>
           <name>tid</name>
           <value><int>18</int></value>
           <name>operation</name>
           <value><string>test for operation</string></value>
           <name>description</name>
           <value><string>test for description</string></value>
           <name>entity_type</name>
           <value><string>node</string></value>
           <name>entity_id</name>
           <value><int>1</int></value>
     </param>
   </params>
</methodCall>

If somebody use service3.x and userpoints service, i hope i can help you.


Which tables should be emptied when clearing database-stored cache manually? Prior to D8 to clear cache manually one could truncate all tables beginning with cache_.

In Drupal 8 there are still tables starting with cache_, but there's also a cachetags table.

Is the advice in D8 still to truncate cache_* if you need to clear cache manually? Is it safe/required/recommended to truncate the cachetags table along with the cache_* tables?

I'm aware there may be contrib modules doing things differently, I'm mostly interested in what core does, and what's considered "best practice" for Drupal 8 in general.

In drupal 8 if you are looking for the safe tables that needs to be cleared manually then clear the tables starting with cache_   and also truncate the cachetags table too.

If you are using drush then use this command for clear cache-

drush cache-rebuild


Regions missing on page templates defined in a controller I have two custom blocks that I created in files placed in the modules/custom/mymodule/src/Plugin/Block folder.

I defined two extra regions in the mytheme.info.yml file
I placed the blocks in the regions using the 'Block layout' page in the admin area.

It's all working great on all pages that use the "normal" twig template naming conventions, such as page.html.twig, page--front.html.twig and other templates I created based on the suggestions in the comments twig debug outputs.

My problems started when I created templates via a Controller. Here is an example from my routing.yml file:

mytheme.bikes:
  path: '/catalog/Bikes'
  defaults:
    _controller: '\Drupal\mytheme\Controller\MyPageController::catalog_bikes'
    _title: 'Bikes'
  requirements:
    _permission: 'access content'

And the controller:

public function catalog_bikes() {
  return array(
    '#type' => 'page',
    '#theme' => 'page__bikes',
  );
}

If i go on mysite.com/catalog/Bikes the page--bikes.html.twig template is loaded, BUT, without the extra regions I added to mytheme.info.yml file

Are you rendering the regions in your twig template?

Like

{{ page.custom_region }}


Custom Access Permissions I need to build a facebook model privacy settings for user. Access permissions must be set to users who are "Public" and "Connected", which the latter is from User Relationship module.

eg: User must have permission settings such as who must view his profile, his nodes, user connections, also some views which are related to user.

Can anyone suggest an idea how can i implement this.

Just use the Group module, and create a content type like "Connected Users". And then create a "group" for each user (using something like the user's name as its label), of group type "Connected Users".

Tune the permissions which come with the Group module (which are different from standard Drupal permissions!) to fit your needs.

Possibly you also want to use all sorts of integrations with modules such as the Rules module or the Views module (the Group module is entirely entity based, so those kind of integrations or virtually unlimited).

Voilà ...

PS: This answer applies for either Drupal 7, or Drupal 8.


CKEditor is adding inline style to resize my textarea on node add/edit form No matter how many rows I define the textarea to be in the content type configuration, I get a huge editor taking up almost the whole browser window in the node add/edit page. I tracked this down to CKEditor, which is hiding the actual textarea and adding an inline height to the table cell it uses to display the iframe containing the actual field. (Argh.)

Please share any advice on how to make it stop or override it? Since it's inline, I'm not hopeful about using normal CSS.

It turns out this is a documented problem in CKEditor. There are some workarounds posted at https://www.drupal.org/node/1154730 but I'd also be intersted in hearing any other ideas.


Contextual filter in path for block view display, alongside pathauto aliases in Drupal 8 On our Drupal 8 site, we are using the article content type for press releases. We have the pathauto module generating automatic aliases for these nodes, so the article node entitled "Cool Things are Happening" would get the url /press-releases/cool-things-are-happening.

Additionally, we have a view of press releases, at /press-releases. This is provided by a view of articles that has a page display.

Our marketing department wants some changes implemented to the page delivered from /press-releases. Since we have the paragraphs module installed on our side, I decided the best way to future-proof the page would be to disable the press releases page display, create a block display of that view, and add a basic page with the press releases block display in a paragraph, and set the alias of that node to /press-releases.

However, one of the requested changes is a year filter feature on the press releases page, so that the results of the view can be filtered by year.

I have that filter working on the view, as I've confirmed in the block display preview. I've added a custom block to the new /press-releases page that has links to /press-releases/2019, press-releases/2018, etc. The idea, obviously, is that the second part of the path would be the value for the contextual filter on the block display of the view.

However, I'm not sure if it's possible, and if it is, then how to specify a wildcard route in Drupal 8 that passes the second url parameter to the contextual filter. Currently, when I navigate to /press-releases/2018, I get a 404, which is not unexpected.

Since the view display is not a page, but a block, I don't see where I can indicate a path with a wildcard value, like /press-releases/%. (It's been a while since I've developed for Drupal 7, but I seem to recall that's how values were grabbed from paths.)

Editing the Contextual Filter on the block display of the view, I tried adding "Raw value from URL". I set the settings

When the filter value is NOT available
 - Provide default value
    - Type: Raw value from URL
    - Path component: 2
    - Exception value: all

However, with these settings, /press-releases and /press-releases/all show the page with an empty view block display, and also paths with the year value (like /press-releases/2018) are also empty. However, node paths still work. I'm not sure if I'm using the wrong settings, or if this way is not going to work regardless.

This answer shows how to get a value from the URL using the InboundPathProcessorInterface in a custom module, but I'm not sure how to then pass that value to the view's block display in the paragraph. Also, if I'm using /press-releases/% as my pattern to match, I don't want to interfere and break existing node paths at e.g. /press-releases/cool-things-are-happening. I only want to match YYYY, where Y is a number. (I could do more advanced validation for the year, but I can pretty much guarantee we are never going to have just a year by itself as the actual title of a press release node.)

How can I pass the year value to the contextual filter? Have I gone down the wrong path for developing this feature?

We are on Drupal 8.7.3.

So I was able to get my functionality by changing the Contextual Filter to a query parameter:

So in my widget block, I changed the link values from /press-releases/2015 to /press-releases?year=2015. Now the functionality works as wanted. Both urls /press-releases/ and /press-releases?year=all show all the press releases, and the node urls still work.


how to alter main menu to add custom class How do I add custom class to main menu. The main menu links are like Fashion, Art, Life and nodes being viewed category can be any one. I want to make the main menu item active as per node being viewed category. e.g if example.com/node/44 -> category = fashion then the Fashion in main menu should be selected. I tried MYTHEME_menu_link and MYTHEME_menu_link_alter but they did not work for me.

Thanks for your help.

I can't tell you how this works programatically, but with menu-position module you can achieve exactly what you're looking for. You'll just add a position-rule for your node-types (or taxonomy item used) to highlight a parent item accordingly.


Not authorised to view page admin So I am following the book Drupal 7 Pro Development book and just completed chapter 2. I cannot access my modules admin page. Here is my menu hook. Can you please point me in the right direction.

function annotate_menu(){

 //Makes category
 $items['admin/config/annotate'] = array (
 'title' => 'Node Annotation',
 'description' => 'Adjust node annotation options',
 'position' => 'right',
 'weight' => -5,
 'page callback' => 'system_admin_menu_block_page', //function from system settings.
 'access arguements' => array('administer site configuration'), //who can see this.
 'file' => 'system.admin.inc', //file where callback function is called
 'file path' => drupal_get_path('module', 'system'), //get system module path
 );

 //Makes menu under category
 $items['admin/config/annotate/settings'] = array (
 'title' => 'Annotation Settings',
 'description' => 'Change how annotations behave',
 'page callback' => 'drupal_get_form', //function called
 'page arguements' => array('annotate_admin_settings'), //formID which is function name in annotate.admin.inc
 'access arguements' => array('administer site configuration'), //who can access settings
 'type' => MENU_NORMAL_ITEM,
 'file' => 'annotate.admin.inc', //file where formID is located.
 );

 return $items;
 }

You've just spelt 'arguments' wrong in both of the 'access arguments' and 'page arguments' properties.

At least one of 'access callback' or 'access arguments' needs to be present in the router item or you won't be able to access the page.

Just fix that spelling, clear the cache, and it should work fine


Add execute button to Commerce POS modal? I'm building a custom POS modal similar to the POS_Button_Modal_View -based ones that present a view. I wrote a modal that presents a page from a given callback:

class POS_Button_Modal_Page extends POS_Button_Modal {

  public function modalPage(CommercePOS $pos, $js) {
    $form_state = array(
      'title' => drupal_get_title(),
      'build_info' => array('args' => array($pos->getState()->getOrder())),
      'ajax' => $js,
      'pos' => $pos
    );

    if (!$js) {
      return drupal_build_form($this->config['page callback'], $form_state);
    }

    $output = ctools_modal_form_wrapper($this->config['page callback'], $form_state);

    return $output && !$form_state['executed'] ? $output : FALSE;

  }
...

The modal displays my page as intended, but I don't know how to build a submit button that works like the buttons in the POS-provided views.

The view in, eg. the SetUser POS modal uses the commerce_pos handler to render a button that executes the command:

class commerce_pos_handler_field_pos_command extends views_handler_field { ...

How can I build a submit button in my custom modal that executes my new command?

My command extends POS_Command with my custom implementation of execute()

class POSCommand_MyCommand extends POS_Command {

  function execute(CommercePOS $pos, $input = '') { ...

It seems like a POS_Button_Command should be created and rendered in the modal. But how does that get connected to my command?

Instead of a regular "page" callback, implement the page as a form with an action (submit) button. When the form is submitted and validates, the modal will be released courtesy of the way ctools_modal_form_wrapper() works.

POS_Command was not the right way to think about the problem in this case. POS_Button_Command is better suited to a simple, pre-defined operation as in setting the order user from a list of users. I was trying to do a more complex operation in the modal, gather some data from form inputs, then run some commerce commands on the order.

Short answer: The POS_Button_Modal_Page class works for loading a custom modal page. Implement the page as a form, and do the execution code in the form_submit handler instead of using POS_Command.


How to make work Restfull /user/register?_format=hal_json I am trying to access. All required modules are included, rights granted. so does not work.
/user/register?_format=hal_json

I get a message:

{"message":"Not acceptable format: hal_json"}

In RestUi settings, hal_json format is enabled.

And in the log:

Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException: Not acceptable format: hal_json in Drupal\Core\EventSubscriber\RenderArrayNonHtmlSubscriber->onRespond() (line 30 of .../web/core/lib/Drupal/Core/EventSubscriber/RenderArrayNonHtmlSubscriber.php).

Drupal 9.0 and Drupal 8.8.4

please add at header:
 Content-Type : application/hal+json


How do I add taxonomy to my custom entity? I am working with a custom entity and I would like to be able to add taxonomy to the entity.  The drupal 8 entity documentation is lacking.

I have tried reading Node.php and term.php entitiy files but I don't understand how any sort of taxonomy is linked to any other entity though this.

Do I need to change something in my entity definition to allow taxonomy to be added? Or is there a way to access the taxonomy entity?

Edit:  I am working on the same pattern to add this to the install file of my module

'category' => array(
                'type' => 'varchar',
                'not null' => TRUE,
                'default' => '',
                'description' => 'The section front  to appear on',
            ),

this is the exception that I get trying to install the module

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error [error]
or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the
right syntax to use near 'NOT NULL DEFAULT '' COMMENT 'The section
front  to appear on',

As Clive said, you use an entity reference field for that, just like articles have a tags reference field to terms.

If you want to define it in code, it's really the same as the node.uid field, which is an entity reference to a user. Or the user.roles field, which is a multivalue reference to user roles. Entities reference others using an entity reference field, it's always the same pattern.


Where should I put this JavaScript code ... the Drupal way? I´ve read that you can create a mini module to limit comments length.
I´ts cool, and it´s working, but I need to add to it some JS so it tells you how many characters you have left.

So I´ve found some easy thing to do (via Google):

Put this inside your head tag:

And put this in your body:

Text ¦ Chars left: 500

<textarea name=”[1][3][t]” rows=”10″ cols=”50″ onkeyup=”limit(this,500,’count1′);” onkeydown=”limit(this,500,’count1′);” onblur=”limit(this,500,’count1′);” onfocus=”limit(this,500,’count1′);”></textarea>

The thing is that I should add that inside the textarea of the comment body. As you can see, the code works, but how do I make it work the Drupal way?

I need only to limit comment length.

Thanks for your help!
Rosamunda

Why don't you simply use the Maxlength module that does exactly what you want already pre-packaged?

Otherwise, I would either write a custom module and use drupal_add_js() and hook_form_alter(), or use them in your template.php file without having to write a module.

If you're stumped, and want to know how to do it, why don't you download the Maxlength module and analyse how it is written to clarify the processes involved?


Override Views Contextual Filter in View Exposed Form Validation I'm using the Content:Nid contextual filter in my view (with exposed filters) and would like to dynamically set the value of this contextual filter from the exposed form validation callback. Is this possible?

Contextual filters work with arguments from the url so for example {drupal site}/search-nid/% where search-nid is the url of your page  and % is the value you wish to submit to the contextual filter.

An exposed filter tends to take it's values from the query string E.G.
{drupal site}/search-nid?field_nid=% (Again search-nid is the page url and % is the value of the nid)

If you are trying to do what I think you are, (Filter results to a specific nid using a URL to "autofill" the filter) I did this in a hook_form_submit function and not a hook_form_validate function.  The function below assumes your module is mymodule and your form id is advancedsearch_form.  The function looked as follows:

<?php
/**
 * Implements hook_form_submit()
 * Takes values from submitted form and appends them to query string
 * uses @see drupal_goto for info one $form_state['#redirect']
 */
function mymodule_advancedsearch_form_submit($form, &$form_state) {
  $qsa = array(); //for QSA arguments

  $field_nid = $form_state['values']['field_nid'];
  $qsa['field-nid'] = $field_nid;

  $form_state['redirect'] = array(
    'search-nid',
    array(
      'query' => $qsa,
    ),
    302,
  );
}

This may not be best practise (In fact I'm sure it isn't as it was a quick hack I implemented in about 5 mins!) but I hope it does answer your question.


Adding default text to input field I was needing to add a default value to a text field that disappears when you click on the field.

I did found this question :

How to add default text that clears on focus to a form in Drupal?

However, my knowledge is pretty limited as far as creating hooks so I'm a little lost as to the solution being drawup up here.

Could someone please point me in the right direct?

Cheers!

Since this is 2014 you're probably looking for the placeholder attribute, and not an old-school javascript solution.

Broad strokes: Implement hook_form_alter() and add the attribute there:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['bar']['#attributes']['placeholder'] = t('Baz');
  }
}


field theme that have add more option I have an Image field that I can add more than one field but I want the user when upload an Image the image appear below the input not above it and sort them desc so the input form will be above the table of images not below them

What you are wanting to do is re-theme cck's theme_content_multiple_values() call that creates the html table with the input on top instead of the bottom.  Quick and dirty in drupal 6 at least, I went into content.module and pulled out that function as well as the helper function that does the sort, copied them into my theme's template.php and named them appropriately with this being the result:

function YOURTHEME_content_multiple_values($element) {
  $field_name = $element['#field_name'];
  $field = content_fields($field_name);
  $output = '';

  if ($field['multiple'] >= 1) {
    $table_id = $element['#field_name'] .'_values';
    $order_class = $element['#field_name'] .'-delta-order';
    $required = !empty($element['#required']) ? '*' : '';

    $header = array(
      array(
        'data' => t('!title: !required', array('!title' => $element['#title'], '!required' => $required)),
        'colspan' => 2
      ),
      t('Order'),
    );
    $rows = array();

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key !== $element['#field_name'] .'_add_more') {
        $items[] = &$element[$key];
      }
    }
    usort($items, 'YOURTHEME_content_sort_items_value_helper'); // MOD 1

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = $order_class;
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array('data' => '', 'class' => 'content-multiple-drag'),
        drupal_render($item),
        array('data' => $delta_element, 'class' => 'delta-order'),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => 'draggable',
      );
    }

    $output .= drupal_render($element[$element['#field_name'] .'_add_more']); // MOD 2
    $output .= theme('table', $header, $rows, array('id' => $table_id, 'class' => 'content-multiple-table'));
    $output .= $element['#description'] ? '
'. $element['#description'] .'
' : '';

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

function YOURTHEME_content_sort_items_value_helper($a, $b) {
  $a_weight = (is_array($a) && isset($a['_weight']['#value'])) ? $a['_weight']['#value'] : 0;
  $b_weight = (is_array($b) && isset($b['_weight']['#value'])) ? $b['_weight']['#value'] : 0;
  if ($a_weight == $b_weight) {
    return 0;
  }
  return ($a_weight > $b_weight) ? -1 : 1; // MOD 3
}

There are only three modifications to the code:

MOD 1 : changed the second argument to point to "my" sort function instead of CCK's

MOD 2: moved the add-more button to display before the table instead of after it

MOD 3: changed < to > to it sorts "backwards" from the default

Clear your theme registry cache and if all is well and good in the world of my thursday brain, you should now have your add more and enter buttons on top of the table instead of below.


Devel module and the WSOD on login I have a lot of trouble with the WSOD and have looked around quite few posts; like WSOD with Devel module and How to see the error messages when I get the white screen of death? as well as https://www.drupal.org/node/1692262

After reading the posts the best thing to do was to uninstall the the devel module, once i did that the WSOD is gone, but what if you need the devel module?

I'm struggling to get the errors up and work out where i have gone wrong. Doesn't Krumo need devel?

This is not a complete solution, but can help.

If you want to look at something but dont want to spend the time investigating your site's aversion to the devel module, then drupal core's watchdog call can be helpful.  Also, I am assuming you have dblog or weblog module enabled to catch the error messages.  To make it more readable, like a krumo output, I often add my Explain function to a custom module somewhere. Then in the place where I would have used krumo($target); I use watchdog('bug_hunt', explain($target, 5, 'target') ); and go to /admin/reports/dblog and filter for bug_hunt.  That 5 is arbitrary in this case; 4 steps into something can get you target->field_one[und][0][value] = Content.Since I have that function terminating the recursion with html line breaks, it reads well in the log pages.

I started doing this when I was trying to expound on processes that did not have a page for krumo to inject into (maestro module workflows, etc).  Since then, it has been a reliable fall-back method for me.

The better solution would be to spend the time finding why devel crashes your site, as it might be an issue that will appear again later on.


How do I know which Drupal 8 modules are supported by Drupal 8 versions? How do I know which Drupal 8 modules are supported by Drupal 8 versions?

For example is Page Manager 8.x-1.0-alpha8 module supported in every Drupal 8 version? And if not how do I know which Drupal 8 version supports some module?

Which version of Drupal 8 supports Paragraphs 8.x-1.0-alpha2 module?

How do i know which drupal 8 modules are supported by Drupal 8 versions?

You can't.

Specific projects might release alpha/beta versions in sync with core but if that's so and which version requires which version is something you have to figure out for each project separately.

You can try to get guess based on the release date, check if a release came out before or after a beta version. But it might be that an older release still works.

No contrib project that I've seen so far explicitly defines version specific dependencies, and it's actually not really possible, because you don't know yet when you release whether the module is going to be compatible with the next beta or not and when something will break it.

That said, there should be fewer and fewer API changes that break contrib modules from now on.