how to configure drupal settings to be available to visualize the available variables?

You can use kint which will print you all the variables
https://www.webwash.net/how-to-print-variables-using-kint-in-drupal-8/
or dpm (in devel module)
https://www.drupal.org/docs/contributed-modules/devel/dpm-and-other-devel-functions


Drupal7 : Error in install drupal in localhost

You need the php's PDO and mysql extensions installed on your system in order for Drupal to use MySql data storage. One or both of them are apparently missing, and Drupal defaults to Sqlite, which is a simple database system and only needs a writable file to work. Please refer to Drupal's system requirements page for further info.


Copying this code snippet into your page.tpl.php won't help because the $page variable will not be defined for this template. You can only move it freely inside the views-view.tpl.php template.

You can add a similar $pager variable to your page template using your theme or module's implementation of hook_preprocess_page(). In this implementation, you can retrieve the current page's view (if any) using views_get_current_view(). See the template_preprocess_views_view() function in Views' include/theme.inc for how to generate the pager from a view object. In Views 3.x the pager is build by the query plugin.


Is there any way to delete ubercart role expiration through rules in Drupal 7

It seems that you are removing the role through the drupal standard rules. Try calling the own uc_ubercart function to better compatibility.

/**
 * Deletes an expiration using user id or user id and rid.
 *
 * This function deletes expirations associated with users and roles. If
 * no role ID is passed, the function deletes all role expirations associated
 * with the given user. Otherwise, the function only deletes expirations whose
 * user and role IDs match. If any roles were actually deleted, the function
 * notifies the user. The menu cache is then flushed, as privileges to view
 * menu items may have been lost in the process.
 *
 * @param $account
 *   A Drupal user object.
 * @param $rid
 *   A Drupal role ID.
 * @param $silent
 *   When set to TRUE will suppress any Drupal messages from this function.
 */
uc_roles_delete($account, $rid = NULL, $silent = FALSE) {}

An example with custom module (without rules):

https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  if ($node->type == 'customtype') {
    $rid = 3; //@TODO: set rol ID
    $account = user_load($node->uid);
    // Delete UC Role!
    uc_roles_delete($account, $rid, TRUE);
  }

}

You can also use this code on the rules action PHP but I prefer the hook.


By default the form will be rendered using the form rendering system, which doesn't include template files, instead functions like theme_textfield is used instead. You can choose to let the entire form or certain form elements be rendering by your custom theme function using the #theme key.

For certain type of fields, this can be dangerous as they require certain markup.


Instead of dealing with Views just copy the page.tpl.php file of your theme to page--front.tpl.php and do whatever you want with it. In particular you can comment out the <?php print render($page['content']); ?> and replace with any code you need.


Basic custom module installation error - "...Controller does not exist in ReflectionMethod"

Your class' name is "EvelatorController", the name of the php file of the class is "ElevatorController.php" - it is just a spelling problem


custom function to delete determined content type's nodes never finish

May be the server execution is taking long time to delete nodes.Try to increase your server execution time or change the code to batch process or pass limited nids to the  delete function.


How can I register an already uploaded unmanaged file as managed file?

I ended up creating a new managed file, pretty easy as the following:

$user = \Drupal::currentUser()->id();
    $image = File::create([
    'uri' => $image_local_path,
    'uid' => $user,
    'status' => FILE_STATUS_PERMANENT,
  ]);
  $image->save();


For the configured custom path:

CustomPageExceptionHtmlSubscriber::on404

   public function on404(GetResponseForExceptionEvent $event) {
    $custom_404_path = $this->configFactory->get('system.site')->get('page.404');
    if (!empty($custom_404_path)) {
      $this->makeSubrequestToCustomPath($event, $custom_404_path, Response::HTTP_NOT_FOUND);
    }
  }

If no custom path is configured the subrequest is built for '/system/404' pointing to the controller you've mentioned:

DefaultExceptionHtmlSubscriber::on404

  public function on404(GetResponseForExceptionEvent $event) {
    $this->makeSubrequest($event, '/system/404', Response::HTTP_NOT_FOUND);
  }

To customize other status codes than 403 or 404 extend DefaultExceptionHtmlSubscriber and override on4xx().


Why is my form themed as table not posting data correctly, or displaying correctly?

The problem is that your textfield elements are located under the #rows property of your render array.

Drupal sees any array key beginning with # as a property/attribute, and any array key not beginning with that as an element that needs to be recursively attended to. As such the children you've got under #rows will be ignored by the form builder.

Since theme_table will run on the render array, your form elements will actually be rendered out to the screen, but the form won't have any knowledge of the values (as they are not technically children of the form).

In my experience the best way to do this sort of thing is to use a specific theme function on the element:

function MYMODULE_theme() {
  return array(
    'MYMODULE_textfield_table' => array(
      'render element' => 'element'
    )
  );
}

function theme_MYMODULE_textfield_table($vars) {
  $element = $vars['element'];

  $rows = array();
  foreach (element_children($element) as $key) {
    $rows[] = array(
      array('data' => 'label'),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => render($element[$key]))
    );
  }

  $header = array(t('Field Label'), t('Field Name'), t('Location'), t('Stuff'));
  return theme('table', array('header' => $header, 'rows' => $rows));
}

Then in your form function you would use code like the following

$form['things'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
  '#theme' => 'MYMODULE_textfield_table'
);

foreach ($type_fields as $field_name => $attrs) {
  $form['things'][] = array(
    '#type' => 'textfield',
    '#default_value' => $attrs['stuff'],
    '#extra_data' => array('field_name' => $field_name)
  );
}

After that your textfields should be registered in the form and you should be able to see the value in the $form_state array as normal.


How to route dynamic routes to a single node while keeping the urls?

Alright got it working! The redirect module hooks into the kernel.request event and will redirect if you're doing wildcard routing like I am below.

You may want to split this up into two services since we're hooking into two events, but they're directly related so I chose to keep it simple.
Basic explanation of methods in here is:

PathSubscriber::processInbound
Check the incoming url and map it to a single node

PathSubscriber::getSubscribedEvents
Register our callback for the kernel.request aka KernelEvents::REQUEST event so we can stop the redirect module from redirecting.

PathSubscriber::stopRedirectIfOurRoute
Check the path and if it matches against our wildcard routing from PathSubscriber::processInbound then set the _disable_route_normalizer to true to disable the redirect module from redirecting to the node's alias. Leave our urls alone!

mymodule/src/PathSubscriber.php

namespace Drupal\mymodule;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class PathSubscriber implements InboundPathProcessorInterface, EventSubscriberInterface
{
    /**
     * Processes the inbound path.
     *
     * @param string $path
     *   The path to process, with a leading slash.
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The HttpRequest object representing the current request.
     *
     * @return string
     *   The processed path.
     */
    public function processInbound($path, Request $request)
    {
        if (self::stringStartsWith('/plan/', strtolower($path))) {
            return '/node/1';
        }

        return $path;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        // register our event right before the redirect module redirects
        $events[ KernelEvents::REQUEST ][] = ['stopRedirectIfOurRoute', 31];

        return $events;
    }

    /**
     * ------------------------------------
     * From the redirect module (redirect/src/EventSubscriber/RouteNormalizerRequestSubscriber.php):
     *
     * The normalization can be disabled by setting the "_disable_route_normalizer"
     * request parameter to TRUE. However, this should be done before
     * onKernelRequestRedirect() method is executed.
     * ------------------------------------
     *
     * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
     *   The event to process.
     */
    public static function stopRedirectIfOurRoute(GetResponseEvent $event) {
        $path = $event->getRequest()->getPathInfo();

        if (self::stringStartsWith('/plan/', strtolower($path))) {
            $event->getRequest()->attributes->set('_disable_route_normalizer', true);
        }
    }

    public static function stringStartsWith($needle, $haystack)
    {
        return (substr($haystack, 0, strlen($needle)) === $needle);
    }
}

mymodule.services.yml

services:
  mymodule.path_subscriber:
    class: Drupal\mymodule\PathSubscriber
    tags:
     - { name: path_processor_inbound }
     - { name: event_subscriber }


Adding a "three line" character (☰) or image to TB Mega Menu dropdown button

element:before {content: "☰";} should do the trick. I'm seeing some other problem in there actually. The presence of <i></i> element means there should be a font icon on load, with the i:before reacting as your three bars. Sirate theme, for example, doesn't have it, so it has to be a bug.

Could you provide a live site so we could give you a solution based on it? TB Megamenu could be different as markup depending on the theme. Or your CSS could be changed, based on some Zen stuff.


Where and how should I use Composer and the drupal-composer/drupal-project scaffold to install the required libraries?

I use https://github.com/oomphinc/composer-installers-extender in my projects. It provides an composer installer for any package type.


The links it is referring to are the comment links, statistics links and translation links of a node.

So in a situation where you want just the comment links, it would be

print render($content['links']['comment']);

For more information, see this page.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_pre_render_links/7


How do I exclude a bunch of nodes from being indexed by Solr?

For d7 you are looking for the hook: hook_apachesolr_exclude

Example from the apachesolr.api.php

/**
 * This is the place to look for the replacement to hook_apachesolr_node_exclude
 * You should define a replacement for the status callback and return
 * FALSE for entities which you do not want to appear in the index and TRUE for
 * those that you want to include
 */

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  return FALSE;
}

See here: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.api.php/7

UPDATE

