Are $form_state values cleaned of malicious code even if #limit_validation_errors is set?

If you set #limit_validation_errors, only elements passed into the value are validated. Everything else is not validated. So for example with this:

#limit_validation_errors = array()

Nothing in the form is validated. And with this:

#limit_validation_errors = array('field_1', 'field_2')

Only field_1 and field_2 will be validated.

To continue on with this, only fields that are validated become part of $form_state['values'], and are then passed on to any submit functions. These values will be as safe as any values in a FAPI form submission, as they will be both sanitized and validated.

Any fields not included in the array passed to #limit_validation_errors will not be part of $form_state['values'], and therefore there is nothing to sanitize, nor any malicious code to validate. The element will simply be missing (or maybe empty, I can't remember off the top of my head) from $form_state['values'] in the submit functions.

For myself, the only use case I've ever found for #limit_validation_errors, is one I stopped using. I would use it on a back button for ajax forms, so that the user could step back a step, without getting errors for any fields on that step of the form. The problem however is that any partially filled fields are then lost on that step of the form when going back, since the submitted values are entirely ignored.

What I do instead, is in my validation function, I check to see if the 'next' button has been clicked before validating.

Example form definition (imagine this is step 2 of a multi-step form)

function some_form_step_2($form, &$form_state)
{
  $form['some_field'] = array
  (
    '#type' => 'textarea',
    // See comments after code about why I did this:
    '#title' => t('Enter a value') . '*',
    '#default_value' => isset($form_state['values']['some_field']) ? $form_state['values']['some_field'] : '',
  );

  $form['actions'] = array
  (
    '#type' => 'actions',
  );

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

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

  return $form;
}

function some_form_step_2_validate($form, &$form_state)
{
  // check to see if the clicked button was the 'next' button
  if($form_state['op'] == $form_state['next'])
  {
    // Ensure a value has been entered into some_field
    if(!strlen($form_state['values']['some_field']))
    {
      form_set_error('some_field', t('Please enter a value'));
    }
  }
}

function some_form_step_2_submit($form, &$form_state)
{
  // Here, if the 'next' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized
  // and validated

  // However, if the 'back' button was clicked, the value in
  // $form_state['values']['some_field'] will be sanitized,
  // but not validated, as the validation only needs to happen
  // when advancing to the next step, not stepping back to the
  // previous step
}

As you can see from the code, the validation only happens when the 'next' button is clicked. The field some_field is actually required, however, if #required is set on the field, it will always be validated when the back button is clicked. This can be prevented with:

$form['#limit_validation_errors'] = array();

However, if the user has entered a partial value into this field, #default_value will be empty if the user goes back to the first step, and then returns to this step, since the value will not be made part of $form_state['values']. The way I've built it, the 'required' asterisk (*) is included with the form field title to show the user it is required, but the validation of the required field only happens when advancing to the following step, not when going back to the previous step. This way the user can go back whether a value has been entered into the field or not.

Another added advantage of this method is that a custom error message can be shown for required fields. If #required = TRUE was set on the field above, instead of  using the method I did, the error message would be 'Please enter a value? is required' (or something close), which is not very clean English. With the code above, the message is instead 'Please enter a value', with the field highlighted.


Drupal 6 database has mixed InnoDB & MyISAM. Need to fix before migration

You could use the backup & migrate module to backup your DB. Then take this text file (UTF-8) and change all MyISAM strings to InnoDB. Save it and restore this backup. Done.


Fieldable panels panes - add a default category when creating

Currently it's not possible to assign a category in hook_entity_info_alter. See feature request https://www.drupal.org/node/2149989

To achieve this, couldn't you just fill the category form field, using hook_form_alter in a custom module, like in my other answer?


The first statement essentially removes a field from the form. The second statement sets the field's language to undefined (neutral). They are not the same, but they both help you to deal with this module's issue as they both prevent the form from passing invalid keys to locale_field_node_form_submit().


I've experienced the same issues with my conversion from D5.x to D6.x and what I ended up doing was to install the Semantic-Views module.  It allows, at a row/field level the ability to add classes to each field.  Not only does this work well it is a heck of a lot easier than creating and maintaining a tpl.php file.  Try it, you'll like it.


I had a similar issue before. As you mentioned, feed auto-discovery works through the link in the  tag (see http://diveintohtml5.info/semantics.html#rel-alternate for more info).

I found that some themes and modules add it in automatically, while others don't. If yours is absent, you can auto-discover the default drupal RSS feed by adding the following to a preprocess function:

$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => '/rss.xml',
    'rel' => 'alternate',
  ),
);
drupal_add_html_head($element, 'mymodule');

Alternatively, you could just add it into the html.tpl.php file, as mentioned in this post: http://www.webbykat.com/2012/03/adding-feedburner-rss-link-your-theme-drupal-7-omega

Regarding Views, I have found that enabling auto discovery means adding a "Feed" display then turning on the setting at Feed Settings > Attach To > Master, as you did. You can also set it to include other displays to get the RSS icon to display in those views.


How to login to my site again after all users were deleted?

If you have backups then restore from backup then delete users again without deleting the ones you want to keep.

If you don't have a backup then you will need at least user 0 (anonymous) and user 1 (superuser).

I am assuming Drupal 7 because you didn't specify version.

You will have to add those back into the database either via database access in your hosting administration area or from the command line.

Note: I am adding the basic MySQL queries here but you should read these whole linked pages for more information.

The process is similar for both users.
You should read Restore user 0 for more detailed information but here are the SQL queries:

User 0 (anonymous):

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('', '', '', '', '', '', '', '');
UPDATE users SET uid = 1 WHERE name = '';

User 1 (superuser): You can change "admin to whatever user name you want to use. I recommend not using "admin" because attackers will try that first if trying to work out your password.

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('admin', '', 'youremail@example.com', '', '', '', 'youremail@example.com', '');
UPDATE users SET uid = 0 WHERE name = 'admin';

Then you will need to do a password reset for the user 1 account.

Other users
Other users can be added just with the first insert statement without the update statement after however you will lose settings like user picture, signature etc. if there is data in those fields (or unless you know what the data should be and ad it back in).

Those users would also not get roles so you would have to assign roles to them after.

They also wouldn't have the same UID as before so in the uncommon case that you have code that specifically references a user ID that will need consideration.

Note that some modules that change the behavior of Drupal users may change the way you need to add these users back.

For example if you user the "User revisions" module then there is also a user_revision database table that needs to be considered when doing these queries.


Remove all Div wrapper from comment form

To achieve this you need to create one template page for comment-form.tpl.php. For this you need to specify in template.php that uses template page.

<?php
function phptemplate_comment_form($form) {
  return _phptemplate_callback('comment-form', array('form' => $form));
}
?>

and in comment-form.tpl.php you can create your own strcution like

print drupal_render($form['name']);
print drupal_render($form['comment_body']);
print drupal_render($form['subject']);
print drupal_render($form['author']['mail']);
print drupal_render($form['author']['name']);

This works for me with register/login form.


How can I deploy user interface translation?

Helper function to add custom translations:

/**
 * Helper to manually add a single translation string.
 *
 * @param string $source_string
 *   Source string.
 * @param string $langcode
 *   The langcode.
 * @param string $translated_string
 *   Translated string.
 */
function MYMODULE_add_translation($source_string, $langcode, $translated_string) {
  // Find existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(['source' => $source_string]);
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation([
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ]);
  $translation->save();
}

Usage in an update hook:

/**
 * Add translations.
 */
function MYMODULE_update_8002() {
  MYMODULE_add_translation('Adjust', 'de', 'Anpassen');
}


What are the options for an e-card wizard module?

Take a look at ecards module

As mentioned in the page, you can see a demo on http://www.mahlove.com/friendship-day/friendship-day-ecards/160


How do I use $form_state to return data from the from submission handler to the form builder?

The only functions that get $form_state are form builders, form validation handlers, and form submission handlers.

To say the truth, your code doesn't need to use MYMODULE_form_page(): You can simply use the form builder function.

