Can't pass php variable to javascript in Drupal 7 Can somebody help me with this problem.
In the body of a Basic page:

drupal_add_js(array('my_var' => array('orderid' => '123')), 'setting');
drupal_add_js('sites/all/scripts/printout.js');

In printout.js:

alert("Before");
alert(Drupal.settings.my_var.orderid);

Result:
"Before" was alerted then returned to Basic page, no orderid.
What have I done wrong?

Make sure you call for jquery setting inside Drupal behaviour, you can do like this:

(function ($) {
    Drupal.behaviors.example_name = {
        attach: function(context) {
            alert(Drupal.settings.my_var.orderid);
        }
    }
})(jQuery);

or you can call inside jQuery's .ready() event (less preferable than behaviours approach in Drupal world):

jQuery(document).ready(function($) {
   alert(Drupal.settings.my_var.orderid);
});

These both approaches ensure that jQuery is loaded before calling a variable.

P.S. I recommend using console.log instead of alert for quick debugging, like this:

console.log(Drupal.settings.my_var.orderid);

Then go to your developer console / firebug (depending on browser you use) and you'll see an output in console.

You have to say drupal where to put the javascript like this:

$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end     of   the document
);

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

But like i learned a more sophisticated way would be to use Drupal.behaviors.

Look at my question:
How to pass values from php to javascript properly?


How can I get the form builder service using dependency injection? How can I change form builder call in class in to dependency injection method?

My current code:

class CustomBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');
    return $form;
  }

}

And I tried:

class CustomBlock extends BlockBase {

  /**
   * formBuilder.   *
   */
  protected $formBuilder;

  /**
   * Class constructor.
   */
  public function __construct($formBuilder) {
    $this->formBuilder = $formBuilder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
        $container->get('form_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = $this->formBuilder->getForm('Drupal\custom_module\Form\CustomForm');
    return $form;
  }

}

But getting following error:

  Fatal error: Call to a member function getForm() on a non-object in H:\wamp\www\myproject\modules\custom\custom_module\src\Plugin\Block\CustomBlock.php on line 44

AJAX form test mock module's AjaxFormBlock.php is quite a nice example for getting both in one, the form builder and the form interface! Look how it implements FormInterface, ContainerFactoryPluginInterface to then provide the form from within the block and injecting the form builder via dependency injection to then be used to get the form in the block's build() method at the same time.
Of course, when you only need the form builder, you don't need to implement the FormInterface! Then you just need the ContainerFactoryPluginInterface.

namespace Drupal\ajax_forms_test\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an AJAX form block.
 *
 * @Block(
 *   id = "ajax_forms_test_block",
 *   admin_label = @Translation("AJAX test form"),
 *   category = @Translation("Forms")
 * )
 */
class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactoryPluginInterface {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new AjaxFormBlock.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $form_builder;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('form_builder'),
      $container->get('messenger')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return $this->formBuilder->getForm($this);
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['test1'] = [
      '#type' => 'select',
      '#title' => $this->t('Test 1'),
      '#required' => TRUE,
      '#options' => [
        'option1' => $this->t('Option 1'),
        'option2' => $this->t('Option 2'),
      ],
      '#ajax' => [
        'callback' => '::updateOptions',
        'wrapper' => 'edit-test1-wrapper',
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  /**
   * Updates the options of a select list.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The updated form element.
   */
  public function updateOptions(array $form, FormStateInterface $form_state) {
    $form['test1']['#options']['option1'] = $this->t('Option 1!!!');
    $form['test1']['#options'] += [
      'option3' => $this->t('Option 3'),
      'option4' => $this->t('Option 4'),
    ];
    return $form['test1'];
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger->addStatus('Submission successful.');
  }

}

Another nice example is core's SearchBlock.php.
Also worth checking out the docs on Dependency injection in Plugin (Block).

Simple Answer with updated code you just forgot to Import namespace at top and you have not defined the FormBuilderInterface type of object @ constructor

 use Drupal\Core\Form\FormBuilderInterface;
 class CustomBlock extends BlockBase {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
   protected $formBuilder;

  /**
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder The Form Builder.
   */

  public function __construct(FormBuilderInterface $formBuilder) {
    $this->formBuilder = $formBuilder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
        $container->get('form_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = $this->formBuilder->getForm('Drupal\custom_module\Form\CustomForm');
    return $form;
  }

}


A gallery display formatter for Media I'm using Media, version 7.X, and I'm looking for a module that creates a display widget as a gallery for a "file" field.

I'v tried Media Gallery but I can't use "dev" versions.

Any suggestion?

Create Block using views module and show in sidebar.


How to get a field value of multiple nodes? I have some node ids from entityfieldquery. I would like to get the values of a field from all of these nodes. Should I use db_query, or should do a node_load_multiple, and get the field value with a foreach? db_query seems more efficient.

You can use field_attach_load() which will load the fields for a group of entities. You can also pass in the field_id value so it doesn't load unnecessary fields. I benchmarked field_attach_load() against entity_load() (which is what node_load_multiple will call) and the former was approximately ten times faster.

Here is an example:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'post')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (isset($result['node'])) {
  // field_attach_load() requires entities to be passed on it with the bundle
  // and the ID instead of just IDs. We need to add these values to the result
  // of EntityFieldQuery()
  foreach ($result['node'] as &$node) {
    $node->bundle = $node->type;
    $node->id = $node->nid;
  }
  field_attach_load('node', $result['node'], FIELD_LOAD_CURRENT, array('field_id' => 'body'));
}

ya u r right.
node_load_multiple fires huge pressure on db and it can effect on ur site's performance.
So, always use db_select or db_query for ur use, if there is no option available then only use loads....


Send an email when the roles are changed I'm trying to send an email to users after their role has changed. So far, the rule is triggered every time the profile is saved (even without role change); I suspect that the data comparison is not handling the array correctly?!
Any help to improve the following rule or to achieve the same feature with a different condition will be very much appreciated.
{ "rules_role_changed" : {
    "LABEL" : "Role changed",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "account:roles" ], "value" : [ "account-unchanged:roles" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "account:mail" ],
          "subject" : "Role change for [account:name-raw]"
        }
      }
    ]
  }
}

To detect 'any' change to the users roles, you can use the following PHP via the condition "Use PHP code"

return (count(array_diff_key($account->roles, $account_unchanged->roles)) + count(array_diff_key($account_unchanged->roles, $account->roles))) <> 0;

The other PHP answers will not necessarily fire when a user has been 'removed' from a role.

You always need to check the state of both unchanged and changed account, something like this:

{ "rules_role_changed" : {
"LABEL" : "Role changed",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_update" : [] },
"IF" : [
  { "NOT user_has_role" : {
      "account" : [ "account-unchanged" ],
      "roles" : { "value" : { "4" : "4" } }
    }
  },
  { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "mail" : {
      "to" : "lorem",
      "subject" : "ipsum",
      "message" : "dolor",
      "language" : [ "" ]
    }
  }
]
}
}

What this does is it checks if the user had the role before it was saved, and if the role has been added on the update - this means that user did not have the role before but does have it now.
Here is a screenshot of the config:


Resizing the Height of 2 blocks to always be the same depending on block with most content I have two blocks based off views on the home page of my site:

block-views-featured-resource-block
block-views-featured-resource2-block

I want them to be the same height as each other on the home page ALWAYS. They are both drawing from nodes. The nodes for each has a description field. And it varies depending on which node is set for the home page, so the length of the description for each changes regularly.

