Adding custom field to apache solr drupal 7 I have tried Apache Solr Autocomplete to make autocomplete option in solr search. But it is not work for me. Is there any other alternative to do this?

And also I need to know, how to add custom field to be indexed in solr. I have tried hook_apachesolr_index_document_build_node and my_module_apachesolr_query_prepare in my custom module. But when I put this the index is not added to solr.`

Any suggestions?

The apachesolr module defines a hook that allows a search document to be updated before it is sent to the Solr server for indexing. Actually, I lied, there are two.

hook_apachesolr_index_document_build and hook_apachesolr_index_document_build_ENTITY_TYPE (for specific entity types).

<?php
/**
 * Implements hook_apachesolr_index_documents_build_ENTITY_TYPE().
 */
function mymodule_apachesolr_index_document_build_node(ApacheSolrDocument $document, $entity, $env_id) {
  // While indexing article node content
  if ($entity->type == 'article') {
    // Get the field value that needs to be indexed
    if ($fields = field_get_items('node', $entity, 'field_example_field')) {
      // Only need the first value
      $value = field_view_value('node', $entity, 'field_example_field', $fields[0]);
      // Add the value to the document to be indexed. ss_ prefix denotes a string type
      $document->setField('ss_index_field_name', $value);
    }
  }
}

The content is added to Solr via the line $document->setField('index_field_name', $value); While the example is very simple, this can be used to index values from complex relationships that wouldn’t normally be possible.

Any content that already exists in the index will need to be reindexed.

Now that that new custom field exists, it can be made available for the search results display. Using hook_apachesolr_query_prepare the search query can be altered, in this case to add the new field.

<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // Make 'index_field_name' available for search results
  $query->addParam('fl', 'ss_index_field_name');
}

The new field can also be used to filter search results, again using hook_apachesolr_query_prepare.

<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // filter where 'index_field_name' = 'indexed_value'
  $query->addFilter('ss_index_field_name', 'indexed_value');
}


Show menu link descriptions for a custom navigation menu I have the following navigation, displayed in page.tpl.php:

theme('links', array('links' => menu_navigation_links('menu-site-navigation')));

There are four navigation elements that show up. I would like to display the description that goes along with these elements as well, how do I go about that?

In my template.php file I have the following code, but I can't figure out how to only apply this change to menu-site-navigation

function MYTHEME_link($variables) {
   // if there is a description for the menu item, show it
  if(!empty($variables['options']['attributes']['title'])){
      return '' .
      ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) .
      '
' . $variables['options']['attributes']['title'].'
';
  }
  else{
    return '' .
    ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) .
    '';
  }

}

Here are two things that may help you get this going:

It looks like you're calling the theme_links() rather than the theme_link() function in your page.tpl.php file, so make sure that the call and theme function implementation match.
You could add additional information to your links when you theme them to distinguish them from other links.  For example, notice how I'm adding an id in the 'attributes' section below, so I can check for it later, in my theme_links implementation

Does that help?

 print theme('links', array(
  'links' => $secondary_menu,
  'attributes' => array(
    'id' => 'secondary-menu',
    'class' => array('links', 'inline', 'clearfix'),
  ),
  'heading' => array(
    'text' => $secondary_menu_heading,
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));


Total sum using view php I have two footers in a view page with the sum results from View Aggregate Plus (VAP). The last row is the sum result.

  footer A:    var A
      10
      20
      30 (sum result from VAP)

  footer B:   var B
      25
      30
      55 (sum result from VAP)

I would like to sum the results of footer A and footer B (Total =20 + 30), using global php (module view php).

The available variables below:

What is the output code to get the total summation result ?

What you are trying to do is to use module in alpha version (bad practice) that keeps PHP code in database (very, very bad practice)  for task that can be accomplished by modules without these flaws, like Views Calc, Views Aggregator Plus or even built-in aggregation.

My current favourite is Views Aggregator Plus:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

And example on it's page is quite similar to what you want to accomplish here.

For a whole table sum, just add Global: mathematical expression column to sum values in row, and then Views Aggregator Plus to sum that column. Column may be hidden, for example with CSS.


Hide columns depending on checkbox state with Javascript I have a form with a fieldset where I created a simple checkbox:

$form['my_fieldset']['my_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('my title'),
    '#default_value' => 1,
    '#disabled' => FALSE,
);

Then, in other fieldset, I have a tableselect with these columns:

slot1
slot2
slot3

The data for these columns is as below:

'slot1' => array(
    'data'=> array(
        '#type' => 'select',
        '#title' => 'Slot1',
        '#title_display'=> 'invisible',
        '#default_value'=> '',
        '#value' => 'slot1',
        '#options' => $my_options,
        '#name' => 'slot1',
        '#attributes' => array('class' => array('update-slot1')),
    ),
),
'slot2' => array(
    'data'=> array(
        '#type' => 'select',
        '#title' => 'Slot2',
        '#title_display'=> 'invisible',
        '#default_value'=> '',
        '#value' => $emulator_data['slot2'],
        '#options' => $cards_available,
        '#name' => 'slot2[' . $emulator_data['container'] . ']',
        '#attributes' => array('class' => array('update-slot2')),
    ),
),
'config' => array(
    'data'=> array(
        '#type' => 'select',
        '#title' => 'config title',
        '#title_display'=> 'invisible',
        '#default_value'=> '',
        '#value' => 'config',
        '#options' => $my_options,
        '#name' => 'config',
        '#attributes' => array('class' => array('update-config')),
    ),
),

What I need is to hide 'slot1' and 'slot2' columns if the checkbox is checked and hide the 'config' column if it's unchecked, using javascript.

#states is a good JavaScript only approach to hiding simple markup, but sometimes we need to modify the render array itself

To add/remove form elements or complex render arrays based on feedback, you can do so by checking the value of $form_state['values']['my_fieldset']['my_checkbox'] in a condition around your table column logic. Also wrap the other_fieldset with a div defined in #prefix and #suffix that has that wrapper id.

if (isset($form_state['values']) && $form_state['values']['my_fieldset']['my_checkbox']) {
  // Add slot1/slot2 columns here.
}

Then add an AJAX/AHAH to the checkbox element:

$form['my_fieldset']['my_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('my title'),
    '#default_value' => 1,
    '#disabled' => FALSE,
    '#ajax' => array(
      'callback' => 'my_module_form_ajax_callback',
      'wrapper' => 'other-fieldset-id-wrapper',
      'method' => 'replace',
      'effect' => 'slide',
    ),
);

Then implement a function to return the form element you want to replace. Note that you do not modify the form/form_state here and modifying the form will have no effect. However the value of the checkbox will be stored in form_state values when the form is re-rendered.

  function my_module_form_ajax_callback($form, $form_state) {
    return $form['other_fieldset'];
  }


Multilingual site page not found error on default language URL path prefix I have a multilingual site with 3 enabled languages.
Default language is Dutch. However when going to http://MYSITE.com/nl I receive a page not found error. /fr and /en is working as usual.
How can I use /nl for my Dutch content? When using the user interface text block to display language links, on a /nl page the NL link is set to active.

On admin/config/regional/language/edit/nl Path prefix language code was set to empty. Setting the code to /nl solved the problem.


Taxonomy autocomplete returns "connection reset" I have an autocomplete issue on an otherwise functional Drupal 8 site. I'm hoping someone has either found and fixed this problem before, or can steer me on how to diagnose it myself.

When editing a node, taxonomy autocomplete fields appear to hang - the spinner keeps going round forever. However, looking at the Network inspector, the lookup has returned "Connection Reset".

Further information:

Other kinds of autocomplete work on the site (e.g. node lookup when adding a redirect)
I am logged in as an admin user with full permissions to everything
The vocabulary is not empty
The autocomplete field is set to "create if term doesn't exist".
The form saves fine on submit, either creating a new term or working out which term to link to if I enter the exact text correctly
I am on the second-latest version (8.1.9)
Accessing the lookup URL directly from a separate tab gives "This site can't be reached / the connection was reset"
PHP error log - empty
Drupal "recent errors" log - empty
Behaviour same in Chrome and Firefox
Linux server, Windows client for browsers

The URL being accessed looks like this:
http://[mysite.co.uk]/entity_reference_autocomplete/taxonomy_term/default%3Ataxonomy_term/UhDfSC7PJL0Sf6NxfMCVY27CaUM15rrS-gVsL6eD66E?q=[search_term_here]

EDIT:

As requested, here's the list of contributed modules:

Protected Pages
AT Theme Generator
AT Tools
Admin Toolbar
Admin Toolbar Extra Tools
Adminimal Admin Toolbar
Chaos Tools
Chaos Tools Views
Chaos Tools Blocks
Bigpipe
Calendar
Calendar Datetime
Devel
Feeds
Audiofield
Computer field
Datetime
Image
Simple Google Maps
Image Effects
IMCE File Manager
Backup & Migrate
Blog
Coffee
CookieConsent
Entity
Exclude Node Title
Libraries
Masquerade
PathAuto
Profile
Redirect
Redirect Import
Scheduler
Special Menu Items
Token
Twitter Block
Typed Data
User Display
Supercache
Rules
Security Review
Honeypot
Google Analytics
Flood Unblock
Superfish
Views PHP
Views Slideshow
Views Slideshow Cycle
Views templates

So after much frustration, I've finally got to the bottom of this. The answer is not within Drupal, but rather in my cPanel setup. I'll post the answer here because it may save someone else the headaches I've had.

The problem was that my cPanel hosting had xVarnish enabled. I'm not sure if it was suddenly added by a package upgrade, or if the behaviour changed, or if its effect only kicked in after a certain time span, but I certainly didn't switch it on! In any case, disabling xVarnish not only fixed this problem but also an "access denied" on image styles that had cropped up too.


Views filter using user field I have a webform for students to select their teachers.
The data displayed in Views to show the submitted values are the following:

----------------------------------
Instructor  | student
----------------------------------
teacher A   | student name A
teacher B   | student name B
teacher A   | student name C
teacher A   | student name D
--------------------------------

When "teacher A" login, I am expecting "teacher A" can see all his students, without entering filter value "teacher A"

----------------------------------
Instructor  | student
----------------------------------
teacher A   | student name A
teacher A   | student name C
teacher A   | student name D
--------------------------------

I want to have something like automatic filter with the field "Instructor", not typing own name in the exposed filter. So every teacher can get his own students automatically in the table.

Is there any specific module to do that, or a way to get that?

if instructor is a user entity (or reference), you can add a contextual filter in your view for your field, like this:


How to have calendar popup in a form field of 'date' type? Using Drupal Console, I created a custom content entity in which there is a 'date' field:

$fields['subscription_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date souscription'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))

The edit-form works as supposed and, particularly, editing 'subscription_date' brings up the calendar popup:

In my custom module, I defined a table form to 'mass' edit this entity:
I defined the date field in the form this way:

$form['souscriptions'][$key]['date'] = array(
    '#type' => 'date',
    '#default_value' => $default_value,
);

In Firefox, it looks like:

and editing a date field doesn't show the date popup :-(
While in Chrome, it's OK:

Any idea why?
What should I add to my form to have at least the simple calendar popup I have in my content entity edit-form?

Forgot to say: i'm using Drupal 8.4.2

This issue is coming because of jQuery confliction.
Either you can update jQuery version or find out the confliction of jquery object.


How to remove entity type from drush? How do I remove an entity type via drush?

List of entity types I can get via:

drush eval 'print_r(array_keys(entity_get_info()));'

Array
(
    [0] => node
    [1] => taxonomy_term
    [2] => comment
    ...

Entity types can't be generically deleted. First of all, node is entity type and can't be deleted using node_type_delete. You can only delete content type - and that's a bundle of entity called node.

To delete bundles that belongs to other modules, module providing entity type needs to provide drush command to delete bundle. You will find that command in module's documentation. And to remove entity type altogether, you need to disable and uninstall module that provides said entity type.

An Introduction to Entities may be a good read for you now. I advise caution, because it's status is "Needs technical review", but it covers basics nicely.


How to dynamically change the text of the Global: result summary based on exposed filter on Views? There is a content type and it has a field called field_type. It's a select list and there is 5 options to select such as AAA, BBB, CCC, DDD, EEE.

I'm using the Views module to list the nodes of this content type. I added the field_type as exposed filter for this views.

In the header of the views, I added the Global: Result summary to show result summary.

 "@total results found."

What I want to do is dynamically change the text based on the exposed filter. For example if the AAA is selected on the field_type exposed filter then the results summary should display:

 "@total AAA found."

How can I do that?

I took the liberty of writing a little module for accomplishing what you asked for, I found it an interesting problem.
You can access it here:

https://www.drupal.org/sandbox/stefanos.petrakis/2666048

Hope this helps


Don't index certain content types I only want to have certain content types indexed, for the default Drupal 7 search. And I would like to do this without installing any other modules.

I would like to do this by hooking into the query (using hook_query_alter) that grabs all the nodes from the search_dataset. This query is found in the node_update_index function (node.module):

$result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

The problem is I never get the ability to alter this query in the hook, my code is as following:

function mymodule_query_alter(&$query) {
  var_dump((string)$query);
}

At some point it should print the db_query_range query. I've also tried printing my debugging to a file so I could catch those queries running ajax time.

Any ideas on what I might be doing wrong?

You can only modify SQL queries that are tagged, which this one is not. Therefore you cannot use HOOK_query_alter() to do what you are trying to accomplish.

This is hacky, but the easiest way to do this might be to implement hook_module_implements_alter() and prevent the Node module's hook_update_index() implementation from firing. You can then copy the node_update_index() function to your custom module, obviously replacing "node" in the function name with the name of your custom module, and modifying only the query to exclude whatever node types you want.

/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ('update_index' == $hook) {
    unset($implementations['node']);
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index().
 */
function mymodule_update_index() {
  $limit = (int)variable_get('search_cron_limit', 100);

  $result = db_query_range( /* Your custom query here */ );

  foreach ($result as $node) {
    _node_index_node($node);
  }
}


Views remove link to content based on publication status Drupal 8. I have a list of images that link back to a content page. If the page is unpublished I want to remove the link.

So far I've set up a hook_post_render that checks the publication status. The only way I can think to move forward is to make make the view put out a link as a separate field, then conditionally remove the value. I don't love it and I'd rather jump in to where views is wrapping the image.

With Views's support for Twig, you can now implement conditional hyperlinking without any hook modification to your view.

Add a Content: Path field to your view with Exclude from display checked.
Add a Content: Publishing status field to your view with Exclude from display checked, using the True/False Output format.
Add a Image (field_my_image_field:target_id) relationship to your view that targets your specific image.
Add a File: URI field to your view with the Exclude from display checked, using the File URI as the Formatter, and the Display the file download URI checked.
Finally, add a Global: Custom field with custom Twig that can check the publishing status value for displaying the link and use the excluded fields as replacement patterns.

For example:

{% if status == 'True' %}

{% else %}

{% endif %}


Set a date field equal to "current time" + "5 minutes" using tokens I am using the Field Timer module to display countdown timer on my article node.

Say my article node has the date/time field named (field_article_datetime)

This module will take the value of the date/time field (field_article_datetime) and convert it into a countdown timer in the display of the article.

When the article node is created, I want to set the value of the date/time field (field_article_datetime) equal to current time + 5 minutes.

To extract the current time, I am using the token [node:created] from the token module, but I cannot find a solution on how to add +5 minutes to the token [node:created].

EXAMPLE:

Say at 12/03/2019 08:50:15 PM, a user has created a new article node... So I need a solution to add +5 minutes to the created time so the date/time field named (field_article_datetime) will be equal to 12/03/2019 08:55:15 PM...

This way, the user will see a countdown timer for 5 minutes on the article node display page.

Note: I am using the Business Rules module (similar to Rules module) to set the value of the date/time field (field_article_datetime) with the help of the token module.

Update #1:
Say the node is already created on the site and I want after the submission of a webform to fetch & update the node with update time + 5 minutes.

I think the best Idea is to use a custom module which will do the below:

Fetch the article by nid.
Set the value of field_article_datetime equal to: updated time + 5 * 60.
Save the Node

Since the above actions will be triggered when a user will submit a webform, so why not create a customwebformhandler.php file.

I have created a custom webform handler file but I need help to finish it since I am not a programmer:

<?php

namespace Drupal\my_module_name\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Update a node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Update a node",
 *   label = @Translation("Update a node"),
 *   category = @Translation("Entity Update"),
 *   description = @Translation("Updates a node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class UpdateNodeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Fetch & Update node object from webform-submission.

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // The webform has an element text field with machine name (update_nid) which
    // contains the node ID of the node to be updated.
    // This is the part where to fetch the node by the value of (update_nid) element.
        Some code here

    // This is the node Updating part.
    $created = $entity->updated->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;

    // This is the node Saving part.
    $node->save();
  }
}

I can't think of a solution with just tokens. Here is a quick and dirty solution without tokens

Setup your Article datetime field so that has a default relative time of +5 minutes

You can hide this field with css so the user will not change it or you can do it in a hook_form_alter function in your MODULENAME.module file

// adjust node_article_form for your content type
if($form_id == 'node_article_form'  || $form_id == "node_article_edit_form"){
  $form["field_article_datetime"]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
}

Of course if a user takes much time to fill the form the set datetime might not reflect exactly the NODE CREATION TIME +5 minutes (as a datetime is set on form creation time)

If the above is not good enough you can probably use hook_entity_presave to adjust the time to be EXACTLY the creation time +5 minutes.

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  // adjust article to reflect your content type
  if ($entity->bundle() == "article" && $entity->isNew()) {
    $created = $entity->created->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;
  }
}

NOTE: if you want to update the timer even on node update you can just delete the && $entity->isNew() part.


What is the difference between drupal_get_form and drupal_retrieve_form? What is the difference between drupal_get_form() and drupal_retrieve_form()? Can someone explain the difference?  I look at the API, but the description seems similar to me.

The difference is that drupal_get_form() handles retrieving, processing, and displaying a rendered HTML form for modules automatically, while drupal_retrieve_form() returns the structured array that defines a form.

Retrieving the form

drupal_get_form() first checks if the form is present in the form cache with form_get_cache(); if it isn't present, it calls drupal_retrieve_form(), and drupal_prepare_form().

Processing the form

drupal_get_form() calls drupal_process_form(), which is the function that calls drupal_validate_form(), and that invokes the submission handlers with form_execute_handlers().

Rendering the form

The rendering is done from drupal_process_form(), which calls form_builder().

In most of the cases, drupal_get_form() is the function to use, such as in the following code.

function node_menu() {
  $items['admin/content'] = array(
    'title' => 'Content',
    'description' => 'Find and manage content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_admin_content'),
    'access arguments' => array('access content overview'),
    'weight' => -10,
    'file' => 'node.admin.inc',
  );

  // …

  return $items;
}

The only module I found that is calling drupal_retrieve_form() directly is the Mollom module in mollom_moderate(), which uses it for automatically submitting a form. The code could use drupal_form_submit(), but (as a comment says), "Programmatic form submissions are not able to automatically use the primary form submit button/action, so we need to resemble drupal_form_submit()."

  $form_id = $form_info['delete form'];
  $form_state = form_state_defaults();
  // We assume that all delete confirmation forms take the fully loaded
  // entity as (only) argument.
  $messages[] = "Attempt to load $form_info[entity] entity via entity_load().";
  $entities = entity_load($data->entity, array($data->id));
  $form_state['build_info']['args'][] = $entities[$data->id];
  $form = drupal_retrieve_form($form_id, $form_state);

  $form_state['values'] = array();
  $form_state['values']['mollom']['feedback'] = '';
  // Take over the primary submit button of confirm_form().
  $form_state['values']['op'] = $form['actions']['submit']['#value'];

  $form_state['input'] = $form_state['values'];
  $form_state['programmed'] = TRUE;
  // Programmed forms are always submitted.
  $form_state['submitted'] = TRUE;

  // Reset form validation.
  $form_state['must_validate'] = TRUE;
  form_clear_error();

  drupal_prepare_form($form_id, $form, $form_state);
  drupal_process_form($form_id, $form, $form_state);

  $result = $form_state['executed'];


How to sql-sync prefixed multi-site installations within the same database with drush? I am running several Drupal 7 multi-sites that share same code base as well as the same database with prefixed tables per multi-site (some tables are shared too).

I chose this setup, because i need several sites, each representing a region. They share the same code but not the same content. (This is why i didn't chose Domain Access). The reason, why all multi-sites share the same database instance with prefixed tables is because i need cross-multi-site queries to aggregate global information. A context-switch within one database (by changing the table prefix whith db_set_active) is much "cheaper" than initializing a new database connection for every of the N regions.

Now I need to sync the data of one multi-site with the data of another multi-site within the same database. I thought Drush could easily do the job with:

drush sql-sync [from multi-site1] [to multi-site2]

But i recognized, that the sync is done per database and not based on prefixed tables... That sounds logical!

So the command above would sync *[same_database]* with *[same_database]*, but what i need is a script that runs like this:

sync [all prefixed1_ tables] with [all prefixed2_ tables] within same database

Now my question: Has anyone worked on synchronization of multi-sites within the same database before, or has anyone a hint on best practice for my synchronization-needs?

Edit: I found out, what my needs really are. Drush's sync is not a real "sync" it is more like a "export from and import to". So it is quite more simple than a complete synchronization-task with "insert", "merge" and "delete". So i am going to write my own drush's script to fulfill my needs.

sql-sync does not support prefixed database tables.  There is work going on in the issue queue to support removal of cache tables via wildcard expressions. Perhaps this code could be adapted to support prefixed tables as well, if a motivated contributor would write and submit a patch.


How to add class in current page link fields? I have an unlimited number of button who are link fields. Like on photo down.
{{ loop.first ? field.element_attributes.addClass(green) }}

I use this in twig to add class green for first button.
Orange button is link of current page where I am. How to add orange class to that field in loop?

There is loop.first, loop.last, loop.index, loop.index0, loop.lenght..Is someone for current page?

If the links are not part of the menu tree, then this can be tricky. Essentially you'll have to evaluate the href value to the current URL.

Otherwise, if they were part of the menu, you can look to the default menu.html.twig file and see in its items loop:

// code ...
{%
  set classes = [
    item.in_active_trail ? 'active-trail'
  }
%}

As it stands in your situation, you may want to do this in a preprocess and not the twig file itself.

function mytheme_preprocess_field(&$variables) {
  // code ..
  $url = Url::fromRoute('<current>');

  // loop field values, compare $url to value
  // if match, add 'orange' to class in the attributes
}

Then you would only have to worry about rendering the link fields in the twig, as the attributes part will take care of getting the class to the output.

I suppose another way of encapsulating this logic would be writing your own field formatter for this purpose.


Does Drupal have a system for noticing and logging changes to records? Does Drupal have a system for noticing and logging changes to existing content into a database or a file log?
I am interested in something equivalent to database triggers.

I am also interested in Feeds in particular as a lot of the data will be loaded from external sources. Do Feed imports have such a facility?

There is the Track Field Changes module which appears to have little support. And also a -dev version of Node Changes module with many more contributors and more recent updates.

Both modules allow you to track field level changes on Nodes essentially. From Node Changes:

  This module stores the changes of a node into a field attached to
  comments allowing to display a kind-of activity stream on the node
  much like on drupal.org issues just with a lot less custom code.

I don't believe either makes use of database triggers.


Cannot log in to drupal admin in a new installation (access denied) I've just made a Drupal 7 installation on localhost with XAMPP. I created an SQL database and did the installation without any error.

However, when I try to login on Drupal admin from localhost/mytest?q=user, I get an error like "Access denied. You are not authorized to access this page".

I tried to change the password on PhpMyAdmin manually, but I still have this error. I don't have any other drupal installation on my laptop.

These are the latest lines on logs.txt in logs file:

[Thu Mar 05 17:43:11.022491 2015] [mpm_prefork:notice] [pid 4801] AH00169: caught SIGTERM, shutting down
[Thu Mar 05 17:43:15.000852 2015] [ssl:warn] [pid 5867] AH01906: www.example.com:443:0 server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Thu Mar 05 17:43:15.001021 2015] [ssl:warn] [pid 5867] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Thu Mar 05 17:43:15.001398 2015] [suexec:notice] [pid 5867] AH01232: suEXEC mechanism enabled (wrapper: /opt/lampp/bin/suexec)
[Thu Mar 05 17:43:15.052113 2015] [auth_digest:notice] [pid 5868] AH01757: generating secret for digest authentication ...
[Thu Mar 05 17:43:16.002626 2015] [ssl:warn] [pid 5868] AH01906: www.example.com:443:0 server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
[Thu Mar 05 17:43:16.002750 2015] [ssl:warn] [pid 5868] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Thu Mar 05 17:43:16.003085 2015] [lbmethod_heartbeat:notice] [pid 5868] AH02282: No slotmem from mod_heartmonitor
[Thu Mar 05 17:43:16.015087 2015] [mpm_prefork:notice] [pid 5868] AH00163: Apache/2.4.10 (Unix) OpenSSL/1.0.1j PHP/5.6.3 mod_perl/2.0.8-dev Perl/v5.16.3 configured -- resuming normal operations
[Thu Mar 05 17:43:16.015126 2015] [core:notice] [pid 5868] AH00094: Command line: '/opt/lampp/bin/httpd -E /opt/lampp/logs/error_log -D SSL -D PHP'
sh: 1: -t: not found

It may also be a cookie problem. To check if that is what causing it, just try to use another web browser to verify if you get the same problem.

If using that other browser the problem disappaears, then DELETE the cookie in the browser where you experience this problem and try again. Pretty sure your issue will be solved then.

Curious to hear if this helps (sometimes it does ...).


HTML img code does not work? I'm using Drupal7 with CK editör.

When I add html code for an image (<img src="...")
I can see it on the editing page; but when I save it, I can't see anything on the page.

How can I solv it?

Check your text formats (Admin > Configuration > Content Authoring > Text formats) and make sure the one you're selecting for your node isn't filtering out the img tag.


Drupal 8 field API vs. $form_state I am creating a field with Field API, and having it shown on user registration form. However, I need its value in order to make validation. For that purpose, I've used dpm($form_state) which gave me the dreadful, dreadful memory exhaustion error. I then used file_put_contents(' sites/default/files/debug.txt', print_r($form_state, TRUE)); which did not produce anything at all. I also tried a few suggestions made on IRC, among which are `$form_state->getValue(['field_tckn']). It seems I can't get what my field's value is, no matter what I do; and all I get is that the field is required when I fill it in; and I'm all out of ideas. Can you recommend anything else?