function MYMODULE_menu() {
  // Module settings.
  $items['MYMODULE'] = array(
    'title' => 'MYMODULE',
    'description' => 'MYMODULE',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_form($form, &$form_state) {
  $form['header_text' => array(
    '#markup' => '

',
  );

  $form['kname'] = array(
    '#title' => t('What would you like to search'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please insert the keyword you whish to search for.'),
  );

  if (isset($form_state['MYMODULE_result'])) {
    $form['footer_text'] = array(
      '#markup' => '
'. $form_state['MYMODULE_result'] .'
',
    );
  }

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

  return $form;
}

function MYMODULE_form_submit($form, &$form_state) {
  $keyword = $form_state['values']['kname'];
  $op = MYMODULE_simple_page($keyword);

  // Form submission handlers don't return any value.
  // If you need to return a value to the form builder, you should use the following code.
  $form_state['MYMODULE_result'] = $op;
  $form_state['rebuild'] = TRUE;
}


How do I fix the "The each() function is deprecated" error?

Just update Drupal 7 to latest version which, as I am writing this answer, is version 7.64. Drupal 7 doesn't use each() in PHP since November 7, 2018, as the CHANGELOG.txt file says. (See the last line of the part I quoted.)

  Drupal 7.61, 2018-11-07

  File upload validation functions and hook_file_validate() implementations are
  now always passed the correct file URI.
  The default form cache expiration of 6 hours is now configurable (API
  addition: https://www.drupal.org/node/2857751).
  Allowed callers of drupal_http_request() to optionally specify an explicit
  Host header.
  Allowed the + character to appear in usernames.
  PHP 7.2: Fixed Archive_Tar incompatibility.
  PHP 7.2: Removed deprecated function each().

As long as you use at least Drupal 7.61, you will fix the error you shown, which (in your case) is caused from menu_set_active_trail(). (The code shown in the documentation page doesn't show any line using each() because the code has been updated to the latest Drupal 7 version.)

If you are using third-party modules, you could still see that error, but caused by other functions/methods. In that case, you need to update all the modules you are using on that site.
If this doesn't fix other The each() function is deprecated errors, you need to check the issue queue for every third-party module you are using, and verify there are patches for fixing that error.


How to I call a preprocess function for a view from a custom module?

A template preprocess hook would be the best place. The naming convention for those functions is standard so you should be able to use

function MYMODULE_preprocess_views_view__widgets__page(&$vars) {
  drupal_add_js('...');
  drupal_add_css('...');
}


REST post plugin broken from Drupal 8.4.5 to 8.5

Wim Leers found the answer:

Change this:

public function post(array $data = [])

to:

public function post(array $data)


Remember what this module does is:

This module removes all the whitespace in your HTML except those between TAGS.

It will not compress all your HTML into one single line.


Show a page with child Terms when parent Term clicked in block?

Try the Views tree module. It is great for taxonomy trees.

This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.

There is also a patch for adding collapsible support but I'm not sure how complete it is. See http://drupal.org/node/1538414


Create a filter using the field (eg field_country), and select 'Dropdown' under settings. If this is a taxonomy term, select 'Expose this filter', then select 'Is one of' as the operator, and save. This will give you the drop down list.

If it is not a taxonomy term, the sequence might vary slightly, but it will be substantially the same.


How to display search block in a modal dialog

You can use Lightbox or Colorbox (there are modules for both).

Each has the ability to display inline content in a modal.

All you would need to do is add your search block to the page and hide it with CSS, then adjust your search button link to trigger the lightbox/colorbox.

If using colorbox, you would do something like the following:

  Load content in a Colorbox

  Check the "Enable Colorbox load" option in Colorbox settings.

  This enables custom links that can open content in a Colorbox. Add the
  class "colorbox-load" to the link and build the url like this
  "[path]?width=500&height=500&iframe=true" or
  "[path]?width=500&height=500" if you don't want an iframe.

  If you want to pass the width and height of the Colorbox as a
  percentage (useful for responsive designs), you can format the link
  like this "[path]?width=90%25&height=90%25&iframe=true" or
  "[path]?width=90%25&height=90%25", where the "%25" is the HTML entity
  for "%".

  Other modules may activate this for easy Colorbox integration.


Ok, it looks like you have to hover the actual body of the block to see those links. It doesn't display them if you hover just the title.


How to reset my password if I forgot it?

While you can change admin password either by drush or by running mysql query if you have access to database if you do not have direct access to your mysql server, install devel and wrap the mysql query with drupal query wrapper functions and run it at /devel/php page.

You may want to consider having nocurrent_password module which removes the current password field and you can directly update your passwords, NOTE: this behaviour will be same for other users as well.


Commerce Product Collection View Block: What Determines CSS For Each Header Link?

It is the same as with any view: You have to override the view template.

In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As the block is using grouping, you need to override the 'Style output' theme template:

views-view-list.tpl.php

If you override that template it will override it for all views of HTML List format, so you now have to select a suggestion. Second in the list is:

views-view-list--collection-products.tpl.php

which will be fine.

Create a new file in your theme templates folder called

views-view-list--collection-products.tpl.php

Then click on the 'Style output' link back in the view theming information. It will open up a file and you copy everything from the

Now you can edit that file to get the markup you want. You can take out the h3 tag for example and replace with a div.


How do I correctly inform the system about my module's new config?

I think I found a strategy that is only slightly hackish to let Drupal know that your module has created a new config. This solution assumes that your new config is in a separate yml file in yourmodule/config/install but it should be adaptable to a situation where you are adding a new config to an existing file....

/**
 * Install new config.
 */
function your_module_update_8003() {
  // Get all current configs for Your Module.
  $existing_settings_config = \Drupal::configFactory()->getEditable('your_module.settings');
  $existing_foo_config = \Drupal::configFactory()->getEditable('your_module.foo');
  $existing_bar_config = \Drupal::configFactory()->getEditable('your_module.bar');

  // Install the new configuration
  // (a new file was added a your_module/config/install/your_module.baz.yml)
  \Drupal::service('config.installer')
    ->installDefaultConfig('module', 'your_module');

  // Reset the existing configs in case they were changed when installing the
  // new configuration.
  $existing_settings_config->save();
  $existing_foo_config->save();
  $existing_bar_config->save();
}

It's not ideal, but it seems to work.


How can I create a new content by adding another two contents of same content type?

Entity Reference Module should be used for such cases

To use the entity reference field in views you should follow the link given below
https://www.youtube.com/watch?v=4Pdii7aFIvc
http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7

In the advanced section of views you have a relationship option where you will get an option to use a referenced entity for the view of content type A(student).


WYSIWYG + CKeditor breaks my  lines and mess my paragraphs

I had the same problem and I solved it by allowing paragraph and line break in the configuration of the Filtered HTML:

Configuration » Content authoring » Text formats » Filtered HTML

In the "Allowed HTML tags" of the "Filter settings" I added <p> and <br>


Check new form-input against old form-input

When you change something in form, that change can be found in $form_state. You need to add an AJAX callback and do your changes in that callback.

Sample code:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'MY_FORM_ID':
      $form['field_select']['#ajax'] = array(
        'event' => 'change',
        'callback' => 'your_ajax_callback',
        'progress' => array('type' => 'none'),
      );
    break;
  }
}

/**
 * AJAX Callback.
 */
function your_ajax_callback(&$form, &$form_state) {
  // dpm($form_state);
  // Check $form_state here and update subscription.
}

Hope this helps!


Add '?' and '=' characters to query string

You declare query parameters in drupal routes in a mymodule.routing.yml file like this:

mymodule.mailcommitter:
  path: '/mailcheck/{uid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ProfilController::checkMailCommit'
    _title: 'commit mail'
  options:
      query:
        token: ""
  requirements:
    _permission: 'access content'

Then, you build an url by route like so

'url' => Url::fromRoute('mymodule.mailcommitter', ['uid' => 1], ['query' => ['token' => 'hello']])

Also check this doc: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes


So, if dont want to use conditional_fields module and only conditional fields core
You can do it, but required field have sometime a little bug.

In the issue someone take some code from conditional_fields that fix this issue, and use it.

your_module/js/conditional_fields.js

(function ($, Drupal) {

// Fix core's required handling.
$(document).bind('state:required', function (e) {
  if (e.trigger) {
    var fields = $(e.target).find('input, select, textarea, fieldset');
    fields.each(function() {
      var label = 'label' + (this.id ? '[for=' + this.id + ']' : '');
      var $field_labels = $(e.target).find(label);
      var $fieldset_legends = $(e.target).find('legend span.fieldset-legend');
      var $labels = $field_labels.add($fieldset_legends);
      if (e.value) {
        $(this).attr({ required: 'required', 'aria-required': 'aria-required' });
        $labels.each(function() {
          $(this).addClass('js-form-required form-required');
        });
      } else {
        $(this).removeAttr('required aria-required');
        $labels.each(function() {
          $(this).removeClass('js-form-required form-required');
        });
      }
    })
  }
});

})(jQuery, Drupal);

In your_module.module in a form alter add:

$form['#attached']['library'][] = 'your_module/conditional_fields';

$form['field_b']['#states'] = [
      'visible' => [
        ':input[name="field_a"]' => ['!value' => '_none']
      ],
      'required' => [
        ':input[name="field_a"]' => ['!value' => '_none'],
      ],
  ];

Don't forget add the js code in your_module.libraries.yml file

Adding JS to a Drupal module

With our above code it worked!.


How can I share cache with multiple users and roles?

Caching is shared with multiple users or roles by default, unless you add a cache context like user or user.roles.

Otherwise it's hard to tell what the code in the question wants to achieve.

If it wants to set block cache keys, then you can't do it from here
and you don't need to. They're set automatically.
get_agent_number_from_context() should probably be a custom
cache_context.agent_number which you then could add to the block
build array to vary the cached block by this variable:

/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['agent_number'],
      'max-age' => 86400,
    ],
  ];
}

How to create a custom cache context:
https://www.drupal.org/docs/8/api/cache-api/cache-contexts#recognize-discover-create
If it wants to cache the expensive data on its own (which
makes sense if you want to reuse the rendered result in other places
not necessarily blocks), then you need to execute
get_expensive_data() in a #pre_render callback to avoid that it
gets executed in case of a cache hit. See
https://dev.acquia.com/blog/drupal-8-performance-render-caching

Edit 1:
The cids you have added to the question contain a cache context for the user. I can't tell by the code shown so far how it ends up in your block. But there is also a cache tag of the user, so there has to be some code retrieving and rendering the current user.

Edit 2:
Assuming the theme is the same there is also a default user.permissions cache context for all render caching which probably kicks in now that user is removed. See https://www.drupal.org/project/drupal/issues/2493033


403 forbidden error loading "sites" files

Have you checked out if you have set the public &/or private file permission on configuration page > Media > File System.
Also do check permission of what ever form your are trying to submit.


Add query condition for referenced user by user ID

if the machine name of user entity referenced in user_points content type is for example field_my_user, the following condition can be added to the query above to select only nodes with referenced user equal to $user_id

->condition('field_my_user.entity:user.uid', $user_id)


Drupal API to check a particular user is logged-in, or not

No, there is no function like is_user_login($uid), but you can see how the core block "Who's online" is created (source).
Drupal has a "sessions" table, where all current sessions are stored.


How to add crumb for each search result item?

If you already have a function to get breadcrumb from URL and assuming breadcrumb is, when is it, customize by hook_menu_breadcrumb_alter hooks, you just have to call this hook :

// Allow modules to alter the breadcrumb, if possible, as that is much
// faster than rebuilding an entirely new active trail.
drupal_alter('menu_breadcrumb', $active_trail, $item);

If this isn't enough to fix your problem, you can also see this contribution on github which seems great regarding the default breadcrumb construction in Drupal : https://gist.github.com/arshad/5490042#file-gistfile1-php-L12

Hope that helps :)