I want each block to expand in size to fit whatever contents are in the description field (might be one sentence or multiple paragraphs) for the node, and I want them both to resize based on whichever of the two has the most characters of content to the same size (one might end up having a bunch of white space below it, but that's ok.

Right now I have them set like so:

block-views-featured-resource-block,
block-views-featured-resource2-block {
    min-height: 350px;
    position: relative;
}

But of course this only resizes each to fill whatever contents are in each block separately...so if the content takes up more than 350px of space one might be larger than the other. I also tried adding clear: both to the above and overflow: auto but neither of those seemed to help.

Anyone know of a way to do what I want with css?

There's plenty of equal height jquery plugins out there.

jquery-match-height and jQuery.equalHeights are two plugins that you can use, but there's others just google it up and you'll see for yourself.

Beyond that it's just a matter of integrating the plugin to your theme.

Javavascript has an equal heights library.


Commerce Feeds: Multiple values in one field or multiple fields? Goal
What I'm trying to ultimately accomplish is create tiered pricing based on quantities.
The client is selling different prices depending on quantity. I'm trying to figure out what is the simplest way to store, access and represent this data using fields. While at the same time i'm importing them through commerce feeds.
About my feed/data
I have a CSV table header with the columns "P1 Price," "P2 Price," and "P3 Price." There are also "P1 Qty," "P2 Qty," and "P3 Qty."
Thus, P1 Price corresponds to P1 Quantity, etc.
My question
Would it be simpler, in terms of less complex rules or views configuration, in the long run if i created separate fields to store each price/quantity, or if I combined them into one field that stores 6 different values?
My primary considerations include, scalability, maintainability, etc.

It sounds like what you need is commerce price table. There isn't a stable release for it yet, but I have seen it demoed where it worked great.

Looks related to Feeds support for importing prices


How to use token as a filter value in views I'm looking for a solution that would allow me to use tokens in views filter values. For example, if I have text field 'my_custom_text' I would like to have a filter that would allow me to use 'Is equal to' operator and a token value instead of hardcoded string.

Note that I can't use contextual filters because I have few filters that needs to be ORed.

Is there a module for that, or do I have to code that myself from ground up?

Use Contextual Filters instead of Filter Criteria.

In Drupal 8, at the time of writing this, you also have to install the views_argument_token module.

When adding a contextual filter, at the pop up window, select "Provide default value" option. From there on the remaining settings should be intuitive.

Would the Token Filter module be helpful? Here is a quote about it (from the module's project page):

... is a very simple module to make token values available as an input filter.
The module now supports native tokens (e.g. [site:name]) and all global tokens by default. It even allows some contextual tokens like node or user to be replaced, but currently does not encourage users to use them in the filter help text.


How to run custom sql commands to database programatically I'm using MariaDB as database backend and I would like to use built in "Sequences" to get an integer number generator. I need to dinamically create sequences and get their values. Following this documentation I know the right sql commands to do it and I have tested it on MariaDB, but I haven't found a way to run this commands from Drupal 8 database connection object. I can only do selects, updates, inserts or deletes. How could I run this custom sql? I need it because I have to create custom sequences on submit some form.

I haven't found a way to run this commands from Drupal 8 database connection object. I can only do selects, updates, inserts or deletes

That's not true, you can also run arbitrary queries, e.g.:
\Drupal::database()->query('TRUNCATE TABLE foo');

You can run your SQL query in your Drupal Project. Read this  Static Queries Article. you will get detailed explaination of syntax and examples.


How can you use multiple lines in a text area? I'm probably missing something really simple here, but I can't seem to find it at all!

I want to have a text area for lyrics in my "Songs" content type.  Naturally, lyrics should be displayed one line per line, and with a space to distinguish verses, choruses etc... e.g.

  I got my head checked By a jumbo jet It wasn't easy But
  nothing is No

  Woohoo!

When I put the above in a text area, I get:

I got my head checked By a jumbo jet It wasn't easy But nothing is No Woohoo!

How do I get this to display correctly?  I am using Drupal 6.

Change the input format (just below the textarea) to Filtered HTML or Full HTML.


Ajax error on node form edit page I'm trying to ajaxify part of node form. I have a hook_form_alter that adds extra ajax property to a widget of select field. The problem I'm facing is the callback method / function, which is not fired when change is happening.

So this is my form_alter code which resides in accountancy_invoice/accountancy_invoice.module:

function accountancy_invoice_form_node_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_invoice_form') {

    $form['accommodation'] = array(
      '#type' => 'container',
      '#prefix' => '
Dave
',
      '#attributes' => array(
        'class' => 'user-full-name',
      ),
    );

    $form['field_invoice_customer']['widget']['#ajax'] = array(
      'callback' => 'Drupal\accountancy_invoice\Form\AjaxifyForm::customerValues',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
      )
    );

  }
}

This is my AjaxifyForm class which resides in accountancy_invoice/src/Form/AjaxifyForm.php:

namespace Drupal\accountancy_invoice\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;

class AjaxifyForm {
  public static function customerValues(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#user-full-name', 'Bryan'));
    $title = "Example Dialog";
    $content = "foo bar content";
    $options = array();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
    return $response;
  }
}

It doesn't really matter at the moment what this ajax should do. For testing purposes I just want to change name from Dave to Bryan in #user-full-name and display sample dialog box.

In the console, each time ajax is triggered I got an error:

This is complete error message (it's trimmed in the screenshot):
↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /node/add/invoice?ajax_form=1↵StatusText: OK↵ResponseText: TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given, called in /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 441 in Drupal\Core\Form\FormState->setError() (line 1093 of /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Form/FormState.php).

This is a generic issue that will show for various reasons, often because of a bug in the code handling the server response. Look in your server logs for more information as to what has happened.

If you expeirence with this kind of error it happens because of bug in drupal core. This is the discussion about this issue: https://www.drupal.org/node/2027059

I've applied patch from #55 and ajax requests has started to work.


How to override default page.tpl from a module, for a specific page? I am coding a module which contains a "please wait" page.

On this page I need to override the default page.tpl template so I can render the "please wait" message alone without all the other regions and "site chrome".

How do I tell drupal not to use the default page.tpl and use my page-special.tpl for the specific "please wait" page ?

EDIT

Please note that I am coding a module, not a theme. So everything should be done from inside the module.

As per Stuart Clark's advice

All you have to do is to create a template, for example : mymodule/theme/special-page.tpl.php

and add this to your module

function mymodule_theme(){
  return array(
    'special_page' =>  array(
      'template' => 'theme/special-page',
      'render element' => 'page'
    ),
  );
}

function mymodule_preprocess_page(&$variables, $hook) {
  if ( my_condition() ) {
    $variables['theme_hook_suggestions'][] = 'special_page';
  }
}

I cannot find a way to override the html.tpl.php in my module. My use case was to create an "interstitial" page to display pre-roll video or an ad, similar to how forbes.com does it. Here is the user story:

"As a user, my first visit to the site will present me with an interstitial page before viewing content. WHen the page is displayed, a cookie is set in the user's browser preventing the interstitial from displaying on subsequent visits for the next 24 hours."

I created a hook_menu creating a page with a path called "welcome"

/**
 * Implements hook_menu().
 */
function liveinterstitual_menu() {
  $items = array();

  $items['welcome'] = array(
    'title' => 'Welcome to San Angelo LIVE!',
    'page callback' => 'liveinterstitual_welcome_page',
    'page arguments' => array(),
    'access arguments' => array('access content'),
  );
  return $items;
}

The page callback is liveinterstitual_welcome_page(), and it looks like this:

function liveinterstitual_welcome_page() {
  // If you want the sidebars and everything in the theme layer, uncomment the next line
  //return theme('liveinterstitual', array('content' => $content));
  //else, to spit out a static html page, save the page to this module's dir and do this:
  echo file_get_contents( drupal_get_path('module','liveinterstitual') . '/liveinterstitiual.html');
  //Shut down Drupal cleanly
  drupal_page_footer();
}

In short, I byassed the entire theme payer by piping the contents of a flat html file. Drupal has similar functions in core that do this by delivering a JSON array for ahah callbacks, for example.

I am open to other ideas, but this one appears to work for now.


How can I have a node with the URL /themes I've created a node and have given it the URL /themes. In full: http://site-name.com/themes.

Permissions on the Drupal system folder 'themes' mean that the URL /themes gives: 403 forbidden.

Is there anyway to have a node with /themes? I'd prefer if possible to keep my current file structure as I think it would be difficult to change with my current host (Pantheon).

In your .htaccess file, the URL re-write has the a code to point the path to the respective folder, if present.. you can change that!


Libraries API not working in my module I'm writing a module that will call some external php libraries. When I was searching for a way to import the library I found the Libraries API. After reading some documentation about the module and core features I found some example code.

When I implement it in my module nothing happens.
My movies.module file contains:

/**
* Implements hook_libraries_info()
**/
function movies_libraries_info()
{

  // This array key lets Libraries API search for 'sites/all/libraries/example'
  // directory, which should contain the entire, original extracted library.
  $libraries['imdb'] = array(
    // Only used in administrative UI of Libraries API.
    'name' => 'imdb',
    'vendor url' => 'https://github.com/tboothman/imdbphp',
    'download url' => 'https://github.com/tboothman/imdbphp/releases',
     // Default list of files of the library to load. Important: Only specify
    // third-party files belonging to the library here, not integration files of
    // your module.
    'files' => array(
      // For PHP libraries, specify include files here, still relative to the
      // library path.
      'php' => array(
        'bootstrap.php',
      ),
    ),
    // Optional: Register files to auto-load for your module. All files must be
    // keyed by module, and follow the syntax of the 'files' property.
    'integration files' => array(
      'movies' => array(
        'php' => array('bootstrap.php'),
      ),
    ),
  );
  return $libraries;
}

No errors are thrown when enabling my module when the library is not installed.

How can my module load the external PHP library using the Libraries APi?

Add a composer.json file to your movies module & name it your custom module's name:

{
  "name": "drupal/movies",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "require": {
    "imdbphp/imdbphp": "*"
  }
}

Add a new line to the merge-plugin include array in the composer.json of your Drupal ROOT with your module's composer file path:

"extra": {
  "merge-plugin": {
    "include": [
        "core/composer.json",
        "modules/custom/movies/composer.json"
    ]
  }
}

Enable the movies module
Run composer update & composer dumpauto in Drupal ROOT. This will install & autoload the new dependencies in your vendor directory.
Now you can use the classes provided by this library. In your case for example:

$title = new \Imdb\Title(335266);

You can load libraries from the Libaries API in Drupal 7 in two ways:

1) You can use the function libraries_load()