Taken from http://www.drupal.org/node/2350819:

If you import a field, it automatically goes into the disabled section because the fact that a field is shown or not is now stored in the entity display config entities, which fields do not now anything off. I should check what our default behavior is, but this is probably by design - which makes sense actually. And if not, it'll be a feature request.


How to add facebook iframe code directly to block? I am trying to display a facebook plugin as a block. I created a new block from the block admin page, and in the "Text" for the block entered the following iframe code and tried a couple of things (none worked) - all show the raw iframe code in the block.

Tried 'Input Format' as FULL HTML (doesnt work)
Tried 'Input Format' as "PHP" (doesnt work, even tried adding  tag.)

Following is the iframe code I am trying:

<iframe src="//www.facebook.com/plugins/follow.php?href=https%3A%2F%2Fwww.facebook.com%2Fzuck&amp;layout=standard&amp;show_faces=true&amp;colorscheme=light&amp;font=verdana&amp;width=450&amp;appId=133506150025748" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px;" allowTransparency="true"></iframe>

Just use "Full HTML" input format and paste the iframe snippet in the source view of the block (e.g click "Source" on rich-text editor toolbar first )


PDF Reader module not displaying pdf I'm using the PDF Reader module to try to display a pdf file. Ideally I'll use the Goolge Viewer, but as of right now none of the displayers display my pdf.