For deleting certain nodes (entities) you can use apachesolr_remove_entity.


Are there hook_functions to handle submissions from the webforms module in Drupal 6?

Take a look at these three hooks.

hook_webform_submission_presave() - which is called before saving.
hook_webform_submission_update() -  which is called after the submission is stored in database
hook_webform_submission_actions() - which provides a list of actions that can be executed on a submission.


Importing Webform Submissions to create content

You can make a view of your results (built-in webform) and with the https://www.drupal.org/project/views_data_export module turn in it into a CSV. Plenty of ways to import that.


Solved that! I should have gone a bit deeper in the Date source code.

The solution is this line:

$render_field_date = field_view_value('node', $node, 'field_date', $field_date[0], array('type' => 'date_default', 'settings' => array('format_type' => 'medium') ) );


As you said, Drush relies on the update status module of Drupal to find code updates.  If you wanted to use this mechanism for your own custom modules, you would have to make a server that had clones of the d.o modules you used, since pm-updatecode works with a single update server, and also has the same xml data structure for the releases of your custom modules.

There are two easier solutions:

Publish your custom modules on drupal.org - very easy, and a great option if your modules can be shared openly.
Just check out your custom modules from git; after running pm-updatecode, iterate over each custom module and do a 'git pull'.

The later could be integrated with drush pm-updatecode, either as a post-updatecode hook or as a feature request submitted in the Drush issue queue (patches welcome).


In the Filter Criteria add a filter Content: Has taxonomy term .

Choose the Vocabulary with your category. In the next step check Expose this filter to visitors, to allow them to change it . Set the Label as you want and "Apply".

Anyway, try to be more specific in your question if you want a better answer.


In which tables and columns data is stored for Story and Page?

This is Drupal way to insert a new node from code.

<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

// save node
node_save($newNode);
?>

Best of luck with Drupal.

You will need to refer Creating Drupal 7.x modules


How to exclude a field when a search is done?

Default Search is not customizable. Consider using one of more advanced solutions:

Search API with client module that will suit your needs.
Finder with proper views configuration.


Drupal 7 module for Password Complexity Rules

You can implement this bit of the rules

  The password must contain both upper and lower case characters: a-z,
  A-Z (network enforced.) · The password must contain numbers and
  punctuation characters as well as letters: 0-9,
  !#$%^&*()_+|~=`{}[]:";'<>?,./@

anything extra is pushing it, plus it is difficult to enforce

You can use this module Password policy for implementing it

  This module provides a way to specify a certain level of password
  complexity (aka. "password hardening") for user passwords on a system
  by defining a password policy.


$head_title is one of the variables passed to the html.tpl.php template file, and set from template_preprocess_html().

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

That variable would be available as $variables['head_title'], if your module implements hook_preprocess_html() or hook_process_html(). Otherwise, you just need to execute similar code to the one used by template_preprocess_html(). To adapt that code for a module, outside hook_preprocess_html() and hook_process_html(), I would rewrite it as follows.

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }

  // Remove the following line if you just need the string.
  $head_title_array = $head_title;

  $head_title = implode(' | ', $head_title);


Why is my form_state being reset after submission?

The issue was in the callback frunction my_action(). I was using the ctools_modal_form_render() function wrong. In the end I replaced the call to ctools_modal_form_render() with ctools_modal_form_wrapper():

function my_action($js = NULL, $nid = NULL) {
  if(!$js) {
    $form_state = array( 'nid' => $nid );
    return drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('My Action Form'),
    'ajax' => TRUE,
    'nid' => $nid
  );
  $output = ctools_modal_form_wrapper('my_action_form', $form_state);
  if ( !empty($form_state['executed']) ) {
    $output = array();
    $output[] = ctools_modal_command_dismiss();
  }
  print ajax_render($output);
  exit;
}


Why cannot I choose MySQL as database type in the installation page?

Create a info.php file and upload it to your server :

 php_info()

upload the file to your server is docroot then visit the URL http://youdomain.com/info.php
search for pdo_mysql and it should be enabled if it does not exist  contact the server admin and tell him to enable the pdo_mysql (https://serverfault.com/questions/471282/how-enable-pdo-mysql) :

  in your case I think you have just the pgsql and SQLite PDO enabled


Including a different jQuery version only on specific page

Here are your options:

Use jQuery Multi, as mentioned in another answer. It can be configured to load the higher version of jQuery just on that page and just for the fancy box. It won't interfere with Drupal's jQuery or with jquery_update's jQuery.
In Drupal 7, you can use hook_js_alter(), which will let you swap out jquery_update's version with whatever you want.
In Drupal 6 with jQuery Update, it provides a hook that lets you alter the JS after it's done doing its thing. You can look at the jQuery Multi 6.x code to see how it uses this hook.
In Drupal 6 without jQuery Update, you can do this using a preprocess_page hook. The $scripts variable will be available there, and you can change it. This can get a bit tricky. You can also see how qmulti does this. jQuery Update also does this in a similar way.

Remember that swapping to a higher jQuery version can break some things in Drupal core and contrib, which is the problem jQuery Multi solves. So if you do this make sure you're not breaking anything. The benefit here is that you just load the jQuery you need, while with jQuery Multi you'll load both.


View | So taxonomy terms plus some links associated with current taxonomy page

If I understand the question correctly:

create a view (table) of the content type that contains the taxonomy terms
add fields as appropriate
add a  Content: Link   field that links to the actual content
under Table Settings, Group by the taxonomy term

This will however, create multiple rows of the each taxonomy term (one for each node in which it is used).

If your intent was to create one row for each taxonomy term with multiple links (one for each node using that term), I don't believe you can do that in Views.


Difficulty to list taxonomy terms in a block for specific content type (d7)

To get the block to appear on certain content types you will need to get the common URL for the content types you are looking to put it on.  You may have to use a module like pathauto to set better URLs for your content.  For example if you are on an article content and the URL is www.example.com/article/3 you would go to the block configuration and at the bottom choose to show blocks only on certain pages.  Then in the text box type the urls of the content types you want them to show on.  Again as Article content type as an example you would enter: article/* or just simply article* like so:


hook_form_alter hiding field only in the form

Have you checked

admin/structure/types/manage/my_content_type/display

Your field is probably hidden here.

Otherwise, hook_form_alter is only for form you are right

An other attribute is :

$form['my_field']['#disabled'] = TRUE;


Drush Segmentation fault when upgrading from Drupal 6 to Drupal 7

Drupal is very sensitive to the order you do things when doing a major system upgrade.  You must follow the instructions in UPGRADE.txt exactly; in particular, if you run updatedb just once, after upgrading your core and all of your contrib code, then the upgrade is sure to go wrong.  The symptoms can vary; I would expect that this is probably what is causing your segmentation fault.

If you look at the UPGRADE.txt instructions closely, you will see that you need to run updatedb on core only, with no contrib modules enabled; after that, you must upgrade your contrib modules one at a time, upgrading their code and then running updatedb for each one.  If a module that has a schema in the database has update hooks that need to run, then updatedb will run them, even if the module is not enabled, so you must be extremely exacting in your code management, or the upgrade will fail.  It is also critical that you upgrade your modules in the right order, because a module will clearly need to have its dependencies available in order to successfully complete its updatedb processes.  If you have a lot of modules, this process can be extremely tedious.

The Drush Site Upgrade command can be used to automate this process to a large degree.  There are still some things that you need to do manually, but it will walk you through the UPGRADE.txt instructions one step at a time, offering to do most of the steps for you automatically.  It will even give you advice about replacement modules for some contrib projects not available in D7, and will run the content migrate code to insure that you CCK content gets upgraded too.

If you go through all of the steps faithfully, and you are still getting a segmentation fault, it could be that your system is running out of memory.  Adjust your settings in php.ini to adjust.  If this still doesn't work, you could be encountering a bug in a contrib module.  When this happens, you can try asking for support in the issue queue of the particular module that is causing you problems.  If this does not get you anywhere, your final resort is to build a new Drupal 7 site from scratch using similar modules, and migrate your data using Drupal to Drupal migration.  In the futue, Drush Site Upgrade will also support the d2d upgrade path, but for now you'll need to do it manually.

Postscript: Understanding what a segmentation fault is is not really important to solving your problem, but there is a good definition on Wikipedia here: http://en.wikipedia.org/wiki/Segmentation_fault.


What is the best way to run HTTPS for drupal commerce

It's hard to say what's 'best', it depends what you mean by that.

If you're just looking for a working solution, the dev version of Secure Pages along with the core patches it recommends works great.

Best thing you can do is install the various options you've identified, do your testing as normal, and ask a more specific question if the modules do something you don't expect.


Filter a view with contextual authored date

Try adding the placeholder % to the path (in the main views UI in the middle column under "Page settings"),

e.g. something like my-view/by-year/% which will accept URLs like my-view/by-year/2019


simplenews subscription form on front page with frontpage module

Try this:

<?php $block = module_invoke('simplenews','block_view',5); print render($block); ?>

The number 5 shouldn't be sent as a string.

And if you are putting this in a textarea on Drupal's backend, you need the PHP input filter, which is generally a bad idea.  Better to go through the theming system, add a region, and put the block there.

http://drupal.org/node/1088718


It sounds like your temp directory is either wrong, or isn't writable.

Visit "admin/reports/status" and fix any problems that are there.

Then visit "admin/config/media/file-system" and make sure the temp directory is set properly and is writable by the webserver.


You can alter the routes (conditionally based on IP) by creating an event subscriber or by using a RouteSubscriber.  You should also look at altering existing routes.


Specifying the default database to store new field tables in

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

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


How do I create menu links programmatically?

In order to create a menu item automatically this can be placed in a hook_update_N on the file mymodule.install and will run when the database is updated (/update.php):

use Drupal\menu_link_content\Entity\MenuLinkContent;
$items = array(
  '1' => 'Menuitem 1',
  '2' => 'Menuitem 2',
  '3' => 'Menuitem 3'
);

foreach($items as $nid => $title) {
  $menu_link = MenuLinkContent::create([
    'title' => $title,
    'link' => ['uri' => 'internal:/node/' . $nid],
    'menu_name' => 'main',
    'expanded' => TRUE,
  ]);
  $menu_link->save();
}

You can also create an entire Menu programmatically:

\Drupal::entityTypeManager()
  ->getStorage('menu')
  ->create([
    'id' => 'menu_test',
    'label' => 'Test menu',
    'description' => 'Description text',
  ])
  ->save();


The file upload in feeds importer is not working

I solved the issue by increasing the PHP upload limit, and the memory limit.


Not sure whether I should call this a solution or a workaround. Anyway:

In D6 I removed audio representation of the filefield. This makes it an ordinary filefield. Then migrated to D7 using the CCK migration kit and then added the audio representation again. Done.


Show or hide field data using java script in node

jQuery will do this for you, but you wiull probably have to either write your own code for list items > 10, or adapt existing code to suit your needs.

There are various show/hide plug ins for jquery. In Drupal the facet api uses a jquery function to do just that as well given it's limit.

Here is the function from facetapi.js

/**
 * Applies the soft limit to facets in the block realm.
 */
Drupal.facetapi.applyLimit = function(settings) {
  if (settings.limit > 0 && !$('ul#' + settings.id).hasClass('facetapi-processed')) {
    // Only process this code once per page load.
    $('ul#' + settings.id).addClass('facetapi-processed');

    // Ensures our limit is zero-based, hides facets over the limit.
    var limit = settings.limit - 1;
    $('ul#' + settings.id).find('li:gt(' + limit + ')').hide();

    // Adds "Show more" / "Show fewer" links as appropriate.
    $('ul#' + settings.id).filter(function() {
      return $(this).find('li').length > settings.limit;
    }).each(function() {
      $('').text(Drupal.t('Show more')).click(function() {
        if ($(this).prev().find('li:hidden').length > 0) {
          $(this).prev().find('li:gt(' + limit + ')').slideDown();
          $(this).text(Drupal.t('Show fewer'));
        }
        else {
          $(this).prev().find('li:gt(' + limit + ')').slideUp();
          $(this).text(Drupal.t('Show more'));
        }
        return false;
      }).insertAfter($(this));
    });
  }
}


Make t() function translate string on template file?

The problem should be solved as soon as the strings are identical.
In the provided code, hello world is not equal to Hello World.

  Matching strings for translation is case sensitive.


I want the view to show no results when the filter doesn't containing anything

This is built into views 3:

Edit your view
Set Advanced | Exposed Form | Exposed Form Style to input required


why "errors validating the config synchronization" when UUID's match?

If you set the uuid to null into shortcut.set.default.yml it will also works ok.


How to add a taxonomy term value as a class?

To append a term's name as CSS class to the term field itself you could simply implement template_preprocess_field() like so:

use Drupal\taxonomy\Entity\Term;
use Drupal\Component\Utility\Html;

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  if ($variables['field_name'] == 'field_MYFIELD') {

    if (!$variables['element']['#items']->isEmpty()) {

      // Get the term ID.
      $tid = $variables['element']['#items']->getValue()[0]['target_id'];

      // Load the term.
      $term = Term::load($tid);

      // Get the term name.
      $name = $term->getName();

      // Make the term name safe to be used as CSS class.
      $name_safe = strtolower(Html::cleanCssIdentifier($name));

      // Append class.
      $variables['attributes']['class'][] = $name_safe;
    };
  }
}