Why is my sub-menu not loading in main menu?

Go to /admin/structure/menu/manage/main-menu
Edit your parent link
Enable "Show as expanded" checkbox
(Repeat the same for all the parent links)
Go to the front page and see the main menu expanded.

Update:

You can use next code to render menu:

 $main_menu = variable_get('menu_main_links_source', 'main-menu');
 $tree = menu_tree($main_menu);
 print render($tree);


Yo will need to use the Features Extra module. It currently supports: vocabularies; nodequeues (definitions); block settings; custom blocks (boxes).


Show related nodes of a specific type when looking at a node of a different type

I would look into using the "context" module for this.

With it you would be able to set "conditions" and "reactions". The condition, being if your topic node is visited, react by showing a view block of the sub-topics. You can configure said block view to show the taxonomy tags based on certain criteria.


How to debug hook_form_BASE_FORM_ID_alter not working?

Not sure if relevant but I while copying your code I did received a warning. Warning: Unterminated comment, but perhaps that sneaked in while placing the code in the question.


"render ($user_profile)" in user-profile.tpl.php = no output

Try installing and enabling the devel module, then edit it so that it reads

<div class="profile"<?php print $attributes; ?>>
  <?php krumo($user_profile); ?>
  <?php print render($user_profile); ?>
</div>

That will show you what the data actually looks like...


finding a route to form mode and add it local tasks

I could find a solution with an handy module: https://www.drupal.org/project/form_mode_control

After installation, you can reach any form by using :

 www.your-site.com/node/add/my_content_type?display=machine_name_of_your_form

or

www.your-site.com/node/{node}/edit?display=machine_name_of_your_form

More then this, this module allow you to set permission to access each form mode.

I am still looking for how to add those forms as local task... but the main thing is done

My objective is: if I go to node/add, or node/{node}/edit, I would like to have the default form displayed but also, all the form mode accessible as Tabs (local task)


How can I get the email field value from a webform and use the rules module to send mail on submit event?

If you have an email field on the webform then that field will be available to you at webform/emails in the selector alongside the radio button = Component Value

That then becomes the 'to' field unless you then overwrite it.

You will also find 'select' type fields in that selector as you can then set email address for each of the options in the email settings directly.

You would use this if for example you had a field on the form for 'country' and needed to send the submission to different contacts based on which country was chosen.

Hope that helps


How do I see if it's improving my response time?

You can check the status at /admin/reports/memcache.


On the views you have page settings option

In that there is access option

You can change the access to role and
by changing the settings u can assign roles who has the permission to access the view.


Content type access permission by user role

Yes, I have got the issue.  This was a silly mistake, the nodes in that content types were not published.

I just published them and they are now visible to allowed roles.

Thanks


In config there are only few field types that are translatable by default text, label and i think date_format(you can check the schema types to see which field types exactly are translatable by default). You can also make any value translatable by adding the translatable: true flag to the field. Now, copy your config/install directory into config/install/language/LANGCODE and edit each one of those config files and keep only the translatable fields..and translate those :)

If you want to provide translations for you module so t() function will pick them up, that is a bit strange in D8 compared to D7 but to put it simply you have to edit your module's info file and put in the following lines:

'interface translation project': yourprojectname
'interface translation server pattern': relativepathtotranslationsdirectory/%project-%version.%language.po


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

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

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

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

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

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


You can use the Hacked! module

This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.
Hacked! also provides drush integration so that you can see what files have changed from the command line.


The function drush_sql_empty_db() has been removed in Drush 7.  You have two choices:

Downgrade to Drush 6 (it is possible to install Drush 6 at a different location, and alias 'drush6' to point to the older version).
Fix the site upgrade command.

The equivalent function to drush_sql_empty_db() in Drush 7 is:

$sql = drush_sql_get_class();
$sql->drop_or_create();

There may be other issues with Drush site-upgrade and Drush 7; I have not tried it in a while.


How to run jquery function on every page load

(function ($) {
  Drupal.behaviors.custom_scripts = {
    attach: function (context) {

      //write your custom code

    }
  }
})(jQuery);

Along with this for the first time you have to clear cache, and this will work in all pages and all the times.


Preprocess a Paragraph when Added to Content Type

If you want it to work when creating a node and when editing the node, you should make the change using both the node add form and the node edit form:

mymodule_form_node_content_type_form_alter()

mymodule_form_node_content_type_edit_form_alter()

Or in your hook_form_alter in the question:

case "node_content_type_form":
case "node_content_type_edit_form":

There's another way to do this using hook_field_widget_form_alter():

function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getTargetBundle() == 'content_type' && $context['items']->getFieldDefinition()->getName() == 'field_paragraph_field') {
    $element['#disabled'] = TRUE;
  }

}


How to get node url from Entity Reference field?

#node is usually part of a render array. Don't know why you named this entity. If it were a real entity object, then you could get the node id directly with .target_id instead of ['#node'].

The problem with keys in render arrays like #node is, they are only included if needed for rendering, so it's not a good idea to write code which fails if it does not exist.

You have to look for the entity object. According to the template doc the entity is named eck_entity:

{#
/**
 * @file
 * Default theme implementation to display an ECK entity.
 *
 * Available variables:
 * - eck_entity: The full ECK entity with limited access to object properties
 *   and methods. Only "getter" methods (method names starting with "get",
 *   "has", or "is") and a few common methods such as "id" and "label" are
 *   available. Calling other methods (such as node.delete) will result in an
 *   exception.
 * - content: All ECK entity items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_eck_entity()
 *
 * @ingroup themeable
 */
#}

If this is the template you use, then try something like this to access the field object and the target id of the node:

{% set field = eck_entity.field_eck_ref %}
{% set nodeId = field.0.target_id %}

This works independently of user permissions.

And only build the url when you are sure you have a node id, because otherwise your code still fails if the field is empty.


Watchdog messages and string replacement

Just use this:

watchdog('mymodule', 'Field !field_name created.', array('!field_name' => $file_field_name));

watchdog() function will translate the string you pass as the second parameter. You shouldn't translate the message before passing it to the watchdog().

Check out this answer for more information and references.

Or consult the following document from Drupal's documentation.


Create a new node by program and fill the specific field automatically

The field permission module lets you define detailed permission on field level. If you have different types of users you may be want to define a new role for your users.


How use bulk action (VBO) with table pagination?

This is only supported in the Drupal 6 version of VBO (the option is called "Preserve selection across pages" and I think it's enabled by default).
There's an open issue request for the Drupal 7 version: http://drupal.org/node/1207348
This is not a priority for me so I don't see it fixed in the next few months (unless someone else takes the lead).


How to show the following n events with respect to the current date or the past events to always ensure n elements in the view?

You will need to develop a custom module with a custom views sort plugin as views don't have something for this.

Read the Custom Views Sort Plugin for Upcoming Events blog post that will help you.


You are missing the braces.

Try this:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN (:nids)', array(':nids' => $nids));

For more information, see http://drupal.org/node/310072, especially the chapter on Placeholder arrays:

  Placeholder arrays

  Drupal's database layer includes an extra feature of placeholders. If the value passed in for a placeholder is an array, it will be automatically expanded into a comma separated list as will the corresponding placeholder. That means developers do not need to worry about counting how many placeholders they will need.

  An example should make this behavior clearer:

<?php
// This code:
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144));