My pdf file is set to full chmod 777 as well as the directory containing it (site/default/files/), for testing purposes only right now just to make sure the error wasn't due to permissions.

Here is screenshot of what I'm seeing -

I can click the 'try downloading the file here' link and view/save the file.

Any ideas?

EDIT: The screenshot is from a dev server connected to the internet.

You should test this module on the live site, but not on the localhost. If you are testing on localhost, Google Docs Viewer will not be able to access in the PDF document and can't show it, but you can download it from local server.


Redirect after comment submit according to value of query string in comment form URL? For redirecting user to some page after comment submit my below code is working fine :

function my_module_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "comment_node_link_form") {
      $form['#submit'][] = 'my_module_submit';
  }
}

function my_module_submit($form, &$form_state) {
    $form_state['redirect'] = 'newsroom/en';
}

For Comment links I am sending some query string in comment form URL and want to redirect to user to page after comment according to query string value, How can we fetch the query string value to pass it to redirect on hook_submit

http://www.example.com/comment/reply/208943?destination=newsroom#comment-form

http://www.example.com/comment/reply/208943?destination=sections#comment-form

How can we fetch value of destination  and pass it to redirect in hook_submit

Please suggest ! Thanks!

UPDATE :  I have tried adding hidden field but not able to access it in hook_submit it shows null :