Get more drupal.org project usage information

The usage page comes from project_usage_overview(); it's not a View.  The only parameters are those provided by Drupal's tablesort API, "sort" and "order".

?sort=asc you've already discovered, and the other parameter changes the sort column (?order=Project would sort by project name).


I was able to delete the files via JSON:API (thank god that exists) using Postman.
The FIDs were: 1,2,8,9 - indicating that the files were very early on in the development of the site. I think they may have belonged to article content types that were recently removed (and therefor orphaned) - however I was still able to build the gatsby sites after this.
However, I think it was straight after I deleted the .cache folder from the Gatsby build that I had this issue, so it's possible that I had the images cached, they were then orphaned (during deletion of the 'article' content type.). Although I would have expected that Drupal would have done appropriate deletion of files and records when removing a content type.


Adding html to t() in Drupal 6 template.php?

You should probably look into overriding the pager theme functions instead.

theme_pager_previous
theme_pager_next


Add another button for UI field set in admin

You're looking for the Paragraphs module.

You can use it to create a paragraph type with the required fields in it (reference, specification, etc), than add a multi-valued field to your node type referencing that paragraph type.

Because it's a field, you'll get the standard add another and sorting functionality.

The How to start with Paragraphs for Drupal 8 docs page should get you going pretty quickly.


Is using nodes for a notification system a performance concern?

I would go with Messaging. Dedicated Entity (if implement properly) is always faster than Node. I participated in the big D7 project and we were happy with Message API. By using a custom entity you can switch to custom storage, like: https://www.drupal.org/project/mongo_entity

This can be helpful for D8:

https://drupalwatchdog.com/blog/2015/3/entity-storage-drupal-8-way


Make an exposed node reference filter to show only nodes created by current user

Either it's a bug by the references module or works as designed.

You can accomplish your goal using the Entity Reference and Views Reference Filter modules.

In Views, add relationship of Referenced Entity.

Click the +Add button and add an entity reference view.

Add relationship of Referenced Entity (this is probably already done as it clones your current view) and make field title have a relationship. Remove all other unnecessary fields, if you have them, and just leave the title (make sure you select for This entity reference (override), so it doesn't affect your page view).

In settings, checkmark ☑ content title.

Now go back to your page view and add your entity reference field as a filter.


Getting information from database and giving it to javascript

You should never need to build javascript with PHP, there's just no need (especially in Drupal, which already has a mechanism).

What you should do instead is put your JS in an external file, then use Drupal's JS settings to pass the data. So the JS file might look like:

(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      var locations = Drupal.settings.myModule.locations;
      // Do something with the locations var.
    }
  }
)(jQuery);

And in your page callback or whatever:

$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');


Print preview and Printer-friendly version look different

You have two separate stylesheets.

The 'preview' stylesheet needs to be configured in the CMS. You just enter into a field something like 'print.css' and create that file in your theme folder. This is nothing different than a typical stylesheet you would use anywhere else on the site.

The actual 'print' stylesheet (what you get when you press the print button) that you have declared in your .info file will style the resulting print.


GA Virtual pageview on Webform reload: is there an easier way?

An easier method (that requires no coding) would be to set the webform's "Redirection location" setting to "Custom URL" and enter 'node/%nid?f=my_webform_success'.

This will post the form to itself and also allow you to add some unique key/value to the URL.

Then within Google Analytics you can set a Goal with the Goal URL set to 'f=my_webform_success' and the Match Type set to "Regular Expression Match".


Set Update Manager to install to sites/all/modules/contrib?

To circumvent these (and other) issues, I typically use the Drush command line utility to install and update new modules instead of the Update Manager.

For instance:

drush dl views --destination='sites/all/modules/contrib' # Download views to this path
drush dl uuid --destination='sites/all/modules/contrib' --select # Select other releases
drush en views views_ui  # Enable Views and Views UI
drush up ctools          # Update CTools

Drush also provides a number of other useful commands, and integrates very nicely with other modules. I highly recommend looking into using it if you haven't already!


How to use standard Drupal 7 farbtastic component? jQuery error

The Drupal core's farbtastic works differently. You will have to attach it to a an element eg: a form widget.
Eg:

colour_mod.module

$form['colour1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enter Colour:'),
    '#tree' => TRUE,
    '#description' => '

',
    '#attached' => array(
        'library' => array(
            array('system', 'farbtastic'),
        ),
        'js' => array(drupal_get_path('module', 'colour_mod') . '/colour_mod.js'),
    ),

);

colour_mod.js:

(function ($) {
  Drupal.behaviors.colour1 = {
    attach: function(context) {
                var farb = $.farbtastic("#color_picker");
   }
  }
})(jQuery);


Until someone tells me how an existing field can be reused I have got a remedy. As my "need" was to reuse fields that I have been creating in various vocabularies, what I have done is the following:

Create a function that goes through all the existing vocabularies and checks if a certain field, passed by parameter, exists.
If so, it returns me the name of the vocabulary where it already exists. This saves me from creating the corresponding database table.
Then I check if the vocabulary where the field exists is my own vocabulary. In case it is not, I link it.

This would be the final result. First, the function:
function existsField($field) {
  $vocabularies = taxonomy_vocabulary_get_names();

  foreach($vocabularies as $vocabulary) {
     $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $vocabulary);
     if (isset($all_bundle_fields[$field])) {
        return $vocabulary;
     }
  }
}

