Moving from custom CMS to Drupal and need to keep a myriad of old mod_rewrites

Moving effort to this question and answer Drupal 7 rewrite not using .htaccess. THis is what I'm trying to do anyhow is eliminate the .htaccess.
However, I discovered a module called htaccess

Htaccess is a module which autogenerates a Drupal root htaccess file based on your settings.
Drupal tries to provide a one size fits all htaccess for Apache webservers, but this goal is increasingly difficult. This module allows the webmaster to set specific options.

Added benefits is that for every drupal core update (in which drupal overwrites htaccess), I just re-deploy my set of rules which this module appends to the active .htaccess file. Additionally, my customization to htaccess are in the database and safe in scheduled backups in from Backup Migrate.


Extending Drupal Functionality to Custom PHP Page

The only file you need to include is '/includes/bootstrap.inc', but you also need to define the DRUPAL_ROOT constant and run drupal_bootstrap() to have access to the API/database/etc.:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Your code here

It's exactly the same code that you'll find in the standard index.php file, minus a call to menu_execute_active_handler() which isn't necessary if you dont want to build and output a normal Drupal page.


Setting up remote drush aliases for aegir

In BOA you can create sub-accounts (clients) with access limited to only associated sites, plus SSH and Drush available both locally and over SSH, with Drush aliases for all associated sites automatically created and updated for you.


How to enable "find content" for a role in Drupal 7?

Go to admin/people/permissions and enable "Access the content overview page "


How to create a new block programmatically?

The info hook defines your block in the system:

function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

and the view hook creates the output (html) for your block:

function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('My last 3 news');

    $query = new EntityFieldQuery();
    //change news by the name of your content type
    $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyOrderBy("created", "DESC")
    ->range(0, 3)
    ->execute();

    $block['content'] = '';

    foreach($entities['node'] as $obj) {
      $node = node_load($obj->nid);
          $block['content'] .= l($node->title, "node/" . $node->nid) . ' - ' . date('d-m-Y', $node->created) . '<br>';
    }

     break;
   }

  return $block;
}

Remember assign a region to your block in YOUR_SITE/admin/content/blocks

Output:

References:

How do I create a static block programmatically?


You also needs views and taxonomy to build the lists.
I'll add also shadowbox or colorbox to play videos in a modalframe.


You need to execute createDerivative() on ImageStyle.

$image_style = ImageStyle::load('550x300');

$file = File::load($img_id);
$image_uri = $file->getFileUri();
$destination_uri = $image_style->buildUri($file->uri->value);
$image_style->createDerivative($image_uri, $destination_uri);

For Drupal 7 there is image_style_create_derivative():

$style = image_style_load('550x300');

$file = file_load($img_id);
$image_uri = $file->uri;
$destination = image_style_path($style['name'], $image_uri);
image_style_create_derivative($style, $image_uri, $destination);


How can I set the language of nodes in bulk to existing content when making a site multilingual?

Here's one way to do this that doesn't involve writing any code.

Install the VBO module.
Create a new view showing Content of whatever content types you need to convert.  Use the Fields display method.
Add a field Bulk operations: content.
Check Modify entity values and select Language.
Choose Apply.
Save the view (add any other filters if necessary to limit the selection) and go to the created view page.
From the view page, choose the option to select all items on all pages and execute the Modify entity values action.
Choose the language and click next.

If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)


How to override default cardinality for the field widget?

You can use Field instance cardinality module which allows the cardinality of specific instances of fields to be overridden.

This module allows the cardinality of specific instances of fields to be overridden.
This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.


Multi-site installation with shared database but different user table

You can try editing you sub-sites settings.php file and you just need to provide different prefix for user table (as you need only this table different).

I am providing sample here so that you can implement and see if it works.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
           'users'     => 'abcsite_',
      ),
    ),
  ),
);

The above code will tell your installation to use abcsite_users (you need to create table first with same structure as of default users table) for entering user details.


How do I set a custom input format for a field?

Managed to create a new field with "Text - Formatted - Long" as default, which allowed me to set up my custom text format. Why is that not possible for plain text field I am not sure.


htmlLawed in text format corrupts Scald insert in CKEditor module

The solution, simply, is to change a Security setting of the CKEditor profile meant by this issue as follows:

1 - go to `admin/config/content/ckeditor/edit/(TheProfileName)

2 - In Security tab, goto Security Settings and choose Run security filters only when CKEditor is set to start automatically.

Of course, you have to notice that CKEditor in this profile is not started automatically.


How can I get the name of the currently logged in user in Drupal 7 in the external file?

I advice you to:

create a module
put your script in that module (inside one or more functions)
implement hook_menu() to define the url you can call (eg. example.com/mytuff/ajax) and set your script's (main) function as the 'page callback'
instead of returning stuff (like page callbacks normally do) print your output and exit() at the end


Trying to get property of non-object in simplenews_scheduler_node_page()

This issue was solved by deleting the node (master newsletter) and creating a new one. I had probably deleted a previous test edition, which caused it to start delivering the error. If there is only one test edition, don't delete it even if the master is preserved.


RDF core module doesn't seem to work after security upgrade

Here is a workaround at #9 that solved the problem for me.

  As workaround, you could use the RDFa Distiller and add the
  following code to .htaccess:

<IfModule mod_rewrite.c>
   RewriteEngine on
+  # call W3C RDFa Distiller to extract .rdf/.ttl/.nt files
+  RewriteRule (.*)\.rdf$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=xml [L,R=307]
+  RewriteRule (.*)\.ttl$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=turtle [L,R=307]
+  RewriteRule (.*)\.nt$ http://www.w3.org/2012/pyRdfa/extract?uri=http://%{HTTP_HOST}/$1&format=nt [L,R=307]
+
   # Set "protossl" to "s" if we were accessed via https://.  This is used later
   # if you enable "www." stripping or enforcement, in order to ensure that
   # you don't bounce between http and https.

Many thanks to jneubert!


Body content appears to anonymous viewer but not to site admin

Check the field permissions in your content type. If you added custom permissions to a field and did not grant admin role access, the node will not be displayed.

By "admin" do you mean uid1 superuser or user in a role named "admin"


get form state values of forms which added via ajax

Try $values= $form_state['values'];

and then dsm the values. You will get all field values of the form.

I think you should get the form values of ajax in $form_state['values']['addstudent_wrapper']['fields_wrapper'][0]['field_name'] and so on.


How do I restrict a user to visit a particular page only certain no of times?

If you want to restrict a casual user to only 5 views of ANY premium content, versus restricting his/her looking at the same piece of content 5 times, you might want to consider storing this information in the user's data field.

In broad strokes, you could in a custom module's nodeapi hook, do something like this:

if op is view
  if type is premium
    if user doesn't have a premium role assigned
      load the full user object
      if s/he has seen 5 pieces of content
        drupal_goto signup page
      else
        increment count of free page views
        save user
        if this is the 5th view
          tell user this is the last freebie
        fi
      fi
    fi
  fi
fi

Look into user_save() and user_load() for how to save and load serialized information into and from the data field/column of the user.  Also look into hook_nodeapi() for how to intercept these views.

Also caveats you will have to be aware of is cron and search, you probably don't want them to be limited by this, and that drupal_goto in there might/will reek havoc if it isn't trapped for these purposes.


cant loop through array with ajax_command_html

Try with this:

  $string = $form_state['values']['search_block_form'];

  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'n.nid = b.entity_id');

  $query
    ->fields('n', array('nid', 'title'))
    ->fields('b', array('entity_id', 'body_value'));

  $db_or = db_or();
  $db_or->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
  $db_or->condition('b.body_value', '%' . db_like($string) . '%', 'LIKE');
  $query->condition($db_or);

  $results = $query
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);

  $commands = [];

  foreach ($results as $result) {
    $node_title = $result['title'];
    $node_id = $result['nid'];
    $entity_id = $result['entity_id'];
    $body_text = $result['body_value'];
    $commands[] = ajax_command_html("#block-system-main", "
" . $node_title . "

" . $body_text . "
");
  }
  return array('#type' => 'ajax', '#commands' => $commands);


Migrating body text from 7 to 8, markup displays until edited and saved

source: body_format

should have been

source: format

Turning off "bypass: true" let me see that it was just dumping them in with NO input set, opening and saving changed it to the default for that field.


Drupal 7.16 started sending duplicate account activation emails

OK, not sure what was happening there! I changed the settings on admin/config/people/accounts and removed the need to confirm email address ("Require e-mail verification when a visitor creates an account.".

This didn't work - still duplicates being sent out when activated.

Then I de-selected "Notify user when account is activated." (Under "Account Activation" tab) and this stopped them being sent.

Then I re-enabled "Notify user when account is activated." AND modified the email template.

Now it's only sending the one email again!

For some reason, this also fixed the rule emails that were getting duplicated... Beezaaar!

Any ideas?


Go to all recommended versions.

I was using different/more recent dev/alpha/beta versions of certain modules, but when I went to the recommended versions of...

panels (8.x-3.0-beta4)
page_manager (8.x-1.0-alpha23)
layout_plugin (8.x-1.0-alpha22)

... everything seemed to work okay. This was as of 7-6-2016


I ended up solving this myself.  My main question I guess was really about a feeds tamper plugin that can insert multiple values.  Turns out it's pretty easy, just return an array and I think set the 'multi' value on the plugin.  I ended up copying the "explode" plugin and modifying it for my needs.  Here is the result.  It's got some hardcoded values which I'm sure could be coded into the form settings.  I kept it simple for my purposes.

$plugin = array(
    'form' => 'my_feeds_tamper_image_import_form',
    'callback' => 'my_feeds_tamper_image_import_callback',
    'validate' => 'my_feeds_tamper_image_import_validate',
    'name' => 'My Image Import',
    'multi' => 'direct',
    'category' => 'List',
);

function my_feeds_tamper_image_import_form($importer, $element_key, $settings) {
    $form = array();
    return $form;
}

function my_feeds_tamper_image_import_validate(&$settings) {

}

function my_feeds_tamper_image_import_callback($result, $item_key, $element_key, &$field, $settings, $source) {
    $out = array();
    $index = 1;
    $fileExists = true;

    do {
        $filename = "public://import/" . $field . "_" . str_pad($index, 2, "0", STR_PAD_LEFT) . "_lg.jpg";

        if( file_exists($filename) ) {
            $out[] = $filename;
            $index++;
        }
        else {
            $fileExists = false;
        }

    } while($fileExists);

    $field = $out;
}


How add sorting by Flag counter in Controller?

The flag count in another table called flag_counts so you should do join with node table try the following:

$database = \Drupal::database();
$query = $database->select('node', 'n');
$query->fields('n', [])
  ->condition('nfd.status', '1', '=');
// Inner join to get the node status.
$query->innerJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
// This join to get the flag counts by node.
$query->leftJoin('flag_counts', 'fc', 'n.nid = fc.entity_id');
$query->fields('fc', ['entity_id', 'count']);
// Sort by count.
$query->orderBy('fc.count', 'DESC');
$query->range(0, 10);
$result = $query->execute()->fetchAll();


That's exactly how it is supposed to work. Hooks are functions defined by Drupal for you to add functionality to the system through your modules. Hooks are like open doors for you to add things.

From Drupal's documentation:

  To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Obviously, the more hooks defined in different modules, performance gets hit. But you can't avoid that. You shouldn't stop adding functionality to your modules through hooks because of this.


Validate based on existing CCK field value?

You should be able to use hook_nodeapi for this!

In this example I'm assuming the node type is blah

In a custom module just write something along the lines of:

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate' && $node->type == 'blah') {
    $sql = db_query("SELECT bl.field_address
           FROM {content_type_blah} bl
           WHERE bl.field_address = '%s'", $node->field_address)

    if ($sql != '') {
        form_set_error($node->field_address, t('This address is already being used'));
    }
  }
}

That way, before a node is saved (during the validation) it runs an SQL query to see if the address field is duplicated anywhere else on any other node with the type blah.  If it is, then it throws an error on the form field!  You will need to tweak the query dependant on your table names etc.

I'm only writing that code from the top of my head, and I've not tested it (sorry) but it should definately be a starting point!  I may have the $node->field_address part wrong!

If all else fails, put a die(print_r($node)); after the if ($op == 'validate'... line and you can get the right part from that!

Hope this helps :)

References:

http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_nodeapi/5
http://api.drupal.org/api/drupal/includes--form.inc/function/form_set_error/6


Assigning permissions based on taxonomies

Organic Groups sounds like a better way to go in this situation. Each class is a group (can still categorize them using taxonomy), but will give you the sub-permissions you require per class (group) (e.g. teacher being able to enroll and administer their own group and students only being able to submit content in their own class)

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

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

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


Delete query is called while updating the value of node

As the comment at the top states: Delete and insert, rather than update, in case a value was added.

So to make sure all old data is cleared, the records are deleted and re-added with new data (as you can see on line 481: $query = db_insert($table_name)->fields($columns);.

Of course you could use the update query, but this query would need to contain all fields because it is impossible to know which fields are added, modified or deleted. A simple delete and add solves that problem.


It is possible, but the values used to filter that list are put in $_SESSION['dblog_overview_filter']. Linking to that page and making it shows the messages filtered by type is only possible if you set that session variable with the right value. Looking at the code of dblog_filters(), I get that the following line would cause that list to show the logs about cron tasks.

$_SESSION['dblog_overview_filter']['type'] = array('cron');

References

dblog_overview()
dblog_filter_form()
dblog_filters()


Scroll to search results on Views Exposed Filter submit button

You can do this in your theme when the page loads and has search results

Create search_results.js

(function ($) {

  'use strict';

  $(document).ready(function() {
    if( $('.views-row-1').length ){
      $("html, body").animate({ scrollTop: $(".views-row-1").offset().top }, "slow");
    }
  });

}(jQuery));

which on page load sees if the first result is not empty and scrolls to it

Load file on specific view page

In your template.php

function THEMENAME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'view_resources_advanced_search') {
    drupal_add_js(drupal_get_path('theme', 'THEMENAME') . 'js/search_results.js');
  }
}

Of course make sure you change THEMENANE and make sure the view machine name is correct in the template.php file


How do I get the user ID from the $user_profile variable?

You cannot get the uid from $user_profile as it does not contain any information we can use to get the current user.

To get the current user's object, use the following:

global $user;
echo $user->uid;


How to resolve fatal error 'Cannot redeclare commerce_kickstart_preprocess_html'?

Because the two file paths are the same file, it suggests a possible problem with your op-code caching.

Check if you have any PHP op-code cache enabled; you should only have one op-code cache utility and may need to disable one.

You may also need to tweak your APC settings (if enabled).

apc.include_once_override = 0

Check also https://stackoverflow.com/questions/4575341/php-with-apc-fatal-errors-cannot-redeclare-class.


Hook for when a new content type is created?

hook_node_type_insert() is invoked from node_type_save() after the node type is added to the database.

See:
hook_node_type_insert()


These are two separate questions. One about the path, another about the breadcrumb.

Breadcrumbs:

Disclaimer: The solution presented here may need more tweaking, if your taxonomy/term/% is replaced by a views page with contextual filter. (I never do that, there are other ways to achieve the same)

Crumbs will do the trick. 90% of the task out of the box. If not, check this doc: http://drupal.org/node/1984484

You need some manual work to make "/category" the top-level breadcrumb item for all the terms: (this explanation is for the 7.x-2.x branch)
Visit Admin > Structure > Crumbs > Entity parent > Taxonomy
Set 'category' as the parent path for your vocabulary.
Go back to Admin > Structure > Crumbs
Move crumbs.entityParent.* into the "Enabled" section, and give it a low enough priority.

Path:

I suppose you have pathauto installed already.
Go to Admin > Configuration > Search and metadata > URL aliases
Look at "Taxonomy term paths".

I read somewhere that the following pattern will do the trick:

category/[term:parents:join-path]/[term:name]

Not tested myself. Good luck with it :)


Include specific stylesheet for specific language?

So you will probably need to remove the style sheet from your info file and add it in a pre-processor.

I normally don't recommend using pre-processor functions but this is kind of the ideal exception to that rule. Checkout template_preprocess_html. In that hook you can pull the active language setting and conditionally add the language specific css file with drupal_add_css

function mytheme_preprocess_html()
{
  // Don't remember the code for this but you can figure that out.
  $language = getLanguage()

  if ($language == 'chinese_traditional')
  {
    drupal_add_css(drupal_get_path('theme', 'mytheme') . '/chinese.css');
  }
}

If the get language function uses a database call it would be better to do this in a custom module. DB calls in the theme are pretty much always a bad idea. You would in that case use the same code in hook_preprocess_page. At least that is what I was always told to do.


goto: Home » Administration » Configuration » Regional and language » Languages.
select the 'DETECTION AND SELECTION' tab.
Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'


You can try Hierarchical Select module. Project page says

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.

It will give you a way to select hierarchical items using select boxes.


Use Pathauto module.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


How can I create a modal popup from a CartEvents::CART_ENTITY_ADD
  event subscriber? Am I missing something to do with the libraries or
  something wrong with my php?

You can't return a response from any event, this is only possible from specific kernel events by setting the response in the event. But the example you have linked should work in your case. It splits the task into two event subscribers:

  public static function getSubscribedEvents() {
    return [
      CartEvents::CART_ENTITY_ADD => 'onAddToCart',
      KernelEvents::RESPONSE => 'onResponse',
    ];
  }

which are in the same service class, so the second event can use the variable the first one has set:

  public function onAddToCart(CartEntityAddEvent $event) {
    $this->purchasedEntity = $event->getEntity();
  }

  public function onResponse(FilterResponseEvent $event) {
    $response = $event->getResponse();

    // We only care if this happened after an entity was added to the cart.
    if (!$this->purchasedEntity) {
      return;

    ...

    $event->setResponse($response);
  }


Drupal 7 : i want to add the registration fields (username/e-mail etc) to a profile 2 registration form

I have achieved the above with a similar setup to yourself.

You state you have used 'registration wizard', so I assume you have created custom forms for the profile2 fields. Furthermore, you are validating and submitting the values at the end.

The simplest method is to create a custom form at the beginning of your process for username, email, password, etc. Then using the user_save() function. Of course you will need to ensure current users don't exist already, which is easy enough using user_validate_mail().

Hope this help.
Amarjit


Easiest way to get term entities from a term reference field?

This one annoys the bejesus out of me too. Things are slightly nicer using the entity API module, but it's still not pretty.

I've resorted to including a helper function in most projects now to extract an array of values for a single field column:

function _field_get_column_values($entity_type, $entity, $field_name, $column_name) {
  if ($field_items = field_get_items($entity_type, $entity, $field_name)) {
    $values = array();
    foreach ($field_items as $item) {
      if (isset($item[$column_name])) {
        $values[] = $item[$column_name];
      }
    }
    return empty($values) ? FALSE : $values;
  }

  return FALSE;
}

Using that your code would shrink a little:

if ($tids = _field_get_column_values($entity_type, $entity, $tags_field, 'tid')) {
  $terms = taxonomy_term_load_multiple($tids);

  // ...
}

It's still not a great solution, but I find it saves a fair bit of time on projects that need a lot of custom code.


How to programmatically set the node updated/changed timestamp

OK, for this approach, the solution was to ensure another table was also updated with the changed timestamp: node_field_revision

e.g:

update node_field_revision set changed = 1535805325 where nid = 2148716 and vid = 2803575;

After that, a normal cache clear showed the new updated timestamp for the node.


Uploaded file not shown in custom content type / Image not attached to content type

These fixed it:

-I changed the content type to image instead of media browser.

-Reviewed the permissions for file and this particular content type.

-Changed the field display of the content type


How to use 'use-ajax' class with pages created by controller?

This is a render array that create a link that open a modal windows.

use Drupal\Core\Url;

public function build() {
$output = array();
$output['overlay_link'] = array(
  '#type' => 'link',
  '#title' => $this->t('Add an activity'),
  '#url' => Url::fromRoute('node.add', ['node_type' => 'event'], ['query' => ['destination' => $destination],
    'absolute' => TRUE,]),
  '#attributes' => [
    'class' => ['use-ajax', 'button', 'secondary'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => \Drupal\Component\Serialization\Json::encode(['title' => t('Add an activity'), 'width' => 800,]),
  ],
);
 return $output;
}


how to setting drupal i18n translation module not to translate system menu I don't want?

You can try Administration Language module.

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.


Multisite config directories of subsides

It's a little bit up to you how you manage your config. In my multisites I have a ../config directory outside the web root. Each site instance then has it's own folder in there. And inside each one I split the config per environment.

shared/ holds the config that is similar on all environments. local/ holds all the extra config for local development. And live/ holds the extra config for the live site. This can be achieved using the Config Split module.

project/
├── config/
│   ├── bar/
│   │   ├── live/
│   │   ├── local/
│   │   └── shared/
│   └── foo/
│       ├── live/
│       ├── local/
│       └── shared/
└── web/
    └── sites/
        ├── bar/
        └── foo/

The settings.php config for the foo/ instance then looks like this:

$config_directories['sync'] = '../config/foo/shared';

And the Git-ignored settings.local.php on my local machine looks like this:

$config['config_split.config_split.local']['status'] = TRUE;
$config['config_split.config_split.live']['status'] = FALSE;

Whereas on the live server it looks like this:

$config['config_split.config_split.local']['status'] = FALSE;
$config['config_split.config_split.live']['status'] = TRUE;


You can create a new node type "vouchers" and use UUID module to add uuids to these nodes. When the office creates a new voucher it will automatically be assigned a uuid which you can then use as your code to give the student.

When the student shows the store their code the store can lookup that voucher in a Vouchers view using the uuid filter. Then the store can mark the voucher with a boolean "Used" custom field to show they are redeemed.


how to create rules to send email notification for node reference content?

Sure, with the Rules module create a new rule with this configuration:

At admin/rules/trigger/add choose a name for your rule
In the Event dropdown choose After saving new content and click 'Save changes'
Add a condition of: Content has type under the Node heading in the conditions dropdown
Add an action of: Load a referenced node under the CCK dropdown heading and choose the node reference field you want to use (the one in the job app content type) and click 'Save'
Add another action: Load a user account under the User dropdown heading. In the User id field, add <?php print $referenced_node->uid; ?> and click 'Save'
Add a third action: Send a mail to a user under the System dropdown heading, changed the Recipient dropdown to Loaded user and configure the Sender, Subject, and Body of the email and click save.

Now when a user creates a job application an email will be sent to the user who created the referenced job posting (assuming there is a value in the node reference field, it should be required).


Why is it easily possible to theme node add forms and not node edit forms?

Have you got the code in your template.php file set up correctly?

It should look like this:

function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'FORMNAME' => array(
           'arguments' => array('form' => NULL),
           'template' => 'page--node--add--mycontenttype.tpl.php',
          'render element' => 'form',
          ),

You can find FORMNAME, by viewing the source of the page and looking for the id of the form.


How can I automatically apply a shipping service and skip shipping selection during checkout?

You can use Rules for this. You can modify the rule export below and either import it directly into Drupal or include it in MYMODULE.rules_defaults.inc:

/**
 * Implements hook_default_rules_configuration().
 */
function MYMODULE_default_rules_configuration() {
  $configs = array();

  $configs['rules_auto_add_shipping_service'] = rules_import('{ "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Commerce Shipping" ],
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : "standard_shipping"
          }
        }
      ]
    }
  }');

  return $configs;
}

In the example above, the rule fires when an order is updated. When an update occurs it:

Removes all shipping line items from the order. (commerce_shipping_delete_shipping_line_items)
Collects rates for the specified shipping method. You can edit the shipping_method_name from flat_rate to any service you are using (it doesn't have to be Flat Rate).
Applies a particular rate. This rate must be collected during the previous step.

Now, your order will always have a shipping rate applied to it.

To skip checkout, you can disable the shipping pane using the UI or use something like the snippet below to handle it in code:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // No need for shipping since it's auto-selected.
  $checkout_panes['commerce_shipping']['enabled'] = FALSE;
}


How to replace 'reply' link with button?

There are two methods below. Both are equally effective except the second one requires that the <button> element be taken out of the list of links and put elsewhere in the template. This is either annoying or awesome depending on what outcome you're going for.
Method 1: Override MYTHEME_links()
In Drupal 7, you can turn the comment "Reply" link into a <button> element by overriding core's theme_links() function. It isn't pretty, but it's effective.
Add the function below to your theme's template.php file (replace "MYTHEME" with your theme name). Clear your cache for the change to take effect.

function MYTHEME_links($variables) {
  $links = $variables ['links'];
  $attributes = $variables ['attributes'];
  $heading = $variables ['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading ['level'];
      if (!empty($heading ['class'])) {
        $output .= drupal_attributes(array('class' => $heading ['class']));
      }
      $output .= '>' . check_plain($heading ['text']) . '</' . $heading ['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class [] = 'first';
      }
      if ($i == $num_links) {
        $class [] = 'last';
      }
      if (isset($link ['href']) && ($link ['href'] == $_GET ['q'] || ($link ['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link ['language']) || $link ['language']->language == $language_url->language)) {
        $class [] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

      elseif (!empty($link ['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link ['html'])) {
          $link ['title'] = check_plain($link ['title']);
        }
        $span_attributes = '';
        if (isset($link ['attributes'])) {
          $span_attributes = drupal_attributes($link ['attributes']);
        }
        $output .= '' . $link ['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Breaking it down...
This bit of code:
      if (isset($link ['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link ['title'], $link ['href'], $link);
      }

was changed to
      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

Of course you'll need to customize the output with whatever you need, whether it be a <form> wrapper or onclick attribute.
Unfortunately we can't use theme('button'...) because that would give us an input element. Of course we could change that by overriding theme_button() but that would affect all input elements on the site, and you would still need to override theme_links() in order to call it.
Method 2: MYTHEME_preprocess_comment()
If you don't mind taking "Reply" out of the links list altogether, this method will also work. It uses the comment preprocessor to unset the link, but not before taking the value of the URL and stuffing it into a new variable.
Again, add the function below to your theme's template.php file (replace "MYTHEME" with your theme name).
function MYTHEME_preprocess_comment(&$variables) {
  if (isset($variables['content']['links']['comment']['#links']['comment-reply'])) {
    $variables['reply_url'] = $variables['content']['links']['comment']['#links']['comment-reply']['href'];
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

Then add this (or a variation of it) wherever you would like it to appear in your copy of comment.tpl.php:
<?php if (isset($reply_url)): ?>
<button onclick="window.location.href='<?php print $reply_url ?>'">Reply</button>
<?php endif; ?>

Clear your cache for the change to take effect.


t() function doesn't translate strings inside node fields

Have a look at the options you can pass on to the t() function. You can explicitly say which language you want.

So you might do something like this to handle you message content :

$to_user = get_destination_user(); // whichever way you do that...
$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $to_user->language ));

In essence something like the above should do it.

Also make sure that the user language is set and valid. For this you might do something like :

$to_user = get_destination_user(); // whichever way you do that...

// get destination user language if set
$message_lang = !empty($to_user->language) ? $to_user->language : '';

// check if language is defined on our site
$languages = language_list();
if (!isset($languages[$message_lang])) {
    $message_lang = '';
}
// check if the language is enabled
if (!$languages[$message_lang]->enabled) {
    $message_lang = '';
}

$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $message_lang ));


They are not visible in search results

http://drupal.org/project/search_config

They are shown in a different container

Templating system, or blocks, or panels

They are visible only to some users based on user-roles

EDIT

Those 2 steps are equal, but becose my understanding problem the last point can be different.

In /admin/people/permissions you should have the options to allow only some roles to access the forms nodes.


Views 3, link picture/title to users blog

Figured this out:

Add field uid to views.
Go to picture field in views, click rewrite results and output this as link, and then for link path: /blogs/[uid]

Make sure the field uid is visabally above al lthe other field in the view.


how to update my custom table after execution of rules

In rules you have option to add PHP code inside the Action ->PHP-> "Execute custom PHP code " in that have a code to update the custom table.

The following variables are available and may be used by your PHP code:

Variable name Type    Description

$site   Site    Site information

$node   Content updated content

$node_unchanged Content unchanged content

you can use for updating the table if its a node

Note : here node represented as a example


Number items in a grouped view, resetting counter with each group

You can use the HTML List format. In the settings of this format, you can set the grouping field and then set the list to an ordered list.
By doing this, you won't need any global counter.
See in the following screenshot how the list would be rendered.


How do I limit use of Simple XML Sitemap to certain roles?

I found the answer based on this drupal.org comment.
You have to use hook_node_insert().
/**
 * Implements hook_node_insert() for MYMODULE.
 */
function MYMODULE_node_insert(EntityInterface $node) {
  switch ($node->getType()) {
    case 'page':
      $user = Drupal::currentUser();
      if (!$user->hasPermission('administer content')) {
        // Turn off Simple XML sitemap.
        $generator = \Drupal::service('simple_sitemap.generator');
        $generator->setEntityInstanceSettings('node', $node->id(), ['index' => FALSE]);
      }
      break;
  }
}


Migrate multiselect taxonomy values from node with csv

I found it myself.
This is working for me:

process:
  title: title
  body: body
  field_company:
    -
      plugin: explode
      source: categories
      limit: 100
      delimiter: ;
    -
      plugin: entity_generate
      ignore_case: true
  type:
    plugin: default_value
    default_value: company

and a CSV like this:

id,title,body,categories
6,company,body text,"cat1, some text;cat1, some other text"


For field definitions, I find that the easiest thing to do, is to create the field in the UI and fetch the definition using field_info_field and field_info_instance and then dump the variable using the devel module (dpm) oe something similar.

Alternatively you could browse code, field types are defined in hook_field_info and widgets are defined in hook_field_widget_info (the form for the field) and formatters are defined in hook_field_formatter_info (how fields are rendered).


Add new items to a multivalue field instead of override existing values

You need to loop through all articles, saving all countries in an temp array. When the loop finished save the countries in the book node.

For example:

$countries = [];
// Loop through loaded articles.
foreach ($articles as $article) {

    // Get the "Countries" Values.
    $countries = array_merge($countries, $article->get('field_article_countries')->getValue());
}
// Set the 'countries' values to the node "book".
$book->set('field_book_countries', $countries);
// Save Book node.
$book-->save();


What are the URL Alias pattern replacements for taxonomy parent terms when building up Node paths?

There are some advanced uses of tokens (not sure off the top of my head if that's just in the context of pathauto or not). You can get what you're looking for with join:

[node:field-name:parents:join:/]/[node:field-name:name]/[node:title]

You could also replace your term pattern with:

[term:parents:join:/]/[term:name]

Using that method your vocabulary can grow gracefully to 4 (or more) levels without having to change the pathauto pattern.

You'll need to go to admin/config/search/path/settings and set the Slash (/) option to "Do not Replace" under "Punctuation" for that method to work.


The discount rate isn't always available as a percentage (like, for instance, taxes are) because discounts can be whole numbers as well. Regardless, you can ultimately get information about how a price is calculated by looking at the commerce_order_total field on an order or the commerce_total field on a line_item.

Here's an example:

In this screen shot, we'll take a look at 4 items. For the comments assume $price = $order->commerce_order_total[LANGUAGE_NONE][0].

$price['data']['components'][0]['price']['amount'] is the original amount. You know this because $price['data']['components'][0]['price']['amount'] is "base_price".
A discount price component will a name of "discount|DISCOUNT_ID" where DISCOUNT_ID is the machine name of the discount that is being referenced.
$price['data']['components'][1]['price']['amount'] in this instance is the discount that is applied.
$price['amount'] is the combination of all of the components under $price['data']['components'].

There is a data array under the price information on the discount. It contains the label and the machine name of the discount, but it doesn't have any other information. Custom discounts might put more information on there, but you can't necessarily depend on anything else being there.


Let users access account before confirming email address

You can do this by help of LoginToboggan module. There are so many features of this module, immediate login is one of them.


Getting a 500 error with the Domain Access module

To debug WSOD, you need info what exactly went wrong. There is a pretty neat article about fixing them - try to follow it. Around step 2a you should pretty much know what you need to look for in documentation.


Dependency injection in Drupal queueworker plugin

Long story short, your plugin needs to implement ContainerFactoryPluginInterface for services to be injected.

Something like this:

namespace Drupal\simplified_bookkeeping\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\custom_example\Entity\BookingEntity;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Processes Sales Tasks.
 *
 * @QueueWorker(
 *   id = "sales_queue_processor",
 *   title = @Translation("Generate sales from bank/cash statements in queue"),
 *   cron = {"time" = 10}
 * )
 */
class SalesQueueProcessor extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryFactory $entity_query, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->entity_query = $entity_query;
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.query'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($bid) {}
}

As an aside, the entity manager service is deprecated; the entity type manager should be used instead. You also don't strictly need to inject the entity query service as you can get an instance from the manager, e.g.:

$query = $this->entityTypeManager->getStorage('node')->getQuery();


Is it possible to assign attributes to different roles?

Yes. There many ways to go about this but the Profile2 module is one that covers the entity field data (variables) per a specified user role.

  Designed to be the successor of the core profile module, which is
  deprecated for Drupal 7. In contrast to the deprecated module this
  module provides a new, fieldable 'profile' entity - leverage the power
  of fields!

Your your student role can be assigned to have to have a student profile which a Teacher can edit, but only a student can view. It has the additional permission View Own Profile... which should restrict students from seeing other profile pages.


You should take a look at the office hours module. While it might not be created for your use case, it allow you to store repeatedly dates for stuff like each friday 10:00-16:00.


drupal_render does not render concatenated elements

drupal_render() renders an array.

The var $complete0 in your code is a string, so you shouldn't be passing it to drupal_render().

Either use render(), which works for strings too, or convert $complete0 to a render array.


How to embed and choose entityform in custom content type?

OK, so I gather the problem you are trying to solve is the fact that a non-administrator cannot pick an entityform from the list? The solution: go to /admin/structure/entityform_types, choose "Edit" for each Entityform and be sure to check the boxes in "Roles" for "authenticated user". That way anyone logged in should be able to see and use the form.


Drupal 7 with front-end in Spanish/English; Back-end in English only

I just found what I suppose is my "fix"... in "admin/config/regional/language/configure", I unchecked "Session", "User", and "Browser" in the "User interface text language detection" section, leaving only "URL" and "Default" checked. This seems to have fixed my issue.


How can I check the fields I've created?

You can activate "Field UI" module in your modules list.


How to know if a specific role can access a page?

You can make use of Masquerade module to switch users who belongs to different roles. This will help you see what other role users see.


To get the base_url (path) you will need this in your THEMENAME.theme file

function THEMENAME_preprocess_page(&$variables) {
  global $base_url;
  $variables['base_path'] = $base_url;
}

Then it will be available in your twig template

But most of the times you will not need the full path to display an image

You can try the following

{% set img_url = item.image.url ? item.image.url : '/'{{ directory }}'/images/default.png' %}


Views Contextual Filter by taxonomy in field collection

Once you have the Relationship to the Field collection, you can add all the other information you need (Relationships to Models and Years if necessary, you'll probably need them too).

Then if you go to add Contextual filters, you will see that Contextual filters for Models and Years fields have become available.

Configure each one to Provide default values from the node you're on (you choose that from the Drop-down under that option).

It's good to test Contextual filters one by one and make sure they work on their own before combining them.

Or in the Views Preview you can test by entering all/[year] to test the second one, or [model]/all to test the first one.

Then place the Block and test that they work in real environment, because Preview only tests the "from URL" part.


How to execute hook_cron after a rule with event Cron maintenance tasks are performed?

You can adjust the weight of your module so that it gets executed after Rules.

See this question  for more details.


Drupal 7 Core Module Function for node_save?

DO NOT HACK CORE

Now that's out of the way, let's continue.

The way I see it, you have a couple of options:

1) Use Rules.

  The rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Although this will allow people to see that there is code being run.

2) Create a custom module, but in your info file make use of the hidden property:

  As of version 7.x, modules and themes may specify that they should not
  be visible on the modules page by adding hidden = TRUE. This is
  commonly used with testing modules used with SimpleTest where
  end-users should never enable the testing modules.


Display one recent comment in node teaser?

Add Views, Token, and Viewfield modules.

Make a new view. The first page gives you most of it: Show comments, newest first. Make a page, limit the number to 1. Continue & Edit, and set the contextual filter to Content: Nid. Be sure and save it. :-)

Edit your content type. Add a new field, of type Views. Set the default view to be the 'recent comment' one you just made. Under 'Default Values,' have it always use the default view, and have [node:id] as an argument. Save that.

Now you can manage the display of this field in the 'manage display' tab, and place it in the 'teaser' view.

You might find that showing the whole comment under the teaser looks wrong, so then it's time to go back to the view and tweak it so it uses fields instead of the whole comment.

HTH.


Import won't import content in CCK image fields

Are the images already in the directory in the new site?  For most import modules, the images Have to been in the directory before you start importing.


hook_options_list not getting fired in a custom module

You can use hook_field_info_alter() to attach custom allowed_values_function to your field and implement your own logic there:

function my_module_field_info_alter(&$info) {
  $info['my_field']['settings']['allowed_values_function'] = 'my_module_my_field_allowed_values_callback';
}

function my_module_my_field_allowed_values_callback($field, $instance, $entity_type, $entity) {
  // Custom logic
  return $values;
}


8 - Is It Possible To Create Routes Through The Admin

You may want to check out the Rabbit Hole module.

  Rabbit Hole is a module that adds the ability to control what should
  happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its
  own page, like an image content type that's displayed in a carousel.
  Rabbit Hole can prevent this node from being accessible on its own
  page, through node/xxx.


You probably missunderstood the two different templates here

The node template(node.tpl.php): This is for rendering a specific node
views template This is for wrapping the node + comments

So all you have to do is to use the node.tpl.php to theme a single file.


What does this error mean and how can I fix it?

It's a notice, not a big deal to make you worry as it says, there is an undefined line in your display suit module


How to utilise RequireJS and still access Drupal(7) JS API?

Woops, I'm not sure how the explanation got lost!

The script include:

<script id="requirejs" data-rev="1485975293" data-main="main.js?rev=1485975293" src="require.js?rev=1485975293"></script>

Alright, so this is in my main.js (data-main) file, that requirejs uses for loading up the dependencies and all that.

I'm just posting the relevant code block here (notice the Drupal.attachBehaviors(document, Drupal.settings); at the end:

    require([
      'jquery',
      'underscore',
      'intentcontext',
      'app',
      'primary-menu'
      ], function ($, _, IntentContext, app) {
      'use strict';

       // DOM ready
      $(function() {

        // js loaded only on homepage
        if ($('body').hasClass('front')) {
          require(['homepage']);
        }

        /*
         * loaded js for foundation and intention
         */
        require(['foundation']);
        require(['intentinit']);

        // call drupal behaviors
        Drupal.attachBehaviors(document, Drupal.settings);
      }); // DOM ready
    });

And then example of a dependent js module (primary-menu.js):

    define([
      'jquery',
      'intentcontext'
    ], function ($, IntentContext) {
      'use strict';

      /*
       * constructor
       */
      var PrimaryMenu = function(context, settings) {
        var
          self = this;

        self.$elm = $(context).find('#block-system-main-menu');
        $('body').once('primaryMenu').each(function() {
          self.init();
        });
      }; // PrimaryMenu constructor

      /*
       * on document ready with drupal behaviors
       */
      (function($, Drupal) {
        Drupal.behaviors.primaryMenu = {
          attach: function(context, settings) {
            var
              primaryMenu = new PrimaryMenu(context, settings);
          }
        };
      }(jQuery, Drupal));
    });

Hope that helps.


I haven't tried something like this before, but one way to solve it would be to.

Create a node type to hold the images.
Create a node reference to the image node type.

This would allow you to have several nodes reference the same image node type. You would also be able to tag images and use views on them, if you wanted to display the images stand alone, in a gallery etc.

You would need to do some work, to theme the images the are referenced though the image node, but it shouldn't be a big deal.


Adding JavaScript and CSS to a particular menu page

Generally, CSS and JavaScript files are added with hook_init(), which allows those files to be aggregated together, when aggregation is enabled.

Using hook_init() (I suggest you not to do this, anyway) you could conditionally add the files basing on the page being visited.

function my_init() {
  if (arg(0) == 'top') {
    // Add the files.
  }
}

The reason I don't suggest you to do this is that the hook would be called for every pages, including the ones you are not adding the files. hook_init() is generally used to add files to each page.

You can add those files in the menu callback (a.k.a., the page callback); if the menu callback is a form builder function, then you can use the #attached property, as the following code.

$form['#attached']['css'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
);

$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);

About the inline code you are adding, I would recommend you to put also that in a file, and to use Drupal behaviors instead of $(document).ready(). If you need to pass arguments to the JavaScript code, you can use JavaScript settings (see drupal_add_js() to understand in details how to pass settings to JavaScript code).
Managing JavaScript in Drupal 7 explains in details how to manage JavaScript code in Drupal 7, and the section titles Behaviors reports how Drupal behaviors are changed in the latest Drupal version.


How to add a property to a field type having data

I ended up using the following code.

function my_module_update_8001() {
  $field_type = 'my_field_type';
  $new_property = 'my_new_property';

  $manager = \Drupal::entityDefinitionUpdateManager();
  $field_map = \Drupal::entityManager()->getFieldMapByFieldType($field_type);
  foreach ($field_map as $entity_type_id => $fields) {
    foreach (array_keys($fields) as $field_name) {
      $field_storage_definition = $manager->getFieldStorageDefinition($field_name, $entity_type_id);
      $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
      if ($storage instanceof \Drupal\Core\Entity\Sql\SqlContentEntityStorage) {
        $table_mapping = $storage->getTableMapping([
          // We pass only one storage definition to make
          // \Drupal\Core\Entity\Sql\DefaultTableMapping::getDedicatedTableNames()
          // return only tables we need.
          $field_name => $field_storage_definition,
        ]);
        $table_names = $table_mapping->getDedicatedTableNames();
        $columns = $table_mapping->getColumnNames($field_name);
        foreach ($table_names as $table_name) {
          $field_schema = $field_storage_definition->getSchema();
          \Drupal::database()
            ->schema()
            ->addField($table_name, $columns[$new_property], $field_schema['columns'][$new_property]);
        }
      }
      $manager->updateFieldStorageDefinition($field_storage_definition);
    }
  }
}


How to port active configuration to module configuration

Use Features: It basically does exactly what you want, it turns your existing configuration into a module_foobar/config/install/

Be aware though that Features merges config (it does add and update existing config, but it does not remove/delete unused config like core configuration management).


If you can figure out the name of the contexts made available from spaces, you can use the condition that is triggered by other active contexts.  I personally have not heard of spaces creating context on their own however.  You may also consider writing your own plugin/module as this is relatively simple to do.  I myself used the path condition files to create the context keywords module(http://drupal.org/project/context_keywords).  You could honestly probably reuse 90% of the code from mine, and just change the part that returns true or false.


In Drupal 6 and Drupal 7, hook_menu() implementations don't get any argument. That is the reason of the error message.
They got an argument in previous Drupal versions, but it was not passed by reference. It's probable you are getting confused between hook_menu() and hook_menu_alter(). The latter gets a $&items parameter, but the purpose of the hook is slightly different. (It's altering routes defined from other modules, rather than defining new routes.)

As side note, I would rather use the following code.

function signin_menu() {
  $items = array();

  $items['signin'] = array(
    'title' => 'Sign in',
    'description' => 'Sign in form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_login'),
    'access callback' => 'user_is_anonymous',
  );

  return $items;
}

The login form should be visible only to anonymous users. Logged in users should not see it, since they already logged in, but the 'access callback' => TRUE line is making it accessible to every user, contrary to what Drupal (correctly) does.


How can I collect data on authenticated versus anonymous traffic?

I think the google analytics module does this out of the box.


There's no need to scale your images when you upload them, the usual method is to serve a cached version of the scaled image when it's displayed. This is usually accomplished by setting up an image style in the Drupal admin UI that has the effects you need, and then using theme_image_style() to output that image:

$file = file_load($fid);
$options = array(
  'style_name' => 'image-style-machine-name',
  'alt' => 'Alternative Text',
  'path' => $file->uri
);

$image_output = theme('image_style', $options);

Doing it this way gives the added benefit of your having the original uploaded file available at any time (for example to link through to as a full-sized version of an image, or in a lightbox, etc.)


Having trouble with ckeditor toolbar buttons

You probably need to configure CKEditor for a specific input format.

You might have an easier time if you install WYSIWYG module AND the ckeditor editor. This setup will integrate better with the Media module for instance. If you install WYSIWYG editor, you then can easily setup the editor per input format.


Give permissions to users to edit Drupal Views content

You can control view page access using "Page settings" section on views settings page,

You can grant permission for views edit to any Role you like form permissions page.

admin -> people -> permission


I ended up creating a multisite structure.

Under sites folder I created a folder for each subdomain like: "aaa", "bbb",...
I created a settings.php inside each folder (starting with php tags, do not close it though):

include_once(dirname(dirname(__FILE__)) . "/default/settings.php");
$conf['site_frontpage'] = "aaa";

(It inherits the general settings.php file since I dont need very different settings per domain)

Created a sites.php file inside sites folder (again starting with php tags):

  $sites['aaa.example.com'] = 'aaa';

  $sites['bbb.example.com'] = 'bbb';

  .......


How to limit preprocess functions base on a theme?

You can check theme active with function:

<?php

$active = \Drupal::theme()->getActiveTheme()->getName();

Get list all themes with:

<?php

$themes = \Drupal::service('theme_handler')->listInfo()


How can I add content in between views in bootstrap grid format?

I am stepping in with the response of Neograph734. Google is your friend and you can easily find the answers there.

But I am going to help you. It is easy to be done:
Create a view (page or block) and setup the filter and order criteria to what you want to display. In the pager section, set items to display to 3.

Make an attachment display with the same filter and order criteria. attach the attachment to the first view. Take "attach after" . Then in the pager section, determine how many items you want to show and set the offset to 3.

This way you can either put in the footer section of the first view or the header section of the attachment the text you want to place there.


My module Login with Email only should solve that:

  This simple Drupal 8 module allows users to log in exclusively with
  their email address from the standard login form.

  Setup:

  Just enable the module.

  Recommended Modules:

  This module is based on the Login Email or Username module:
  https://www.drupal.org/project/login_emailusername


Give some users (e.g., teachers) access to nodes created by a unique subset of other users (that teacher's students)

I've had success with multiple node authors using
nodeaccess_userreference

Gives content access permissions to users for content that references
the users with User reference or Entity reference.

and also with
nodeaccess_nodereference

Gives content access permissions to users if they have access to
content that is referenced with Node reference or Entity reference.
Checks view, update, and delete grant operations, and can pass those
on to the referencing content, or trigger a different grant
configuration according to settings.

In combination with field_permissions or hook_field_access, for restricting access to the reference field, that should enable the feature you're looking for there.
You may want to look at using Rules to set the reference field value on node save as well.


The same list shows up when you click on Place block. Doesn't look quite the same, but it is.

It was moved because they did UX testing and not a single person managed to place a block in D8, they all completely ignored the right sidebar. So a different solution had to be found, which is currently definitely not very nice yet.

This is the issue: #2513580: Implement the new block layout design to emphasize the primary interaction of placing a block


There is no performance issue I see with reference field. Reference field holds lot of other things

A table which keeps relationship between two entities which is exposed to other modules where references are saved as entity ids with no control of user input, whereas for text field you do not have much control unless you put validations and turn into almost what reference field is already doing.
Different contributed module are built around reference fields.
As an example you can expose reference fields as relationship to views module.
Text Field is definitely not a replacement for Reference field.
You would not like to get the performance boost for a reference field on the cost of its functionality.
If you have long list of entities to reference, keep the widget as autocomplete that can help in performance boost a bit.


You can export all your config using Features module: This module dumps to code several config data as content types and Views (but no content), generating modules that once enabled in another site regenerate dumped config.

One you have your config exported install a new Drupal site over SQL Lite and enable the exported modules with the config.

To 'migrate' the theme you only have to copy the theme folder to the new installed site right folder (usually /sites/all/themes/ or /sites/all/themes/custom/).


I did create a Commerce payment gateway with an almost similar challenge. You can have a look at the Commerce Pesapal module code.

A brief description would be;

Register a Commerce payment method.
Create settings for your payment method if any.
Implement hook_menu()and create at least three pages. One to hold the iframe, one to hold the callback from the payment gateway and another that will hold the form used to pass values to the iframe.
The second page can also be used to pass a message to the user.
On the redirect form you will not use a 'Submit' button because we need to pass the values to an internal URL. Instead you will do something like this.

$form['#action'] = $base_path.'Path To Your Iframe';
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Pay',
);

On the iframe page you can get all the variables rom your redirect from using $_GET.

The rest of the details I believe will depend on the gateway provider from that point on.


Version 5.9: Which components does "drush site-alias --local" look for in ~/aliases.drushrc.php?

The filtering is done in the _drush_sitealias_user_specified_list() function with

if ((array_key_exists('remote-site', $one_site)) || (!array_key_exists('root', $one_site)) || (!is_dir($one_site['root']))) {
  unset($site_list[$site_name]);
}

So it looks like the remote-site option is used. But the documentation for the alias settings does mention a this option. So this looks like a bug.

Note: the same condition is still used in the latest version (see https://github.com/drush-ops/drush/blob/master/commands/core/sitealias.drush.inc#L164).


How to use ajax callback on auto complete field inside a block settings form?

To answer the title's question
  '#ajax' => [
    'callback' => '::my_ajax_callback',
    'wrapper' => 'my-specializations',
    'event' => 'change', // run ajax on change
    'keypress' => TRUE, // if set to TRUE, then the element's #ajax['event'] will be triggered if the ENTER key is pressed while the element has focus.
  ],


How to Show Multiple field value according to Row Height

You need to sort by the field delta (The position in the list). So in views add "sort criteria" and search for "work images delta"


Themes will work with the RDF module if they use the proper attributes variables.

If you are generating HTML outside of the core theming (which seems unusual) system you will need to get this information yourself. The RDF mapping api is quite well documented. Essentially there is a mapping between fields and RDF. So a title field could have a mapping of dc:title.

In summary

rdf_get_namespaces() will show the namespaces that need to be included in your document.
rdf_mapping_load() will show the rdf mappings for an entity type.

You can then add rdfa markup to the fields as you output them.

edit

If you are using standard theme functions, then so long as you stick to the D7 guidelines all of the RDF magic should be done for you. Specifically make sure that you use $attributes $title_attributes and $content_attributes.

If you want to know how to define RDF mappings, then please ask more questions.


Attaching a block to a view create with the User type

The way I found around this is that in the the fields I added a Global View.  Now the video is treated just as a field.


The error just means that the feed row style require fields, but the view being created doesn't have fields.
The error is confusing, since I can create a view like that and add a feed.

There are two ways for not getting that error: The first one is selecting Table as Display format, and Content as Feed row style, in the page to create a new view.

In this way, I got the view without errors.

The second way is creating a view without telling the Views module to include a feed. It will be created after.

On the page shown to create a view, I don't select Include an RSS feed, and I click on Save and edit.

On the next page, I click on +Add and choose Feed on the drop-down list that appears. (I cannot show it on the screenshot, but I can choose between Attachment, Block, Embed, Entity reference, Feed, and Page.)

On the next page, on the bottom, you will get the following error.

  Display "Feed" uses a path but the path is undefined.

Click on No path is set, and enter the path you want for the feed.

This is close to what the Views module gives you, with an exception: The feed is not attached to any page, since it says Attached to: None.

Click on None and select to which pages the feed must be attached.


Multiple formatters for a field collection - best approach?

This sounds like it would be best output as two separate views.  The first view would be set in your first format and the second in the other format.  Probably using a view template of some sort.  The issue is that the field collections attached to the node are actually referenced separately and you only know they belong to the same node because the field collection entity has a reference to the NID.

The view would reference by nid in the contextual filters.

The other option is to programmatically load the fields via the node.tpl.php file (assuming you are loading them on the node page). in which you simply gather the data via the $node object and display it as you need.

https://drupal.org/project/field_collection_views

https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

http://www.youtube.com/watch?v=_GlfYhsk3X0


Implement hook_entity_property_info_alter()

function MY_MODULE_entity_property_info_alter(&$info) {
    $info['node']['properties']['article_number'] = array(
        'type' => 'text',
        'label' => t('Article number'),
        'getter callback' => 'MY_MODULE_get_article_number',
    );
}

function MY_MODULE_get_article_number($node) {
    if ($node->type == 'product_page') {
        // Return the article number from the referenced product node
    }
}

Go to admin/config/search/search_api/index/{index_name}/fields and select the property. Now you can use this property like any other field.

In your case you need to configure this field in you view. I assume you added Search: Fulltext search to your filter criteria. Click on this filter and add the property to the Searched fields settings.

I hope this works for you.


How to add terms directly from the content overview?

I think you are looking for something like Inline Entity Form.


Add a local task tab for a content type only

You can use an access check to hide a route.

If the user that will view the tab has the same permission for adding a node of a given type, then simply adding _node_add_access: 'node:MYNODETYPEHERE' would be sufficient. However this is probably not the case.

Instead you can add _custom_access to the route requirements as a method on the controller class.

mymodule.check_test:
  path: '/checktest/{node}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CheckTestController::content'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\CheckTestController::checkAccess'
    # It is highly-recommended to always use the default entity access check for
    # an Entity as pointed out by @pwolanin below. Not doing so may lead to
    # undesirable results and potential information disclosure or access bypass
    # vulnerability.
    _entity_access: node.view

And then a corresponding method on the controller (see Access checking on routes for more details). Something like this might work for you (untested).

public function checkAccess($node) {
  return AccessResult::allowedif($node->bundle() === 'my_node_type');
}

Update 2019.08.30: Incorporated @pwolanin's answer into this one in case anyone misses and doesn't read its importance.


Ubercart 2.x has built in support for creating product classes with attributes. See the documentation for more information


The print friendly module uses the theme system to output your print friendly page. So you need to do this on theme layer using a preprocess function. Use THEMNAME_preprocess_page or THEMENAME_preprocess_print in your template.php. Check the theme_hook_suggestions for more options. From the module

 $variables['theme_hook_suggestions'] = array();
 187   $variables['theme_hook_suggestions'][] = "print__node__{$type}";
 188   $variables['theme_hook_suggestions'][] = "print__node__{$type}__{$nid}";
 189   $variables['theme_hook_suggestions'][] = "print__{$format}";
 190   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}";
 191   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}__{$nid}";


How do I make my service dependent on another module existing?

Yep, you need a ServiceProvider that only registers the service if the module exists in the container.modules parameter

See https://github.com/md-systems/file_entity/blob/8.x-2.x/src/FileEntityServiceProvider.php#L25 for an example


You can use FormattableMarkup to insert variables into html markup:

use Drupal\Component\Render\FormattableMarkup;

  'data' => new FormattableMarkup('<b>@bar</b>', ['@bar' => $foo]);


When I did this a while ago I adapted the excellent field_example module from the Examples Module which is always the first place to look, as it has a lot of Drupal best practice in it.

As they say in the module comments:

     * Providing a field requires:
     * - Defining a field:
     *   - hook_field_info()
     *   - hook_field_schema()
     *   - hook_field_validate()
     *   - hook_field_is_empty()
     *
     * - Defining a formatter for the field (the portion that outputs the field for
     *   display):
     *   - hook_field_formatter_info()
     *   - hook_field_formatter_view()
     *
     * - Defining a widget for the edit form:
     *   - hook_field_widget_info()
     *   - hook_field_widget_form()

So, not for the faint hearted, but as others have said, all the information is there to get you started.


JS error(s) with Media-7.x-2.0alpha4 and CKEditor

For CKEditor: At first glance, it seems that commenting out the following lines in media/modules/media_wysiwyg/js/media_wysiwyg.format_form.js allows the button to work again...

      // Get all the values
      var ret = {};

      $.each($('#media-wysiwyg-format-form .fieldset-wrapper *').serializeArray(), function (i, field) {
        ret[field.name] = field.value;

        // When a field uses a WYSIWYG format, the value needs to be extracted.
        if (field.name.match(/\[format\]/i)) {
          field.name = field.name.replace(/\[format\]/i, '[value]');
          field.key  = 'edit-' + field.name.replace(/[_\[]/g, '-').replace(/[\]]/g, '');

//          if (Drupal.wysiwyg.instances[field.key]) {
//            // Retrieve the content from the WYSIWYG instance.
//            ret[field.name] = Drupal.wysiwyg.instances[field.key].getContent();
//            // Escape the double-quotes and encode it to play nicely within JSON.
//            ret[field.name] = encodeURIComponent(ret[field.name].replace(/"/g, '\\"'));
//          }
        }
      });

  return ret;

Be careful though, this is not a permanent solution as you should never hack core.


How to change the alias for the core forum landing page for drupal 6?

As Jimajamma commented, the answer was really simple.. just go to admin/build/path/add and in the existing system path I entered forum and in the path alias I entered /some-other-name and it worked, and btw if you need it for drupal 7, the go to admin/config/path/add.


Create a new node when a field is added to a node

Option A

I myself wouldn't do that - I think that generally it's a practice that doesn't worth the time and risks (as would be explained in Option B) but anyway:

In drupal 7 this can be done with the Multi Node Add module. There isn't a version for Drupal 8 yet; If you don't have the knowledge to port it to Drupal 8 you might hire a PHP programmer to do that for you. An alternative would be to copy the desired fields from 1 node to another via this module. This module is going through a porting process at this era.

Guessing that both modules work only on 1 content type at a time, and can't recreate content in another Content type: You could handle that by cloning your nodes inside the same content type (X) with Node Clone or a similar module, and than convert all clones to their other, similar content type (Y) with Node Convert or a similar module.

Option B - Advice and workaround with Views.

As an SEOer, I would recommend on finding other way to enrich your sites' content; Cloned content is quite a good recipe for lowering both your PQS (Page quality scores) and in some cases - Your PageRanks as well... This becomes more serious with every passing year.

It could be better to create more sophisticated content pieces based on the first node content via the Views module (which is part of the Drupal 8 core); Here is an intro to Views 8. Many tutorials are available in Youtube for that module.


How to implement User registration settings email in my registration form

You could use the Rules Module for this.

Steps:

Define an Event that whenever a registration is there.
Then Define the Action to send Mail with proper Format.

For more details about the Rules module go through README.txt of this module.


How to save custom fields when using hook_form_FORM_ID_alter?

The only thing your form alter has done it added fields to a form. But you need somewhere to store the values of those fields.

When you add a field to an entity (node) using the Field UI module Drupal creates 2 database tables. One to store the field values and one to store older revisions of that fields value. Without these tables you don't have anywhere to store the values.

Here are steps to add that field your node bundle:

Make sure the Field UI module is enabled.
From the admin toolbar visit Structure > Content types > AYG (the name of your node type) > Manage fields.
On this page add your new fields and configure as required.

Now your new fields will show on your node creation / edit forms and you will have tables to store the values of those fields.


see this issue queue How to Approach Sub-Sub themes with Zen?

You dont copy zen starter kit for every sub-theme. You basically copy the .info file and template.php and create your theme folder. If you copy zen starter kit for every theme you'll run into the problem your seeing you end up "spamming" css files everywhere.

Sub-themes are best built smallest to biggest. By which I mean start off with the smallest number of .info file attributes and build up to the subtheme you want.

With so many subthemes you should be able to come up with 1 generic "base sub-theme" you then base all your subthemes off of in code.

Every sub-theme needs 1 uniquely named CSS file to properly fire off inheritance.


Make sure you also install the eva module, in addition to clearing your caches via admin/config/development/performance.

Also, og_extras only works with og 7.x-2.*.

For the "create content" block, look  for "Node content links" under blocks. You also need to configure the Organic Group module to work with the entityreference_prepopulate module, to make it work properly. See here for guidance.


hook_preprocess_node() or hook_node_view() for html altering the field

hook_preprocess_HOOK will do the job,

You may also take a look at writing your own theme_image_formatter()

It could work in a node_view() but you want to alter the FIELD's HTML.In node_view you would alter the order of fields, hide/show new contents NOT control how they look.. you could absolutely do it, but it will not be the best/Drupal way.

Drupal divides functionality (node_view()) and looks (theme)

In a hook_preprocess_node() you would alter the node template variables, not the field's ones.You would need it to add a class to a node wrapper, to change node templates etc...
you have to go deeper in the theme for this one.

Examples:

// ALL IMAGES get rounded class.
function YOURTHEME_preprocess_image(&$variables) {
  $variables['attributes']['class'] = array('rounded');
}

and for field

// If field_images in FULL view mode of a node, add/edit variables and choose template
function YOURTHEME_preprocess_field(&$variables) {
  if ($element['#field_name'] == 'field_images' && $element['#bundle'] == 'YOUR_NODE_TYPE' && $element['#view_mode'] == 'full') {
 $variables['theme_hook_suggestions'][] = 'field__field_images_YOUR-file-name';
  // Add more variables available in template...
  $variables['toggle'] = 'Read the story';
  $variables['some_text'] = 'Some text';

}


Just had the same problem on another site: for some reason the view title ($handler->display->display_options['title'] = 'Blogs';) was coming out in the page.tpl.php template $title, but not in the views-view.tpl.php $title (despite the default template for that page suggesting that it should). Possibly the variable gets undefined after it's used in an "earlier" template? Or maybe the title variable is only set for the view template if the view is being rendered as a block, on the assumption that the page template has already printed the title for the page?

Anyway, the solution is just to do the printing in the page.tpl.php right before rendering the page content (which will likely come from either the node template or a view depending on the page):

<?php print $title; ?>

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

Of course if you're doing this you need to make sure not to print the $title variable out in the node template because if you do that you'll have the title printing twice.


Why are foreign language registrants redirected to home page after registration?

I wonder if your issue could be related to the language specific homepage (frontpage).

The relative URL to display as the front page is specified within admin/config/system/site-information. Make sure you specify a value for it that is different for each of the site's languages. To do so, you have to make it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

For more details about this, refer to my answer at How to make content translation available for front page?


This function commerce_cart_order_product_line_item_delete is in commerce_cart.module in line 1259 tnen in line 1268 call commerce_entity_reference_delete, function should be in commerce.module file line 124, check the function exist there.
This is some strange if the function exist in commerce.module and return fatal error,
I suggest first be sure that the function exist in code then  clear cache and then try again.
It is allowable call any function in any custom module and drupal not have restriction about this subject.


After research in drupal.org I found out that best way is to place translations in /sites/all/translations. Naming convention is module_name-version-language.po

Moving them out did not affected the current translations as they are already imported into the database.


You need to be able to perform business logic (php) in your Views header (or footer) to perform this task.

The Views header or footer should be able to accept PHP, just change the input filter to PHP. If that input filter is not available, you'll need to enable the PHP Filter module (core, optional) first.

Once you can use PHP in the Views attachment header or footer you can include logic to look at the selected glossary item such as:

$term = check_plain($_GET['glossary_term');
echo "
" . $term . "
";

Then use whatever CSS you need in your theme or module to make this Letter appear however you wish.


How can I customize the header and footer from a custom page controller?

It depends on how you have built these. Generally you will set any blocks in the header and footer to only show on the paths they are meant to show on, in the block visibility settings. If you need completely different headers and footers altogether, you can build a new theme with those headers and footers, and create a custom theme negotiator (https://www.webomelette.com/choose-your-theme-dynamically-drupal-8-theme-negotiation) to set the theme for those pages.


Blocks are invisible after hosting drupal7

Sometime the issue occurs when we migrate the site. Just follow through these steps:-

1) Check the block section of the local and live site
2) Check all blocks from the local and live
3) Now assign the blocks to the same regions in live as it is in the local setup
4) Check blocks are visible on the given region on the page or not.

Edit the blocks to set their display settings.


Translatable strings and Drupal primary language

No unfortunately, strings passed to t() should always be in English.


D8 - How to create a view to show content with a field that is a User Reference to currently logged in user only

you have to create a contextual filter, which will take current user as default value, you can find nice explanation and screenshots here:

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

Just filter on Content: your field name instead of Content: Authored by


You wrote
$block['content'] = my_module_form();
which mean you called a function which return just an array.

You need to tell drupal that i am creating a form, for this use drupal_get_form

case 'my_module_config':
  $my_module_form = drupal_get_form('my_module_form');
  $my_module_form = drupal_render($my_module_form);
  $block['subject'] = '';
  $block['content'] = $my_module_form;
  break;


Can someone help me with contextual filters in profile2

I was able to (finally) populate something on the user id. I guess it's the best way because I am going to be using rules to handle the information after the profile is created. Unfortunately, for some reason when I create a new user sometimes one of my profile id's is set to '0' shrugs which throws off the population of the field (check this especially if you use profile2_regpath).

How I was able to do it was to like this

I referenced the profile based on user id... then I drew three relationships on the profile, the profile type, and the user id.  I finally chose fields that substantiate the information I needed the user to see (in this case they are just testing it out). Please let me know if there is another way. I'm assuming there has to be something else out there or something I am missing. It populates one user at a time based on the profile owner's user id.


Contextual Filter for a Multiple Value Taxonomy Field

Should be possible with View → Advanced → Your Contextual Filter → More → Allow Multiple Values.

Then supply values like "123+456" to get all that have either tid 123 or 456, or values like "123,456" if you only want those that have both terms applied.

Note this does not scale well because of the way Views does its SQL


How do I fix these requirement conflicts?

drupal/webform 5.15.0 seems to be locked below the v5.15.0 and thus blocking the drupal\webform_node update.

check if you have an explicit version number in your composer.json that conflicts with the desired version
On several occasions, I unblocked such situation by removing the docroot/vendor directory followed by a composer install command (and removing the composer.lock file if a new conflict arised)

composer.json is a list of modules with version constraints that is user-defined.
composer.lock is the list of currently installed modules generated by composer install. If composer.lock is present, the list of resolved dependencies will be installed if you do composer install. This allow to define and deploy a set of resolved dependencies. composer update will resolve the dependencies again and update composer.lock (thus the update). From my experience, it could happen that you have unresolved conflict between explicit version definition in composer.json and the composer.lock. So you could get rid of it, and also the whole vendor directory, and do a composer install from scratch again. If the installation fails again, it must be from a human-generated composer.json conflict.


you can create multiple tpl.php files for blocks based on the specific block, the module that created the block.

  Clone block.tpl.php to "block--block--[block-id].tpl.php" file

after try code, I don't' encourage you to do this, but it maybe the solution for you:

<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php if ($title): ?>
        <h2<?php print $title_attributes; ?>><?php print $title; ?>

      <?php endif;?>
      <?php print $content ?>

=> Clear cache


Symfony 2, as in the full stack Symfony 2 has no bearing on Drupal 8 -- we do not use its bundles, we do not use the same routing as Symfony does (we use a botched up work on top called Symfony CMF which is made less dog slow by bastardizing my menu work on top of it but it's still undocumented, incomprehensible, does not yield to static code analysis tools and altogether is broken and slow). We do not use the same ORM (Doctrine). We are using some Symfony 2 components however there is very little visible of it to the "end" developer. For example, confusingly enough, sometimes you need to use events (what was hook_boot/hook_init in D7 is replaced by Symfony HTTP kernel events) whereas most often Drupal still uses its hooks. Confusing is the name of the game where Symfony 2 interacts with Drupal. It's an extremely poor fit and the (non)amount of the documentation of how this fit (does not) happen makes it even harder.

Edit: we do use the service container http://symfony.com/doc/current/book/service_container.html at least the static parts of it -- however dynamic service additions and alterations are done via Drupal specific means (service providers which attaches to the system via a special magic way which is neither events nor hooks. Welcome to Drupal 8.)

So: if you know Symfony 2 inside and out then a little of that will be usable in Drupal 8. If you don't then don't bother with Symfony 2 books or tutorials.


Link formatter to display link title, image and summary

You can do a lot with Custom Formatters and Tokens, also check out Field Formatter if you need to wrap the link around an image field.

For most control create one yourself, there are different tutorials for that, start here: Create a custom field formatter


How to check the value from data sheet during Feeds import?

Thanks everyone, I got the answer. Instead of using Rules, I created a "custom feeds module."

Steps:

Create a folder named "custom_feeds"
Create two files, one is "custom_feeds.info", another is "custom_feeds.module"
Add following information in the .info file:

name = custom feeds module
description =custom feeds module
core = 7.x
package = Feeds
dependencies[] = feeds</code>

Add following code in the .module file inside <?php ?>:

function custom_feeds_feeds_presave(FeedsSource $source, $entity, $item) {
  // check that this is fired only for the importer being used
  if($source->importer->id=='recommended_product_import'){
     // "equivalent" is the column name in excel sheet
     if(!strcmp($item['equivalent'],"")){
       $entity->feeds_item->skip = TRUE;
     }
  }
}


You can allow any content type as content in the group. So if you want to set post in group you can edit post content type and make as group content.

When you edit the post content type usign admin>structure>content types>post you will find the following options to add this content type as group option.

After doing this when you  visit post create page you will find group select box. From here you can select the group.


Problems rendering drupal 7 user registration form with ajax in BootStrap 3 Modal

By rendering the user registration form twice, duplicate form id's were being created. After recreating the second form with a different ID, things are good.


Rules: after saving new content + after updating existing content both triggered on node create

You could add a condition in both rules to check whether the $node->created and $node->changed timestamps are same.

For a newly created node $node->created and $node->changed time will be same, while for an updated node both will be having different timestamps.

You probably need to add an Execute custom PHP code in rule condition to do this.


You could check out the field group module. You have several options to group your fields:

Fieldsets
Horizontal tabs
Vertical tabs
Accordions
Divs
Multipage steps: Note: This is only client side.


How to get Search API module to index the full country and state name from Addressfield Module?

you might want to use SOLR search and write a synonym.txt file to translate the state and country codes into names


image_style_url() function not giving proper image in drupal 7

Then it is likely the rule you are referencing is not configured to do what you want it to do. It may be cropping instead of scaling or do a scale and crop.

Edit the image style at: admin/config/media/image-styles/edit

Check to see if it is scaling or cropping. Adjust it or create a new one and reference that in your code.


Config import for certain items appears to fail. How do I fix this?

I've found that this sort of thing is because the config in your sync directory is not quite legitimate. My guess is that this is an issue on your dev and local environments too, not just staging.
I've found that the cause of this issue is usually a result of one of two things:
1. Configuration files were manipulated manually and the configuration in the file isn't possible.
An example, looking at your pastebin, the change for core.entity_view_display.node.page.default.yml is to remove the created field from the list of hidden fields on that display. However, there's no configuration for how the field should be displayed. A field can't be not displayed and also not hidden. To maintain the integrity of the config, the system defaults a field to hidden when it's not in either place.
2. Database updates were run, updates that change configuration, but configuration was not exported on the dev environment after the update.
An example, looking at your pastebin, it looks like some new configuration options (with appropriate default values) were added. It also looks like a module changed from working with true and false to 1 and 0.
To resolve this issue:
First go to your primary development environment. Then get your latest database of record, clear cache, and deploy (database updates, then import your configuration). The result should be the same thing you're seeing on staging, i.e. some configuration will appear to be not fully synced. This is expected (for the reasons described above). Next re-export your configuration, commit, and re-deploy.
To avoid this issue in the future:

Don't manipulate config files directly. If you do, test the configuration locally to make sure you got it right (this includes after resolving merge conflicts in config files).
Always export configuration after running database updates. Sometimes the updates change configuration.


Using custom ranking for some searches and not others in D7

Search API was built to give a great deal of flexibility to searches. You can create separate search indexes to meet different criteria, weight individual fields differently per index and keep all of your configuration managed in the UI, versus trying to write custom logic into MODULE_ranking().

Download Search API, install and configure your indexes at: /admin/config/search/search_api