// Will get turned into this prepared statement equivalent automatically:
db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array(
  ':nids_1' => 13,
  ':nids_2' => 42,
  ':nids_3' => 144,
));

// Which is equivalent to the following literal query:
db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");
?>


How to use custom block view mode in View?

Don't use custom blocks, use nodes or a custom entity type. Custom blocks are designed to be displayed as a block, not a view inside a block. They don't have a template on their own. See https://www.drupal.org/node/2704331.

Yes, it's not great, but it is unlikely that this will change any time soon.


Change url alias for user profile pages based on role

One way would be to create a hidden field on the user account page, and populate that field with Rules during registration. For example, for someone with the Staff role, give it the staff value; for user with the Faculty role, give it the faculty value.
Then, with the Pathauto module, define a pattern for user paths, for example [user:XXXXX]/[user:uid], where XXXXX is the name of the hidden field you created, prefixed with field.


Is there any way to make Commerce Customer Profile save/store data in a predictable manner?

I'm not really sure what the best solution is. I'm also not particularly fond of the code I wrote to prevent customer profile changes from harming the data integrity of historical orders. Those two caveats aside, maybe the following options can help:

You could patch commerce_order.module to add specific exemptions for your fields in the function commerce_order_commerce_customer_profile_presave(). You'd basically add a whitelist to the top of the foreach() loop there over field instances and if you see one that shouldn't be taken into consideration for profile copying, use a continue statement. Note that this approach means any changes to these fields would "appear" on previous orders that were placed with alternate values for these fields - if that doesn't matter to you, then this should be safe and fine.
You could look into Commerce Single Address. I'm not sure it's what you want, but it may offer some insight. You may need to add code to it to handle updating those previous references that were giving you an issue.

Ultimately we need to get a reasonable API around this so there are hooks and alternate options for the copy behavior. If you decide to patch commerce_order.module, make sure you maintain that patch in your codebase and have a process in place to re-apply it whenever you update Drupal Commerce.


Combining the Same Terms in different Vocabulary as one

You should try putting both Category and Tags under a single master vocabulary. Then assign both Category and Tags as parents of the shared term. So you have:

Level 1: MasterVocabulary
Level 2: Category [parent:MasterVocabulary], Tags [parent:MasterVocabulary]
Level 3: SharedTermA [parents:Category, Tags], TermB [parent:Category], ...


Contextual Filters within Block Display?

In the Block Display, create a contextual filter with these settings:

Content: Nid (not title)

Under "When the filter value is NOT available" check "Provide default value" then choose "content id from url"

Under "When the filter value IS available or a default is provided" check "Specify validation criteria" then choose "Basic Validator" or any other you like.


How to put a Slider widget into the Better Exposed Filters for Ubercart price and other product features?

Jquery UI and most of its widgets are embedded with D7 core, in misc/ui folder. First add these lines to your theme template file (sites/all/themes/YOUR_THEME/template.php) :

/**
 * Implements template_preprocess_views_view().
 */