2) You can use the #attached method of a render array as follows:

$form['myelement']['#attached']['libraries_load'][] = array('my_library');


Ultimate Cron Background Process Taking a Long Time I'm having background process on Ultimate Cron process various queue items, but the fastest it usually processes them is at least one minute, and sometimes 3 minutes per item.

This seems incredibly slow to me.

Should I increase the number of threads? I'm not finding much documentation on how to speed up the process - I don't mind if it requires a bit more processing power - this is a required operation for the Drupal install in question, and it has to be run pretty much all the way through every 15 minutes.

There are no errors, just very slow processing.

I think we need to check from start to end point. This issue is like some processes which takes more time to execute. So we need to check what is that process and we can find that using Elysia Cron plugin.

This plugin helps you to find which cron process has taken much time and where to take possible actions.

PS: If this stuff helps you please leave me a comment and support :)

Thanks!


With search_api_solr, how can I apply an significant field based boost when using solr 6.x? I am using the solr backend for search_api on a drupal 8 site.

I have added the value of a taxonomy term reference field (field_promoted_search) to the index.

If an item of content has field_promoted_search with value matching the search term, I would like it to get a significant boost (eg ^1000), pushing it to the top of the search results.

Adding a high 'boost' value at admin/config/search/search-api/index/content/fields worked as expected when the server was using solr <6, but since moving to 6.1.0, this does not work as expected. This may be because search_api_solr/solarium is using a multiplicative boost rather than additive. This is not seem as useful to me as this multiplies the relevance achieved by other fields, rather than solely privileging field_promoted_search, though I am uncertain of this aspect.

I have tried adding a boost query for this promoted search field to the solarium query using hook_search_api_solr_query_alter. This requires me to pass each search key as a boosted query, and the effect seem to be affected by the order of the keys (and also my result does not end up top).

$keys = $query->getKeys();
unset($keys['#conjunction']);
// Boost results where search term matches promoted search field.
$boost_keys = [];
$boost_value = 1000;
foreach ($keys as $key) {
  $boost_keys[] = '"' . $key . '"^' . $boost_value;
}
$solarium_query->getEDisMax()->setBoostQuery('ss_promoted_search:' . implode(' OR ', $boost_keys));

When I attempt to use a boost function instead, I get an error from back from Solr and the query does not run (I have tried several functions).

// Format is: "funcA(arg1,arg2)^1.2 funcB(arg3,arg4)^2.2"
$solarium_query->getEDisMax()->setBoostFunctions("ord(ss_promoted_search,1)^1000");

Any advice much appreciated.

My reference for additive vs multiplicative boost methods is this very helpful article.

None of the API function provided by Search API and Search API Solr Drupal work properly. You can either check solarium docs or switch back to Solr 5 or Solr 4. Boosts work properly with Solr 5.x. Data type indexed is also important. Try indexing it as Fulltext field.


How do I add an access condition to a menu item? How can I add new conditions on top of existing conditions that determine whether a menu item is visible? These conditions should not be limited to permissions settings.

As an example use case (not necessarily the reason for this question): Suppose I have a content type of which users are only allowed to create one node. I have a menu item for adding that type of content. But if the user has already created a node of that content type, I want to hide the menu item. My first thought is to run a query to check for the existence of a node created by the current user that is of the specific content type. If one exists, hide the menu item.

I would think this type of functionality should go into hook_menu_alter() and add the required logic there. But I'm not sure how to do that without bypassing the existing checks, like checking if the user has permissions to create that type of content. Would I have to include that logic within my own condition? Or can I add to the existing access logic without overwriting it?

Edit: Some people seem focused on answering "how do I limit a user to creating one node of a content type". That is not the question here. The question is how to I add custom access conditions to a menu item.

What you need to do is to add your callback via hook_menu_alter(), and then inside your callback you simply do your logic then return the data via the original callback.

To be certain that you don't overwrite any other hook_menu_alter() changes, you should pass the previous callback to your callback via the access argument.

This is all theoretical, but the code should go something like this:

MYMODULE_menu_alter(&$items) {
  $items['menu']['access arguments'] = array_merge(array($items['menu']['access callback']), $item['menu']['access arguments']);
  $items['menu']['access callback'] = 'MYMODULE_access_callback';
}

MYMODULE_access_callback() {
  $args = func_get_args();

  // Do Stuff.
  if ($something == FALSE) {
    return FALSE;
  }

  $function = array_shift($args);
  return call_user_func_array($function, $args);
}

One option would be to create a new role that has create content permission for your content type. After a user creates a node of that type, take away that role and they wont be able to create any more.


How to allow for files of any extension to be uploaded? I'm surprised this hasn't been asked before like this.

I want to allow users to upload files of all file extensions, without enabling each extension by hand. How do I do it?

You can use Allow  all file extension Module

  This module reverts Drupal 7's file upload widget to the Drupal 6
  behavior, and trusts the site administrator to be smart enough to
  allow uploads with any file extension. It also lengthens the allowed
  file extensions box from 128 characters to 2048, allowing you to
  specify a larger number of extensions.

  While I realize this is somewhat insecure and would have liked to add
  more functionality to this module, this isn't something I should have
  needed to do at all, and I don't have a whole lot of time to spend on
  it. If there are any bugs, I'll try to fix them, but beyond that, I
  won't be adding new features to it. If you would like add new features
  to this module, I would gladly accept a co-maintainer (or even
  transfer ownership to someone else).

  Warning: The ability to leave the allowed file extensions box blank
  was removed for a reason. If you leave it blank and allow random users
  to upload files of any type, you'll have an insecure site. As such,
  you are strongly cautioned only to allow trusted users to do this.

you just need to define any file extension that user need to upload it in file field that attached to content type example:
add new file field to any content type and in field setting add the approved extension


Adding Bootstrap Tabs to a content view I've created a custom content type which I want to display in a view using Bootstrap's Tabs component.

I've found this tutorial of sorts, but I'm a bit lost trying to process it all (I'm very new to Drupal).

It looks like it does almost exactly what I need it to. I basically need to display the content I have in that view to be placed inside Bootstrap's Tab markup. I know the theme I'm using already has Bootstrap embedded and available, but I can't seem to figure out to make a "Bootstrap Tabs" option available in the "Style" option of my page view.

Can anyone share some pointers on where to start looking for a solution and on what I need to read up on?

EDIT:

I've been following the tutorial and was able to get somewhere with it. Right now, a Format option for Bootstrap Tabs shows up when editing the view and, when selected, it is followed by a form questioning which field should be used for navigation - as intended, I recon.

Although right after answering the form question, above the preview area, an error message shows up stating:

  Template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" in the Drupal theme registry.).

Which in turn also shows up in the view after saving.

Can anyone share some pointers on why this happens and how to fix it?

you can also use the https://www.drupal.org/project/quicktabs for this
    (The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes* and other quicktabs*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:)
available  for drupal 8


How to insert an image into a drupal form Is it possible in drupal7 to insert a photo in drupal form? I have a start interface that contains two buttons leading to two athors interfaces and I would like to insert a photo above the two buttons. I have tryed the next but it didnt work

function my_module_start_form($form, &$form_state) {
  $image_options = array(
    'path' => 'path/to/img.jpg',
    'alt' => 'Test alt',
    'title' => 'Test title',
    'width' => '50%',
    'height' => '50%',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
  );

  $image = theme('image', $image_options);

  $form['start']['image'] = array(
    '#markup' => $image,
  );

  $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );

  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );

  return $form;
}

May be this will help..

 function my_module_start_form($form, &$form_state) {
 $image_options = array(
'path' => 'path/to/img.jpg',
'alt' => 'Test alt',
'title' => 'Test title',
'width' => '50%',
'height' => '50%',
'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

 /*$image = theme('image', $image_options);
  $form['start']['image'] = array(
    '#markup' => $image,
  );*/
    print theme_image($image_options);//print the image

    $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );
  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );
    return $form;
}