Next, the final code:
$vocabulary = existsField('field_image');

if (empty($vocabulary)) {
  FieldStorageConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'type' => 'entity_reference',
     'settings' => [
        'target_type' => 'media',
     ],
     'cardinality' => 1
  ))->save();
}

if (empty($vocabulary) || $vocabulary != $vid) {
  FieldConfig::create(array(
     'field_name' => 'field_image',
     'entity_type' => 'taxonomy_term',
     'bundle' => $vid,
     'label' => 'Logo',
     'description' => 'Logo to represent the term.',
     'required' => FALSE,
  ))->save();
}


How to make vertical tabs display on a custom entity?

This seems to be the reverse of the question remove vertical tabs, and should have a very similar answer.  In the documentation for the vertical tabs module, the first code snippet is how to enable vertical tabs on any form.  The second snippet looks more appropriate, as it is how to enable tabs from your custom module that creates your custom entity.

<?php
$vtabs = variable_get('vertical_tabs_forms', array());

// Enable vertical tabs on a form.
$vtabs['my_form_id'] = TRUE;

// Disable vertical tabs on a form.
$vtabs['page_node_form'] = FALSE;

// Enable vertical tabs but be selective of which fieldsets are included.
$vtabs['page_node_form'] = array('menu' => FALSE);

variable_set('vertical_tabs_forms', $vtabs);
?>

Edit:

The site variables here is a huge array that is always accessible to drupal.  Some of these settings can be stored in your site's settings.php file, as this variables array is present even there.  However, because of the nature of the change that you desire, I think the best choice for you is to have a hook_install in the module that defines your custom entity.

Assuming module name "your_entity", add a file "your_entity.install" to the module.

function your_entity_install() {
  // Enable vertical tabs on entity form.
  // this is supposed to be true as long as this module is enabled
  $vtabs = variable_get('vertical_tabs_forms', array());
  $vtabs['your_entity_form'] = TRUE;
  variable_set('vertical_tabs_forms', $vtabs);
}

Then disable and re-enable your module.  These variables can be set in the form_alter, but that would only be recommended if you needed the value to change based on other information that is not present at an earlier time.


The problem ended up being a server space issue. Increased space and the images were able to load.


Displaying articles created by user in profile page using views

Create a view for content of type all
Inside the view display node title and all other fields as per your requirement.
Add a contextual filter content : author uid
While adding that you will have a option for provide a default value
select that option and inside that use filter by 'currently logged in user'.
Save it by this you will be able to see all the nodes of current logged in user.
Inside the path you can enter just any path like '/my-nodes'. and you are done.
If you want you can avoid providing default value and switch to manual input
by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).

For user name you can add a relationship content author:uid then
 in the contextual filter use User name with relationship author:uid


Failed asserting that two strings are equal in a patch

It looks like the problem might have to do with HTML escape sequences for quotes, ampersands and other meta-characters (at least in part).

Compare these lines:

-  content: '/* \" \' */';\n
+  content: '/* quot  */';\n

and these:

-}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon & escaped double \" quotes \"."}q:after{content:' (brackets & escaped single \' quotes \') '}q:after{content:"I'm Quote"}'
+}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon &amp; escaped double \&quot; quotes \&quot;."}q:after{content:' (brackets &amp; escaped single \' quotes \') '}q:after{content:"I'm Quote"}'

Hopefully that sets you on the right path. Don't just look at your diff, look at the PHPUnit test to see exactly what test you are failing. Good luck!


As already mentioned in the comments, you could parse the HTML from the web page and extract the node ID from a class value.

But that's very messy, and it'll break if Drupal.org changes its markup for node pages.

A more robust approach would be to use the API, and consume the project's update feed. That feed contains the raw URL of the project node, from which you can get the ID.

I'll leave the PHP implementation to you, but the steps are as simple as:

Load a DOMDocument up with the contents of https://updates.drupal.org/release-history/MODULENAME/all.
From the root node, select the first <release_link> element and extract its value.
Extract the nid from that URL.

I realise that method also relies on the XML not being changed, but I think that's less likely to change than the markup on the HTML version.


Is it possible to remove classes from a field that uses the Rendered entity format?

Generally:
You could modify the display of the content type referenced by the Entity reference field. There you can use Display suite again for formatting the fields of the referenced content type and have it styled your way.

Especially, regarding this:

  Configure

Edit

Delete

Manage display

There is an option "Display Links" on the Rendered Entity. If you uncheck this, you can get rid of this code. This is done in the content type where  the Entity Reference field is included, not in the referenced conten type.

If you want to change this:

Go to the content type you are referencing and check the display. It seems you are using the 1 Col Display, so you can use ds-1col.tpl.php template. There you can change the classes.


How to solve my Field mapping problem during import of Registration codes?

Preparing your cvs file
First remove all the column names from the first row, otherwise they will be added and will throw an error, as they won’t be in the correct format.
Drupal Regcode import tab
You can map to the following six fields:

begins: When code should be active from in date format
expires: When code should expire in date format
code: The registration code text format (for numbers and letters) and should be unique
is_active: Whether the code is active text format ‘Yes’ or ‘No’ Default is Yes
maxuses: Maximum times the code can be used number format default is 1
uses: Number of times the code has been used number format default is 0

If your cvs file codes are in the first i.e column one (A) then you would map it as code and if the next column is maximum times the code can be used then you would map as code, maxuses separated by a comma. Note: no colons.


Pass book node id as second parameter to drupal_block("book_navigation")?

After digging into the Book module code, I discovered that in a twig template (with the twig_tweak module installed) I can use

    {{ drupal_block("book_navigation", {block_mode: "book pages"}) }}

to create a list of chapters for only the current book (which is what I need). This is equivalent to the configuration option "Show block only on book pages". Probably in documentation somewhere, but much googling didn't find it for me.


Drupal offers a helper function for building URLs in Twig templates.

{{ url('entity.node.canonical', {node: nid}, {query: {foo: 'bar'}}) }}


Create View with 2 rows of diferent Content

Views Node Split module does what you are trying to achieve.

  This module allows site administrators or builders to have a different view mode for the first nodes of a view result


How to fetch list of published webforms from webform module?

In Drupal 7 it would be something like:

$nodes = node_load_multiple(array(), array(
  'type' => 'webform',
  'status' => 1,
));

Have a look at the docs for node_load_multiple. You could (and probably should) also use EntityFieldQuery as mentioned in the docs. The given examples assumes that you use the default webform content type.

You could then use the $nodes array to build options for a Form API select element:

$webforms = array();
foreach ($nodes as $nid => $node) {
  $webforms[$nid] = check_plain($node->title);
}
$form['available_webforms'] = array(
  '#type' => 'select',
  '#title' => t('Webforms'),
  '#options => $webforms,
);


Please try this. may be it will help you.

**Your Code:**
$form['more_info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Additional Information'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,

  // Expand the expand_more_info fieldset if the box is checked.
  '#states' => array(
    'expanded' => array(
      ':input[name="expand_more_info"]' => array('checked' => TRUE),
    ),
  ),
);

Instead of that you can try it in another way which is mentioned below in hook_form_alter() function.

Example:

$form['more_info'] = array(
                          '#type' => 'fieldset',
                          '#title' => t('Additional Information'),
                          '#collapsible' => TRUE,
                          '#collapsed' => TRUE,
                     );

**$form['more_info']['und']['#states']**= array(
                                'expanded' => array(
                                 ':input[**name="expand_more_info[und]**"]' => array('checked' => TRUE),
                                ),
                             );

Note: you can use 'visible' instead of 'expanded'.
you can try this in your custom module or template.php


drupal 7 webform add classes to submit button

You can do this hook_form_alter(). As all the form element are available in hook_form_alter.

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'webform_client_form_YOUR_NODE_ID') {
        $form['actions']['submit']['#attributes']['class'][] = 'newclass';
    }
}


How can I monitor the number of user password reset requests?

Note, in user_pass_submit

watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));

There's already a watchdog log entry created when the user requests a password reset.

Perhaps you can simply monitor the watchdog log at

Admin > Reports > Recent log entries?


Problems connecting to database in drupal 6

All of those values are set in $db_url, in the sites/default/settings.php file.

$db_url = 'mysqli://username:password@server_ip_or_host/databasename';


How can I bypass required fields when saving a node as unpublished?

There's the Require on Publish module. You'll have a checkbox for all fields beneath the default "Required" checkbox that says "Require on publish". So you need to have the default "Required" checkbox unchecked and just check "Require on publish". Quite clever actually.

This module allows fields to be required only when the piece of
content is being published or is already published. This can be used
when you have fields such as tags or SEO information on your piece of
content that editors really don't need to fill in until the content is
going live.
Usage
When managing a field for a content type, click the new 'Required on
Publish' checkbox instead of the 'Required field' checkbox.


I would try the following.

Take a backup of the database. Backup and Migrate makes this easy.

Make sure core and modules are up to date, especially Pathauto and Token.

Browse to admin/config/search/path/patterns, and set the path pattern to [node:menu-link:parents:join-path]/[node:menu-link].  Credit to Menu path in Pathauto.

Browse to admin/config/search/path and delete the bad aliases, or admin/config/search/path/delete_bulk and just delete all the content aliases.  Be careful here, and make sure you have a backup.

Spot check a few nodes, and make sure the "Generate automatic URL alias" is set.