function my_module_form_alter(&$form, $form_state, $form_id) {
       if ($form_id == "comment_node_link_form") {

           $form['redirect_to'] = array(
             '#type' => 'hidden',
             '#value' => $_GET['destination'],
           );

          $form['#submit'][] = 'my_module_submit';
      }
    }

After More deep debugging I found that action of comment from is set to

  comment/reply/nodeid

So with below URL's:

  http://www.example.com/comment/reply/208943?destination=newsroom#comment-form

  http://www.example.com/comment/reply/208943?destination=sections#comment-form

My query string variable destination  is lost or either at form submit it shows null because from moves to action URL where no query string was set.

To solve this I have added query string in action URL which works very well :

function my_module_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "comment_node_link_form") {
      $form['#action'] = $form['#action'] . '?destination=' . $_GET['destination'];
  }
}

ie: All I have to do is add required query string to $form['#action']

Hope this will help any one who is trying similar solution.


setContainer Error When Registering an EventSubscriber Service I am trying to create a basic event subscriber, but when I add the services.yml file and attempt to rebuild the cache with drush cr, I get this error.

  In Drupal.php line 130:

  \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

If I clear the cache from Drupal, it works fine, but Drush always errors out. If I remove the services file, Drush works fine again.

Has anyone seen this before? I don't want to move forward without resolving this. I have added services and event subscribers in this project before without an issue. I double checked spacing structure, etc.

module/gary_custom.services.yml

services:
  gary_custom.custom_event_subscriber:
    class: Drupal\gary_custom\EventSubscriber\CustomEventSubscriber
    tags:
      - { name: event_subscriber }

module/src/EventSubscriber/CustomEventSubscriber.php

namespace Drupal\gary_custom\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CustomEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    \Drupal::logger('debug')->debug('get sub events');

    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

  /**
   * This method is called whenever the KernelEvents::REQUEST event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function checkForRedirection(GetResponseEvent $event) {
    \Drupal::logger('debug')->debug('hitting');
  }
}

I am using Drush 9.4.0.

The problem is the logging line in getSubscribedEvents:

\Drupal::logger('debug')->debug('get sub events');

Drupal::logger queries the container for a service, but the container hasn't been set at the point the event subscriber discovery happens.

By the time the event handler is invoked, the container has been initialised, so the logging in checkForRedirection should work fine.


'TwitterException' with message 'Not Found' Viewing the syslog, I see errors like for the Twitter Module 7.x-5.11

Do you have an idea of how to solve it?

'TwitterException' with message 'Not Found' in /home/superstar/public_html/sites/all/modules/twitter/twitter.lib.php:164#012Stack trace:#012#0 /home/superstar/public_html/sites/all/modules/twitter/twitter.lib.php(117): Twitter->request('https://api.twi...')#012#1 /home/superstar/public_html/sites/all/modules/twitter/twitter.lib.php(1248): Twitter->auth_request('https://api.twi...',

This looks like it is failing in a portion of the code that has to do with authorization. Just starting with the simplest explanation, are you sure that your credentials/oauth settings are correct?


Import images after git clone So I did a git clone to get my Drupal 8 site working locally on another PC. This project already has a lot of nodes (articles) with images attached to them.
The site works perfect, but of course I did not push the images to git. So ATM I'm a bit confused as to where I should add these images. Is there a proper way to import these with a module or setting? I'm still learning so could be a simple thing I missed. Thanks in advance

The stage_file_proxy module is what you're looking for.
You can configure this module to download images on the fly, i.e. as they're needed, or have your local environment serve them straight from your remote environment.
From the project page on d.o, the simplest install:
composer require drupal/stage_file_proxy
drush en stage_file_proxy
drush config-set stage_file_proxy.settings origin "https://www.example.com"

The module's INSTALL.md file goes into more detail about all of the module's options.


Skip items with empty values in View I've a view filled with events. Some events carry a date, some don't.
How can I leave out those without a date? There should be somewhere a empty($date) ? hide($view) : break;. But I don't know how to do this with a view. Any suggestions?

Add a filter to the View, and filter out all events where date is NULL.


Login and get homepage content with a Bash script In some developments for drupal 7, I need connect with one user via a bash script then get the content of the connected homepage.

After several searches, my last try :

URL="https://www.mainsite.com/subsiteone/"

curl -s -f -o $output -H "Content-Type:application/xml" --insecure  $URL  -w "@formatsender.conf"  > ./test.txt

formid=$( grep 'input type="hidden" name="form_build_id"' $output | cut -d"=" -f4 | sed -e 's/"//g' | sed -e 's/\/>//g' )
echo $formid #show the good pofm id

curl --request POST ${URL} --data "name=usernameone%26pass=userpasswordone%26form_build_id=$formid%26form_id=user_login"

the last curl shows the content of the login page (not connected) without any error message.
I don't understand where is my mistake..

You might want to double checking your encoding or the headers that you're sending over that might cause the problem. I've found trying to do this with a pure Bash solution very fickle at times. Here's an example function I've used that will login into a D7 site on the /user page (an easier manner since every D7 install can be logged in from that path).

#!/bin/sh

# https://gist.github.com/cdown/1163649
#Usage: urlencode "string"
function urlencode() {
  old_lc_collate=$LC_COLLATE
  LC_COLLATE=C

  local length="${#1}"
  for (( i = 0; i < length; i++ )); do
    local c="${1:i:1}"
    case $c in
      [a-zA-Z0-9.~_-]) printf "$c" ;;
      *) printf '%%%02X' "'$c" ;;
    esac
  done

  LC_COLLATE=$old_lc_collate
}

#Usage: login "user" "pass"
function login() {
  URL=https://www.example.com/user
  name=$(urlencode "$1")
  pass=$(urlencode "$2")
  post_data="name=$name&pass=$pass"

  #Retrieve login page, login form, & input fields.
  login_page=$(curl -s -H "Content-Type:application/xml"  "$URL")
  login_form=$(echo $login_page | grep -o '<form[^>]*action="/user"[^>]*id="user-login"[^>]*>.*</form>')
  login_input=$(echo $login_form | grep -o '<input[^>]*/>')

  #Create Post Body
  while read -r input; do
    input_field=$(echo "$input" | sed -e 's/.*name="\([^"]*\)".*/\1/')
    if [[ $input_field != "name" && $input_field != "pass" ]]; then
      input_value=$(echo "$input" | sed -e 's/.*value="\([^"]*\)".*/\1/')
      input_field=$(urlencode "$input_field")
      input_value=$(urlencode "$input_value")
      post_data="$post_data&$input_field=$input_value"
    fi
  done <<< "$login_input"

  # Depending on your hosting environment you might need additional headers to make yourself not look like a bot
  user_agent="User-Agent:Mozilla/5.0 "
  referer="Referer:https://www.example.com/user"
  origin="Origin:https://www.example.com"
  content_type="Content-Type:application/x-www-form-urlencoded"

  # For further authenticated requests, you will need to parse output "Set-Cookie: ..." and set
  # the session cookie in a -H "Cookie: ..." option
  curl -s -L -H "$content_type" -H "$user_agent" -H "$referer" -H "$origin" --request POST "${URL}?destination=/" --data "$post_data"
}

login 'USER' 'PASS'

I've found logging into Drupal via Bash much easier with if you can work with a scripting language that has built in HTTP clients & parsers. Depending on your scenario, you might want to consider that if you need a more robust solution.


Can the Devel page generation times be placed at the top of the page? Can the Devel page generation times be placed at the top of the page?.

Devel places the page timer and memory usage  figures at the bottom of the page making it necessary to scroll down to view them.

Is there some setting to place it below at the top, either above or below the page header?

The devel_timer() function present in the devel.module file returns the page execution time for every page which is as below:

/**
 * Displays page execution time at the bottom of the page.
 */
function devel_timer() {
  $time = timer_read('page');
  return t_safe(' Page execution time was @time ms.', array('@time' => $time));
}

as the function is present in the module file(which is available on all pages) therefore you can call the function anywhere you want something like below:

$page_execution_time = devel_timer();
print $page_execution_time;

UPDATE: another way of doing it with the JS is to get the value of page execution time from the default wrapper and display it in the custom wrapper as below:

I have tried it in the custom block(whose format was FULL HTML) that I placed in the header and it was giving the correct result (as the page execution displayed in block was same as displayed at the bottom of page), however it would be good to move the JS code to JS file (for testing I have tried this).