page not found on install So i wanted to install Drupal on my local mac. I download drupal 7.12 put its content into my htdocs (i'm running MAMP) goto localhost got through all the steps and his save and it took me to "http://localhost/install.php?profile=standard&locale=en" where i get this message

then if i goto localhost i get this

I can't seem to figure out what went wrong Could some one point me in the right direction ?

I'm not sure exactly what your problem is, but it's probably faster to simply try re-installing again from the start than to troubleshoot your installation.  It's hard to estimate how much time it will take to troubleshoot when you don't know what's wrong but you know roughly how long trying to install it again will take.

Although I use MAMP with Drupal myself, if you're a first-time user it might be easier to try Acquia Dev Desktop, which is an "Apache server in a box" like MAMP but already includes the latest version of Drupal and is ready to go as soon as you install it.  Acquia is a company run by the founder of Drupal so you know you're in good hands.

Alternately, although not specifically a Drupal company, Bitnami offers Drupal as an "Apache server in a box" like MAMP as well as as a virtual machine and as a cloud server on Amazon cloud.

There's also Pantheon, which is a Drupal platform that will let you register an account and create Drupal sites in the cloud for free (note that Pantheon will, however, charge you if you decide to take your site live on their service).

I listed many options; of them all, Acquia Dev Desktop is the simplest to set up and get running.

Check the directory name. I had the similar issue, resolved once I changed the directory name from camel case to lower case.


Drupal's 7 sites folder with its mysterious permissions and ownership The problem is that I had to give sites directory and all subfolders and files of it permissions 777 in order for drupal to recognize this folder and not redirect me to install.php page. But on a virtual hosting I noticed that sites is a protected folder and all of its content esspecially sites/default/settings.php with 550 permissions. I did not get the magic trick here, how does drupal recognized that folders. I have created drupal's folders and files both as root and other sudo users, but it did not help. And drupal still see only sites with 777 permissions.

You need to insure that the php process (web server) is a member of the group for the Drupal files.  You should make sure that the owner of the files is some user other than the php process / web server, because you do not want to allow the web server to overwrite the Drupal code files.

To change the group of all of the files in your root:

sudo chgrp -R webgroup /path/to/drupal

To add a group to the web server user:

sudo usermod -a -G webgroup www-data

For more advice on correctly setting file permissions for Drupal, see Securing File Permissions and Ownership.

Edit: It was suggested that this answer be expanded to point out that the above page contains a script for setting your permissions. There is also a Drush command for setting permissions in progress at http://drupal.org/node/990812. Both of these scripts can be helpful, but only if you set the user and group ownership of your files correctly, and insure that the web server user is a member of the applicable group as explained above. Please read the quoted page carefully, as it explains these concepts.

try this just replace "USER" with your login name without the Quotations this should solve all permission problems

cd /var/www
sudo chown -R "USER":www-data .
sudo chmod -R 750 .
find . -type d -wholename "*/sites/*/files" -exec sudo chmod -R 770 {} \;
sudo chmod g+s .
find . -type d -exec sudo chmod g+s {} \;

this will set all the permissions as suggested by drupal
if the problem still persists then the problem isnt with permissions


Non-breaking space in menu link name How to put non-breaking space into a menu link name in Drupal 8? I tried &nbsp; but it got displayed   literally.

Use this in your theme so menu items can be processed as html

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 * processes 1 nested level of menu items
 */
function THEMENAME_preprocess_menu(&$vars){
  if($vars['menu_name'] == "main"){
    foreach($vars['items'] as &$link){
      $link['title'] = Markup::create($link['title']);
      foreach($link['below'] as &$nestedlink){
        $nestedlink['title'] = Markup::create($nestedlink['title']);
      }
    }
  }
}

Alternatively you can use css to make regular white space not wrap

.menu li a {
    white-space: nowrap;
}

Of course you have to adjust css for your particular menu class

Solution without code: On windows use the keyboard combination alt 0 1 6 0  (hold alt key while typing the digits on the numerical pad) for a &nbsp;. On Mac use alt space.

Free extra hint: use alt 2 4 0 if you need to enter a &shy; soft hypen


Removing breadcrumb from the Homepage in Bartik theme (Drupal 7) I am trying to remove the breadcrumb from the homepage (Home link). I am using a bartik theme. I have a page--front.tpl.php and have tried removing the following code snippets and clearing the cache, but the Home breadcrumb is still there. Any help would be greatly appreciated

<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

and

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

Edit: I just realised that my front page isn't actually picking up the page--front.tpl template. Why might this be??? :(

You can also comment them out on the page.tpl.php like so

<?php /* if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

   <?php endif; */?>

And then if you want them back later... take the /* s out. :)

You can also use this code.

if (!$is_front && !empty($breadcrumb)) {
  print $breadcrumb;
}

Otherwise, go to your theme folder and remove the code in page.tpl.php. This will be remove the breadcrumbs from your site.

Be careful: It will completely remove the breadcrumbs. If you want to get them back later, then keep the code in another file.

This is the code for the Bartik theme.

<?php if ($breadcrumb): ?>
  <div id="breadcrumb">
    <?php print $breadcrumb; ?>
  </div>
<?php endif; ?>


How to display flags to anonymous users and redirect to login after clicking a flag? I want to display flag to anonymous user and upon clicking the user should be redirected to register/login page.

I found one answer to this problem in the question about
"How to display a flag to anonymous users?".

I tried this solution but did not work, may be I did not put the code in correct place?

I am using Bartik as my template and I put the code in node.tpl.php.

Any suggestions?

Maybe the Flag anonymous module is what are you looking for.

Why not just use the Session API module.

  The Session API is a very simple set of functions that extend the core
  sessions workings, allowing data to be stored and associated with a
  user's session.

  There is no need to install this module unless you are instructed to
  do so by another module.

  Currently this module is used by

  Flag DrupalChat Mozilla Persona Session Favorites Domain User Default
  The Sign-Up Problem


How to execute custom code on user signup I need to do a REST request every time a new user signs up.

The REST request returns some data that I need to store for the Drupal user account, and be able to present as content somewhere.

What is the best/cleanest way to do that?

You can do it in a simple custom module, be sure to first understand Drupal hooks system as this is the base for (almost) everything Drupal.

In your module, you can implement hook_user_presave() to be called before a user account is saved. It will be called for both creation and update, so you will need to guard your code with a condition to detect new user. After the REST call, there is several option to store the returned data. The easiest one is the use the data attribute of the user account. It is a simple PHP array that will be serialized in a database columns. It is not very good performande wise and not very flexible (you can query the stored data) but it is easy.

function MODULE_user_presave(&$edit, $account, $category) {
  // Accoding to user_save's documentation, this is a new user if
  // $account->is_new is set to TRUE or if $account->uid is not set
  if ($category == 'account' && (!empty($account->is_new) || !isset($account->uid)))) {
    $edit['data']['MODULE'] = MODULE_get_data_from_rest($account);
  }
}

The Rules or Workflow modules may be what you are looking for.


Reading textarea values per row: what is the internal method? If I'd like to create a textarea field for a admin configuration form that would include different configurations on multiple rows then how can I read these values/rows?

I know there must be a internal method for this since it is very common form field/input type. I just wouldn't like to invent it again.

And I just ran into a module that was using this same principal but it matched the rows with regex \n\r which turned into few gray hairs if you had only one value since it didn't then match if you didn't deliberately press enter. And for clarity it obviously didn't check that if the first line included text, just that regex and therefore no settings were saved.

That was also a wake up for that there must be some more intelligent and elegant way...

Drupal doesn't provide a method for that.

Just use whatever PHP splitting method makes sense for your use case. A very simple example might be:

$text = str_replace(array("\r\n", "\r"), "\n", $text);
$vals = explode("\n", $text);


Why isn't the user #1 able to edit the user details? I have one site in Drupal 6. When I log in as user #1, and I visit the page at user/[uid]/edit, I am not able to access this page. I get an access denied error.

Can any one please tell me what may be the problem, and the solution?

This is probably a conflict/misconfiguration of some module (or permissions) you have installed on the site and that deals with users or permissions.

Super user (uid: 1) has all privileges, whether or not the admin role exists.

Make a dev version of the site and start disabling modules one by one to find which one caused this.

Which modules do you have installed? Any custom modules? Is there anything in the database/error log?

You have to make sure the the permission " Administer users " is checked for Administrator role in your permission page.

update


add css if url contains I have one node type and two page types for this node.

http://site.com/themes/*

and

http://site.com/years/*

And i want to hide one of the "view-filed" in all "years" pages using the css.

Found this but it doesn't work

function mythemename_preprocess_page(&$variables,$hook) {
  $alias = explode('/',drupal_get_path_alias(request_uri()));
  if($alias[1]== "years") {
   $vars['theme_hook_suggestions'][] = 'years';
  }
}

https://groups.drupal.org/node/130944#comment-762483

I would be very grateful for any help.

Here's how I would do it (but I'm rather new to this, so maybe your approach is better)...

function mythemename_preprocess_page(&$vars, $hook) {
  if (arg(0) == 'years') {
    drupal_add_css(path_to_theme().'/css/years.css');
  }
}

I would suggest doing this with pure CSS selectors.

I'm pretty sure you can do something like this:

/* Hides the link text. */

a[href*="find_this_part_of_URL"] {

display: none;

}

I suggest you do NOT hide page content with this CSS, as it is bad for search engine optimization, but if you honestly can't get the theme to cover up a link, so you can focus on fixing the theme hook, use the above code.


Line break in Page / Node Titles Is there some way we can use <br> or javascript line breaks in Node, Page and/or Block Title fields?

I have found there is good reason why Drupal restricts html in titles. If you need a subtitle, it is best to create an additional field in the content type, then position it using the Display Suite module.

Try css, change title width for pages you want to have breaks.


Error Passing Extra Parameter to Custom Form I have a simple custom form that works until I try to add a custom parameter for my module called "forms_admin".

These are the contents of my forms_admin.routing.yml

forms_admin.settings:
  path: 'admin/config/system/forms/{arg1}'
  defaults:
    _form: '\Drupal\forms_admin\Form\FormSettings'
    _title: 'Forms Settings'
  requirements:
    _permission: 'access content'

This is a relevant part of my FormSettings.php file (Currently do not have any custom Validation or Submit actions)

public function buildForm(array $form, FormStateInterface $form_state, $arg1 = NULL) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#required' => TRUE,
    );

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