function YOUR_THEME_preprocess_views_view(&$vars) {//replace YOUR_THEME by your theme name
  $view = $vars['view'];
  switch($view->name) {
    case 'YOUR_VIEW' : //replace YOUR_VIEW by your view name

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

Don't forget to clear cache.

Your filter must be compatible with is between, lower, greater operators. This is fine for  numeric fields. In the filter setup, set it as exposed and choose "is between" operator.

Last, in views advanced settings, in the BEF setup screen, select Jquery ui slider for your filter and adjust other settings like range at convenience.

EDIT

To answer your comments, don't edit Bartik or other core files.
You can easily create a subtheme as following :

Create the folder: /sites/all/themes/vassia
Create the file /sites/all/themes/vassia/vassia.info
put this code in vassia.info

name = vassia
description = my first subtheme
core = 7.x
base theme = bartik

stylesheets[all][] = css/vassia.css
stylesheets[all][] = css/colors.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

Create a file named: /sites/all/themes/vassia/css/vassia.css for your future css custom
If you need colors features, copy the file /themes/bartik/css/colors.css to /sites/all/themes/vassia/css/colors.css and copy the folder and its contents /themes/bartik/color/ to /sites/all/themes/vassia/color/
Go to the the Administration > Appearance page to enable your new subtheme called Vassia

Everything is very well explained in Creating a subtheme DO page. Now the slider part

Create a file /sites/all/themes/vassia/template.php
Write exactly this code in your template.php file :

<?php
/**
 * Implements template_preprocess_views_view().
 */
function vassia_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch($view->name) {
    case 'productviewwithsliders' :

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

Double check the view name. Clear all caches

Enjoy


Add lightbox to product list in Ubercart

Maybe you should create the product list with Views instead. Not only can you easily add lightbox like you write yourself, but you can make a lot of customizations should the need arise.

If you don't want to use Views, it's most likely the taxonomy module that generates the product list, that's how it's done on many UC sites. You could install the devel_themer and inspect the product list page with it. It should allow you to see what theme functions is being used to create the page. This should also help you figure out how you can add the customizations your want via template files or theme overrides.


You can do it both ways:

You can add menu block to your template - just like any other block (this method is the easiest).
If you need more customization, you can do it in template:

page.tpl.php

<?php if ($primary_nav): print $primary_nav; endif; ?>

template.php

if (isset($variables['main_menu'])) {
  $variables['primary_nav'] = theme('links__system_main_menu', array(
    'links' => $variables['main_menu'],
    'attributes' => array(
      'class' => array('links', 'inline', 'main-menu'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    )
  ));
}
else {
  $variables['primary_nav'] = FALSE;
}


I'm trying to get all duplicate rows using db_select

At the moment your query is:

SELECT
FROM
{node_revision} n
WHERE  (n.nid NOT IN SELECT MIN(n.nid))
GROUP BY hash

You need to add some fields...

db_select('node_revision', 'n')
  ->fields('n', array('vid'))
  ->where('n.nid NOT IN SELECT MIN(n.nid)')
  ->groupBy('hash')
  ->execute()
  ->fetchAll();


Where to export i18n mode for menus in features?

This is stored in the menu itself. Menu_links aside, the menu features wil be stored in some custom.inc file.


This is the same question I had asked myself and I wanted to increase the lifetime to something like 6 hours.

However, the point behind CSRF tokens is that they change frequently so that nobody can try to steal one of those tokens and then use it to make a forged request. Here's the workflow I ended up using in my application:

Request a CSRF token.
Use the token to make requests.
If the request fails because the token has expired, go to step 1.

Hope it helps. Happy coding.


There's a few ways to do that, but an easy one is to use the Panels module to define the page, coupled with domain_ctools

Then you can just add a selection rule or access control rule to specify the valid domains via the user interface.

Alternatively, you could do something with hook_menu access callbacks.


How to fix the garbled text in my text editors?

I had the exact same issue with aGov distro. I had to swapped from ckeditor module to WYSIWYG module + ckeditor lib.

That fixed the issue with ckeditor. However, today I got the garbled text again while having batched processes running which preventing them to complete. Thinking back, I realised the problem started when I installed Devel themer & simplehtmldom API (7.x-1.12). Uninstalling simplehtmldom fixed the issue for me.


How do I programmatically disable/enable a block?

Use db_update.

db_update('block')
   ->fields(array(
     'status' => 0,
     'weight' => -10,
     'region' => 'disabled',
   ))
   ->condition('module', 'modulename')
   ->condition('delta', 'modulename_delta')
   ->execute();


How do I include a term's additional fields on node display?

I've not played with semantic fields before, but I can tell you that configuring a term's display is the same as configuring a nodes display. The administration for a vocabularies display can be found at Structure --> Taxonomy --> VOCAB_NAME --> Manage Display or the path

admin/structure/taxonomy/VOCAB_NAME/display

Again, same as nodes you can configure the labeling & formatting options from this area. However, the location to configure a node's display is Structure --> Content Types --> YOUR_TYPE --> Manage Display

These settings are used for Drupal's native output. Using views can bypass these settings depending on the view (fields) or can work together (full, default, teaser).


Student TV channel - taxonomising YouTube videos

I suggest using series and genre as the main taxonomies as you've said and then using Tags to generate a taxonomy for cast and crew.

You can use the Taxonomy Manager module to bulk add and edit taxonomies, including tags.


Why is the "webform submission updated" hook not using the correct data?

For whatever reason querying the database give the correct data and yet the FillPdf sevice uses the older one, we moved the routine to the point where the results are showed, where its activated with a button. This option works fine.


Are there any quality of life add ons for Content Admin page? Easier sorting, searching, etc

The content page is actual just a view.  You can just edit it to make it do what you want to.  This is set up via the initial site creation so you will not loose your changes when core is updated.


Node translation vs. Entity (field) translation

Randy Fay recently created a post discussing the possibilities achieved with of Entity Translations, where Gabor Hojtsy commented on some of the considerations to weigh:

  Some good things offered by [good old] node translation include support for separate node commenting (eg. your German and English comments will not be intermixed); support for per language revisions; publication workflows (eg. the German node can be in a pre-publication revision workflow while the English is already published, coordinated actions can publish multiple language versions when all reach a certain step in the workflow, etc); different permission handling (eg. certain people can only edit German translations not English originals), thanks to Drupal's excessive node access system, etc. Think about menus. Most sites do not plan to have 1-1 menu structures for all translated versions.

The major caveat as I see it for Content/Entity/field-level Translation right now boils down to that age old Drupalism special case: the node title... Its not really a field, so its not translatable without another module, and potentially some patch work.  As of right now, I think field translation is still very much "experimental" ground, but more power to you for pushing forward into new territory.


Possible display options in Drupal views

Restrictions to access view can be set through Views UI to "role", "permission" or "none". See this page in Views documentation.

As for "role", those are IDs of different roles on your website. You can find those IDs in adiministration admin/people/permissions/roles - just hower over role edit link, number is in its URL.


Recommendation On Search Form For People

I would recommend using the views module.

This is kind of a duplicate of your other question How to implement 'Starts With' for exposed filter of User ID, where I explained how to do what you want with views.


What are the differences between Search API/Views and regular Views?

This question is pretty vague and probably should be blocked.. but I'll take a stab at it.

Search API views have a bunch of different features.  They allow full text search across multiple fields.  E.g. title and body and possible extra text fields all combined in one search filter.

You can set your search api setting to also deal with stemming (e.g. search for learn and also get learning, learns, and the like.

Search API views also allow you to sort by Relevancy.  E.g., if the search terms are found more times, the relevancy is higher.  You can also set up boosts for different fields.  E.g. if the term is in the title or product fields, it has a score of 10 rather then in the body where it has a score of 0.5.

This allows you more control over what shows up at the top of the search.

Search API views can also be set up to return 'excerpts' from the content with the search terms highlighted.  This can be useful in helping people decide if the content is what they want.

There are a bunch of other things that Search API / Views can do, like synonym setups (e.g. orthopedic is the same as orthopaedic).  Weighting specific nodes higher. Many of them may be at the search engine level (e.g. Solr) or require some extra modules (DB Server).

There is also the possibility of setting up auto completion suggestions as well.


How can I determine which module is associated with a field plugin?

The answer to the question title should be straightforward. You can get the extension from plugins via getProvider(). So you could make a list of all FieldType plugins or get the provider of a specific field type directly from the plugin defintitions:

$module = \Drupal::service('plugin.manager.field.field_type')
  ->getDefinition($field_type)['provider'];

For field definitions this is a bit more complicated. Field storages have this method as well, but for configured fields it always returns the module field. This is not what you want. But there is a different place. When creating field storages the provider of the field type plugin is stored in the property module. So starting from FieldDefinitionInterface you should be able to get the module name:

$module = $field_definition->getFieldStorageDefinition()->get('module');


How to achieve triggered redirect after log in so that administration interface will be available on the redirected url?

Try Login Destination , it will redirect you to the destination

  module allows you to customize the destination that a user is
  redirected to after logging in, registering to the site (7.x), using a
  one-time login link or logging out (7.x).

  The destination can be an internal page or an external URL.

  It is possible to specify certain
  conditions like referring pages or user roles and make the destination
  depend upon them. You may use PHP snippets to provide custom
  conditions and destinations.

  It is also possible to keep users on the
  currently visited page after logging in or out.

also take a look at Login Redirect module


After some research here is the result. I think it work fine

$totalRevenueQuery = db_select('commerce_payment_transaction', 'cpt')
    ->fields('cpt', array('currency_code'));
  $totalRevenueQuery->addExpression('SUM(amount)', 'amount');
    $totalRevenueQuery->leftJoin('commerce_order', 'commerce_order', 'cpt.order_id = commerce_order.order_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_line_items', 'field_data_commerce_line_items', 'cpt.order_id = field_data_commerce_line_items.entity_id');
    $totalRevenueQuery->innerJoin('commerce_line_item', 'commerce_line_item_field_data_commerce_line_items', 'field_data_commerce_line_items.commerce_line_items_line_item_id = commerce_line_item_field_data_commerce_line_items.line_item_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items.line_item_id = commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_id');
    $totalRevenueQuery->innerJoin('commerce_product', 'commerce_product_field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.commerce_product_product_id = commerce_product_field_data_commerce_product.product_id');
    $totalRevenueQuery->condition('commerce_product_field_data_commerce_product.product_id', $product_id);
    $totalRevenueQuery->condition('field_data_commerce_line_items.entity_type', 'commerce_order');
    $totalRevenueQuery->condition('field_data_commerce_line_items.deleted', 0);
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_type', 'commerce_line_item');
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.deleted', 0);
    $totalRevenueQuery->condition('commerce_order.type', 'commerce_order');
  $totalRevenue = $totalRevenueQuery->execute();


The admin_devel module actually comes with the admin_menu module.

It adds a debug function for javascript debugging (along the lines of dpm for php), which you can include and use.

It also adds a button you can press to rebuild system links, which is on the admin menu settings page.

This rebuilds menu item links that are handled by the drupal core system module.


You could look into hiding the tab using hook_menu_alter. If you set access callback to FALSE then it will be hidden.


You might be confusing things which makes your question hard to answer.

Please note that comments are not a content type, but they are part of nodes, and thus can be appended to any content type. Comment's can't be used inside the Panels module because they are part of a node (one is to import the whole node).

If you meant page rather then panel. Please make sure the comments module is enabled in modules. And then go to the 'basis page' content type and check the 'comment settings' tab (at the bottom) to see if comments are open.


How can I make search with a substring of a word?

Add ngramfilter to text type definition in schema.xml in solr config directory.

<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="25" />


View the original price, the discounted price and the discount percentage

If this is Drupal 7, you can use the Commerce Price Savings Formatter.  This extends the price field to show the "list price" and "sale price" and automatically calculates the percentage.

The module page links to a video explaining how to use the module.


Populating the $variables['classes-array'] in preprocess_html function

The problem was solved by putting the debug code after the change of values have taken place in the code.


how to Views call images of each node? I saw that is not in SQL of the view

It sounds like your view is configured to show nodes instead of fields.

When a view is showing nodes (either as teaser or full), the view only uses SQL to get which nodes to show. Then it calls node_load() and node_view() before outputting. node_view() will output a node just like you were looking at it regularly and this is where the image is being pulled in, not in views itself (hence why there is no SQL to get the image).

When a view is showing fields, it grabs all the fields data using SQL instead of node_load() and displays that data using it's own templates instead of node_view().

Let me know if I can clarify further.


Drupal core adds the text/javascript as default type.

You may include the file using drupal_add_js

drupal_add_js('file.js', array('attributes' => array('id' => 'my-template', 'type' => 'application/ld+json')));


install the livechat module and rocket_chat module.
  Setup the rocket_chat module.
  Go to [Structure][Block layout]. there you can place the livechat block
  using the "Place block" button.
  This works as a normal block we recommend you add it to a footer or alike
  for performance.

Source: Rocket chat module README.md

In other words, go to /admin/structure/block find the Footer region and click on Place block search for "RocketChat Livechat" and click Place block.


Which are the differences between hook_node_view_alter and hook_preprocess_node?

hook_preprocess_node is more generic, and thus more limited, and happens after hook_node_view_alter.

Both operate on the similar array, basically, but hook_node_view_alter operates at earlier stage. So, first reason is ordering of actions, second is accessing a bit different data sets, as they changes between stages of execution. dpr() or var_dump() their arguments to see exact differences. That's all. Nothing much to it, really.


JS Resize function for div containing a a slideview slideshow and set as a page background

Found two options: cycle2 for which the project is still in development stage:
http://drupal.org/sandbox/BenYoung/1832338
(and did not work when following the installation guidelines, since I never got the Cycle2 option in the dropdown and needs jquery 1.7 which apparently causes a lot of trouble)

And one that is actually fully functional
Flexi Slider here http://drupal.org/project/flexslider , for which I found also this great tutorial here http://coldfrontlabs.ca/blog/creating-responsive-image-slider-galleries-adaptive-images-drupal-7.
Strange that they're so well hidden when adaptive design and full width sliders are so requested now...

Now it works as I wished for it to be, except for one thing I will ask a different question for.


Try this:

/**
 * Variable preprocessor for the page template.
 */
function THEMENAME_preprocess_page(&$variables) {
  if (arg(0) == 'classified') {
    // Do things here.
    $variables['my_new_variable'] = 'Something';
  }
}

Note that the template page-classified.tpl.php will also match all sub paths of that page too, like:
yoursite.com/classified/something
yoursite.com/classified/something/something


How to override node_search_execute() to implement partial matching search?

hook_search_execute() is a hook that modules integrating with the Search module implement to execute the search. As such, hook_search_execute() is invoked only for those modules that have a tab in the search page, not for every modules implementing it. Since the Search module doesn't use hook_search_execute_alter() there isn't a quick method to totally override node_search_execute().

There are some way to make Drupal call another function instead of node_search_execute(), but those involve writing code. The quicker is probably altering the search/node menu to change the page callback, which normally is
search_view().

foreach (search_get_info() as $module => $search_info) {
  $path = 'search/' . $search_info['path'];
  $items[$path] = array(
    'title' => $search_info['title'],
    'page callback' => 'search_view',
    'page arguments' => array($module, ''),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => $module == $default_info['module'] ? -10 : 0,
  );
  $items["$path/%menu_tail"] = array(
    'title' => $search_info['title'],
    'load arguments' => array('%map', '%index'),
    'page callback' => 'search_view',
    'page arguments' => array($module, 2),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    // The default local task points to its parent, but this item points to
    // where it should so it should not be changed.
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => 0,
    // These tabs are not subtabs.
    'tab_root' => 'search/' . $default_info['path'] . '/%',
    // These tabs need to display at the same level.
    'tab_parent' => 'search/' . $default_info['path'],
  );
}

Since the goal you are trying to achieve is allowing searching by partial matching, you just need to install one of the modules that allows this, such as:

The Porter-Stemmer module
The Fuzzy Search module
The Apache Solr Search Integration module

The first module is the lighter one, since it doesn't depend from other modules, while the second one requires the Search API module, which in turn requires the Entity API module; the third one integrates with Apache Solr, and it is just a possibility for you if you have a server running Apache Solr. The Search API module also integrates with Apache Solr.

Reference

Drupal 7: Partial word search


Exposed form in block not found in block view drupal 7

Have a look at the Views Block Exposed Filter Blocks module.

Views normally restricts exposed form blocks to page displays. So if you want an exposed form for a block display you either have to go with this module or you build your own block in code and embed the exposed form there.


Try BigBlueButton

BigBlueButton Demo, http://demo.bigbluebutton.org/


Why my query string generates page not found for my view?

Are you using views_data_export? The most likely reason you are getting a 404 (are you sure it's not a 401?) is that your path starts with "/admin" and the menu system may be protecting it because its not sure which view you are loading.

Also, by default, Commerce rewrites all order and product SQL statements to enforce the permissions system. You can turn off the SQL rewriting if you know what you are doing (this is a security risk).


In image_link setting, How can I change "content" to the specific node

keep

'image_link' => 'content',

and after your code, before print:

$output['#path']['path'] = "node/30?ptype=20";


How to keep theming of a view after changing type of view?

Use the Theme:Information link in the edit view page

https://www.drupal.org/node/352970


It turns out that twig can't handle hyphens in their variable names.
Changing the variable names from

{{ social_media.facebook-color }}

to

{{ social_media.facebook_color }}

resolved the issue


Simple newsletter send only This is a test version of the newsletter

First, the newsletter module isn't yet stable, so I am giving you a solution for the Simplenews module.

If you want to send Views in a newsletter, you want to use the Viewsfield module. It allows you to create a Views field for your Simplenews content type. Then create a single Simplenews node and add your required View (there's a dropdown available with all active Views).

Since the content of the Views might change and you want to send the newsletter on a regular basis, you also need the Simplenews Scheduler module. It allows you to send the newsletter for example once a week with the updated content of your selected view.

I did something like that some time ago and also added a documentation on drupal.org.


hook_boot() is invoked too early to use the session, as Drupal has not yet initialised the session. Furthermore, hook_boot() has been removed from Drupal 8. hook_init() is not invoked for cached pages, but there is a trick to avoid the page is cached: Call drupal_page_is_cacheable(FALSE) in hook_init().

The function that actually stores the current page in cache is drupal_page_set_cache(), which contains the following code.

  if (drupal_page_is_cacheable()) {
    $cache = (object) array(
      'cid' => $base_root . request_uri(),
      'data' => array(
        'path' => $_GET['q'],
        'body' => ob_get_clean(),
        'title' => drupal_get_title(),
        'headers' => array(),
      ),
      'expire' => CACHE_TEMPORARY,
      'created' => REQUEST_TIME,
    );

    // Restore preferred header names based on the lower-case names returned
    // by drupal_get_http_header().
    $header_names = _drupal_set_preferred_header_name();
    foreach (drupal_get_http_header() as $name_lower => $value) {
      $cache->data['headers'][$header_names[$name_lower]] = $value;
      if ($name_lower == 'expires') {
        // Use the actual timestamp from an Expires header if available.
        $cache->expire = strtotime($value);
      }
    }

    if ($cache->data['body']) {
      if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
      }
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
    }
    return $cache;
  }

When drupal_page_is_cacheable() returns FALSE, the page is not cached; drupal_page_is_cacheable(), when called without arguments, returns the value of the parameter passed to the function in a previous call.

As hook_init() is invoked before drupal_page_set_cache(), calling drupal_page_is_cacheable(FALSE) causes the current page not to be cached.

I would call drupal_page_is_cacheable(FALSE) strictly when necessary, which in you case means when you are sure you need to set $_SESSION['is_redirected'].

Notice that a page is served from the cache when there isn't any session enabled. The function called to get the page from cache (_drupal_bootstrap_page_cache()) contains the following code.

  // If there is no session cookie and cache is enabled (or forced), try
  // to serve a cached page.
  if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
    // …
  }

If then you need to clear the cache for the front page, you can use the following code.

cache_clear_all(url('<front>', array('absolute' => TRUE)),  'cache_page');

The other alternative to hook_boot(), and hook_init() I can think of is hook_exit() which is called also for cached pages. The only reason I would not use it is that it is invoked after the current page is rendered, which means that when you redirect the user to a different page, the user would wait for two different pages to be rendered (the one rendered before the redirect, and the one to which the user is redirected).

If you are going to use hook_exit(), you need at least to call drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); if then you need specific functions, you need to change bootstrap phase, such as with drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL) when you need a function defined from another module.

Remember that with hook_boot() you cannot call functions defined from other modules, as they are not yet loaded; you can only use PHP functions, and a very strict number of Drupal functions, which at least includes the functions defined in bootstrap.inc.


What does combined block caching option 'DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE' do?

According to the documentation:

  Page and user settings can be combined with a bitwise-binary or operator; for example, DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change depending on the user role or page it is on.

In other words: When the block is cached, information about the user role and page are stored with it. The cached version is served only in situations where both the current user role and the current page match those of the cached block.

A good example in Drupal 7 core is the Author Information block (see block info, block view). It must vary by page, because every page can have a different author, and it must vary by role, because not every role may have permissions to view the author information.


You cannot add wildcards to menu item paths. I do not know why you want to do this as it is not neccessarry - when a logged in user clicks on "/user" he gets to his account page.


There are 2 ways to do this.,

Step :1

  Add the nid to the views and exclude it from the display.
  Place this nid before all fields in the views. Only by placing it above the all fields, we can get this as a token in the replacement.
  Now use node/[nid] as the path to link.
  This will worl

Step : 2

  Add content:link as a field.
  Add set the nid in the replacement pattern.

Difference between the 2.

  Step:1 shows the read more only when the length is greater than the
  trim value. Else it will not show.

  Step:2 will show the read more in all the cases. Even the body is
  empty it will show read more, but this will not happen in step 1.


Where is the pager data in the Views object

In hook_views_pre_execute (hook_views_pre_build is too early), the pager data, in general, can be found at
$view->pager

and the specific piece of data I asked about can be found at
$view->pager->options['items_per_page']


I need to control access to a Views-generated JSON feed with OAuth (Drupal 6)

With the services and services_views modules, it's possible to repurpose any view into a service with OAuth authentication.

From my testbed, here's what the URL for the service looks like:

http://services.localhost:8082/sample_endpoint/views/tracker.json

where "sample_endpoint" is the name of the endpoint, "tracker" is the name of the view being provided as a service, and ".json" is the format for the returned content.


Inquiring about finding mentors in the drupal community

Welcome to Drupal! There are established core-office-hours for folks looking for mentorship (and looking to mentor); Your best best is to start there and outline your skill set. Someone will be more than happy to help. See http://drupal.org/core-office-hours - So you don't have to beg in IRC. Just show up at the appropriate time. :)


The closest thing I know of, is the relation and relation select module combo. Relation select hasn't seen any development for quite a while, but you might be able to get where you want. It allows you to setup a view with exposed filters can be be used to selecting the node you want to reference.

This is Drupal 7 only.


Why do you need to add a class btn just to make it a button? Can't you just use the following css:

#navbar ul a {}

and style that to make it look like a button?


Webform Multistep - conditional wizard skipping

Wizard pages support conditional logic which can be used to skip steps as needed.


How do I create a custom view filter for an existing field?

If you do not need to code your Views filter, in your Articles View, you have a Filter criteria section where you may add views filters based on many different entities, including fields (what you call CCK fields)￼.


How to programmatically add links to the links variable

Drupal 6

In Drupal 6, you can't use hooks or alter hooks inside themes, so you'll need to create a custom module to modify the links. Once done, you'll want to implement hook_link() (if you're creating a new link) or hook_link_alter() (if you want to modify an existing link).

Adding a new link:

example_link($type, $object, $teaser = FALSE) {
  $links = array();
  // Add a custom link to nodes
  if ($type == 'node') {
    $links['example_mylink'] = array(
      'title' => t('Test link'),
      'href' => 'foo',
      'attributes' => array(
        'title' => 'Test link',
      ),
    );
  }
  return $links;
}

Modifying existing links:

example_link_alter(&$links, $node, $comment = NULL) {
  // Remove the read more link
  unset($links['node']['node_read_more']);

  // Change the title of the read more link
  $links['node']['node_read_more']['title'] = t('More information');

  // Move read more link to first slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links = $links['node'];
  $links['node'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $links['node']['node_read_more'];
  unset($links['node']['node_read_more']);
  $links['node']['node_read_more'] = $link_read_more;
}

Drupal 7

In Drupal 7, this is a little more straightforward, as themes can implement alter hooks. The alter hook you're looking for is hook_node_view_alter():

function example_node_view_alter(&$build) {
  // Remove the read more link
  unset($build['links']['node']['#links']['node-readmore']);

  // Add your own custom link
  $build['links']['node']['#links']['example-mylink'] = array(
    'title' => t('Test link'),
    'href' => 'foo',
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Test link',
    ),
  );

  // Move read more link to first slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $links = $build['links']['node']['#links'];
  $build['links']['node']['#links'] = array(
    'node_read_more' => $link_read_more,
  ) + $links;

  // Move link to the last slot
  $link_read_more = $build['links']['node']['#links']['node_read_more'];
  unset($build['links']['node']['#links']['node_read_more']);
  $build['links']['node']['#links']['node_read_more'] = $link_read_more;
}

You can place this directly in your template.php file.


Auto Complete for product variations use

You will need to write your own module and implement a hook_form_alter to override the normal Commerce way of displaying attribute selection.

A good example to look at is the Commerce Fancy Attributes module, which replaces the drop down with image selection. http://drupal.org/project/commerce_fancy_attributes

You can change the input type to autocomplete and point it to the correct callback url which returns your zipcode options in the format required for the product field.

$form['attribute_field_name']['#type'] = 'textfield';
$form['attribute_field_name']['#autocomplete_path'] = 'path/that/returns/list/of/zip/codes';


How to conditionally display some things in the message text created by the Message module?

I couldn't figure out how to do this what I thought was the "right" way - that being inside the message type itself.

Instead, I added a preprocess field from DisplaySuite and put that into my display.

function mytheme_preprocess_message(&$variables) {
    $message = $variables['elements']['#entity'];
    if (isset($message) && $message->type == 'my_custom_message' && isset($message->field_foo) && array_key_exists(LANGUAGE_NONE, $message->field_attachment_themed)) {
        $html = $message->field_fooLANGUAGE_NONE][0]['value'];
        $variables['parsed_output'] = $html;
    }
}

Then I just named my preprocess field parsed_output, and it now displays exactly how I want, and I can add whatever custom code I want to my preprocess_message().


How to change Search API index field machine name?

My answer I found in search_api_solr module search_api_solr.api.php file. I used hook_search_api_solr_field_mapping_alter
/**
 * Change the way the index's field names are mapped to Solr field names.
 *
 * @param SearchApiIndex $index
 *   The index whose field mappings are altered.
 * @param array $fields
 *   An associative array containing the index field names mapped to their Solr
 *   counterparts. The special fields 'search_api_id' and 'search_api_relevance'
 *   are also included.
 */
 function hook_search_api_solr_field_mapping_alter(SearchApiIndex $index,
                                                               array &$fields) {
   if ($index->entity_type == 'node' && isset($fields['body:value'])) {
    $fields['body:value'] = 'tm_text';
   }
 }

Here you can add required Solr index field name('tm_text') for according field('body:value').


Changing Column width of a table view (Drupal 7 Views 3)

A more general approach than useful answers from @Michael Greisman @Neograph734 is to create some utility CSS classes that can be deployed on any View. That means if this requirement comes up when creating a new View, you already have a solution ready to deploy.

This is something that has been really helpful on a site where I have configuration responsibility but all template / CSS work is done by a contracted developer (who suggested this approach).

Create some CSS classes that can be used to fix column widths. In our case, using % values worked best, but do whatever makes sense for your site. Example:

.fix-width-20 {
width: 20%;
}
.fix-width-40 {
width: 40%;
}
.fix-width-50 {
width: 50%;
}

On a view with the table format, go to the 'Style settings' for the Field that is populating the column (or columns) where you want precise control of column width. Add the name of the CSS class that fixes the width. Example:


How to create reviews for user comments?

The scenario is not very encouraging for Drupal 8 in voting modules at this time, but you can check some modules that can help you:

Votingapi Widgets

  A flexible field based Voting System based on
  https://www.drupal.org/project/votingapi .

Like Button

  Add a Like button to Drupal content and comments! Get instant
  statistics and insights! Sort content by likes!

Star Rating

  Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.


Sort the products by SKU when seeing order details

uc-order--admin.tpl.php is the "default admin notification template". In other words, the email sent to admins to notify them about a new order.

You can change the order of the products listed in the order view page by implementing hook_tapir_table_alter()

I have not used this code in production, and do not know what effect it will have on other pages/processes, so test it thoroughly:

function YOUR_MODULE_NAME_tapir_table_alter(&$table, $table_id) {
  if ($table_id == 'uc_op_products_view_table') {
    $sorted_rows = array();
    foreach ($table['#rows'] as $key => $row) {
      if (!empty($row['#entity']->model)) {
        $sku = $row['#entity']->model;
        $new_key = $sku . '_' . $key;
      }
      else {
        $new_key = $key;
      }
      $sorted_rows[$new_key] = $row;
    }
    if ($sorted_rows && ksort($sorted_rows)) {
      $table['#rows'] = $sorted_rows;
    }
  }
}


I recommend making a sandbox install of Commerce Kickstart to see how they set up "Product display node" and "Product entities" to work together. Your "Training" content type would be the Product display node, and each course offering would be the product. To replicate this on your existing site, the high-level approach (you will need to sort details) is this:

Install Commerce and create references from Commerce product entities to your Training content type
Create some products that represent your courses. You can add custom fields where needed.
Display the products that are referenced to the Training nodes using Views module or methods similar to those used in Commerce Kickstart
This should give you a list of courses on each Training node that can be added to Commerce cart.


author_picture twig variable outputting title and bio?

According to the documentation, {{author_picture}} is showing the node author user entity, rendered using the "compact" view mode.

In other words, you can adapt it by browsing to http://your_site/admin/config/people/accounts/display/compact


How to use field.tpl for rendered node in views3

If you want to override the views field template, the correct template file name would be views-view-fields.tpl.php.

You need to copy the template sites/all/modules/views/theme/views-view-field.tpl.php to your current enabled theme folder. Then update the file as you need.

Rescan template files in your view theming information. The file views-view-field.tpl.php should be highlighted with bold. You may need to fluch the cache. It is a view template to all the fields as a row.

If you want to theme a specific field, you could use views-view-field--[field_name].tpl.php. It is the most specific view template.
You can check more in Views theming.


Using pathauto to create multiple aliases, one for each term?

Under Configuration, if you go to Modules and click on Configure for Pathauto, you should see the option for the URL patterns. There is a section for taxonomy as well. However, I realize you want to change a node's URL based on the taxonomy term you've associated with it. At this point, it's just a matter of figuring out what token is going to do that for you.I have not used it, but I would imagine the Field Tokens module may help you do what you want to do. If you search for "pathauto" on that page, some people discuss using it with Pathauto down in the comments.


Cannot configure the site as SAML SP with simplesamlphp_auth

The problem was - as so often - between the keyboard and the chair. I had some subtle mistakes in a couple of file paths in config/config.php. Apparently simplesamlphp_auth doesn't do any validation of file names, so mistakes blow up without any apparent context at runtime.


How to deal with exploding node_access queries?

I don't know how much of an answer this is, but: the approach I was taking to node_access that led to the original post was almost certainly wrong.  In particular, I was setting up separate gids for each item I was writing into node_access, rather than keeping gids associated with user IDs as they are almost surely meant to be.  After a bit of work, I was able to restructure this aspect of the site around this more correct approach, and was able to cut down the number of clauses added by node_access by about a factor of 10.  Life is a learning experience, I guess; I could probably elaborate a bit if anybody cares...


Null value in DB displays content on page

Use the Devel module and enable it's database query log. See this question.


Drupal 7, MySQL, InnoDB, and transactions

The constructor for the DatabaseConnection_mysql class, has this code and comment:

public function __construct(array $connection_options = array()) {
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) ||
    ($connection_options['transactions'] !== FALSE);

In addition, there is support and workaround for the MySQL implementation of transactions (including no proper support for DDL transactions).

This suggests that the documentation in the settings file is incorrect.


empty optional fields: saved node contains the token name instead of an empty section

I have figured it out with my own custom module:

function mymodule_tokens_alter(&$replacements, $context) {
    if ($context['type'] == 'node') {
        $keys = array_keys($context['tokens']);
        foreach ($keys as $key) {
            if (isset($context['tokens'][$key]) && !isset($replacements[$context['tokens'][$key]])) {
                $replacements[$context['tokens'][$key]] = '';
            }
        }
    }
}


So to help keep your theme files cleaner, the preference is to place theme overrides in a custom module. This allows you to switch themes without having copy, paste, and rename a bunch of code.

Also this may be your only choice if, for example, you're trying to override a theme function that's being called from an admin page, you have an admin theme enabled, and you don't want to bother with creating a subtheme for your admin theme.

The workaround here is to use hook_theme_registry_alter(); see this page on Drupal Stack Exchange.


It will only help if your files are actually on a CDN...if they are, then install that module, set it up, and you should see some performance benefits.

If not, then installing it will have zero effect, except to add a very slight extra overhead to your page build (when the module is included/hooks are run/etc).


The file module has that built right in. Edit the settings for your file field, and find this bit:

Save that, and go back to your node edit form where you will see:

With both the included field formatters you should see the contents of the 'Description' field for the link text of each file.


How do I get Search API to index rendered content including referenced nodes?

You should be able to traverse through the reference fields on the Search API Add Fields page. Then you want to add all the referenced text fields, so they become part of the main node. However, it is possible that Search API currently has some limitations there, it didn't show configurable fields for me when I tried something similar a few days ago. I'm sure that will eventually be fixed, though. There might be issues already.

PS: You might want to check out Paragraphs. It's a similar concept, with a much better editing experience, you can have different types of embedded content elements and edit it all in the same form. We're working on Search API integration right now and will also look into the problem mentioned above.


What's the prupose of the version property of a theme library?

For Javascript files, version would allow modules that implement hook_library_info_alter() to check if the version of the JavaScript file is older than the one the module is trying to add, for example with code similar to the following. (It's the same code the documentation page reports as example.)

  // Update Farbtastic to version 2.0.
  if ($extension == 'core' && isset($libraries['jquery.farbtastic'])) {
    // Verify existing version is older than the one we are updating to.
    if (version_compare($libraries['jquery.farbtastic']['version'], '2.0', '<')) {
      // Update the existing Farbtastic to version 2.0.
      $libraries['jquery.farbtastic']['version'] = '2.0';
      // To accurately replace library files, the order of files and the options
      // of each file have to be retained; e.g., like this:
      $old_path = 'assets/vendor/farbtastic';
      // Since the replaced library files are no longer located in a directory
      // relative to the original extension, specify an absolute path (relative
      // to DRUPAL_ROOT / base_path()) to the new location.
      $new_path = '/' . drupal_get_path('module', 'farbtastic_update') . '/js';
      $new_js = [];
      $replacements = [
        $old_path . '/farbtastic.js' => $new_path . '/farbtastic-2.0.js',
      ];
      foreach ($libraries['jquery.farbtastic']['js'] as $source => $options) {
        if (isset($replacements[$source])) {
          $new_js[$replacements[$source]] = $options;
        }
        else {
          $new_js[$source] = $options;
        }
      }
      $libraries['jquery.farbtastic']['js'] = $new_js;
    }
  }

Technically, the same type of code could be used to check which CSS file version is being used, before replacing it with a different one. I can imagine doing that for an external CSS file, for example when a specific version used from a library causes problem with other libraries. I haven't seen a module using similar code, though.

Otherwise, version has only identification purposes, much more helpful when a module implements hook_library_info_build() to dynamically load different versions of a CSS file.


I've made a bit of progress.  I had created the HtmlfilesNodeMigration class outside of the actual hook_migrate_api function.

So instead of:

return $api;

}

class HtmlfilesNodeMigration extends Migration {
//code
}

I needed:

return $api;
class HtmlfilesNodeMigration extends Migration {

  }

}