How can I disable a single checkbox in a 'checkboxes' FAPI element? Title basically says it all, I want to disable a single checkbox of a checkboxes type FAPI element.

I don't want to do if with JavaScript, nor is changing it from checkboxes to multiple checkbox elements an option as the element is provided by another module.

Thoughts?

A clean way does exist in Drupal 7! Apparently, per this post, it's not yet documented.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#disabled'] = TRUE; //disables all options
  $form['checkboxes_element'][abc]['#disabled'] = TRUE; //disables option, called abc
}

Another example.

You can also set #access function to FALSE, to completely hide the checkbox.


Why is my webform returning a 404? I have several webforms on the site, and all work as intended, except one, which throws a 404.  Everything seems to be as it should, so I'm not even sure where to start.

While doing the research to add the additional information, I discovered the uid for the node was set to 0. Updated that to 1 and the webform now appears.


How can I migrate URL fields to link fields? I have run migration using drush migrate-upgrade by setting up Drupal 7 used module in Drupal 8 site and DB path etc. But one  of my content type use field https://www.drupal.org/project/url but now link field is in Drupa 8 and version of this module is not available in Drupal 8.

In support I have gone thorugh https://www.drupal.org/project/url/issues/1778224 but didn't helped much.

How I can transfer data along with revisions data related to this field and create/migrate similar field in Drupal 8 content type (rest of fields got migrated in 8 from 7)?

Have to create solution based on https://www.drupal.org/docs/8/api/migrate-api/writing-migrations-for-contributed-and-custom-modules#field-migrations

<?php

namespace Drupal\custom_url_migrate\plugin\migrate\field;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;

/**
 * @MigrateField(
 * id = "url",
 * core = {7},
 * type_map = {
 * "url" = "link"
 * },
 * source_module = "url",
 * destination_module = "link"
 * )
 */
class url extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function getFieldWidgetMap() {
    return [
      'url' => 'link',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldFormatterMap() {
    return [
     //'default' => 'link',
      //'url' => 'link',
      'url_external' => 'link',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function processFieldValues(MigrationInterface $migration, $field_name, $data) {
    $process = [
      'plugin' => 'sub_process',
      'source' => $field_name,
      'process' => [
        'uri' => 'value',
      ],
    ];
    $migration->setProcessOfProperty($field_name, $process);
  }

}


Variable available everywhere in template? I'm developing my first website with Drupal. So far it's going well but I have a few details I haven't figured out.

I want to load a random variable on each page load, in order to load a different color scheme each time.

My template is called 'fest' so I put this in my template.php:

$color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
$variables['color'] = $color;

If I put it in fest_preprocess_html the color var can be accessed in html.tpl.php but not in page.tpl.php. I want that variable available in node, page, html, everywhere.
Putting this code in plain function fest_preprocess didn't work either.
What am I doing wrong?

--EDIT
Check @Berdir's answer, which led me to resolve this issue. This is the code I used after all:

function mytemplate_get_color() {
    static $color = NULL;

    if (!$color) {

        $colors = Array('red', 'blue', 'magenta', 'green');
        $rand_key = array_rand($colors, 1);
        $color = $colors[$rand_key];
    }

    return $color;
}

$variables are unique for each template. So if you implement hook_preprocess_html() and add something, then it is only available for html.tpl.php and nothing else.

I think the easiest way to achieve your goal is to create a new function in your template.php which sets the random color them the first time you access it and the returns the them on following calls. Then you can simply call that function from any template you want and it will return the same value on the same request. Such a function would look like this:

function yourtheme_get_color() {
  static $color = NULL;

  if (!$color) {
    // First call, define $colors here and then set $color.
    $color = $colors[array_rand(Array('red', 'blue', 'magenta', 'green' ), 1)];
  }
  return $color;
}


drupal 7: include javascript with rules I have: drupal 7 - php module enabled - rules module enabled

On one of my rules I have the action: custom php code

when I enter <?php echo 'test code'; ?> it correctly shows the text

I want to include javascript, I've attempted:

<?php
    drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
    drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
?>

and

<?php
echo '<script src="http://www.googleadservices.com/pagead/conversion.js"> </script>';
?>

but when I view the source, there's nothing included. It's somehow stripped out or something.

What am I doing wrong? Is there a better approach?

Thanks for your advice

You can use hook init to check for the path and add JavaScript in custom module.

<?php

function yourmodule_init() {
  if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
    drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
    drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
  }
}

?>

OR

You can edit template.php and add below code.

function yourtheme_preprocess_page(&$variables) {
     if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
        drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
        drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
      }

}


How to inspect a variable when testing with `drush test-run`. When testing with my SimpleTests, I want to inspect a variable. var_dump() and the likes are not being rendered in the output of Drush, Xdebug interactive debugger does not work due to the simulated browser being ran in DrupalWebTest.

How can I render, export, inspect or otherwise dump the contents of a variable in my code? I.e. the DrupalWebTest of dpm(), var_export() and such.

Call DrupalTestCase::assert() passing the message to show.

$this->assert(TRUE,
  t('Variable content: @variable', array('@variable' => var_export($variable, TRUE))
);

This is similar to the code used by DrupalTestCase::assertIdentical(). The difference is that in your case the first argument is TRUE because you are just outputting the content of a variable, which never fails.

protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
}


How do I alter the submission button class? <input type="submit" class="form-submit" value="" name="op" id="edit-submit">

I want to alter the class from "form-submit" to "form-submitone".

How can do I do it? Where does the class "form-submit" come from?

If I were you, I would not change the class name but rather add your own class to the form element. You can do this by implementing hook_form_alter in a custom module or (in case of Drupal 7) in your theme. The code would look something like this:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'my_form') {
    $form['actions']['submit']['#attributes']['class'][] = 'form-submitone';
  }
}
?>

By the way, the submit button element is not necessarily $form['actions']['submit']. You will have to figure out which element is the submit button in your specific situation. You can do that by outputting the $form variable; I recommend installing the Devel module and adding dsm($form); to the function above.


How do I programmatically use the S3FS module? I've included S3FS module in Drupal 7. I'm able to store files by using S3FS as a field of a node.

Now, I need to store a file on S3 bucket when a cron job is executed. How can I programmatically use the module?

I used the following command to write the file. The system picks up the S3 connection (as I mentioned earlier that I'm able to store file as a field of a node):

file_put_contents('s3://Dir1/output.json', $jsonStr);


Trying to modify a menu with hook_menu_alter What is the best way to add a link to the user menu for a menu defined in my custom module?

Implement the hook_menu() in your custom module, then clear the cache and you will see the link in the User menu (you need place the block for the User menu in a region).

function YOUR_MODULE_NAME_menu() {
   $items = array();
   $items['/path'] = array(
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'user-menu',
   'title' => t('Title'),
  );
  return $items;
}


how do I activate the INSERT module? i want to use the INSERT module, to be abel to insert images into my content in a WYSIWYG style. I have downloaded & installed colorbox, have added a new field to my content type that allows me to upload images, I have installed CKEditor and Insert but when I upload a image in my added field, I do not get an insert button to place the image into my content. What am I missing?

I was missing to check Enable insert button under the INSERT settings in my image field configuration where yo also select the Enabled Insert styles


drupal_mail sending wrongly encoded special characters in mail subject I am using drupal_mail() function to send email. I have PHPMailer module with Mime Mail. It works perfectly, embedding images, sending HTML code, but for some reason, the subject line is pledged with bad characters, all the special chars of other languages do not display, a 'X' character display instead, but in the body of the message, it appears perfectly.

function mymodule_mail($key, &$message, $params) {

    $message['headers']=array(
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=UTF-8; ',
        'Content-Transfer-Encoding' => '8bit',
        'Return-Path' => $params["from"],
        'Reply-To' => $params["from"],

There are no bugs. Maybe lazy code from the developers.

Just simply put this line

mb_encode_mimeheader($params["subject"],"UTF-8", "B", "\n");

for the subject and works in all languages and codifications (chinese, etc.). It is tremendous that phpMailer class in itself handles perfectly, but when you use the phpMailer module, this encapsulating dissapears and you have to hard-code in the mymodule_mail() function.

Sincerely, Drupal is not suited for big projects.


Export a sqlite database through drupal admin? I have a drupal site running on sqlite. I'd like to backup the entire sqlite db, but keep running into "reading secure data from server" issues on my server. How do I go about backing up just the sqlite db from within the drupal admin area?

Not aware of an out of the box way to get it done in the admin area, but you shout be able to back the sql lite file up by downloading it in cpanel or ftp. There is a discussion about doing just that right here https://www.drupal.org/node/1156588


Entityform redirect from query I am struggling to get the appended parameter from the url when redirecting an entityform.

I have an entityform that user can get to from multiple pages on the website. I want to redirect the user back to the page they came from versus just sending them to a generic landing page after filling out the form.

I can get the path into the url - www.website.com/form-page/?source=page-I-came-from
However, when I go to redirect them, What do I put into the redirect field so it redirects them to www.website.com/page-I-came-from

I have tried:
%get[url]
%get[q]
[url:absolute]
[url:path]

If I put [current-page:url] I get the entityform page url - How do I get the path from the url from the referring page to show up. I have tried many things and I am falling short.

I have not found anything that can help me to get this to work and I have spent hours trying.

Please does anyone know how I can do this?

It looks like there is a token [current-page:query:?] you just need to replace the ? with your query parameter, so [current-page:query:source] should do the trick.


Close Lightbox on Custom Form Submit I am using form Api to create a custom form. My form is below.

function myform_form() {
  $form = array();
  $form['name'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#required'      => FALSE,
    '#weight'        => 2,
  );
   $form['telephone'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#weight' => 3,
    );
     $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
     );
  return $form;
}

function myform_submit($form, &$form_state) {
  drupal_set_message(t('Your form has been submitted successfully.'));
  $form_state['redirect'] = 'thankyou';
}

I used to show this form in lightbox as this :

 Form

Form is correctly showing in lighbox. But when i submit the form it opens the thankyou page in popup.

I used

 Form

It closes the popup event if form validation returns false. I don't want to close the popup if there is any validation error. I added this to myform_submit function :

parent.Lightbox.end();

But drupal_add_js is not working in myform_submit function.

Updated :

I send a parameter to thank you page and added this on the page load.

<?php if($_GET['redirect']) { ?>

<?php } ?>

Its redirecting but it shows content in popup for few seconds and redirect after that. I don't want to display popup for a second also after submitting the form.

Solved this by creating a Menu showing processing message and redirect it using :

      window.parent.location = "thankyoupage";


Changing the path of jQuery to use a CDN instead of the local file system I am creating a custom theme and I would like to know how to update the path of jQuery to use a CDN like the following:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

I don't want to use another module. I just want a simple way to change the path of the script.

Add the following code in the template.php file of your theme. (Replace mytheme with the actual short name of your theme.)

function mytheme_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['type'] = 'external';
  $javascript['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
}

As you are replacing the copy of the jQuery library with the same version copy hosted on Google, it doesn't make much sense to do it for just a theme. It would make sense to change it independently from the theme used from Drupal.

If you plan to use a different version of the library, you should first check there aren't incompatibilities with the jQuery version, and JavaScript code used from Drupal, or third-party modules. In case of incompatibilities, some JavaScript files used by Drupal could need to be replaced (using hook_js_alter()). That is what the jQuery Update module does.


Is this block safe from code injection exploit? Thanks good people here, I have create a simple module which generate two blocks as follows:

function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' =>  DRUPAL_CACHE_GLOBAL,
    );

    $block['myadblocks2'] = array(
        'info' => t('My second ad blcoks'),
        'cache' =>  DRUPAL_CACHE_GLOBAL,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = '';

        //Define the block content.
        $block['content'] = '<script>some ad js comes here</script>';
    }
    elseif ($block_key == 'myadblocks2') {
      $block['subject'] = '';
      $block['content'] = '<script>some other ad js</script>';
    }

    return $block;
}