return $form;
}

And my third file is: forms_admin.links.menu.yml

forms_admin.config:
  title: Forms
  route_name: forms_admin.settings
  parent: system.admin_config_system
  description: 'Forms settings'
  weight: 0

The moment that I add {arg1} to my forms_admin.routing.yml and , $arg1 = NULL to my FormSettings.php file, I am unable to acces the website.

I receive a white page with the error that states:

  The website encountered an unexpected error. Please try again later.

After removing arg1 from my two files and going to the Recent Log messages, this is the error I receive:

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg1") to generate a URL for route "forms_admin.settings". in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 182 of /var/www/test_site/docroot/core/lib/Drupal/Core/Routing/UrlGenerator.php).

I have tried changing arg1 to other names, not making $arg1 = NULL, etc. and I receive an error every time.

What am I missing?

The problem is that your FormSettings class is not the controller in this case. It's the controller method which is where the routing system expects $arg_1.

I think you need to define your own controller which accepts the request and passes the argument to the form. Extending the core Drupal\Core\Controller\FormController class is probably the simplest way forward.


Drupal 6 Apache Solr Search Problems with result ordering & fields As I am implementing a website made in Drupal 6 and using Apache Solr search as the search application in the website.

Drupal Version 6.22
Apache Solr Version : 3.6
Apache Solr Module: 6.1.x

Below are the two problems I am facing.

While searching a particular content the business requirement is to search only in the Title field, Body field and in the Terms attached in a node. How can I achieve that?
I have used the HOOK_apachesolr_modify_query() in some other purposes. Do I have to mention all the filters here again? like,

mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $query->add_filter('title', $keyword);
   $params['fl'] = 'title';
}

The second is that once the contents are being searched as per the requirement I should get the result based on the following algorithm.

1st result = (Match in Title + Match in Body + Match in Terms names) (Keyword present in all)

2nd result = (Match in Title + Match in Terms names) (Keyword only present in title & term names)

3rd result = (Match in Title + Match in Body) (Keyword present in Title & Body)

So I added a boost factor from the Apache Solr admin section as
Title = 1.0
Term = 0.50
Body = 0.25

But the ordering is not maintained.

I even also mentioned

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $params['qf'] = array('taxonomy_names^0.50', 'title^1.00', 'body^0.25');
}

But no effect. Please suggest any ideas.
Help me on these issues, I am really stuck here :(

I would suggest you look into the Views module and/or Apache Solr Views. This blog post http://blog.hsl.virginia.edu/drupalpress/apachesolr-views-drupal-6/ might also be useful.


What's a good balance between reusing fields versus creating new ones in the context of fields scalability? I've read the following phrase on a website:

  Instead of adding new fields to a content type, adding existing fields is a better option to reduce the system’s complexity and to improve scalability.

And some doubts arise.

In the system we are developing, we have the possibility to reuse a field across 3 or 4 content types but instead of improving scalability as the quoted phrase says, I'm afraid it will diminish it, because the field's table would faster become a bottleneck (at least that's my reasoning in this case, as all values of that field together, would be a couple millions per year and that would make the table too big). Do you agree?

How many rows would be a sensible maximum to aim for when architecting? That way we could decide when to reuse fields and when to create new ones (even though the chance to reuse is there).

The amount of data in a field usually isn't a problem. If you're worried about that, look into alternative field storage plugins or write your own. For example MongoDB, which can deal with pretty much anything you put into it. It is for example used on http://examiner.com.

A real problem however is the number of fields you have. Because currently in Drupal 7, the complete field configuration of all fields, no matter if they're loaded or not, is fetched from the cache on every single request.

I've seen sites with 250+ fields, where loading and unserializing the field configuration takes 13MB+ memory.

Edit: The field info cache has been improved (see http://drupal.org/node/1040790 for details) with Drupal 7.22, only the fields of bundles that are displayed on a certain page are loaded from the cache and they're separate cache entries. That only works if there are no wrong API calls that request instances across multiple bundles.

As per my suggestion Using same fields in separate content type is good idea. Because it will improve your site performance. In Drupal 7, When you are using select operation that time, Using same fields in content type is really Useful to your Drupal7 site.


Custom module is not working I created custom module to display Hello world text in custom page. I did not install drush and composer in my windows machine as I don't have admin access. I have pasted my files below:

example.module

<?php

function example_menu()
{
  // The paths given here need to match the ones in example.routing.yml exactly.
  $items['/mypage/page'] = array(
    'title' => 'First page',
    'description' => 'This is a example page.',
    // The name of the route from example.routing.yml
    'route' => 'example.my_page',
  );
  return $items;
}

example.routing

example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::mypage'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

src/Controller/ExampleController.php

<?php

namespace Drupal\example\Controller;

//use Drupal\Core\Controller\ControllerBase;

class ExampleController
{
    public function myPage()
    {
        $element = array('#markup' => 'Hello world!');
        return $element;
    }
}

And I have example.info file as well and the module is enabled. When I run the controller, it says page not found. Can anyone tell me that Am I missed anything in the code?

hook_menu doesn't exist anymore in D8.
Instead use a example.links.menu.yml file.

example.my_page:
  title: 'First page'
  description: 'yout description'
  route_name: example.my_page


How to get the current viewed users uid If I am viewing a users profile page, how do I obtain and display (in a block) their uid? NOTHING to do with the current logged in user. I need to display the users id in a block on their page.

If you are showing a standard drupal user profile page this should get you going:

  $user = user_load(arg(1));
  $user->uid; // access user id

This assumes the path is user/uid. If your path looks different adjust the arg(position_in_path) to your needs.

as BetaRide in the page profile you can use arg(1) it will give you user profile and then you can use user_load()


Drupal Album/Photos modules error. Not show photos/image/uid www.sitename.com/photos/image/697 --> go... But, not show image and other content and blocks...

Error messages:
1- Unable to generate the derived image located at public://styles/large/public/photos/image_1/6396455561366990133.jpg.

2- DrupalDefaultEntityController->load() array_flip() [function.array-flip]: Can only flip STRING and INTEGER values!.

3- format_date() /includes/common.inc dosyasının 2014 line) date_timezone_set() expects parameter 1 to be DateTime, boolean given.

Help me please...

The problem was the Photo Information Block being inactive; it has been now fixed.


Comment.tpl.php how to add a link back to the node In the comment.tpl.php I've shown the comment parent node title by:

$node->title

I need to make this title link back to the parent node:

$node->$node_url

But this doesn't work. How should I do that?

You can use the entity_uri() and l() functions, similar to how it's done in template_preprocess_node():

$uri = entity_uri('node', $node);
$link = l($node->title, $uri['path'], $uri['options']);

You can achieve your goal with the following line of code:

<a href="<?php print url('node/'.$node->nid) ?>"><?php print $node->title; ?>.


Query on custom drupal 7 field I'm facing problem in Drupal query for order by custom field
Here is my query

$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype', array(':ntype' => 'portfolio'));

this work fine but when I change that to this

$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype order by n.field_weight DESC', array(':ntype' => 'portfolio'));

That query not working. It saying field not found?

Try something like (supposing "weight" module is used and weights are stored in the "weight_weights" table - to be adapted for another module ) :

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'type'));
$query->join('weight_weights', 'w', 'n.nid = w.entity_id');//join can not be chained
$query->condition('n.type', 'portfolio', '=');
$query ->orderBy('w.weight', 'ASC');