Double check that the nodes have a menu entry set on the node edit page, and that the parent is correct.

Double check the menus and make sure that the links have the paths set to node/XXX.  You need to click the EDIT link to see this.

Browse to admin/config/search/path/update_bulk to create all of the aliases for the existing nodes.

Clear Drupal cache from admin/config/development/performance

That should work.


Implementing LDAP with exsisting user base

You could try having them create the new LDAP accounts and then merging the users. User Merge

  This module helps users to merge together duplicate accounts. It uses a hook system so other modules can do whatever they need to manage their relationships to users.


Confirmation message not getting rendered when printing the elements seprately in twig and ajax is enabled

You need to still include {{ title_prefix }} and  {{ title_suffix }} in your template

In the comments in the default webform.html.twig it gives a short description of the default variables "Additional output populated by modules" which includes essentially anything else apart from the form elements themselves


Should you use multi-site or multiple Drupal instances to host different content for subpath sites?

Subsites should work for Drupal 7 as well (assuming this is what you're working with).  I've found these instructions helpful in the past: http://drupal.org/documentation/install/multi-site

If the company subsites you are running are under one parent company where there is one body of management (a common decision maker), then subsites makes sense.  If they are different companies which may want very different functionalities for their sites, then it may not be wise to combine them into subsites which rely on the same code.


Where to put a personnalized copy of a layout from layout_discovery?

I putted my layout in drupal\themes\mytheme\layouts\twocol\layout--twocol--node-end-of-a-suggested-name.html.twig and declare it in a mytheme.layouts.yml file at the root of my theme and it worked.


How can I sort a product display view by product popularity

Commerce Product Popularity provides a Radioactivity field for popularity.


Should I ignore the vendor directory in git for Drupal 8?

There isn't really a right or wrong answer, it will come down to your situation. Composer themselves have pretty strong feelings that yes, you should ignore it, and in an ideal world that's definitely what you should do, but it's not always that straightforward.

It depends mainly on your hosting and deployment process. If, for example, you're on Pantheon, and don't wish to implement a complicated upstream workflow, involving a dialogue with their technical staff, you're forced to commit all dependencies to the repo. There's no Composer sitting at the other end waiting to run when your code is pushed, if you don't push those files up yourself, they're not there, and things will break.

Similarly if you're on shared hosting and don't have a CI workflow, you're probably going to be forced into lugging all the files around with you in one way or another.

Basically if it fits into your development/deployment workflow to be able to exclude those files, it's a good idea to (for the reasons listed in the link above).

If it doesn't, committing them to the repo is absolutely fine.


Show a list of my product with my coupon discount

==UPDATED==

Looks like you need views integration for the UC Coupon Module, not fully supported yet.

Maybe you want to try and port this patch to Drupal 7?


How do I get the token for a date field type to display as a custom format?

A date may be a range, therefore [node:field_date] cannot be considered as a date token. Install Entity API and enable the module "Entity tokens" to get access to the actual date value,
Beware that for an obscure reason Entity token replace the underscore ([node:field_date...) of the original tokens name by a dash ([field-date...), you will then have access to a properly formatted date (in my case "[node:field-date:value:custom:Ym]", in the original question I guess therefore "[node:field-fact-sheet-date:value:custom:F,Y]")


Sorting entities in a view by a field in a 'sibling' entity

(1) you cannot do this simply by editing the view, but (2) you can do this with a custom module. I expand on (1) and (2) below.

(1) holds because there is no single ;-terminated SQL query which will do this. The reason is that when you have 2 profile2 profiles the data you're fetching is spread across 4 tables structured like this. As you can see from that, the 2 profile2 tables reside in separate tables, and you can't tell that they belong to the same user except by checking a 3rd table. SQL queries simply can't manage this.

(2) is possible because a custom module lets you run multiple lines of PHP, drawing on additional query to fetch the field you want to sort by. You want to do this in hook_views_pre_render. Here's a module I created to do something similar on an existing site I had: http://www.pastebucket.com/40183


Assuming you're using the default admin theme you should see a tab on each user edit page for each profile type in the top right hand corner, e.g.

You should also see a tab on the user page itself for each profile type, the fields are displayed in there.


Stop Drupal from encoding '&' as '&' in YouTube URLs

Try disabling the HTML corrector on the text format. Also, though, I don't think URL-encoding amphersands in URLs actually breaks them. & should work as a query string parameter separator as well. If not, though, see my suggestion :)


How to determine if a translatable field has translation enabled?

To check if the translation is enabled on a field:

if ($entity->get('name')->getFieldDefinition()->isTranslatable()) {
  // The field translation is enabled:
}

which is by the way the same field definition you get in your code example, only here it is retrieved from the field directly. There is no difference between translatable and translation enabled as long as the entity is translatable.


hook_menu, display a form at the top and table at the bottom

Here's an implementation of my earlier suggestion to append the table as a form markup and rendering the form with table in the menu callback

/**
 * Form builder function
 */
function mymodule_form() {
  $form = array();
  $form['sometext'] = array(
    '#type' => 'textfield',
    '#title' => t('Some random textfield'),
    '#default_value' => 'Hello world',
  );
  $form['tablemarkup'] = array(
    '#markup' => my_module_table(),
  );
  return system_settings_form($form);
}

/**
 * Callback function for returning form with themed table
 */
function mymodule_page() {
  $output = array();
  $form_data = drupal_get_form('my_module_form');
  $output = drupal_render($form_data);
  return $output;
}

/**
 * Function to return themed table.
 */
function my_module_table() {
  $header = array(
    'data' => 'Table title',
  );
  $rows[] = array(
    'Table data value',
  );
  return theme('table', array('header' => $header, 'rows'=> $rows));
}


How to avoid "The form has become outdated" after login in separate tab

The error is related to form CSRF protection, the error message comes from core form validation.

To avoid the error, it's possible to remove that CSRF token validation check in hook_form_alter e.g:

function my_module_form_alter(&$form, &$form_state, $id) {
  if (strpos($id, 'webform') === 0) {
    // Bypass per user CSRF token check and allow cache.
    unset($form['#token']);
  }
}

The caveat is, the form will no longer have default CSRF protection.

Alternatively, you might be able to detect the user has logged in (e.g custom local storage set event) and reload the original page to refresh it as is.


Why does default.settings.php suggest writing the value of the hash salt in an external file?

The main reason to do this is to prevent the salt from accidentally being committed to your content versioning system.

Most advanced hosting environments (both Drupal hosts and all-in-one Drupal stacks) provide ways to do this.

Similarly, it is useful to go through the trouble of abstracting DB settings and the like, both for security and to make it easier to move your code from one environment to the next.


Drush has built-in functions to handle I/O.

If you're using Drush <9.x, there's the procedural drush_confirm() that will prompt a user for a response to a given message. If you're using 9.x+, any custom command class extending the DrushCommands class will have access to the $this->io()->confirm method which does the same thing with Symphony's CLI components.

See the latest Drush docs for more info on I/O.


I found that Semantic Views worked best for me in this situation. It cuts down on the amount of HTML outputted by Drupal Views and allows you to define the HTML tag that wraps each field as well as add a CSS class.


Theming a node reference field in a template file

Hi you can use theme_render_template() function like below.

$subject_node_object = node_load('node/' . $node_id_from_ref_filed);// Pass your node ref here.
// Use below code in your course node template.
print theme_render_template(drupal_get_path('theme', 'YOUR_THEME_NAME') . 'PATH_TO_TEMPLATE/subject-node.tpl.php', $subject_node_object);

You need to create a template for you subject content type fields.


Use Drush. The following commands worked for me.

drush updb -y
drush cr


Css from zenbased theme not getting processed

This is a good checklist for resolving css bugs - I would suggest two more that I've used when stuck on css bugs that may help you resolve this quicker next time.

Check the element in firebug or developer tools to confirm whether the CSS file you think should be loaded actually is and what css styles are actually being applied to it. In this case, you could have determined that the file was loaded but the styles weren't so you could isolate your debugging to the syntax of the statement.
Try using an external validator on your css file, like:

http://jigsaw.w3.org/css-validator/

Most of the feedback from this will be noise but it may highlight syntax errors in your file.


Flex Slider issues after upgrading Drupal to v7.39

Don't know why but in the admin/config/development/performance section I unchecked the compress javascript option, saved the page and suddenly my flex-slider images returned.  Strange though, isn't it?

Anyway - solved.


Form select option results in "Illegal Choice has been detected"

That's because the form gets generated both upon output and submission, and you're using form values that are time-dependent. When you first output the form it generates options like this:

1313615248
1314220048
1314824848
1315429648

And when a user submits the form, it will generate new values, with a few second difference:

1313615268
1314220068
1314824868
1315429668
(+20 second difference)

So none of the previous options are present here. Drupal's validator by default checks if the submitted option is among generated options.


How to rearrange EVA fields in profile2?

I installed Profile2(7.x-1.3) and Entity Views Attachment(7.x-1.2) on Drupal 7.34.

When you create two eva fields in your respective views and set "Entity type" as Profile and Bundle as "Your profile name" as shown in the following figures: Entity Type - Profile, Bundle - Custom. "Custom" is the name of the profile I created.

After saving the views with their respective eva fields , the fields for display automatically appear in the "Manage Display" tab of your profile as shown below(note the fields with prefix EVA) :

Here you can reorder EVA fields with ease.

And this is how the views are rendered in the user's profile page :

I included above screenshots, in case you have missed some settings. If you still can't see the required fields, then create a new issue here for EVA or here for Profile2. Hope I could be of help. Please excuse me for my late reply as I am new to Drupal.


How to show an image instead of a tab title for a field group?

Each tab has a unique CSS id or class you can use CSS background-image and text-indent to hide the text of a field.


Merge two fields using Display suite, like views inline fields

Here's a list of possible approaches:

Code field: You can accomplish this with a custom code field in Display suite. A code fields supports usage of tokens and html. Additionally, you can use a Display Suite code filter to use php itself. More info found here: http://www.youtube.com/watch?v=mvFP16PJt4c
Use a Custom formatter: If you need more heavy processing you can utilize the custom field formatter module.
Preprocess Field: Additionally, you can access variables that are preprocessed via a "preprocess field". A preprocess field will print out the value of the key in the $variables array. Lullabot has an example on using the preprocess field.
Entity Views Attached: This might be a bit extra overhead but if you download the eva module you can create views and pass the current NID in and combine fields through views. This is often helpful if you need to create various different photo galleries with different fields, etc.


The best way to synchronize old host and new host when migrating a Drupal site?

I think you're on the right track. It is nearly impossible to implement a migration project and not plan for incremental updates. The migrate module supports that with its "update" function (as shown in the screen shot).

That said, there shouldn't be a problem of duplicate UIDs after the initial migration of data, unless you are letting people create accounts on both the legacy system and the new instance.


Step 1 - Use VBO and Rules

You could process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list of nodes that you want to be processed (ie those for which the date field matches your criteria).
Add a loop to perform a Rules Action, for each node contained in your Views results.

For any node related data you may need in your Rules Actions, make sure that they are contained in the Views result.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

Step 2 - Trigger the rule

Use the "Rules Once per Day" module to actually get your rule triggered. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt the rule from Step 1 to run ... once a day, on any day.


How to get values of delta field from "block" table in drupal 7 from the database for the activated theme in a custom module?

SELECT delta,
FROM  `module__block`
WHERE theme LIKE  'business'
LIMIT 0 , 30 ;

shows only blocks.

SELECT delta, theme
FROM  module__block
WHERE theme LIKE  'business'
LIMIT 0 , 30;

It will shows both the block names and theme name.


Select List value in an If statement - Computed Field

Write the following code under Computed Code (PHP) texarea in computed filed settings

$calc =  $entity-> field_sample['und'][0]['value'];

if($calc == 'AM')
{
 //action
$entity_field[0]['value'] = 'After Meridian';
}

elseif($calc == 'PM')
{
//action
$entity_field[0]['value'] = 'Prime Meridian';
}

This is a sample tested code which prints the selected item at output of computed field.

Note: replace filed_sample with your select list field machine name.


How to display a message even when user is logged out?

Try removing the return statement at the end of your submit or even replacing it with a drupal_goto('reset_psw').

There are lots of similar questions on google and S.O., you could have a look.

UPDATE

You should use the validate handler for such a case, this simple example should get you going https://www.drupal.org/node/717740


How can I require that browscap.ini / get_browser() is functioning before allow a my module to be installed?

I fixed it using the following code:

/**
 * Implementation of hook_requirements().
 *
 */
function aserv_support_requirements($phase) {
  $requirements = [];

  if ($phase == 'install' || $phase == 'runtime') {

    if (!get_cfg_var('browscap')) {
      $requirements['aserv_support'] = [
        'title'    => t('Browscap not installed'),
        'value'    => 'Browscap has not be installed. Please install Browscap before enabling this module.',
        'severity' => REQUIREMENT_ERROR,
      ];
    }
  }

  return $requirements;
}

/**
 *  Implementation of hook_enable()
 */
function aserv_support_enable() {
  if (!get_cfg_var('browscap')) {
    drupal_set_message(t('ERROR Enabling Aserv_Support: Browscap has not be installed. Please install Browscap before enabling this module.'), 'error');
    module_disable(['aserv_support']);
  }
}


programmatically create one bean block to the default theme

I used hook_block_info_alter(&$blocks, $theme, $code_blocks) to alter the blocks in my custom modules .module file

inside of my  hook_block_info_alter i wrote an if statment

if($blocks['bean'][$key]['theme'] == variable_get('theme_default', '0')){}

to make sure I was only altering regions only for my default theme


This code is actually correct. When checking for an object, it's always a good idea to use isset() to make sure the variable exists!

This code was adjusted to the following:

function mymodule_node_insert($node){
  if (isset($node->form_id) && ($node->form_id == 'whatever_node_form')) {
    // do stuff
  }
}


Custom module - find out the name of the field

OK. I ended up doing it a little differently:

In my field_widget_form function I added a hidden field. In this function it is possible to access the $field and therefore the name of the field using

$field['field_name'];

So I saved that value to the hidden form. Then when I trigger a function within that form it is able to access that value. So in my different function that relies on the machine_name of the field I actually access the value of the form that is set when the widget form is built.


MailChimp campaign not showing up in Drupal 7

You need to have libraries 2.0 module installed and download a special mailchimp API library.  https://drupal.org/documentation/modules/mailchimp


How to assign uid in "users" table with imported users?

Inserting data directly into Drupal tables is generally a bad idea (until you are familiar enough with the database schema to know what you're doing). For programmatically inserting users there are functions like user_save() and drupal_form_submit() that you can use.

As for generating the unique uid: if you can't just provide incremental values in the data insertion loop then you might be able to use the following code instead (copied from user_save() function):

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

I'm not familiar with the Migrate module so I don't have more specific advice to offer currently, but the above info and links should be helpful.


You can create a view and go to Format section and display it as content then select the view mode you want. After that go to  admin/config/system/site-information and change the Default front page to the view that you have created.


How can users share entities if they have a relation?

Do you know about Node Access Relation, it sounds like maybe you want to use it.

  You use or plan on using the Relation module and want to grant users
  access to view/edit/delete content based on their relations.
  You find
  Drupal roles too broad but per-node access controls too much to manage


How do I set a tag via cookie and filter content on the whole site based on that tag?

you can build a view to show your content, then add a "filter" for the city term and "expose it" to your visitors. There is an option to remember the selection for each user.


Override display of content type using Views

Use Panels instead, are designed for this very reason, and more.

Alternatively do this: Create a new node display (admin/structure/types/manage/node_type/display) with all fields you want and in Views, below "Format" there is a "Show" option, change it to "Rendered entity" and choose the node view you have created. The downside of this method is that all views advantages like: "Rewrite results", "Style settings" etc are not available, ds or preprocess functions should lift this weight if need it.


Migrate existing dev desktop site from PC to Mac without existing db dump

DevDesktop stores the mysql databases in its application installation folder.  Assuming, you installed to the default location, in your PC backups, navigate to C:\Program Files (x86)\DevDesktop\mysql\data
This folder contains a copy of the MySQL databases.

Restoring to PC for use or export:

On the PC (assuming you haven't installed any other devdesktop sites), copy all the files and folders from the mysql/data backup directory into a fresh install's MySQL's data directory.
For export:  Start MySQL and export a copy for backup purposes/importing elsewhere as needed.
For immediate use/development on PC: Start MySQL and your DevDesktop to confirm the site is running; resume normal dev desktop development on PC

Loading directly to a fresh install of DevDesktop, MAMP, Vagrant, or other MySQL service on Mac

You could also copy the contents of that backup folder directly to the corresponding mysql/data backup directory on your Mac.  NOTE: copying the entire directory will wipe all existing databases/user accounts in MySQL on your Mac's MySQL server, be sure to back it up first if you have existing data).  If it's a fresh install of DevDesktop (or other) on the Mac, copy all the files and folders from the mysql/data backup directory of the PC to the corresponding folder on the Mac.
Start DevDesktop or other local webserver app to confirm the site is running; resume normal dev desktop development on Mac

Merging with existing mySQL data, hosting database along side others on existing install of DevDesktop, MAMP, Vagrant, or other mySQL service on Mac

If you do have existing MySQL data on the Mac (be it MAMP, DevDesktop, Vagrant instance or other), backup the corresponding /mysql/data folder from that application.
Replace with the backup folder from the PC
Start MySQL and export the database.
Then swap the original Mac MySQL data back into place.
Restart MySQL and import the database backup you just exported.
Now you have both your PC devDesktop database and Mac databases available on the Mac.


I think you need to do an isset($node->field_tags[$node->language]), if it is empty $node->field_tags[$node->language] will not exist. Could you check if it is only articles with the empty field_tags that are affected?


The theme layer loads after your module has, so you won't be able to modify that part yet. I think you can just set the weight on your functions: http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

Or just rename your ID's and classes to be specific to your module to reduce conflicts. I usually would name my ID's or classes nothing to generic, usually a shorthand for the name of the module then the name of the id or classes i want to reduce conflict.


Create a View (using the Views module) that shows Content and displays a Grid of fields in Display format. Add the field Updated datein the list of Fields. Be sure to select Published: No in the Filter Criteria. You can add other fields if you want (e.g. Title). This will get you the date of the last update. If the node is not edited after being unpublished, the unpublished date will be the last update.

EDIT:
If you specifically want to show the unpublished date, I am not aware of a module for this. I suggest another approach that is a bit circuitous, but it works. It involves creating a date field to store the unpublished date, and using Rules to set it when the node is unpublished.

Download the following modules: Date and Rules.
Edit your Content Type. Create a date field
Create a Rule that reacts to After updating existing content of type XX. Add a condition node:status equals unpublished
The Action should be set the date field value to now

That's it. Now, if you want to hide the date field in the node edit form or display, you can play around with your theme's CSS classes or explore other modules. Let me know if you have questions


How to get main menu to highlight the link to the current page?

normally this is accomplished via css in the theme, with the active attribute:

li a.ctive {
  ...
}

it is not core functionality. You could look at the different -child pseudo-elements to tweak it, or use some JS, but I think that portion of the question would be off-topic here - you are better off asking on stackoverflow


What's the best module to serve mp3 or audio files securely? Problem with jPlayer, etc

For a real good private file protection use the Private Files module.


Updating to Drupal 7.x-dev until next stable release

No you are not: the Drupal core development workflow makes minor versions just tags of the main 7.x development branch. Periodically, the branch maintainer decides enough things have been committed to the branch to make a release worthwhile, and a new minor version release is packaged.

So let's say you download a snapshot of 7.x-dev dated 2011-08-15. At the end of the month, Drupal 7.8 is released. Drupal 7.8 would contain all of the changes you had received in the 2011-08-15 snapshot, and anything else committed between that point and the end of the month. It's essentially the same as if you downloaded a new development snapshot on 2011-08-30.

So, if you need to use the dev branch, feel free to do so with relative impunity.


Programatic output of views block breaks jquery

I would assume you are just missing the jQuery Cycle plugin.  You might try adding

drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/js/jquery.cycle.all.min.js');
drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/contrib/views_slideshow_singleframe/views_slideshow.js');

before outputting the view and see if that works.


You want to use Organic Groups, and if needed, Role Delegation. I think you can get by with just Organic Groups maybe ... Drupal core can send out notifications of new accounts by itself upon account creation.

Orangic Groups is a contrib module:

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

  They do so by posting the usual node types: blog, story, page, etc. A
  block is shown on the group home page which facilitates these posts.
  The block also provides summary information about the group.

  Groups may be selective or not. Selective groups require approval in
  order to become a member, or even invitation -only groups. There are
  lots of preferences to configure groups as you need.

A synopsis from Role Delegation project page is:

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.

Fully understanding and leveraging these modules to fit your workflow, business logic, etc is a task I leave up to you. Your question is far from simple.


Yes, it's possible. I would recommend using role based pricing. Customers who deserve the special pricing should be given a specific user role. Then on the product type, add a secondary price field used specifically for users with that role. Finally, add a product pricing rule that checks to see if the order owner (i.e. commerce-line-item:order:owner) has the user role. If so, you should swap in the price value from the secondary field using "Set the unit price to some amount" and fetching the secondary price using the appropriate token. Remember that you'll have to first run an "Entity has field" condition on the line item to find its product reference field and again on the product to find its secondary price field.


Fatal error: Cannot use object of type stdClass as array in

There are two related but distinct concepts that seem to be conflated in your code, i.e. hook_form, and the notion of a drupal form builder function. Hook_form uses the template explained by @gisleHannemyr.

The template for a form builder function is:

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

Use hook_form to create or override node creation forms, and a form builder function for any other (non-node-related) form.

If you simply want to alter an existing (node or other) form, you should use hook_form_alter, instead.


Load Preceding Nodes in a View Block Sorted by Date in Relation to the Current Node

<?php

$curnode = menu_get_object();
if (!$curnode) return '';

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('created', $curnode->created, '<=')
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 10); //CHANGE RANGE FOR YOUR LIMITS

$result = $query->execute();

$items = array();
if (isset($result['node'])) {
  $nodes_nids = array_keys($result['node']);
  $nodes = entity_load('node', $nodes_nids);
  foreach ($nodes as $node) {
    $items[] = l($node->title, 'node/' . $node->nid);
  }
}

return theme('item_list', array('items' => $items));

?>


Create an expiration date field that auto expires

You can use Scheduler to unpublish the node (and then optionally use Scheduler's hooks/events to delete the node). However, to get the date set into the Scheduler unpublish_on field, you could use Rules (reacting on 'after creating' event) or use your own custom mymodule_hook_save() to set the date.

We are also in the process of migrating Scheduler's actions and events for Rules, (see https://www.drupal.org/node/2651348) and I think that Rules would then let you delete the node reacting to being unpublished by Scheduler.


You should use java-script and the iframe support in color-box.

<script type="text/javascript">
  $(document).ready(function() {
    $("a", ".the-class-added-to-links-clicking-which-will-open-theurl-in-coloyxbox").click(
      function(event) {
        event.preventDefault();
        var elementURL = $(this).attr("href");
        $.colorbox({iframe: true, href: elementURL, innerWidth: 645, innerHeight: 509});
      });
  });
</script>

Code Source : https://stackoverflow.com/a/8933655/493742


When you click "edit":
 Drupal will take you to the page where you can delete that term; right beside the "save" button:
 For bulk deletion you may take a look at the taxonomy manager module.


is getString() returning translated content?

you can check translation with something like

if ($entity->get('field_anc_label')->getFieldDefinition()->isTranslatable()) {
  // The field translation is enabled.
$links['node']['#links']['node-readmore']['attributes']['title'] = $entity->field_anc_label->getString();
}else{
$links['node']['#links']['node-readmore']['attributes']['title'] =
t($entity->field_anc_label->getString());
}


Copy multichoice-alternative.tpl.php to your theme's templates folder. Make your changes in this file.

In your theme's template.php file you are also allowed to create process and preprocess functions for any theme function. So, you could create

function THEME_preprocess_multichoice_alternative(&$variables) {,

wherein you could add/subtract/alter any variable within $variables. This would allow you to pass such variables through to the multichoice-alternative.tpl.php file, which in your case now resides in your own theme's templates folder.

As to overriding the class, first see if what you need done can be done in the theme layer. If that fails you can always create your own class to inherit from class MultichoiceQuestion, make your changes, then look for the code instantiating instances of the parent class and replace with your own class. And if you do make a note so that when you upgrade the module you can make the changes again.

BTW, it is the norm in Drupal  to put more complex processing (PHP) in the default template process and preprocess functions instead of the template file, and to just put enough processing in the template file to print out the variables and do some conditional logic to assist with that.


Make a field in a Views block visible ONLY to the acccount/profile owner

Create the block without the edit link. Then implement function hook_views_pre_render in your theme.

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after. Altering the
  content can be achieved by editing the items of $view->result.

  This hook can be utilized by themes.

Within this you do a conditional check to see if currently logged in is the same as profile owner, then if so add the link to $view->attachment_before

I think you would get quite a lot of answers on this question as there are so many ways to do it.

If you want to do it without coding I think you might get it right with Views arguments in filters installed. You create the link field in an attachment to the block using the currently logged in user as contextual filter, then (via installed module referenced) do the conditional check in your filters section of views on this attachment.


Why does the "admin/modules" page show up in the wrong language?

I did a similar verification in one of our sites, which has 3 languages (EN, NL and FR). I disabled the "module_filter" module, so that I could see what the result would be if I look at what's shown on admin/modules. I also use "admin menu", but for my verifications I've not experimented with anything related to that menu (I just wanted to check what the CONTENT of  admin/modules actually is, depending on the language I used. And I experimented with EN and NL (=Dutch), assuming that FR would give similar results like NL. And I've been using the (same) Seven theme for admin

To actually do my experiments, I've enabled the "language switcher block" so that it is shown within my theme used for Administration. I have this block shown in the "Content" region above the block "Main Content Page" (so that I can switch between EN and NL for my experiment). BUT: nowhere in the question here it says anything about using that "language switcher block". So that's already something for you to check: you are aware I assume about how to use that block for switching languages, right?

Anyway, when I then use that language switcher block to switch from EN to NL, PARTs of what is shown on that page is in NL (Dutch), though other parts remain in EN. E.g.:

the descriptions for my modules (from the .info files) are shown in Dutch
but the strings like "Requires" and "Required by" are NOT translated in Dutch. Though the values like "(enabled)" or "(disabled)" or also translated to NL, like to "(ingeschakeld)" or "(uitgeschakeld)".
the (hardcoded) tekst near the top, like "Download additional ..." is NOT translated.
typical messages (in green, yellow or red) near the top are translated to NL also.
Module names, like "Color" are not translated (to something like "Kleur").
links like "configure" are also translated to "instellen".
module groups like "Core" are translated to "Kern".

With all this, I have the impression that by using the "language switcher block" and setting it to the NL-language, this admin/modules page gives me an "as good as it gets" translated version of that entire page. But if you don't use that  "language switcher block" (to switch to NL), then everything remains in EN (of course). And for things that are not translated, I guess that's because it's either not using the typical t() function, or the required translated string is still missing (for NL in my case).

Not sure to what extend it will actually answer your question, but at least it should help to understand what is happening, and how the "language switcher block" seems to be part of the puzzle.

But, don't worry ... D8 has a lot of improvements for multi-language stuff (not sure yet about this specific "issue" however ...).


No, there isn't.

I maintain the Translation Management Tool project, that offers a way to export nodes and other translatable content as XLIFF. There is no POT export option but it should be possible write an export format for that.


Try:

drush dl delete_all

You have to check the project URL:

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

And use the last part, the project machine name.

The delete-all string is the drush command provided by this module.


Where is the "add to cart" configuration?

Go to the 'Order item types' page and click the "Manage form display" link for your order item type. You will then see a tab for the "Add to cart" form display.

For the 'default' order item type the url will be: /admin/commerce/config/order-item-types/default/edit/form-display/add_to_cart

There is an open issue for finding a more discoverable way to expose these settings.


Pass node id to custom access denied panel page and/or view pane

I found a solution that works.

I've just changed the default value of the view's contextual filter to PHP code and added this:

$node_path = explode('/', drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/') ));
return $node_path[1];


Achieve single node field edit to have different values for each user?

As you described it, it is not possible with core Drupal's field system. While you can create a node editable by many users with a multivalue field, the field (and its values) do not have property of ownership. Thus, your requirement to see different values for different users would not work.

There are alternative ways to achieve this. One path is to add 2 fields to the user profile.

Activity: an entity reference to your activity node.
Value: the user's field value you want to capture.

If the values are inherent single property of a user, you can add them directly to the user profile and use a Field Group to present it as combination of fields for the user to enter.

If the user can have many different Activity & Value combinations, you could use either use something like Field Collection or ECK/Inline Entity Form to present an embedded form in the user profile where users can add many different Activity/Value combinations.


You are probably looking for a way to pass a contextual filter from the current page to the entity selection view.

Currently an argument can sadly only be static.

However there is a patch that allows you to add an argument using a token provided by the current page you are on.

You can find the patch here: https://drupal.org/node/1699378#comment-6809760


Field Group is a module that provides this functionality.
https://www.drupal.org/project/field_group


How to export menu per role permission in features module?

I ended up using this module roles_for_menu this module exactly what I need, it allows me to export the configuration in features.

Features module support it.


Download count of file in table of files

There's many ways to get this working depending on the type of file access you want.

File Download Count - counts download when it's really been downloaded and not just clicked, new so I can't post more than 2 links. Google this.

Public Download Count - track public files

Download Count - track private files


Do some tasks after a simplenews newsletter has been sent

The best way would be patch simplenews to offer more events.

Second best would be to override simplenews via a custom module to offer more events.

There are other options but those are the best following the Drupal way.


The menu_block module with the patch in https://www.drupal.org/node/2809699 should work.

Note: you'll have to select the "Use the following as title" field to "Active trail's parent title" when configuring your block.


I'm afraid not. The taxonomy index table is maintained specifically for nodes. There is no equivalent for other entities. It would be possible to maintain an index of your own though.

A workaround would be reusing the same field on different fieldable entities. Then you would only need to query the data field table to get all referenced entities.


Assuming you're using Drupal 7 you can use code like the following:

// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// Prepare the statement and bind params
$statement = $conn->prepare("Call GetNodeList(?,?)");

$op_status = $statement->bindParam(1, $node_type, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 25);
$op_status = $statement->bindParam(2, $publish_state, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT);

// Execute the statement and reset the connection's statement class to the original.
$exec_result = $statement->execute();
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);

// Get your data
while ($row = $statement->fetchColumn(0)) {
  // ...
}

That method is completely culled from this article and has worked for me well in the past.


What meaning do the primary / secondary menu links have when it comes to SEO?

Usually there is no meaning other than that you apply. For most sites, Primary links (or Main menu) are used to navigate the content of the site, and Secondary links are more for the infrastructure links (Contact, Site policy etc). You can use them any way you wish in the context of your own site. There should be no SEO impact.


Is there any way to alter the response of JSON API module?

Please see how jsonapi_entity_base_field_info adds a computed property to the file entities. That should do.

If you don't want to create a virtual field, you can add a normalizer that only acts for that specific content type as a service. You'll need to use a higher priority than serializer.normalizer.entity.jsonapi (set to 21). Your custom normalizer can inherit from Drupal\jsonapi\Normalizer\ContentEntityNormalizer and add your custom stuff in getFields.


The Path field has been deprecated, use Link to content instead. More info in this answer: How to get Node Url in RSS view?

When you have to construct a different output out of field values it's good to use the Custom text Field.

Exclude from display your Title, Image, and Link to content fields, reorder the fields so the Custom text field comes last.

Enter your anchor HTML into the Custom text area and use the  Replacement patterns you see in the list below the area to construct the full HTML code. One of them will be the URL token. Something like:

{{ title }} {{ field_image }}

Make sure your Title field settings aren't using links, and you may have to adjust the image field code further.


You can display information from nodes that are connected through Entity reference fields right in the Views interface.

In your case you're referencing Resources from Projects, so you need to add the Relationship for the Entity reference field, then you will be able to add Fields that you can find on the Resources Content type (they will automatically use the Relationship).

If it's a field that both Content types have (for example Title) then if you don't use the Relationship on it the title will be for the Project node, and if you do make it use the Relationship it will show the Resource title.


Why are some images not displaying after migration to localhost?

So, I'm my case the files were getting corrupted durring transfer via ftp. Archiving the files first and then transferring the archive solved the problem.


How to search both Users and Nodes simultaneously in drupal 7

As AyeshK noted in the comments, you can't get this functionality with Drupal core (or even Views).

There are a couple of modules you can try though:

Search API multi-index (relies on Search API)

  This module is an addition to the Search API module which allows users to search on several indexes at once.

  When the module is enabled, you'll get a new Views base table where you can search all enabled Search API indexes at once. Performance might suffer, though, if not all indexes lie on the same Solr server (or other backend server that supports this feature).

  Please note that, since multi-index searches aren't supported explicitly by the Search API, most other Search API add-on functionality (facets, autocomplete, saved searches, search pages, etc.) won't work with searches created with this module.

Entity Backend Search (in alpha)

  This module enables highly customizable search pages for any entity type on a site for the editorial staff. It does not require any modules outside Drupal Core and is very easy to configure.


Use the same login credentials with different core versions

You could set up the existing Drupal 7 site as an OAuth provider and then set up the Drupal 8 site to allow for OAuth logins and then you could share credentials between the sites.

You won't get any sync for free but at least you wouldn't have to enter the password again.


Invalid address: return even on successfully sent e-mail

This is because of the absence of $message_text['from'];
In SMTP module smtp.module.inc line 74-85 there is hack that handles the absence of 'Reply-To' by setting it to $message['from'] which is also absent, consequently 'Reply-To' will be empty hence throwing the error Invalid address:.
add $message_text['from'] = 'your from address' this will solve the issue.


Why does drupal use .yml and not officially recommended .yaml

Drupal uses '.yml' because Symfony uses '.yml'

This was discussed in https://www.drupal.org/project/drupal/issues/2091669

I am assuming that '.yaml' would not work, but I haven't tried it. For consistency reasons it is best to stick to '.yml'.

EDIT: Looks like Symfony has started recommending '.yaml' from version 4.0. Can be seen by comparing this page https://symfony.com/doc/4.0/routing.html with the 3.4 version


TB Mega Menus: Image block doesn't show anything

I would suppose that you need to choose "FULL HTML" format for your block content.


How to redirect based on matching a node field?

Non-Views Answer

I finally figured out how this can be done without incurring the overhead of views.  I'll leave the views answer below in case it is useful for someone, but this version seems snappier to me.  As always, critique very welcome!

/**
 * Implements hook_menu().
 */
function MYMODULE_menu()
{
    $items = array();
    $items['pub'] = array(
        'title' => 'publications by Docid',
        'access callback' => TRUE,
        'page callback' => '_MYMODULE_pub_to_docid',
    );
    return $items;
}

/**
 * Redirect to a publication page based on its legacy_docid
 */
function _MYMODULE_pub_to_docid() {
    $path = current_path();
    $path = str_ireplace('pub/', '', $path);
    $args = explode('/', $path);
    $query = new EntityFieldQuery();
    if (_MYMODULE_isInteger($args[0])) { // Sanity check, local helper function just to check that the value is an integer.
        $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_doc_legacy_docid', 'value', $args[0]);
        $result = $query->execute();
        if (isset($result['node']) && count($result['node'] == 1)) {
            $node_holder = array_slice($result['node'],0,1)[0];
            $node = node_load($node_holder->nid);
            $language = language_list()[$node->language];
            drupal_goto(drupal_get_path_alias('node/'.$node_holder->nid, $node->language), array('language' => $language), 301);
        } else {
            return MENU_NOT_FOUND;
        }
    }
    return MENU_NOT_FOUND;

}

Views Answer

Here is a views answer, but I'd still like to know if there is a better or preferred way of doing this.  I added a function in my_module:

function my_module_views_pre_render(&$view) {

  if ($view->name=='staff_views') { // user redirect
    drupal_goto(drupal_get_path_alias('user/'.$view->result[0]->uid));
  }
  if ($view->name=='pub_by_docid') {
      if (count($view->result) == 1) {
          $node = node_load($view->result[0]->nid);
          $language = language_list()[$node->language];
          drupal_goto(drupal_get_path_alias('node/'.$view->result[0]->nid, $node->language), array('language' => $language), 301);
      }

  }
}

Note that this function is actually redirecting for a view that matches users based on their legacy user id first, and then for a view that matches document id as mentioned originally in my question.

Update: I've updated the code here to reflect the suggestion from J. Reynolds that I include a http response code of 301 to avoid drupals default of 302.

I also found that to get things to work for non-English publications, I needed to add a language option to drupal_goto(), which needs to be a language object.  That is the reason for the line creating the $language variable.