My intention is to user these blocks instead of my current blocks that were volnurable to to script injection.

However, I am not sure the new module-based blocks will be more secure than the old admin-generated blocks. So appreciate your critical review of the module above.

Is this block safe from code injection exploit?

Essentially yes.

You're hardcoding the javascript, so there's no vector by which an attacker can inject code from the client side. This will of course change if you're interpolating variables into the JS code that have come from a potentially insecure source (i.e. the user). Those will need to go through filter_xss().

That's a bit over-simplified, there could of course be other vectors outside of this context which would allow an attacker to manipulate the PHP file itself, which could theoretically be invoked from the client. But in-and-of-itself, the method you've chosen is secure against XSS attempts.


How do I exclude admin strings from interface translation? I want to translate my Drupal 8 site to another language.

I have several translatable strings in my custom theme and modules specified via either the t method or {% trans %}.

To translate these I have activated interface translation. I can now find my strings by going to admin/config/regional/translate.

The problem is this page lists all strings including all strings defined by core. For this project I don't want to translate the admin interface, we specifically want it to stay in the default language (English). This means 90% of the strings listed should not be translated.

I know that I can set the admin interface to stay in a certain language by checking a box on the user account settings page, but this only works when on an admin page. When visiting a node in a translated language, the admin toolbar will still be translated if there are translated strings. If this problem could be solved it would probably be the best solution to just have that box checked.

But for now it seems like my only other option is to only translate the strings I want translated and none of the admin strings. To do this I feel like I have to be able to filter the list of strings on the interface translation page somehow. But there is no way to filter out strings based on which theme or module they are defined in. Or is there?

I have seen that there is a context parameter you can pass to the t method or {% trans %}. Maybe if I add a key like "translate" or something here, I could filter out strings with this context and only translate them. The thing is it feels like using the context parameter in the wrong way and it does not seem to be any way to filter by context either.

Does anyone have a good solution for this?

There is no solution that I'm aware of. You can't change the context of strings in core or contrib modules without changing the code. Which you shouldn't do.

The fact that toolbar doesn't show the english strings if your admin language is english is a big that's trying to be fixed here: https://www.drupal.org/node/2313309

I don't know if that's still doable in 8.x.


node/add url redirect I have two group content types (I use OG groups) which are still under development. I created dummy content types so that these links will appear in the group content creation links.

But they are not ready yet. Instead i would like to redirect the user when he clicks on the link to an article which basically describes what the functionality is and is under development.

I googled and searched drupal answers for this but could not find anything that fits my problem. Please let me know if someone knows how to redirect node creation links in a group context to a static article page. Thanks.

You can use hook_menu_link_alter() to hide those links. For example:

/**
 * Implements hook_menu_link_alter().
 */
function MYMODULE_menu_link_alter(&$link) {
  if ($link['link_path'] == 'node/add/dummy-type')) {
    $link['hidden'] = 1;
  }
}

Or can use hook_menu_alter() to redirect to other URL. For example:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/dummy-type']['page callback'] = 'drupal_goto';
  $items['node/add/dummy-type']['page arguments'] = array('node/1');
}

You can also use hook_menu_alter() to hide the links:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/add/dummy-type']['access callback'] = FALSE;
}


How to recover drupal password in localhost? I have a complete Drupal website on localhost. I forgot the password and username for my account. I found the username in the database, but the password is hashed.

I can't send emails from localhost, so recovering the password using the email is not possible.

How can I recover the password?

You can update the password via mysql. You can run the following query in mysql to update password. The given hashed value is the hashed value of password: NewPassword

UPDATE users SET pass = '$S$DRSUIz9NFfxOXKPveQ00UTGMzsJe62LjYvVHfYJ8I8wuy4zRqVBK' WHERE uid = 1;

For detailed instructions go through these article Resetting the administrator password with sql-query (Drupal 7)


Creating a tag list in a view of multlingual nodes I am creating a multilingual site in English and Swedish on Drupal 7.

I have a content type called ‘News’ which has a taxonomy term field that categorises the news posts. I have the content type set up with ‘Multilingual support’ set to ‘Enabled, with field translation’.

The views at /en/news and /sv/nyheter are working to the extent that they only show news in the users language. However, I can’t work out how to create a tag list in a block that shows the taxonomy terms for the users language.  i.e. when I am at /en/news I get a block which shows only English tags, (e.g. Fundraising (4), Events (2), Membership (2)) and and when I am at /sv/nyheter I only see Swedish tags (e.g. Insamling(4), Evenemanger(2), Medlemskap(2)).

What Translation mode should I use for the taxonomy?

What settings (fields, filters, relationships, etc.) should I use in the view?

Is it possible to create a view with two paths, one of the Swedish /sv/nyheter and one for the English /en/news?

I can provide more details on how I currently have it set up if necessary, and am also up for changing how it is set up to get it working. If you can point me to examples of this working with a views export and details of how you have the taxonomy set up that would also be really handy.

Thanks!

You should use " Translate. Different terms will be allowed for each language and they can be translated." in the vocabulary's settings.

In the view's settings, make sure that "news category" content field's "formatter" option is selected as "Link (localized)" or "plaintext (localized)".


Session cookie prevents pages to load There is a problem with Drupal 6 site. It seems seesion cookie is preventing some pages to load.

Site has approximately 5 to 10 pages (out of 30 000) of difference content types which can't be loaded. No errors returned — browser's wheel turning endlessly. After disabling cookies pages load just normally. After some testing I can say, that the problem in session cookie.

The problem doesn't exist in the development environment. I have made some testing on production (stopped Nginx and restarted Apache as single web-server) to make it similar to to development environment, but nothing changed. Now I have no idea how to debug the problem.

Thanks for any pointers.

[Solution]

The problem was in big sessions table (2GB). After truncating the table error has gone.

On large sites with many users and many simultaneous connections keeping sessions in database will cause a problems. So there are some tricks that may help you:

Don't keep unneeded sessions for anonymous users. To do this, choose one of the following, from what I advise most, to what's easiest:

Upgrade to Drupal 7
Migrate to Pressflow
Use No Anonymous Sessions module

Move your sessions where they will do less damage:

Memcache API and Integration module allows sessions in memcached bin
Memcache Storage (possibly with Cache Backport) offers the same functionality
Create your own session module looking at code of the above, for example to keep sessions in shared memory or in files on a ramdisc.

Flush sessions every midnight (or other hour with no visitors)


Why do i get a select dropdown when in mobile view from superfish I have a navigation menu from superfish in the header for my site.  It looks fine in my regular desktop and even landscape view of tablets but when it gets down to the size of a phone the wheels kind of come off.  In the mobile view I still get the ususal three horizontal bars that expand into the dropdown menu. But a "select" element shows up for some reason.  I dont know what i changed because this doesnt show up in my original installation but in my dev sight it does.

Does anyone have any idea where this "select"  comes from?

This is from a superfish plugin called sf-smallscreen.

You can either change it to kick in at a lower screen width, or you can disable it completely at /admin/structure/block/manage/superfish/1/configure -> Superfish Plugins -> SF-Smallscreen -> Disable