$result = db_select('node', 'n')
                ->fields('n', array('nid','type','field_weight'))
                ->condition('n.type', 'portfolio', '=')
                ->orderBy('n.field_weight','DESC')
                ->execute();

You can use this code.


Show table records in view via hook_form I managed to get things looking a bit better, However I dont know why the checkbox below is showing like the picture. I want to select the checkbox and make it do something with the corresponding article. By the way I have it, will it work? Thanks in advance.

`function rss_list_form($form, &$form_state) {

$results = db_query("SELECT * FROM {rss_table}");
$i = 0;
foreach($results AS $result) {

    $form[$i] = array(
        '#type' => 'checkbox',
        '#prefix' => '
',
        '#suffix' => '
',
    );
    $form[$result->GUID] = array(
        '#type' => 'item',
        '#title' => $result->title,
        '#markup' => $result->description,
        '#prefix' => '
',
        '#suffix' => '
',
    );
    $i++;
}
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);

return $form;

}`

I manage to get things working like I wanted !! So I will include a screenshot and the code for people on the same boat.

function rss_list_form($form, $form_state) {

$header = array(
'article' => t('Article'),
);

$rows = array();
$sql = "SELECT * FROM {rss_table}";
$result = db_query($sql);
    foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
        'article' =>
        '
'.$dbrow->title .'
'.'
'
        .'
'.$dbrow->description.'
'.'
'
        .$dbrow->date .'
'.''.$dbrow->link.''.'
',
    );
    }
$form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
);
$form['import'] = array(
    '#type' => 'button',
    '#value' => t('Import'),
    '#weight' => 0,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
$form['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
);
return $form;

}

Do it without the table first. Just the form with the form elements. Once you get that right and it works you then have to create a new theme function for it:

implement hook_theme and define a theme function for the form
set form['#theme'] in the original form to that of your new theme
function
implement the new theme function. Here you need to load all of your
form elements into structures as required by theme_table, and
call theme_table on it. And then call drupal_render_children on the
form so as to render the rest of the form (hidden elements etc that
are required by Drupal FAPI).


Changing url of exposed filter When I used an exposed filter the filter selection is passed as name/value pair in the url, for example:

members?field_a=valuea&field_b=valueb

How can I set it up to use more of a "pathauto" style url:

members/valuea/valueb

A colleague of mine created a module called path data a while back. His intentition was to solve this very problem. Unfortunately it has turned out that it conflicts with regular path aliases, so it will work on a site like drupal.org that doesn't use aliases, but will break links on a path-alias using site.

Currently, it's my belief that the only generic way to solve this issue is either manipulating the URLs at the httpd layer, or using hook_url_inbound_alter and hook_url_outbound_alter. You can read a bit more about the mentioned hooks at this question.

However, if I were to give this another shoot myself, I would attempt a Views specific solution instead, as this problem is common enough that it could be justified to have a module for this.

In hook_views_pre_build, one could take data from a url like "members/valuea/valueb", push these values into $_GET['q'], let views build it's query seeing the get arguments "in the url", then possibly remove them again in hook_views_post_build.

You could use the following code.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "abcd") {
    $form['#submit'] = array('custom_search_redirect');
  }
}

function custom_search_redirect($form, &$form_state) {
  $form_state['redirect'] = "members/valuea/valueb;
}


Custom theme doesn't show up in Blocks section I've looked through different threads about this issue and didn't see any answers. I have a fresh install of Drupal 7 with no extra modules enabled. I've started building a custom theme but it doesn't list itself in the blocks section even though it's enabled. It shows the original bartik theme and the admin seven theme. The odd part is I added a new block under Header which I have listed in my .info page and it showed up in my theme but I can't edit the block because the it only gives access to those two themes and not mine. How can I fix this?