How can I render a block in the sidebar in php?

If you need to assign block to region programmatically you can implement hook_block_info_alter

function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  if (isset($blocks['views']['name_of_view-name_of_view_display'])) {
    // assign block to region
    $blocks['views']['name_of_view-name_of_view_display']['region'] = 'sidebar_second';
  }
}


How do I get rid of a staged configuration import?

If you export the configuration again current configuration files should be deleted and new ones will be created with the configuration hold in your database.

Anyway you should make a backup first, just in case. You can use drush for this. Use drush archive for a complete backup (including files):

drush ard

Use drush sql-dump to backup only the database:

drush sql-dump > /patch/to/new/file/with/db-dump


db_query() doesn't seem to run in module

You write that

  but also make some changes to a record in another mySQL database that's connected to one of our internal non-Drupal systems

so I figure that you need to query a different MySQL database, but in your don't change the active database using db_set_active. This is most likely the root to your problem.

If the SELECT query works, then the code you have provided should work just fine.

A simple way to test your problem, would be run db_query on a known record and see if you can alter it. Devel also offers query logging, which would allow you to log the actual UPDATE and alternatively try to run the raw query through a MySQL interface.

Another explanation could be that you have the ismi.new_people table in the Drupal db, so you in fact are updating the wrong table/database.