Creating table view with user profile2 I installed profile2 and i created two different profile types. I used views module to create a table of some fields of user profile types. Now i want to create a link in table to see user whole profile fields in page. I don't know what is the user profile2 link? I also could not see users profile2 field by administrator user.

In the View create a relationship with the User uid. After this You should see a few more field options for you to use.


How can I get comment creation date? How can I get comments creation date of a node and convert it to custom format in my theme, I tried to make some operations on node comments date in "MyTheme.theme" file and in MyTheme_preprocess_comment section.

/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}


Error on import multisite backup I had to import a multisite (Drupal 7) to Acquia dev desktop.
The import seemed to be successful.
But the following error is displayed when the page is accessed:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'kanu_backup.semaphore' doesn't exist: ...

What should I do?

Have you tried running your update.php file?

(https://www.drupal.org/upgrade/running-update-php)

II. Run update.php
In your web browser navigate to the directory where Drupal is installed:

http://www.example.com/update.php

or

http://www.example.com/test_site/update.php  (if you are upgrading a test site)
The update script should only be run once. It will complete all the updates at once. If prompted for which version, choose the closest starting version that makes sense for you.

This will update the default Drupal and contributed module database tables automatically (versions prior to 4.7 will require manual upgrade of the contributed modules). Once the script has stopped loading, be sure to scroll to the bottom to look for errors.


More on recommendable caching practices? Having read this Q & A, I feel like asking some more, perhaps very basic, questions anyway.

I'm just about to deploy a taxonomy- and Views-intensive site, and I'm wondering about the best cache practices with regards to Drupal and Views configuration.

Needless to say that all my caches are turned off for the purpose of reliable development, but for the sake of speed and server efficiency, some caching should be enabled when the site goes live.

The following questions come to my mind:

Should the Expiration of cached pages and Minimum cache lifetime
settings depend on the frequency of adding content to the site?
Is it possible to broadly define types of Views that should have their cache
turned on? and which should not?
If you were to turn the cache on, where would you do that: on the production site, or the development one before
deployment?
Has anybody developed a comfortable operational pattern
using a staging and production sites using Deploy module, with
regards to cache? If so, what practice do you recommend?

There is great info on views caching on this Q&A. It should answer your questions 1-3.
The 4th should probably be asked as a separate question.


Getting my paths/breadcrumb right with views Is it possible to get SEO friendly URLs when using a view? I have a site I am building that has a homepage which leads to two main views ("Homme" and "Femme"). I need the URL and breadcrumb to read "Home >> Homme >> name-of-the-article." Then, on the article page, I need "Homme" to be a link. Pretty straight forward and what you would expect in a site, right? I did download and install the Pathauto module, but I can't seem to get it working. I have a custom content type called "Men's blog post" and I set the path to be: "homme/[node:title]";  something similar is for "Femme."

This is not working. Do you have any idea?

Does the node title in the url include spaces? IF so, know that the spaces in the name which do not work well in urls.  You should set the title to have dashes to be a machine readable title. To do so change the configuration settings in pathauto to use a '-' separator.


Did the updated module actually update? Just performed an update to Drupal 7.56. In the process I updated all modules, including Google Analytics. The weird thing is that on my machine, where I performed the update, Google Analytics updated just fine.

But, after placing the files onto the server, and updating the DB with a copy of my own, the server is saying Google Analytic is still in need of an update. Everything else appears fine.

I checked the files for the Google Analytics module, and they are indeed the updated version.

Any ideas?

Thanks,
Cy

Try to run http://serversite.com/update.php.

You may have forgotten to clear the cache before you download the Database you upload to the server.

Next Time try try to clear the cache before you export your database file. Also I will recommend you use Backup and Migrate Plugin, that should be efficient in the future without error


How do I override the vocabulary template but only on a specific content type I have a vocabulary called "Sectors" and a content type called "News". Basically the vocab displays which sector the blog article is related to and links to the corresponding CMS page about that sector.

How do I customise the template that shows that vocabulary on my pages of that content type?

Many thanks.

I think you can make that with views :)

You have to create your views with the fields  you need. After that you will be able to theme them globally and locally.
check views's theme suggestion

i hope it helped you


(Newbie question) Something goes wrong here with db_add_field I'm trying to adapt that D6 module to D7.
I'm on the "add afield" part of .install

Here's my code :

function node_statistics_install() {
    db_add_field('accesslog', 'nid', array(
    'description' => 'Field added by node_statistics',
    'type' => 'int',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'length' => 11,
    'default' => 0,
  ));

but nothing happens in the database on install, no errors in drupal logs...
Am I missing something?

First, make sure that Statistics module installed/enabled.

Second, replace your code with the following code:

function node_statistics_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['accesslog']['fields']['nid'] = array(
    'type' => 'int',
    'length' => '11',
    'default' => '0',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by node_statistics',
  );
}

function node_statistics_install() {
  $table = 'accesslog';

  $schema = drupal_get_schema($table);

  db_add_field($table, 'nid', $schema['fields']['nid']);
}

Note: make sure to uninstall and install your module after you apply the new code.


How to show more than two fields in a Openlayers popup on a views_geojson layer? I have finally gotten my OpenLayers working, and I'm trying to show 7 fields about my points in a popup. By default, Views_geojsononly allows you to define a title and description fields for tooltips. I am assuming that this applies to the popups as well. Only being able to show two fields kind of limits the utility of the feature.  So, I'm wondering how I can show more of my fields in the popups? I'm using the Dev version of OpenLayers 7.x-3 and all the stable dependecies.

So, if anyone else runs into this a simple rewriting of the fields in views will get you to where you want. You can add your html there to format the fields.


Use computed fields as Apache solr facets Today I wanted to add a computed field to my facet to make a faceted search using that field but when checking the facets page that field wasn't in the allowed field to make facets. When i realized none of my computed fields was in that list i came to the conclusion that you can't use computed fields as facets.
Looking on google didn't help me confirm my dobuts, there's actually no result that talks about solr facets and computed fields so i decided to ask here:

Can you use computed fields to make facets? If yes, is there something i have ti do (install a module, change a setting...) to enable this since at the moment i can't see them from the available facets?

I think you need to store the computed field in database in order to make apache solr index it.
There is check box in computed field to save it to database: Store value in database

Just enable it and see if it works.


Social share module: confirmation page I'm looking to add a the social share block only on the confirmation page. Right now it shows up everywhere. Is it possible to control where it goes?

Here's the path to a completed webform.
node/1015/done?sid=1516

For Show block on specific pages I added
node/*/done

The node/*/done seems to be the fix.
Just thought I'd pass it along.


How to display specific nodes in an EVA based on common taxonomy I am trying to display nodes in an EVA, attached to a node type that shares taxonomy.  The EVA passes the node ID to the EVA, so I have a contextual filter, but am having trouble figuring out how to filter the EVA nodes by their shared taxonomy values.  It seems like I need to create a relationship in some way, but that doesn't work.

How can I filter out the nodes in my EVA that share the same taxonomy terms of the main attached node?

From the EVA project page:

  In addition, the unique ID of the entity the view is attached to -- as well as any tokens generated from that entity -- can be passed in as arguments to the view.

Pass the Taxonomy terms as arguments to the view attachment. You may then add a contextual filter to the view attachment which can make use of these arguments and  require the arguments be of terms within the appropriate vocabulary.


Glossary view: Show all results separated by letter I have a glossary view set up.  When I go to example.com/glossary/all, all of my results are shown, but I'd like them to be separated by letter. The layout I'm looking for is exactly like this...

https://drupal.org/glossary

For example..

A

Amy
Angie
Annie
Amanda

B

Billy
Bob
Ben

C

Catwoman
Cathy
Crystal
Caitlyn

Is there a way I accomplish that with Views?

Check out the Glossary module.

  The glossary module scans posts for glossary terms (including
  synonyms). The glossary indicator is inserted after every found term,
  or the term itself is turned into an indicator depending on the site
  settings. By hovering over the indicator, users may learn the
  definition of that term. Clicking the indicator leads the user to that
  term presented within the whole glossary or directly to the detailed
  description of the term, if available.

or

Lexicon

  A lexicon is a stock of terms used in a particular profession, subject
  or style; a vocabulary. The Lexicon module generates one or more
  Lexicon pages based on terms in taxonomies and optionally marks terms
  in the content and links them to the appropriate Lexicon page.

or

take a look at G2 Glossary module.


Can multiple users edit a node to create several different revisions without being able to publish them? I want to create a Wiki style website where many users can edit a document but can not publish their edits. Imagine having four users -- an administrator and three normal users. The three users can't publish anything they create or edit. So... one user creates a node. The administrator publishes the node after reviewing it. Then a second user edits the node and it's saved to a draft and after the third user edits the node and it's saved to a different draft. Now there is a published node and two different drafts of the node from two different users waiting for the administrator to publish one of them. Is there a clean Drupal solution for this?

The Workbench module with Workbench Moderation seems to do what you require. Users create drafts, which can then be markled for review. Once an admin reviews the content he can choose to publish it, update it or send it back to the user for further work. Each user has their own drafts, so different users can have drafts of the same document.

You can have as many stages and transitions as you want, so you could have a reviewer role who reviews content and sends it off to a publisher role to be published.

Workbench is Drupal 7 only, but Workflow seems to do similar things for Drupal 6, although I've got no experience with it personally.