I also have all of these error messages in the admin and I've barely added anything to my theme. Not sure what I'm missing.

  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/beta/modules/system/system.module).
  Notice: Undefined index: name in _ctools_list_themes() (line 574 of /home/infanity/public_html/beta/sites/all/modules/ctools/includes/plugins.inc).
  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/beta/modules/system/system.module).
  Notice: Undefined index: name in _ctools_list_themes() (line 574 of /home/infanity/public_html/beta/sites/all/modules/ctools/includes/plugins.inc).
  Notice: Undefined index: name in system_sort_modules_by_info_name() (line 944 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_sort_modules_by_info_name() (line 944 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Warning: uasort() [function.uasort]: Array was modified by the user comparison function in system_themes_page() (line 139 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_themes_page() (line 148 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_themes_page() (line 190 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in theme_system_themes_page() (line 2728 of /home/infanity/public_html/beta/modules/system/system.admin.inc).

I've stripped my theme to just the .info file which the manual says is all that's required and I still get errors and although enabled still doesn't show up as the default theme in the block section. Here is my .info file labled fod.info in a folder labeled fod in the sites/all/themes folder.

name = fod
core = 7.x

stylesheets[all][] = css/style.css
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[navigation] = Navigation
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

And here are the errors I'm still getting in the admin.

  Notice: Undefined index: name in block_help() (line 69 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/betaD/modules/system/system.module).

If you want to skip the full story

Search for any "*.info" file in your drupal repo that has no line similar to "name = xxxx".

My problem was due to a file named "lcov.info" in a grunt module (grunt-svgmin) in my theme.
I happended "name = lcov is not a theme" at the beginning of the file and the issue fade away.
I'll check svg-min later.

Full story

I had the same notice problem for few days.

The notice was a pattern of 3 lines :

in block.module :

line 146 :

'title' => check_plain($theme->info['name'])

and line 165

'title' => check_plain($theme->info['name']),

in system.module line 647 :

'title' => $theme->info['name'],

This pattern is replicated a variying number of times depending on the pages.

I've tried switching theme in vain.

I first tried to cleanup - hence the last part may apply.
It worked at first (which explains my first response), but came back.

*What I did : *
Open system.module and go to line 645

  foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

insert these two var_dump lines :

 foreach (list_themes() as $theme) {
    var_dump("-----------------");
    var_dump($theme->info['name']);
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

Visit your site. It should show something like

string '-----------------' (length=17)
string 'A Theme' (length=5)
string '-----------------' (length=17)
string 'Bartik' (length=6)
string '-----------------' (length=17)
string 'Garland' (length=7)
string '-----------------' (length=17)
null
string '-----------------' (length=17)
string 'Seven' (length=5)
string '-----------------' (length=17)
string 'Stark' (length=5)
string '-----------------' (length=17)
string 'Zen' (length=3)

See this empty line where it is written null ????
This is the F....g theme.
So I looked up to the admin theme to find the culprit and got rid of "engines" folder
...But discovered engine is not a theme, so added it back.
I then went

drush pm-list --type=Theme

And found a disabled theme named *lcov (lcov) *

Believe it or not : it is not a drupal theme !!

it is a file named lcov.info in a node module -- grunt-svgmin -- in my theme

*TADA !!! *

First attempt

The sub theme I heritated was based on ZEN, but zen was not inclued any longer.
Also, theme name included numbers abc123

On a another instance of the local site I :

Added a fresh version of zen and activated it

ran drush zen "My human readable Theme name" mymachinethemename
/* the latter will generate a clean version of your ZEN subtheme */

Adjusted the subtheme.info file for regions, assets and optins

Moved the badly named theme to another folder outside of the site

started adding back assets from the old theme, then templates and includes, piece by piece,
renaming functions to match the theme name

No need to say you need to backup and work on a dedicated branch and database.
You might have to reposition blocks in admin.

Not sure it was the most efficient but as I'm roughly new to drupal it was a great way for me to dig in this legacy theme.

Charles

Try to save you themename.info file as ANSI code.


Displaying the username of the user who created the node in the node template file I created file node--my_content_type.tpl.php, where I'd like to print the username as string. I tried the following code, but unfortunately it doesn't work. How can I do it?

<?php
  print $name;
?>

$node->name will get you the name of the author who submitted the node. It will return it as string, not as link to the user account.

$user = user_load($node->uid);
print $user->name;

This way you can get the name of author by loading the user.


Is it possible to Insert a view in a content type in drupal 7? Is it possible to Insert a view in a content type in drupal 7?
Is so can you help me do that?

The Entity Views Attachment module is the successor of the Views attach let you attach the output a view to the content of any entity.

Use PHP input filter for the content and use the following snippet:

    $view = views_embed_view('views_machine_name', 'display_id');
    print $view;

To get the display_id, hover the display option in the view, e.g. page, block, default etc. At the bottom of your browser, you'd see a url. display_id would be of the form: page_1, block_1, block_2, default.

For more control, you may use:

  // This would return an object of view.

  $view = views_get_view('views_machine_name');

  //print_r($view) to get the available data.

You may also have a look at Insert view module.


Allow Anonymous user to Subscribe while site under maintenance mode The title says it all.
I have customized the Maintenance mode page, to Coming soon!!
how i want to enable the visitors of the website to Subscribe So they'll will be notified when the website is officially lunched.
how can i Achieve this, am developing the website in Drupal in 7.

Maintenance mode is not really for this.

I would recommend using a custom theme for "Coming soon".   That way you can have them come to a home page with information and sign up/register for the site.

When you're ready to put the real site up, change themes.

I have prepared a step by step guide for allowing the anonymous user to subscribe for the node update.

Visit this link for a complete guide:
http://c.pachabhaiya.com/blog/2013/08/drupal-how-to-make-anonymous-user-subscription-on-a-particular-node-update/

Possibility for the anonymous users to subscribe to particular node.
Send email notifications automatically to the subscribed users when
that particular node is updated.


How to share Redis cache across Drupal servers? I have configured 2 Drupal servers to share the same Redis cache. One of the Drupal servers is being used for editors within the local network, the second server is used to serve up guest traffic. However, I noticed that Redis is storing cached based on the host key, so each of the two servers is storing separate keys in Redis.

What Redis configuration would be used to have it share the same keys and either override hostname to a single host or have it not use host as the key?

If you use the Redis module for Drupal, you can set the database and prefix used by your sites. The default Redis database is 0 (so multiple sites use the same database) but the default prefix is the HTTP_HOST variable (so multiple sites use different prefix). You can however, set a shared prefix on both site in their settings.php:

$conf['cache_prefix']['default'] = 'mysite_';

You can also set prefix per cache bin, to only share a subset of the cache between them. See Redis module's README.txt for more details.

Of course, this should only be done if your are sure the cache can actually be shared. In your case, I guess the sites share the database and are used to balance the load.

I am not sure if thats a good idea and if it will ever work (there might be a reason caches are namespaced per host)

There is nothing you can do at Redis level to do what you want, you have to change the way Drupal creates cache keys (drop the hostname prefix).


How can I inspect $element variable in theme function? I would like to change formatter of Field Collection Table, so that class added to a table row corresponds to a value of field of field collection item. As a first step, I would like to inspect theme function of that module. However, if I modify it to:

function theme_field_collection_table_multiple_value_field($variables) {
  $element = $variables['element'];
  $header = array();
  $cells = array();

  // Order field widgets by their widget weight.
  $instances = field_info_instances($element['#entity_type'], $element['#bundle']);
  uasort($instances, '_field_collection_table_sort_items_widget_helper');
  foreach ($instances as $field_name => $instance) {
    if (empty($element[$field_name])) {
      continue;
    }

    $header[] = _field_collection_table_get_title($element[$field_name]);
    $cells[] = array('data' => $element[$field_name]);

    // Remove the original field to prevent duplicate printing.
    unset($element[$field_name]);
  }

  $element['field_collection_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array($cells),
    '#weight' => 0,
  );

  $element['#sorted'] = FALSE;
  dpm($element);
  return drupal_render_children($element);
}

no krumo element is displayed. I cleared both opcache and drupal cache several times, but the problem persists. Also, I did deliberate error to make sure, that theme function applies. Do you know, what am I doing wrong?

If dpm($element) isn't returning output at that stage, you can log the data instead (temporarily) to the watchdog log.

e.g:

watchdog('dev', '<pre>' . var_export($element, 1) .'</pre>');

You can then view it at Admin > Reports > Recent log entries

I think you should initialize the $element variable as a array element before this part of code..

   **$element = array();**
     $element['field_collection_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => array($cells),
        '#weight' => 0,

);


Replacing theme() with render() in a block_view I'm trying to replace the theme() with render() as recommended:

https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7
So I started with:

 function mymodule_block_view()
 {
  $variables['module_path'] = drupal_get_path('module', 'mymodule');
  $block['subject'] = t('mymodule Slide');
  $block['content'] = theme('mymodule', $variables);
    return $block;
  }

And I tried

 function mymodule_block_view()
 {
    $variables['module_path'] = drupal_get_path('module', 'mymodule');
    $block['subject'] = t('OpenDTP Slide');
    $rdr = array(
      '#theme' => 'opendtp_slide',
        '#module_path' => $variables['module_path'],
     );
    $block['content'] = render($rdr);
    return $block;
}

But it says Undefined variable for module_path that I used in the tpl.php file.
How I'm a supposed to use variables in the template then ? What is the correct way of doing it ?

How about:

...
$rdr = array(
  '#theme' => 'opendtp_slide',
  '#module_path' => drupal_get_path('module', 'mymodule')
);
...


Programmatically load the contents of a Product in a particular product type I am developing an Ecommerce site and I am using Drupal-commerce module for it. I have an issue regarding loading the contents of a product which is: How can I programmatically get the contents of all the products in a particular product type?

This can be done with an EntityFieldQuery:

<?php
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->execute();
  $nodes = node_load_multiple(array_keys($result['node']));
?>

This code will help you.

$banner_query = db_select('node','n');
$banner_query->innerJoin('field_data_field_weight','w','w.entity_id = n.nid');  // join with another table
$banner_query->fields('n',array('nid'));
$banner_query->fields('w',array('field_weight_value'));
$banner_query->condition('n.status',1,'=');
$banner_query->condition('n.type','skin_and_hair_banners','=');
$banner_query->orderBy('w.field_weight_value','ASC');
$banner_res = $banner_query->execute();

while($banner_fetch = $banner_res->fetchObject()){
    $banner_load = node_load($banner_fetch->nid);
    echo "<pre>"; print_r($banner_load)
}


How to a use a template file to theme a form? While nodes, comments, blocks and many other things in Drupal are themed using theme template files (like node.tpl.php), forms are a different story. There are no theme template files for forms. How can I get a particular form to use a custom theme template?

It's completely reasonable to want to use a tpl file to display a form. You can use lots of extraneous CSS and #prefix/#suffix properties to achieve similar results, but by using tpl's you don't have to clutter up the separation of your logic and presentation layers and don't have to target ugly CSS selectors like #user-login label. Here's an example in Drupal 7...

mytheme/template.php:

function mytheme_theme($existing, $type, $theme, $path) {
    // Ex 1: the "story" node edit form.
    $items['story_node_form'] = array(
        'render element' => 'form',
        'template' => 'node-edit--story',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    // Ex 2: a custom form that comes from a custom module's "custom_donate_form()" function.
    $items['custom_donate_form'] = array(
        'render element' => 'form',
        'template' => 'donate',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    return $items;
}

custom_donate_form():

function custom_donate_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

mytheme/template/form/donate.tpl.php:

Contact Information

                <?php print render($form['first_name']); ?>

                <?php print render($form['last_name']); ?>

                <?php print render($form['address']); ?>

                <?php print render($form['city']); ?>

                <?php print render($form['state']); ?>

                <?php print render($form['zip']); ?>

                <?php print render($form['email']); ?>

                <?php print render($form['phone']); ?>

            <?php print render($form['submit']); ?>

<?php print drupal_render_children($form); ?>

This is using Foundation, which gives us a form like this:

I'm pretty sure you're able to use a template for forms, but you have to use hook_theme to register the template in the first place. I had a situation where the form really needed to be table based rather than div based and the simple #prefix and #suffix changes didn't really cut it. If interested I could probably try and dig up an example.


Custom ckeditor.styles.js file with WYSIWYG module I am trying to customize the "Font style" dropdown in CKeditor through the WYSIWYG module, but I see no way to specify a path for ckeditor.styles.js in the wysiwyg module's profile editor.

Refer to this post for futher information - it says there should be a way to specify a location for that file.

These are 2 ways (there are certainly more) to add custom ckeditor stylesets using the drupal wyswiwyg module.

Using the contributed module Ckeditor Styles
Using hook_wysiwyg_editor_settings_alter as follows:

(code "inspired" by ckeditor_styles module)

In a custom module add the hook_wysiwyg_editor_settings_alter implementation:

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 *
 * @param type $settings
 * @param type $context
 */
function MYCUSTOMMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  // We only add the settings to ckeditor wysiwyg profiles.
  if ($context['profile']->editor == 'ckeditor') {
    $format = $context['profile']->format;
    $path = drupal_get_path('module', 'MYCUSTOMMODULE') . '/js';
    $settings['stylesSet'] = "mycustomstyleset:/$path/ckeditor_styles.js";
  }
}

and add a file named ckeditor_styles.js in a sub directory js of the custom module:

CKEDITOR.stylesSet.add('mycustomstyleset',
  [
    { name : 'Red', element : 'span', styles : {'color' : 'red' } },
    { name : 'CSS Style', element : 'span', attributes: { 'class' : 'my_style' } },
    { name : 'Marker: Yellow', element : 'span', styles : { 'background-color' : 'Yellow' } },
    { name : 'Heading 4' , element : 'h4' },
    { name : 'Blue Button', element : 'div', attributes : { 'class' : 'blue-button' } },
  ]);

Just put your overridden ckeditor.styles.js file in the root of your theme, then go to /admin/config/content/ckeditor/edit/, then for each of your profiles, edit them and open up the css fieldset, find the Predefined Styles field and choose Use theme ckeditor.styles.js.

From the *Predefined Style*s field help:

  Define the location of the ckeditor.styles.js file. It is used by the
  Style drop-down list available in the default toolbar. Copy the
  sites/all/modules/contrib/ckeditor/ckeditor.styles.js file into your
  theme directory (themes/seven/ckeditor.styles.js) and adjust it to
  your needs.


Clean Deleted Field from Database I have created fields deleted them. Tables for the fields are gone upon deletion, but they are still in field_config and field_config_instance

Is there anyway to clean them?

Thanks

using drush:

$ drush eval "field_purge_batch(500)"

you might have to run a few times, or increase the $batch_size
then there might still be field_deleted and field_deleted_revision tables, even after running cron

query

SELECT * FROM `field_config` WHERE `deleted` = 1
SELECT * FROM `field_config_instance` WHERE `deleted` = 1

if you come up empty, you can safely delete those leftover tables

Can't seem to find any solution. So I ended up deleting them from those two tables manually.


How can I programmatically bulk delete redirect entities based on their status code? I have a list of 3089 301 redirects URLs and want to delete them programmatically from the database.
E.g List of source URLs
/about/test/2013/page_61732.html
/about/test/additional/branches/page_38678.html
/about/test/additional/branches/page_38678.html
/about/test/additional/branches/page_38678.html
......

If I understand your question correctly, you want to delete all redirects with a status code of 301. That could be done like this:
$ids = \Drupal::entityQuery('redirect')
   ->condition('status_code', '301')
   ->execute();

$entities = Redirect::loadMultiple($ids);

\Drupal::entityTypeManager()->getStorage('redirect')->delete($entities);

If you only want to delete redirects that have a certain source URL, you should be able to add
->condition('redirect_source__path', $sources, 'IN')

to your query.

<?php
        use Drupal\redirect\Entity\Redirect;

        //list of all source urls
        $newInputs = [
            '/about/*****/2013/page_61732.html',
            '/about/*****/additional/branches/page_38678.html',
            '/about/*****/additional/branches/winners/page_38681.html',
            '/about/*****/additional/development/winners/page_38703.html',
             .....................
        ];

        foreach ($newInputs as $input) {
                 $sourceUrl = trim($input);

                 $query = \Drupal::entityTypeManager()->getStorage('redirect')->getQuery();
                 $redirects = $query->condition('redirect_source.path', substr($sourceUrl, 1))
                           ->execute();

                 $storageHandler = \Drupal::entityTypeManager()->getStorage('redirect');
                 $entities = $storageHandler->loadMultiple($redirects);

                 foreach ($entities as $entity) {

                         //get redirect source path
                          $sourceRedirectUrl = $entity->getSourceUrl();

                          if ($sourceRedirectUrl == $sourceUrl)
                             {
                               $entity->delete();

                              }
                           elseif (urldecode($sourceRedirectUrl) == urldecode($sourceUrl))
                              {
                                $entity->delete();
                               }
                           else
                               {
                                print 'Error !! Bad Url in the record';

                                Print "Source Url from list : ".urldecode($sourceUrl)." \n Source Redirect Url " .urldecode($sourceRedirectUrl). "\n";
                                }

                }
          }

      print 'There were ' . $done . ' redirects deleted.' . "\n";


Should I choose Drupal 6 or Drupal 7? I want to use Drupal as a Framework for my application. Apart some modules, such as Image, Imagecache, Views, and Panels, I will make custom modules. I need the best performance and result.

What version of Drupal should I use?

While Drupal 7 is probably the "right" thing to do, there are a few good reasons to stick with Drupal 6.

One is the status of the modules you need.  Drupal 7 versions will be less mature than their Drupal 6.  They may have better features, but may also have bugs.  Some just don't have Drupal 7 versions yet.  You need to go through your modules and make this assessment yourself.

The other is how much legacy code you wish to reuse.  Yes, you can port, but that leads me to my next point.

Most of the projects I work on are sites for clients, and are firm-fixed-cost and firm-schedule.  In my case, I have to be conservative with third-part module choices.  My clients don't care if a project is late because of a bug in a module.  In their eyes, that is my responsibility.  Yes, I can debug modules and provide patches.  But, this takes time and   maintainers don't always accept patches.

All of this weighs into the version choice decision.

Go for Drupal 7; IMO there's no need to use Drupal 6 for new sites.


JavaScript files not loading The JavaScript files for my theme aren't loading. What am I missing?

My theme.info.yml:

name: theme
type: theme
description: Custom theme.
core: 8.x
base theme: classy
version: 8.x-1.0
libraries:
  - theme/global-styling
#stylesheets-remove:
#  - '@classy/css/components/tabs.css'
#  - core/assets/vendor/normalize-css/normalize.css
regions:
  logo: 'Logo'
  navigation: 'Navigation'
  slider: 'Slider'
  content: Content  # the content region is required
  contact: 'Contact (Content Top)'
  testimonials: 'Testimonials'
  call-to-action: 'Call To Action'
  footer_logo: 'Footer logo'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_copyright: 'Footer Copyright'
regions_hidden:
  - sidebar_first

My theme.libraries.yml:

global-styling:
  version: 1.x
  css:
    theme:
      css/animate.css: {}
      css/bootstrap.css: {}
      css/et-line-icons.css: {}
      css/font-awesome.min.css: {}
      css/extralayers.css: {}
      css/settings.css: {}
      css/magnific-popup.css: {}
      css/owl.carousel.css: {}
      css/owl.transitions.css: {}
      css/full-slider.css: {}
      css/text-effect.css: {}
      css/menu-hamburger.css: {}
      css/style.css: {}
      css/responsive.css: {}
      css/custom.css: {}
      //vjs.zencdn.net/5.8.8/video-js.css: { type: external }
  js:
    //vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js: { type: external, minified: true }
    js/modernizr.js: {}
    js/bootstrap.js: {}
    js/bootstrap-hover-dropdown.js: {}
    js/jquery.easing.1.3.js: {}
    js/skrollr.min.js: {}
    js/smooth-scroll.js: {}
    js/jquery.appear.js: {}
    js/wow.min.js: {}
    js/page-scroll.js: {}
    js/jquery.easypiechart.js: {}
    js/jquery.parallax-1.1.3.js: {}
    js/jquery.isotope.min.js: {}
    js/owl.carousel.min.js: {}
    js/jquery.magnific-popup.min.js: {}
    js/popup-gallery.js: {}
    js/text-effect.js: {}
    js/jquery.tools.min.js: {}
    js/jquery.revolution.js: {}
    js/counter.js: {}
    js/jquery.countTo.js: {}
    js/jquery.fitvids.js: {}
    js/imagesloaded.pkgd.min.js: {}
    js/classie.js: {}
    js/hamburger-menu.js: {}
    js/main.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

Try this : Add this code in .info.yml

libraries:
        - 'theme/global-styling'
        - 'theme/global-scripting'

And include the CSS and JS the libraries.yml file like below.Include styles and scripts seprately.

 global-styling:
    css:
      theme:
       css/style.css: {}

 global-scripting:
    css:
      theme:
         js/script.js: {}