Another possible problem is database  permissions. Do your DB user have read only access?


I was thinking about building a simple access system, but that would be like re-inventing the wheel.

Take a look at content_access in combination with ACL. The flexiaccess might be another option.


Remove the ability to import previous imported file

you can simplely remove it by using hook_form_alter

don't forget replace  form_id and yourmodulename with yours  in following code

function yourmodulename_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
    unset($form['feeds']["FeedsFileFetcher"]['upload']['#file_info']);
}
}

update
in this section we prevent user to resubmit the old file,this mean if user push import button without browsed new file we prevent him to remport

function mymodule_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
      $form['#validate'][] = 'mymodule_prevent_import_validate';
}
}

function mymodule_prevent_import_validate($form,$form_state){
    if(!isset($form_state['values']['feeds']["FeedsFileFetcher"]['file'])){
            form_set_error('upload', t('Not new file uploaded'));
            return false;
    }
}


You need to download, install and enable the IFE  (aka. "Inline Form Errors") module.

Like all Drupal modules, its project page is immediately below https://www.drupal.org/project/.

Here is a link to the project page where you can download it:  IFE project page.


how to get view_mode from within hook_field_formatter_view

Imho a formatter shouldn't be dependent on the view mode. It's the site builder's choice which formatter to use in which view mode, and through that decide how things look. It sounds to me like you'd be better off either having two formatters, or having one formatter which can be configured.