Can I use the Services module without coding skills? I'd like to create an xmlrpc endpoint to import (add, update, delete) users from one Drupal site to another and believe that the Services module is the right tool for the job. However, by reading the documentation and looking at the screencasts out there, it seems to me that it requires some coding skills (like the Migrate module) in order to get the most out of this module.

I'd like to know if I could import my users with this module without any coding skill or if it requires more developers skills.

Using migrate and services are for separate use cases IMO.

I'd use Migrate for a one-off or periodic import and use Services for RESTfully add/update/deleting one at a time.

The services module includes integration with the user module and you can pretty much administer/point and click to get an xmlrpc endpoint with the user resources added.

You'd have to write a bit of code on the first site though, you might use a user hook http://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_insert/7 (or update, delete etc) and then use the data to make a http request to your other site http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7


Unable to link media in CKeditor My setup is as follows:

Drupal 7.34
Media 7.x-2.0-alpha3
CKEditor 4.4.6.08188c4

My problem is:

When I add an image from the "library" via media browser in CKeditor and try and link it via the "link" icon - the image does not link up. If I switch to source view I can see that no  tags have been added. If I save page - image link is not applied.

However, the link is saved if I edit source and add link  tags in manually.

From the question details it is not clear if you're using the CKeditor module, or it you're using the WYSIWYG module in combination with the CKEditor library (so without the CKeditor module).

As a possible alternative to consider, I'd suggest you try this:

if you're using the CKeditor module, then replace the 4.4.6 ... version of CKeditor with some 3.6.x version of it (such as CKEditor version 3.6.6.1.7696), and see if your problem is resolved (the 4.x version is known to have "some" issues which don't exist in the 3.x version ...).
alternatively, use the WYSIWYG module (without the CKeditor module, but only using the CKEditor library with version 3.6.6, since WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various 'cleanup and output' options within /admin/config/content/wysiwyg/profile/your_txt_fmt/edit (with 'your_txt_fmt' the text format you're using, eg 'filtered_html').


Speech API Javascript and Drupal Forms I'm using WebSpeech API to allow users speech recognition on my site. I'm using example 3 on this page: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html.

My code looks like this:

function _google_speech_speak_form($form, &$form_state) {
$modulepath = drupal_get_path('module','google_speech');
$form['textarea'] = array(
    '#type' => 'textfield',
    '#title' => t('Speak It'),
    '#prefix' => '
',
    '#suffix' => '
',
   );
$form['button'] = array(
    '#type' => 'button',
    '#attributes' => array('onclick' => 'return (false);'),
    '#value' => t('Click to Speak'),
   );
$form['submitt'] = array(
    '#type' => 'button',
    '#value' => t('Save'),
   );
$form['#after_build'] = array('_google_speech_speak_after_build');
return $form;}

function _google_speech_speak_form_submit($form, &$form_state) {
$speechkey = $form_state['values']['textarea'];
drupal_set_message($speechkey);
echo "test";}

function _google_speech_speak_after_build($form, &$form_state) {
drupal_add_js(drupal_get_path('module', 'google_speech').'/webspeech.js');
return $form;}

Webspeech.js:

 Drupal.behaviors.[google_speech] = function(context) {
 $('#edit-button').click(function() {
  var recognizing;
 var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset;

recognition.onresult = function (event) {
  for (var i = resultIndex; i < event.results.length; ++i) {
    if (event.results.final) {
      textarea.value += event.results[i][0].transcript;
    }
  }
}

function reset() {
  recognizing = false;
  button.innerHTML = "Click to Speak";
}

function toggleStartStop() {
  if (recognizing) {
    recognition.stop();
    reset();
  } else {
    recognition.start();
    recognizing = true;
    button.innerHTML = "Click to Stop";
  }
  }
 });
 };

I referred to this question: How to make form buttons call only javascript?
The "toggle" button is not refreshing the page (which is good) but it's also not toggling speech recognition like it should. There are no errors on the screen or in the logs. Any ideas?

To properly add JS or CSS to a form you use the #attached array key. See this similar question answered already here with links to documentation. Then your JS button should work.

https://drupal.stackexchange.com/a/70036/3279


"drush config-split:export" returns "Not enough arguments (missing: 'split')." I recently upgraded from Drupal 8 to Drupal 9. I've used drush config-split:export (drush csex) quite often. After the upgrade, it keeps throwing an error which is very vague.

Not enough arguments (missing: "split")

No documentation says what the problem is, nor what that argument should be.
Any help would be much appreciated.

In order to use config-split:export with Drupal 9, make sure you go to admin/config/development/configuration/config-split. There you should see if you already have a split configuration and use machine name: drush config-split:export [machine_name]


Migrating site from MariaDB to MS SQL 2012 I'm trying to migrate the site from a linux+mariadb platform to IIS+MS SQL platform. Could someone please tell me what is the best way to do this?

What I've done so far:

Installed a vanilla Drupal site on IIS server to ensure everything works.
Tried migrating the database with SQL Server Migration Assistant (SSMA): https://stackoverflow.com/a/13898291/3199478

It's a Drupal 8 site so the Migrate and Migrate D2D modules are useless.

I recommend giving this tool a try. I have used it in the past (to do MSSQL -> MySQL) to setup a datasource for a legacy migration. In your case, you don't need a migration, you just need the db to be in MSSQL format. This is a great litmus test that might save you hours and hours of time.

https://dbconvert.com/mysql/mssql/

It's reasonably priced and worth a shot. If it works fine, you'll move right along.


How to update drupal by drush automatically In common use,after typing "drush up drupal" it need type "yes" for confirm.If I need to use Linux's cron to run drush automatically,how to bypassing the confirm part?

Updating Drupal Core to the latest version e.g. currently Drupal 8

drush up drupal -y

Updating a specific Drupal Core Version.

drush up drupal-7 -y


How to remove author name and date created from Simplenews emails? When I create a newsletter using the Simplenews module and save it, I don't see the author name and date created in the node. However, when I send email, it contains author name as a link and date and time of creation + 'html' as shown.

rktaxali Thu, 05/19/2016 - 11:42 html

Unsubscribe from this newsletter

Any suggestion, how to remove the author name and date row from email?

On a similar note, the email also includes the node title twice in the body of the email, e.g.

Quarterly News Letter

Quarterly News Letter

This is sample newsletter sent by the simplenews module ...

Any suggestion, how to remove the two repeating lines at the top of the email?

I would suggest you two options:

You can put node.tpl.php specific to your simplenews content-type and remove the unnecessary content from it.
Add css file specific to the mailing system. I use mimemail system, so I did the following:

function THEME_NAME_preprocess_mimemail_message(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'THEME_NAME').'/css/mail.css');
}

In the mail.css, you can hide those fields using display:none;


How to calculate the sum of 2 fields in a content type and display the result in a 3rd one when the node is saved? Could anybody figure out to me how i could create a field that computes the sum of values in 2 other fields.

In other words how to do a simple addition (say of price and vat) like so:

price
+
vat
======
result

The result should be displayd after the editor saved the node.

Computed Field is a good solution. You can achieve a similar results without an additional module (provided you already have a custom module).

If you need to store the result when the node is saved, you can implement hook_node_presave() to set the value of the third fields just before the node data is saved to the database.

MODULE_node_presave($node) {
  $value = 0;
  $price_items = field_get_items('node', $node, 'field_price');
  if ($price_items) {
    $value += $price_items[0]['value'];
  }
  $vat_items = field_get_tems('node', $node, 'field_vat');
  if ($vat_items) {
    $value += $vat_items[0]['value'];
  }
  $node->field_value[LANGUAGE_NONE] = array(array('value' => $value));
}

Because the value is always calculated and simple, there is really no need to store it in the database. If your are already using the Entity API module and its entity metadata wrappers, this is easily doable with a hook_entity_property_info() implementation.


How to create a vocabulary and populate it with terms using features I'd like to create a feature that creates a vocabulary and populates it with taxonomy terms.

Creating a vocabulary is easy with features and it can be done using UI (I only need to select the desired existing vocabulary and add it as dependency and a file features.taxonomy will be created)

However, there's no way to export terms to a feature, so I created a feature_name.install file and added the following function on it:

/**
 * Implements hook_install().
 */
function feature_name_install() {
  // Populates 'Vocabulary name' vocabulary with taxonomy terms.
  $vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_machine_name');
  $terms = array();

  $terms[] = t('Term 1');
  $terms[] = t('Term 2');
  $terms[] = t('Term 3');

  foreach($terms as $name) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $name;
    taxonomy_term_save($term);
  }
}

The problem with this code is that when installing the feature it is loaded before creating the vocabulary so tries to add terms to a vocabulary that does not exist yet and produces an error.

I have tried using hook_post_features_enable_feature but I didn't succeeded (I may be using a wrong syntaxis, see code below).

/**
 * Implements hook_post_features_enable_feature($component).
 */
function feature_name_post_features_enable_feature($component) {
  $component = 'feature_name';
  // Populates 'Vocabulary name' vocabulary with taxonomy terms.
  $vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_machine_name');
  $terms = array();

  $terms[] = t('Term 1');
  $terms[] = t('Term 2');
  $terms[] = t('Term 3');

  foreach($terms as $name) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $name;
    taxonomy_term_save($term);
  }
}

Can anyone tell me how to solve this?

The problem with exporting content like taxonomy terms is keeping the taxonomy id intact when migrating it from site to site which is exactly what the features extension module UUID Features solves by using the UUID api:

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.
  What's that you say? You thought features was only for configuration?
  This module is meant to be used in the cases where certain pieces of
  content straddle the line between pure content and configuration.