My understanding of the Drupal way here is that you provide the general purpose tools (just like a module typically provides permissions, but not a new role - leaving it to the site builder to aggregate perms into roles appropriate for their particular needs). Every time I create a new view mode I want to have complete power to make it do exactly what I want.


Found a solution.
Just copy the entire templates folder of the omega base theme to your subtheme.
Within that folder, just edit or add new tpl files.
Those files will be injected to the specific block/content.


How can I limit filter to child terms of selected parent in Views?

I would take a look at Simple Hierarchical Select. From the module page:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.


How to get the url from a link field in preprocess function

If you inspect with $variables['items'][0]['content'] with Devel kint

kint($variables['items'][0]['content']);

  But it doesn't work and I think it's because by the time I get to that
  point, Drupal has already used the uri for the #title.

Correct, so all you gotta do is check if the title is equal to the url utilizing Url::toString.

  if ($variables['field_name'] == 'field_event_location_link') {
    $link_url = $variables['items'][0]['content']['#url']->toString();
    if ($variables['items'][0]['content']['#title'] == $link_url) {
      $variables['items'][0]['content']['#title'] = 'Location';
    }
  }


If this were an SQL query your new column could be a subquery. I mean this new value of # of classrooms with assigned teachers has its own business logic, seperate from the list of data your already returning.

You can accomplish this using Views Field View. This lets you embed a view result -- per row of your existing view. From the project page:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

  It's highly recommended to use this module in conjunction with views
  caching. Views Content cache and Cache Actions are good ways of
  caching views.

So:

Make a new view; called for instance with the human name of "sum rooms assigned teachers" (the machine name will be sum_rooms_assigned_teachers).
For this View simply use display mode of Show Fields; and include like the NID as a field; Under advanced settings enable Aggregation for the View. For the NID value use the Count aggregation.
Add a contextual filter to this view based on the school name.
Save your view.

Then in your parent view:

After installing Views Field View. Add a new Field your view of Global: View.
select the view named sum_rooms_assigned_teachers. Provide the contextual filter to the view of your school name or ID; it will look like [!field_school_entityreference_id] or something similiar.
Give this field whatever label you want.

Your main view should now show a room count. In the helper view you may want to deny access to anyone but the Administrator or other role -- as this is simply a helper view for this other view; and rather useless by itself.


db_query gives PDO Exception "General error: 1366 Incorrect integer value:" when I try to update table

From the Drupal API on db_query:

  Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.

The recommended method:

// Insert values returned from Twitter API.
$tweetsdb_id = db_insert('tweetsDB')
->fields(array(
  'handle' => $handle,
  'tweet' => $tweet,
  'time_string' =>$time_string,
  'tweetid' => $id,
))
->execute();


Adding text to a field before save (Drupal 7)

you could create your own module and implement this hook:

hook_node_presave

This hook allows you to modify the node object (and corresponding fields) before it is saved or updated within the database.