Lat/Long not getting imported into Geofield via feeds importer

There is a bug in the Geofield module. When lat/long are set via Feeds, the Geofield module assumes the field to be empty because some other properties of the field are not set.

There is a patch available that could fix the issue:
https://www.drupal.org/node/2534822


How to display only  certain values  otherwise display empty field in Views

You can make use of a computed field (fruits_computed) which takes the input value of the fruit field (fruits) and filters values via php, sth. like this:

$allowed_values = array('orange');
if ( array_in($fruits_value, $allowed_value) ) {
$output = $fruits_value;
} else {
$output = '';
}

Then in views, you do not use the fruits field, but fruits_computed.


Wich template to override for user account form

use the native interface to add fields and change display

/admin/config/people/accounts/fields

/admin/config/people/accounts/display/full

if the html structure need to be changed , the template

  user.html.twig

can be override in the theme child templates folder.

As an exmaple for custom added individual fields, with fundation classes :

  {% if content %}

        {{ content.field_user_photo }}

        {{ content.field_user_name }}
        {{ content.field_user_status }}
        {{ content.field_user_email }}
        {{ content.field_user_phone }}

  {% endif %}


How to pre-populate multiple "field collection" fields in node form

After hours of debugging I found a good working solution to pre populate fields in field collections. (see Drupal forum)

So whats the plan?

  Manually generate a node-add form for the desired bundle.
  Change the form state of the generated form and set the desired number of fields you want to pre-populate.
  Rebuild the node-add form with the new form state values.
  Use hook_form_alter() to pre-populate values.

Ok. So lets assume we have a bundle called bundle_with_unlimited_fc which belongs to the node entity type. Furthermore all our custom code will reside in our module named my_module.

We can use hook_menu_alter() to define a new page callback. Everytime a new bundle_with_unlimited_fc is added Drupal will call now this function.

function my_module_menu_alter(&$items) {
  $items['node/add/bundle_with_unlimited_fc']['page callback'] = 'my_module_build_form';
}

Now definde our form builder function. Notice the function argument which comes from the Drupal implementation of our altered menu item.

function my_module_build_form($type) {
  // get the standard node form;
  // we cannot get it from drupal_get_form() because we need the form_state reference,
  // so we copy a bit of code from node_add() and drupal_get_form()
  global $user;
  $form_id = 'bundle_with_unlimited_fc_node_form';
  $form_state = array();
  $form_state['build_info']['args'][] = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );
  $form = drupal_build_form($form_id, $form_state);

  // we now have exactly the form which node_add() is returning BUT
  // we also have a reference of the form state array ready to alter;

  // how many items do we want?
  $num_items = 5;
  // this is exactly what the ajax request for the add more button does
  $form_state['field']['--machine-name-of-field--'][LANGUAGE_NONE]['items_count'] = $num_items;

  // now this is important!! set a flag inside the form state so that the hook_form_alter() function
  // is able to know when it should pre-populate (remember: hook_form_alter() will be called twice
  // during this process)
  $form_state['my_module_prepopulate'] = TRUE;

  // reset the html ids so that our new rebuilted form will get nice ids and not form_id--2
  drupal_static_reset('drupal_html_id');

  // rebuild the form and return it;
  // through drupal_rebuild_form() hook_form_alter() will be called again - this time with our
  // prepopulate flag and 5 empty form elements ready to prefill
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

Thats nearly all there is. Just setup your hook_form_alter() and you will be ready.

// hook_form_FORM-ID_alter().
function my_module_form_bundle_with_unlimited_fc_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['my_module_prepopulate']) && $form_state['my_module_prepopulate']) {
    $delta = 0;
    $max_delta = $form['--machine-name-of-field--'][LANGUAGE_NONE]['#max_delta'];
    while ($delta <= $max_delta) {
      // prepopulate whatever you like with help of #default_value'
      $form['--machine-name-of-field--'][LANGUAGE_NONE][$delta]['#default_value'] = 'Value to show';

      $delta++;
    }
  }
}

So thats it basically. Hope that this solution will help some people to save time...


Display of multi values image field problem

I could be way off, but with the information given, your problem might because of lightshow.   Try another module such as colorbox


Is my web hosting company's "Full Backup" sufficient protection before an update?

You need two things to restore a Drupal site: A copy of the database and the folders that hold Drupal.

I'm not familiar with shared hosting, but I'm guessing that Drupal is installed in your home directory as opposed to /var/www or /srv/www.

That means a full backup does give you everything you'll need to restore Drupal. Make sure you know how you'd restore it though. No point backing up if your not sure where the files are and how to restore them.

If you want to extra safe or do it yourself, install the Backup and Migrate Module, make a backup and make a copy of your Drupal root directory. (That's the one with sites, includes, themes etc. in it).

Then if you want to restore Drupal. Delete the bad Drupal root directory and put your old drupal root directory back in. Install Drupal as normal, enable backup and migrate module (it'll be there because you've put in your modified Drupal root folder) and then restore from the Backup and Migrate backup.


By using taxonomy_vocabulary_machine_name_load() and taxonomy_get_tree() I was able to extract the 2 taxonomies I needed for creating the prefix and suffix of the SKU.

I created tables of key, value pairs that contained the tids and the SKU codes.

By using json_encode() I was able to pass those tables into an inline js script I attached to commerce's product form using $form['#attached']['js'].

Now by having a JavaScript array mapping tids to SKU parts, it's easy using jQuery to fill in the SKU textfield accordingly. :)


Edit your field on which you want to add an HTML tag to a specific class.(Style settings category)
See screenshot.
You need to add "Authored on" field and configure the display as you want to be shown.


How programmatically display the Image field before Taxonomy name in Better Exposed Filters?

I was prompted how to do it. Thanks a lot to xandeadx.

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {

foreach ($form['TAXONOMY_ELEMENT']['#options'] as $tid => &$name) {
    $term = taxonomy_term_load($tid);
    $name = '<img src="' . file_create_url($term->FIELD_IMAGE['und'][0]['uri']) . '" />' . $name;
  }
}

In my version TAXONOMY_ELEMENT = tid_1


Redirect to mobile page (not theme switching)

I suppose if you really wanted to, you could do something along the lines of this in a custom module:

function YOURMODULE_init() {

  if ($_SERVER['REQUEST_METHOD']=='GET' // most ajax/ahah etc use POST
      && arg(0)!='admin' // admin theme/backend
      && strpos($_GET['q'], 'sites/default/files')===FALSE // are we looking at anything under files that doesn't "really" exist, eg imagecaches that aren't created yet
      && $_GET['q']!='m') { // aren't already "here"

    include 'PATHTOSCRIPT/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if ($detect->isMobile()) {
      drupal_goto('m');
    }

  }

}

but they could never leave, or rather, be able to go to any other page on your site.

Addition:  per @MPD's comments, some further protections.


You can try to add fivestars module to your website, but then your users will be voted with stars instead of flags.

If you dont mind that you have to:

install fivestar module
add a field on your user profile of type "Fivestar Rating"
add a rule so people cant vote on themselves using rules module.

hope this helps


Altering UserPasswordForm redirect with a custom submit

By adding a submit handler to the submit element you override the main submit handler attached to the form. The use case for this option is if you want a submit element to have a completely different action.

Append your submit handler to the form and it should work as you have intended:

$form['#submit'][] = 'maubl_user_submit_forgot_pass';


Using forms and templates and _submit callback

Many questions here:

Your form function function should return the form array and doesn't need an argument unless you need it for something specific.
You should at least have an element of type 'submit' (not button) in your form.
Chances are good your submit function will get called if you implement it this way.
If the form fails validation, FAPI will restore it to the values submitted, keeping what was typed by the user.
You shoudn't try to embed business logic in your template, but rather in your module and/or a preprocess function.


Related content in a view using entity reference

As mentioned in the comments you don't need any Relationships to filter out the related content. Simply add the Contextual filter for your Entity Reference field, and configure it with a Default value to pick up Content ID from URL, and validation criteria to the Artist content.

You can use the Relationship if you need information other than the Artist node ID in your Views, for example, if you have an independent Views Page showing all Releases, and you want your Contextual filter to be in your URL showing the Artist name and not the ID number:

/releases/Beatles

for all Releases nodes referencing the Artist Beatles.

And it's still working the same as it did in Drupal 7, apart from the different wording in the names, you just added the wrong Relationship.

It should not be the 'Content using field_artist', but Content referenced from field_artist.

'Content using' that field are the nodes with the ER (News, Releases, etc.) so you're just pointing back to what you already have in your Views. This is a "backwards" Relationship.

The 'Content referenced from field_artist' Relationship is pointing towards the Artist nodes, and through adding that Relationship you'll have the Artist data available in your (Releases) Views. This is the Relationship you want to you in this case.


How to register a theme function from the theme

The description of hook_theme() is:

  Register a module (or theme's) theme implementations.

So you can implement this hook in your theme.


How to get user data when I provide the uid or username - Services

URL to fetch the user information by providing uid as follows.

http://[yourdomain]/[endpoint]/user/[uid]

Example: http://www.example.com/rest/user/2 will fetch user information, having user id 2.

You can get the user data by providing username, you can use pass name (username) as a parameter to the service URL like follows

http://example.com/<endpoint path>/user?parameters[name]=krishna

If you have enabled session authentication you might have to pass X-CSRF-Token in headers.
For session authentication you can find my answer here


How to create a node programatically with drupal_form_submit()?

The advantage of this method over node_save is that if you have field validation done by modules like field_validation or your own custom validations that you have previously implemented, the node saving will fail if the data sent does not comply with those validations.

global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'MYCONTENTTYPE',
  'language' => LANGUAGE_NONE,
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['MYCONTENTTYPE'] as $field_name => $values) {
  $form_state['values'][$field_name] = array(LANGUAGE_NONE => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body'][LANGUAGE_NONE][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
$form_state['values']['field_MYFIELD'][LANGUAGE_NONE][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('MYCONTENTTYPE_node_form', $form_state, $node);

// Tell watch dog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message', array('%message'=> $message, '%field' => $field_name));
  }
}


How to obtain the complete list of available Drush Output Formats?

To see the verbose list of output formats use help with a command name. For example the help for the watchdog list command drush help wd-list:

Normally you get:

 --format=<json>                           Select output format. Available: table, csv, html, json, list, var_export, yaml.
                                           Default is table.

But if you use --verbose:

drush --verbose help wd-list

You get the full list:

 --format=<json>                           Select output format.
                                           All available values are:
                                            - table: A formatted, word-wrapped table.
                                            - config: A configuration file in executable php format. The variable name is
                                           "config", and the variable keys are taken from the output data array's keys.
                                            - csv: A list of values, one per row, each of which is a comma-separated list of
                                           values.
                                            - html: An HTML representation
                                            - json: Javascript Object Notation.
                                            - labeled-export: A list of php exports, labeled with a name.
                                            - list: A simple list of values.
                                            - php: A serialized php string.
                                            - print-r: Output via php print_r function.
                                            - var_export: An array in executable php format.
                                            - variables: A list of php variable assignments.
                                            - yaml: Yaml output format.
                                           Default is table.

To get a global detailed list of all formats defined in drush you can use the drush function outputformat_drush_engine_outputformat():

drush ev 'var_dump(outputformat_drush_engine_outputformat())'

EDIT:

If you want to see only the format names you can use:

drush ev 'print_r(array_keys(outputformat_drush_engine_outputformat()))'

Output:

[0] => table
[1] => key-value
[2] => key-value-list
[3] => json
[4] => string
[5] => message
[6] => print-r
[7] => var_export
[8] => yaml
[9] => php
[10] => config
[11] => list
[12] => nested-csv
[13] => csv-or-string
[14] => csv
[15] => variables
[16] => labeled-export
[17] => html


How can I make a view which displays the categories of a parent category?

Views comes with a default view that overrides the taxonomy pages. Enable this and then edit the view. Under "Advanced" change the depth of "Content: Has taxonomy term ID (with depth" to display the depth of your choosing. I think there may also be a setting in the Taxonomy Display module that also allows you to modify the depth without using views.


How to find a Data Selector in a rule condition?

Found the way:

To drill to the selector I have to create 2 "entity has field" conditions.

1) entity "site:current-cart-order" has field "commerce_costumer_billing"

2) entity "site:current-cart-order:commerce-customer-billing" has field "vat_number"

then I can select the data selector


I just had a similar issue and found out I needed to edit the database login-information on my remote site as it had the local site's info in it since that's where the files came from.

Maybe that's the case on your site too?

In short: Check that the remote site's settings.php-file has the database information from the remote site and not the local site.


You could use Panels and create a forum looking View (table) thats a copy of the same view that shows your Group content and then add it somewhere on the page. I wouldnt know how to add the 'forum' on a seperate page though.

You could add a select list in the group node form and have 'forum' or 'post' options.


Sensitive data on configuration managment

From page 17 of the Drupal PCI Compliance Guide:

  Removing credentials from settings.php. One can include a settings.local.php file within settings.php to ensure that sensitive information is not distributed.

This is good advice and is what most people do.

If you have a lot of information you want to store securely, looking at the Encrypt module or even a Lockr integration might be advisable.


I have done this before using Core drupal tools. Although I suspect different than your current approach.

I use a drupal Queue. and I fill it with items:

                                                    Queue
          Task1Items              Task2Items          Task3Items              Task4Items
    [---item1---item2---item3|item4---item5---item6|item7---item8---item9|item10---item11---item12]

I put all the tasks, in the ordering for the various steps of your task into a Queue. Then be sure to use a Drupal Reliable Queue:

  There are two kinds of (default) queue backends available: reliable, which
  preserves the order of messages and guarantees that every item will be
  executed at least once. The non-reliable kind only does a best effort
  to preserve order in messages and to execute them at least once but
  there is a small chance that some items get lost. For example, some
  distributed back-ends like Amazon SQS will be managing jobs for a
  large set of producers and consumers where a strict FIFO ordering will
  likely not be preserved. Another example would be an in-memory queue
  backend which might lose items if it crashes.

After inserting all the items. Your batch call simply iterates over the queue you've populated. Use something like Ultimate Cron to setup a group of task workers, or Background Process, or Ultimate Cron Queue Scalar to speedup your workload if you want.

Another handy module to view your queue visually is the Queue UI module. As the core Queue API is a developer API and has no UI by itself. Don't want to write php code to create/manage a queue -- look at Rules Queue.


Content Access

  This module allows you to manage permissions for content types by role
  and author. It allows you to specify custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Nodeaccess

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.

If you want to add it by custom code use hook_node_access

function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $check = (
      ($node->type == 'node condition')         );
    if ($check) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}


Notification and Messaging module for sending mails

Html mail is not reliable, buggy and some features are not supported. I've got rid of it. Mime mail is much better. Mail system and SMTP module must also be installed.

In the settings SMTP Authentication Support SMTP server, SMTP port, User name, E-mail from address, E-mail from name must be filled, Allow to send e-mails formatted as Html could be ticked and password of your SMTP server must also be entered.

In the module Mail system in the submenu New class MimeMail_SmtpMailSystem must be constructed and filled in Site-wide default MailSystemInterface class and Mime Mail module class. In the settings Mime mail E-mail format Full HTML can be selected and Sender e-mail address need to be filled.

This configuration must work.


Field with content entries from a content type

No.
Fields can be reused between any content type. In node's field administration page, use the existing field and values you attributes you set to that field will be available in both node types. But you can have different field labels and descriptions.


Drush and MAMP3: cannot connect to database

Thanks for those suggestions.  I inadvertently stumbled on  a solution.  I'm no expert here, so there could (and probably are) reasons why this isn't a good idea but I'll share it anyway.

I simply created a sim-link by doing the following:
cd /tmp
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Worked like a charm.


It seems that the database is using lexicographic ordering, while your intention is to use numeric ordering. Numeric ordering is only used when the type of the field is a numeric type. Check whether the field is of a numeric type.


How to theme the Event content type node creation form in drupal 6?

It all depends on what changes you want to make, but the standard way of altering forms in D6 (and D7) is invoking hook_form_alter() in a custom module. Do a switch on the form_id, and enter your edits, something like this:

YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // print $form_id; exit;
  switch($form_id){
    case 'event_node_form':
      // change the form. The following will alter the text on the submit button:
      $form['submit']['#value'] = 'Go!';
      break;
  }
  return $form;
}

If you don't know what the form_id is of the form you want to edit, just uncomment the print $form_id line and visit the form in your browser. You can refer to the D6 form api guide to find what form elements go with which properties. Hope that helps!


Why can Wordpress ship with latest version of jQuery but Drupal cant?

My understanding is that the version of jQuery gets locked down with the version of Drupal during development to ensure stability. It is all part of the testing process. The Drupal developers fully test the system before releasing a new major version of the CMS, including the JavaScript functionality. The incremental changes that go on throughout the year do not provide the time to test at this level so the jQuery version stays the same.

I am not very familiar with Wordpress, but my understanding is that they make considerably more regular major upgrades to the versions of their CMS. So jQuery gets updated more frequently. However, from what I've read little testing takes place.

While getting stuck with an old version of jQuery can be frustrating, I'd rather go for a stable well tested system.


How do I override headers displayed in permissions tables?

Implement hook_page_alter() and

function mymodule_page_alter(&$page) {
  if (current_path() == 'admin/people/permissions') {
    foreach ($page['content']['system_main']['permission'] as $index => $permission) {
      if ($permission['#markup'] == 'Organic Groups') {
        $page['content']['system_main']['permission'][$index]['#markup'] = 'Foobar';
      }
    }
  }
}


You can create a new module and implement the hook_feeds_presave() function like the following example:

function hook_feeds_presave(FeedsSource $source, $entity, $item) {
  // create your filter conditions here
  if ($entity->feeds_item->entity_type == 'node') {
    // Skip saving this entity.
    $entity->feeds_item->skip = TRUE;
  }
}


Programmically create a content type with publishing options

You have to add a base field override to change the default value of status, promote and sticky for newly created nodes. For the first and second option the default value is predefined as TRUE and for the third option as FALSE in the base field definition of the entity type. See this example for promote:

Drupal\node\Entity\Node::baseFieldDefinitions

$fields['promote'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Promoted to front page'))
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE)
  ->setDefaultValue(TRUE)
  ->setDisplayOptions('form', [
    'type' => 'boolean_checkbox',
    'settings' => [
      'display_label' => TRUE,
    ],
    'weight' => 15,
  ])
  ->setDisplayConfigurable('form', TRUE);

The base field override needs only to be present if you want to change this preset for a specific content type.

Example for the status field:

foobar/config/install/core.base_field_override.node.car_brand.status.yml

# core.base_field_override.node.car_brand.status.yml
langcode: en
status: true
dependencies:
  config:
    - node.type.car_brand
id: node.car_brand.status
field_name: status
entity_type: node
bundle: car_brand
label: 'Publishing status'
description: 'A boolean indicating the published state.'
required: false
translatable: true
default_value:
  -
    value: 0
default_value_callback: ''
settings:
  on_label: 'On'
  off_label: 'Off'
field_type: boolean

You can override the fields promote and sticky the same way.

The same task in PHP:

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'car_brand');
$fields['status']->getConfig('car_brand')
  ->setDefaultValue(FALSE)
  ->save();

The method BaseFieldDefinition::getConfig loads an existing base field override or creates one if none exists from the base field definition in the entity type.

Using the PHP code in an install hook is IMHO the better solution, because you only need to change the default value and don't need to repeat all other values.


Title in page does not change with different page of the same View

If you are using AJAX in your view, the title won't change. Also, try adding !1 or %1 to your view title.


How NOT to delete original account picture when uploading a new one?

When a user adds a new pictures make a copy of this pictures with rules to a user specific directory. When a user wants to restore his picture browse this directory, let the user decide which picture he wants and copy it back with rules.


How to fetch form state value of a form on clicking custom button?

In that case, you can create a container in the form, and fill it with the values after AJAX has been fired. Then you only need to return that container in your ajax callback.

if($form_id == 'user_register_form')
{
  $form['mybutton'] = array(
    // ...
    '#ajax' => array(
      'callback' => 'my_ajax_callback',
      'wrapper' => 'form_state_values_wrapper',
    ),
  );

  $form['form_state_values'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '',
  );

  if(isset($form_state_, $form_state['values']))
  {
    $form['form_state_values']['#markup'] = '
' . print_r($form_state['values'], TRUE) . '
',
  }

}

function my_ajax_callback(&$form, &$form_state,$form_id) {
  return $form['form_state_values'];
}


Prevent Drupal from rewriting # as %23 in URLs

function drupal_urlencode($text) {
  if (variable_get('clean_url', '0')) {
    return str_replace(array('%2F', '%3F', '%3D', '%26', '%2523'),
                       array('/', '?', '=', '&', '#'),
                       urlencode($text));
  }
  else {
    return str_replace('%2F', '/', urlencode($text));
  }
}


How to add edit link within add to cart form in ubercart drupal 7?

This is probably confusing due to UC's reliance on TAPIr to render the cart items. Anyway, you can modify data inside in the $form['items'] array to change the output of those elements. For example, if you wanted to add an edit link underneath the product description:

function MYMODULE_form_uc_cart_view_form_alter(&$form, &$form_state) {
  foreach($form['items'] as $key => $value) {
    //Check a TAPIr row for a product associated with an editable nid
    if(is_int($key) && isset($value['nid']['#value']) && isset($value['desc'])) {
      if(node_access('update', $value['#entity'], $user)) {
        $form['items'][$key]['desc']['#markup'] .= l('(EDIT)', 'node/'.$value['nid']['#value'].'/edit');
      }
    }
  }

There might be a cleaner way to do this, but I haven't thought about TAPIr in a while.


Prepopulate an entity reference in an inline entity form

I tend to use CER (Corresponding Entity References) for things like this.

As an added benefit, you can hide the reference field on specification_text_section giving a slightly cleaner editor experience.

I have a couple of similar setups where I have IEFs on the grandparent, parent, and child, so you can create all 3 from any level and CER handles reverse reference. So, if I create a parent node, I have 2 IEFs, one for the grandparent and child, but don't show the field referencing the parent in either IEF forms.


How can I show parent and child terms in facet search filter block for a taxonomy field having simple hierarchial select as widget type

I'm presuming you are using FacetAPI and Search API Solr.

You need to add some settings to the facet itself at Search API > Index > Facets > [Taxonomy name]:
http://example.com/admin/config/search/facetapi/[indexname]/block/field_[taxonomyname]/edit

You'll need to

Expand the hierarchy
Treat parent items as individual facet items
Don't flatten hierarchy
and minimum count zero (ie: show even when empty)


How do you format the exposed filter options?

Views 3 for Drupal 7 kindly gives each exposed widget DIV a class with a unique name. Then it's a matter of adding clear and float attributes.

If you're using Views 2 you will have to override the views-exposed-form.tpl.php file in the views/theme folder. You can just copy and save this code in a file called views-exposed-form.tpl.php in your theme file path. It should override the original template file.

<?php
// $Id: views-exposed-form.tpl.php,v 1.4.4.1 2009/11/18 20:37:58 merlinofchaos Exp $
/**
 * @file views-exposed-form.tpl.php
 *
 * This template handles the layout of the views exposed filter form.
 *
 * Variables available:
 * - $widgets: An array of exposed form widgets. Each widget contains:
 * - $widget->label: The visible label to print. May be optional.
 * - $widget->operator: The operator for the widget. May be optional.
 * - $widget->widget: The widget itself.
 * - $button: The submit button for the form.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($q)): ?>
  <?php
    // This ensures that, if clean URLs are off, the 'q' is added first so that
    // it shows up first in the URL.
    print $q;
  ?>
<?php endif; ?>

    <?php foreach($widgets as $id => $widget): ?>
      <div class="views-exposed-widget views-widget-<?php print $id ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>

      <?php print $button ?>


Having the NOT IN SQL query equivalent in a view

Forget the Views Raw SQL module. Simple SQL is not going to give you the result you need. Queries look for what is there, not what isn't.

You will need to construct two lists. First, the list of programmes the user has selected.

$selected_programmes = array();

foreach ($user->field_taxonomy_programme['und'] as $selected_programme) {
  $selected_programmes[] = $selected_programme->name;

}

Second, the list of available programs.

$available_programmes = array();

$vocabulary = taxonomy_vocabulary_machine_name_load('programmes');

$programmes = taxonomy_get_tree($vocabulary->vid);

foreach($programmes as $programme) {

  $available_programmes[] = $programme->name;

}

Then you can use the two lists to produce a list of the unselected programmes, which can then be used to construct your query.

$unselected_programmes = array_diff( $available_programmes, $selected_programmes);

There is no way around it. The only way to construct a query for values which are not present is programmatically. I would suggest the use of a block with a php snippet to display this information.


I ran _system_rebuild_theme_data() but that didn't seem to improve the situation, so I checked the theme status in the system table; the base theme had been disabled. There lay the rub.

How or why the base theme became disabled remains a mystery. At the time this site was built, it was not required for a base theme to be enabled for the subtheme to access its functions; this changed, but I hadn't touched the theme in the month I've been working on this site, other than rebuilding the cache, so presumably it had been enabled before.

Since Omega was disabled, it was not supplying the right theme variables for our custom subtheme (though .tpl.php files did seem to get found), thus the broken display this morning.

Because Omega 4 is designed to be built and configured programmatically, perhaps, the base theme is hidden by default, and there was no way to enable it from the UI. I had to edit the .info file so that it was no longer hidden, at which point it showed up on /admin/appearance as usual.

If I had been able to use Drush on this server, this all would have been a non-issue. Many thanks to @Clive for his quick response and suggestions.


Add additional CSS class for particullar field in a node

You could try theme_field as well

  Returns HTML for a field.

This is the default theme implementation to display the value of a field. Theme developers who are comfortable with overriding theme functions may do so in order to customize this markup. This function can be overridden with varying levels of specificity. For example, for a field named 'body' displayed on the 'article' content type, any of the following functions will override this default implementation. The first of these functions that exists is used:

THEMENAME_field_body_article()
THEMENAME_field__article()
THEMENAME_field__body()
THEMENAME_field()


Decode an image in base 64 to a file, using feeds, feeds tamper and jsonpath

Feeds Base64 images module

I have developed a module for this which adds two additional targets for file and image fields:

Filename
Base64

The 'Filename' target always needs to be mapped first.

I created this module years ago, but I never published it on drupal.org... until today!

https://www.drupal.org/sandbox/megachriz/2961717


"Cannot modify header information - headers already sent by (output started at codefolder\modules\user\user.module:1)"

Check that you don't have any ending php tags at the end of your php files. Sometimes whitespace (spaces, tabs, newlines) will sneak in at the end of the file after the tag and cause php go into html mode and send the headers too early.


Try adding the following, but this will still reload the page, which may not be ideal.

url: 'internal:#nolink'

These module maybe interesting as it may not be necessary to manually edit the menu code. You can add a class to a menu item and add CSS

pointer-events:none; cursor:default; text-decoration:none;

https://www.drupal.org/project/link_attributes
https://www.drupal.org/project/menu_link_attributes


How to specify the default installation profile

oops its my mistake.

D7 by default doesn't consider standard and minimal profiles, so its selects acquia profile by default.

I had problem with my custom installation profile, that's why it doesn't showed up in the profile list.


Accessing user's custom field in html.tpl.php

If you are using the global variable $user, it doesn't always contain a full initialized object. In fact, during the bootstrap, $user is initialized with the data contained in the "users" table, from the following code.

  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

  // We found the client's session record and they are an authenticated,
  // active user.
  if ($user && $user->uid > 0 && $user->status == 1) {
    // This is done to unserialize the data member of $user.
    $user->data = unserialize($user->data);

    // Add roles element to $user.
    $user->roles = array();
    $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    $user->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $user->uid))->fetchAllKeyed(0, 1);
  }

If you want to be sure to get a fully loaded user object for the currently logged-in user, you should use the following code.

$account = user_uid_optional_load();

After that, you can get the value of any user field.

$fullname = field_get_items('user', $account, 'field_first_name');

You can also get the rendered value of the field using the following code.

$rendered_value = field_view_field('user', $account, 'field_first_name');

The other reason for which $user->field_first_name['und'][0]['value'] could not contain any value is that the language-neutral value of the field is not be set. ('und' is the value of the constant LANGUAGE_NONE, or LANGUAGE_NOT_SPECIFIED in Drupal 8.) If you use field_get_items(), or field_view_field(), you are sure to get the correct value.

As side note, it is preferable to keep the logic in the template.php file, in functions that are called from the template files.


How to (ab)use image effects to serve API generated images?

If you are getting the image from another server/site you don't need an image field. If the link isn't going to change, you can store it in a text field and build a link like this

your_module_node_view($node, $view_mode, $langcode) {
    $url = $node->field_cool_image[LANGUAGE_NONE][0]['value'];
    //redefine field_cool_image to display your image
    $node['content']['field_cool_image'][0] = array(
        '#markup' = ''
    );

}

otherwise build the link when the node view is built.

your_module_node_view($node, $view_mode, $langcode){
    //whatever method you use to build a url
    $url = my_build_url($node);
    $node->['content']['my_cool_img'][0] = array(
        '#markup' = ''
    );
}


The related code is found in block_block_list_alter() function, inside /modules/block/block.module file.

Here's how you would perform a similar check in your code:

// Get the pages to check. This should be in the same format as what Drupal
// core uses - meaning one path per line and you can use placeholders.
//
// Variable below is just as an example.
$pages_to_check = 'page1' . PHP_EOL . 'page2' . PHP_EOL . 'page3/*';
// This is a good practice, because it will make sure that paths are always
// checked consistently and won't depend on the case.
$pages = drupal_strtolower($pages_to_check);
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
  $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
}
// Now you can do whatever you want based on whether or not the current path
// matches the pattern. For example:
if ($page_match) {
  // You are on one of the listed pages.
}
else {
  // You are not on one of the listed pages.
}

Hope this helps.


I've seen many modules for this, but don't seem to see any that allow searching by field.

There are many modules which provide this feature, not necessarily out of the box, but with some customization.

I would say, the best module to start with this would be Restful.
I have personally used it for a similar use case for building the service endpoints which could be filtered using specific field values, and it work charms!
The documentation seems to have improved a lot since the last time I've seen it!

There are other modules present which help you create custom endpoint too. However, the ease of building such filterable endpoint is good with Restful as per my experience.


An illegal choice has been detected when I submit my webform module

Editing webform-form-**.tpl or any template file is designed to alter the theme or display of the webform. It seems you are having issue with the forms content, specifically default values.

If you are using the Form API to create your form in your own module, you will need to declare it as described in the FAPI documentation.

<?php
  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
    '#default_value' => $category['selected'],
    '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
  );
?>

The error that you are getting tends to occur when form elements are submitted that were not defined in the original form. And by the look of your template edit, that could easily be the case.

Check out your log at Administer > Logs > Recent log entries to see what is causing the error.

To get an empty entry submitted from the select options force the 'empty option' form declaration. Works like a treat.

'#empty_option'=>t('- Select -'),

Good luck.
xK


What would be the most efficient way to select node for a content type?

<?php
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'status'))
  ->condition('type', 'info_page')
  ->addTag('node_access')
  ->execute();
while ($result = $query->fetch()) {
  print_r($result);
}

Query against node table must be a dynamic query with "node_access" tagging to prevent node access system by-passing.


I'm guessing you're on drupal 7?

Rather than trying to disable/show a 404 you could install this module:
https://www.drupal.org/project/globalredirect

That will make it so that if anyone tries to access one of the "node/*" urls they will be automatically be redirected to the proper alias of the page. Would that work for what you need?


How to change commerce order owner to someone else?

-> If you want to do programatically, then Load Order as
$order = commerce_order_load(1);
$order->uid = 4;
commerce_order_save($order);

-> By admin UI
   Edit order and in User Information, specofy username of user you want to assign and save.


You can actually use drush make for this purpose. Drush make files can add in third-party dependencies which can be useful for just this kind of thing. Unless you intend to share this module with the community, in which case, you can issue a wget from the module itself similar to how other contrib modules do it. (See JW Player for an older example of that)

This is a good post on the topic by basically a Drupal genius. (Not me, I swear)

http://davehall.com.au/blog/dave/2011/05/17/drush-make-and-module-dependencies


How to block permissions tab for certain users?

This cannot be done without code.  If you take a look at user_menu() you'll see that access to both of those pages is determined by the administer permissions permission.

To block access to one but not the other will require you to implement hook_menu_alter() and change which permission is checked for one of those pages.


Yes you can, you can do it with views
go to admin admin/structure/views/view
create users views, add filter last acess -30 mintures,
you can import below views

$view = new view();
$view->name = 'logout_users';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'logout users';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'logout-users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Last access */
$handler->display->display_options['filters']['access']['id'] = 'access';
$handler->display->display_options['filters']['access']['table'] = 'users';
$handler->display->display_options['filters']['access']['field'] = 'access';
$handler->display->display_options['filters']['access']['value']['value'] = '-30 minutes';
$handler->display->display_options['filters']['access']['value']['type'] = 'offset';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'logout-users';


Send email to all users that are tagged with the same tag a node is when created

install: views-rules-module, and rules-conditional module. Add in views a rules-view (is a new display type added by rules-view-module) of type USERS, add your category-field, hide from display, add relationship to taxonomy-vocabulary, add field: term-ID and UID. Both fields in views middle column set your fields as type: INTEGER. If you want you can delete user-field_category from this view. If needed, filter users by role or whatever to shorthen your view results, and important: no-pager, display all rows.

Now in rules: react-on: new content of type: your-content-type, conditions: entity-has-field: node-created-content: your field_category, actions: fetch-entity-by-id: taxnomony-term: value: drill in node until you find node-term-ID.

Add your new view-rule (find link at bottom settings in actions), now you have term-ID from user & UID, inside view-loop and a conditional, add an if, data-comparision, your NODE-term-ID vs USER-term-id, if equal, fecth USER by ID, with your variable UID, and send email. Done.
Note: is possible that you will need to transform your NODE-term-ID as an integer.

Your rule will look like something like this:

EDIT: first install rules Version: 7.x-2.11, i can see that you do not see 'conditional label' in rules action. To avoid to update rules module, install disable-updates-module

FIRST action should be 'fetch entity bt ID: tanonomy term', select your new node, and drill until you find term-ID.

SECOND action: add your users-views-rule. all following actionts take place inside rules-view-loop.

THRID action: inside rules view, data compare: your variable term-id from rules-view-users with NODE-term-ID (first action), if values match (are equal) then fetch USER by ID with your variable value UID from rules-view, now you have user object avilable, do send email to that user, rules-view will compare next user, and so on. here is another img of how will look your rule, notice how actions are taking place inside rules-view-loop.

and here is an img where you can find how to add your rules-view, it says "Add a view loop" at the bootom of img.

And this is how you set your fields inside rules-view, this is located in middle colum of your view.


How to replace the title of the profile in the breadcrumb, by the name of the user?

you can implements this hook in a custom module or in your theme.

hook_preprocess_breadcrumb()

Then you can access $variables and manage it easily (like put the username in the last element of the array).
Regards,


Two simple ways I might approach this:

Context Module
jQuery

1) Context Module: create a new context where Condition is "Views" (select the appropriate view) and the Reaction is "Theme HTML" (add the class you want to display in the body there).

Cons: the class is not dynamic, unfortunately. Or at least I have not investigated any way to make dynamically name the class (i.e. page-[node:field_field_yourfieldvalue]). Because of this, you will most likely need to create a new context for each variation if you choose this approach.

2) jQuery: if you want to get the classes in views and add an altered version of these classes to the body tag, then you could use some javascript to pull that off. Something to the effect of this might work:

var myClasses = $(.view-name).attr('class');

$('body').addClass(myClasses);

Something like that, just cleaned up. Hope that helps :)


efficient way to apply content permissions

Have you tried looking into Organic Groups?  It seems like the PERFECT solution to your problem.  It'll require a bit of work to set up, but the benefits will FAR outweigh the work.

You could have each department set up as a group, and then users can be assigned to those groups.  You can then set permissions that allow users to create content but only for their specific group (using OG means that this can be ONE content type).

You'd only need one user role (an organic groups user..you could also have a department admin per department should you want).

You can also do some more awesome stuff from here on out.  Just as an example, these departments could then view their own department content - but you can also display all posts from all groups.

There are some REALLY good videos at Modules Unraveled


There are the children classes of Query:

class DeleteQuery implements QueryConditionInterface
class InsertQuery
class MergeQuery implements QueryConditionInterface
class SelectQuery implements SelectQueryInterface
class TruncateQuery
class UpdateQuery implements QueryConditionInterface

Only SelectQuery implements addTag method. However, if you realyl are creating query object just there, you wouldn't need a tag anyway. Tags are only useful for hook_query_alter, and you shouldn't need to alter query you just created.

Your best options, as far as I know them, are:

Enable query log in your database
Devel module with it's query display


Memory usage PHP peak=40.25 MB -- too much for a single request?

The memory limit setting (often 128MB) is per process, so you're only using around third of it. If a single request needs more than 128MB of memory, it will fail. This doesn't appear likely in your case.

  What happens if there are many concurrent users?

That depends on your total amount of RAM. You can in theory handle up RAM / 128 MB users.

If you have 15 concurrent users, each using 40MB, and you have 512 MB, then you'll go over that limit, because 40 * 15 = 600.

The normal configuration is then to use the hard-drive, often called swapping. This normally means the death of all performance, and should always be avoided, to the level where it's better to out right reject more incoming connections.


Prevent users from editing a node if a CCK field has a specific value

What you want is probably a custom node_access module - just remember that permissions in Drupal are additive, so your custom module is granting permission, rather than taking it away. So, for instance, a user should not already have the "edit this content type" permission or they'll have it for ALL nodes of that content type.

Also, why even assume they can attempt to edit? If they don't have permissions to edit that page, short of them manually hitting the /edit URL for a node, they're not going to have a chance - no edit button will be visible.


Different slide intervals for Views Slideshow

You might be able to override the defaults with something like this:

$('.views-slideshow-cycle-main-frame').each(function(index) {
  var timer = 3000;
  if (index == 1) timer = 5000;
  if (index == 2) timer = 10000;
  $(this).cycle({
    timeout : timer
  });
});

This goes in an external js file or using drupal_add_js().


In your module

function custom_theme($existing, $type, $theme, $path){
      return array(
        'mortgage_page' =>  array(
          'template' => 'theme/mortgage',
          'render element' => 'page'
        ),
      );
    }

function custom_preprocess_page(&$variables, $hook) {
  if ( preg_match("/mortgage\/.*\/view/", drupal_get_path_alias($_GET['q'])) ) {
   $variables['theme_hook_suggestions'][] = 'mortgage_page';
  }
}

Check for path alias to be correct and change theme_hook_suggestions to your theme.


How to display one of Drupal's default forms

user_profile_form() is an existing function, but it's not defined in a module file; that means that the file where the function is defined needs to first be loaded, in a way or the other.

Instead of defining a page callback that then calls drupal_get_form() to get a form defined in a form builder implemented in the same module, I would rather define the menu callback using the following code (the code I am writing is for Drupal 7, but can easily adopted for Drupal 6, if there is the need.

$items['path'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('input_simple_form'),
  'file path' => drupal_get_path('module', 'user'),
  'file' => 'user.pages.inc',
);

The code for the form builder could be something similar to the following one:

function input_simple_form($form, &$form_state) {
  $form = array_merge($form, drupal_get_form('user_profile_form', $account));
  // ...
}

user_profile_form() uses a third argument, the category of the profile to show. Its default value is "account"; if you are getting an error about a missing third argument, then you can explicitly pass that parameter too, for example using its default value, as in drupal_get_form('user_profile_form', $account, 'account').
"user.pages.inc" is the file containing the user_profile_form() form builder, in Drupal 7, and Drupal 6. The reason that you get the error you see is that such files are loaded only when Drupal is instructed to load them; that is done by using the "file" and "file path" array indexes. ("file path" is only required when the file is not between the files of the module implementing hook_menu().)
I used input_simple_form() as form builder, in the case you need to use its own validation and submission handlers.
There is a $account variable that has not been defined in the example code I wrote. That is one of the required arguments that user_profile_form() needs, as the function needs to know for which user account the form is being build. That is the other reason to use your own form builder, which should load the user object for the account used for the user profile form, or pass the value of the global $user to drupal_get_form('user_profile_form').


Display a single view in different view format

I think Your Question resembles the video tutorial series in Code karate:

Multiple Views Series

Please Check It out... By adding and removing classes when clicking the grid and list icons using jQuery make this done..


How do I make a user profile field a link

If I'm understanding the question correctly it sounds like you need an additional module that will correctly validate/display the link in the user profile.  Overview of the steps needed:

Download the Link module:
Add a new field to the user profile of type "Link" (found in confifuration --> people --> account settings --> manage fields)
Set any other config options you need


Yes it is!

You embed blocks into Homebox regions, so just create a block display of your view, and include it into your Homebox on the layout page.

Any disabled blocks will be listed at the bottom, just pick a region for them!


How to add one entity reference field that can reference either a node or a user?

I do not think you can do this with the Entity reference module.  Look at its code:

/**
 * Implements hook_field_info().
 */
function entityreference_field_info() {
  $field_info['entityreference'] = array(
    'label' => t('Entity Reference'),
    'description' => t('This field reference another entity.'),
    'settings' => array(
      // Default to the core target entity type node.
      'target_type' => 'node',
      // The handler for this field.
      'handler' => 'base',
      // The handler settings.
      'handler_settings' => array(),
    ),
    'instance_settings' => array(),
    'default_widget' => 'entityreference_autocomplete',
    'default_formatter' => 'entityreference_label',
    'property_callbacks' => array('entityreference_field_property_callback'),
  );
  return $field_info;
}

I suggest you try a work-around.  For example, you could create a content type that includes two entity-reference fields, one of type Node and one of type User.  Maybe, for convenience, include a boolean or integer field indicating which of the two to use.  Then use references to your new content type where you want to use node-or-user entity references.

Alternatively, you could use the Field collection module, which works the same way, creating node types to handle collections of fields:  https://drupal.org/project/field_collection.


How to create a custom markup for a views-block?

If you want to create custom markup/template for that particular view of content type then create file and name it as views-view-fields--[view-name]--page/block.html.twig and save it in template directory of your theme.

Now to get the variable just goto the content type -> manage fields. There you will find the machine names of fields. those are the variable you need to place in html structure like this
{{ fields.field-machine-name.content }}
 Hope this helps :)


How to get or extract the link path for terms in View

A quick solution will be:

Use "pathauto" to generate path for term pages (taxonomy/term/term_id => fruit/apple)
Use "global redirect" to force default path to custom paths
In your View build the URL like taxonomy/term/term_id?quantity=100 and should be translated at rendering time to fruit/apple?quantity=100

Thank you.


Go to your Drupal installation directory     /sites/default/settings.php and add the following line

ini_set('arg_separator.output',     '&amp;');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     10800);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  10800);
ini_set('session.gc_maxlifetime',   10800);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');
ini_set('session.gc_probability', 1);


Just to offer a solution that doesn't make use of arg() (which it's advised to avoid where possible according to the docs page)

You can use the menu_get_object() function:

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // User is on a taxonomy term page
}


hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.
  Parameters

  $node: The node that is being inserted or updated.

function hook_node_presave($node) {

if ($node->type == 'your_node_type') {
// you can write your desired code here

}

}


To logout using REST in Drupal 8, you can do a POST to:
https://example.com/user/logout?_format=json&token=logout_token
Use the following headers on your request:

Content-type: application/json
X-CSRF-Token: csrf_token

The values for logout_token and csrf_token are available in the login response.
Be sure to visit admin/config/services/rest and enable the following for the User resource:

methods: POST
formats: json
authentication: cookie

Earlier versions of Drupal 8
Do a GET on ?q=user/logout
This is noted in the JS D8 REST docs: https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services
Although it should not matter, the Content-type may need to be set to application/x-www-form-urlencoded.
Here's an example usage from jDrupal: https://github.com/signalpoint/jDrupal/blob/8.x-1.x/src/includes/rest.inc.js#L113


How to jump to another know page on a button click?

If the whole implementation (including the URL computing) is done on the client side with javascript then the easiest solution would be to simply use code like the following:

$('#go_button_id').click(function() {
  location.href = 'url_to_the_computed_page';
});

On the server side you could use Drupal's block hooks and form API to create a block with a simple form and then use $form_state['redirect'] = 'url_to_the_computed_page'; in the form submission handler for the redirect.


Imagecache preset is missing in field configuration

Do you have the ImageCache Profiles) module installed and enabled? Here is a quote about it (from the module's project page):

  ... allows you to set user profile pictures that are consistent throughout your site and allows avatars on the user profile pages, nodes and comments to be a different size.


How to use drush config:set for translations?

For getting the site name in Spanish for example it's

drush config:get language.es:system.site name

Unfortunately the following doesn't work and I wonder if this is a bug or what's missing.

drush -y config:set language.es:system.site name "Hello World"

This just gives me

  Invalid character in Config object name language.es:system.site.

Will update answer later.

Created an issue on drupal.org: drush config:set for other than default collections raises exception. Where I also provided a patch you may use if you are really in need right now.


Validation error every time on save comment form

I traced the problem down to the the panels pane that displayed the comments list. If the comments list was disabled, comment submission worked fine; turned back on the validation error returned.

Looks like this is caused by a (likely) bug in CTOOLS. The patch in comment #1 fixed the issue.


Turn off Drupal caching without Access to admin panel

Yes, you can run Drush under Microsoft Windows if you use the Drush Windows Installer. Drush will allow you to turn of caching with the command:

drush en cache_disable --yes

It is not easy to set up the Drush Windows Installer.  As an alternative, you may consider explicitly set variables in your settings.php to turn of various caches.  Note that when set, these values will be locked to whatever is set in the file, and cannot be changed through the admin interface (so remove them when you're done debugging).

To disable page, JS, and CSS caching, set cache, preprocess_js, and preprocess_css all to '0' in the $conf array:

$conf = array(
  'cache' => '0',
  'preprocess_css' => '0',
  'preprocess_js' => '0',
);

If you set other values by means of the $conf array, add these fields, do that, rather than replacing the entire array.


Drupal fancybox views gallery - display only first item of attached images

Use the display CSS properties.

.field-content ul li{
    margin:0;padding:0;
    display:none;
}

.field-content ul li:first-child{
    display:block;
}


How can I hide a field in the node add form but it unhide it on the node edit form?

You can Show/Hide the status field using hook_form_alter like this:

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    $form['YOUR_FIELD']['#access'] = FALSE; // Node is new!
  }
  else {
    $form['YOUR_FIELD']['#access'] = TRUE; // Node is not new!
  }
}

Then replace YOUR_FIELD with the field name of your status field.


Aegir fails on verify task after import task (Import an existing not aegir site)

I found the right way to make import in the docs, my problem was how to start my import site with my DB, the best way is here:
http://docs.aegirproject.org/en/3.x/usage/sites/importing/#importing-a-single-site-manually.
To load your DB you may use drush @www.site-domain.it sqlc < file-db.sql
I hope this can help others to make import files.


URL Redirect created over SSL only works over SSL

I am feeling a little sheepish here:

Caching was turned on for anonymous users. When accessing the site as https I was also logged into Drupal, unlike when I was accessing the site over http.

As such the anonymous users were not getting the redirect or alias applied until the cache was cleared. Should have been an obvious first step.


Form submission not working in template file

You can render form specific form elements with the help of drupal_render. And in order to make submit button work, render all hidden form items and your submit button will work fine then.

Necessary fields for form submission are:

echo drupal_render($form['form_build_id']);
echo drupal_render($form['form_token']);
echo drupal_render($form['form_id']);

and ofcourse your submit button too.


Javascript happens on the client-side so there's no need to use PHP at all here. Using the PHP filter is in fact strongly discouraged as it introduces potential security risks.

To include javascript in an HTML page you use the <script> tag like so:

<script type="text/javascript" src="/sites/all/scripts/countdown.js"></script>


CSV node import using feeds module on a Mac

I've had the most success importing CSV files by importing them into Google Docs (spreadsheet) first and then exporting from Google Docs as a CSV file. It might seem like a silly workaround but Google spreadsheets seems to handle inconsistencies in CSV files a little better than Excel or Numbers.

Give it a shot. I've just used the same method for a Feeds CSV import.


Create dynamic external link URL without filtering or stripping protocol

I realised it's not Drupal changing the URL but GMail that doesn't like the protocol.

So I created a simple PHP redirect script and link from my Drupal module to that instead e.g.

<?php

header("Location: FMP://192.168.123.123/DatabaseName.fmp12?" . $_SERVER['QUERY_STRING']);
exit;

?>


Views Field Show "NEW" if less than 1 day old

Probably need to strip the html from $submitted and convert to timestamp first,
e.g something like:

$submitted = $view->style_plugin->rendered_fields[$view->row_index]['submitted'];

if (strtotime(strip_tags($submitted)) > strtotime('-1 day')) {
  echo '
NEW!
';
}


When you add the image field to views, make sure to set it to 'Link image to: Nothing'


Node count published, unpublished and total

In my opinion this is not as simple as it sounds although it should be considering the capabilities of Drupal.

I'll provide you with my solution (Drupal 7) which i implemented once in a site:

Create a users view in which you should do the following (in that order):

Remove any default Sort Criteria and don't add anything in that section
Add a field of "User: name"
Add a "User: Content authored" relationship
Add a filter "Content: Type" = Article
Add filter "Content: Published" = Yes
Add a contextual filter of "User: uid"
Activate aggregation
Set aggregation settings of user name field to "Count"

Now when you type the uid of a user in the "Preview with contextual filter" field of the view you will get the number of published articles that particular user has created.

Clone that view and (in the cloned view) change the Content:Published filter to No from yes. Now you have a 2nd view that gives you the number of unpublished articles for every user.

Last install and enable Views Field View module and create the following users view (in that order):

Add a field of "User: Uid" and exclude it from display
Add a field of "User: name"
Add a global view field. In the window that pops up choose the 1st view you created and the display you want from the "Views Settings" section (master display can be chosen if you like) and finally (and most importantly) in the "Contextual Filters field" use the [!uid] token (replacement patterns: [!uid] == User: Uid (raw)).
In the exact same way add a another global view field to "pull" the 2nd cloned view in this current view.
Recommendation: style the view as a table for trial reasons then theme as you like.
Also be careful to always have both global view fields after the user uid field in the Fields listing.

So this final view will present all the users of the site and next to each user the respective number of published and unpublished articles they have created. If you need the total number of articles then create an extra view without any Content: published filters and use it accordingly.


You have to tell Search API exactly what it should index:

Go to Admin -> Configuration -> Search and metadata -> Search API
For the relevant index, choose "Fields" from the drop down
Add your desired field(s) to the index and configure appropriate data types
Re-index all content


Administration page doesn't show pop-up (overlay) windows

The block layout is in the standard installation of drupal. This popup should work out of the box.

When you press the button "Place block" this ajax is used:

/admin/structure/block/library/mytheme?region=header&_wrapper_format=drupal_modal...

So I would check first if this ajax is fired and second if there are any js errors in the browser debug tool (F12).


How to get accurate information about available security updates after End-of-Life?

Have a look at the myDropWizard module, a recently released module for Drupal 6. Some more details about it (from its project page, which also includes a screenprint about it):

Reports accurate update status for Drupal 6 modules now that Drupal 6 is End-of-Lifed and most contrib modules are unsupported by the community.
It does four main things:

It still shows security updates if a module is unsupported, so you'll know about security updates you haven't applied, regardless, and
It uses an alternate data source that reports whether a module is supported by the Drupal 6 Long-Term Support (LTS) vendors, so you'll know if it'll be getting security updates going foward
It will let you know about additional security updates made by the D6 LTS vendors! The LTS vendors are required to post their patches publicly, but there won't be any Security Advisories going out to let people know, and it won't be in the normal Drupal.org update status data (we create special security releases for the patches released by the LTS vendors, which appear in our data)
It integrates with Drush 7 or later. See "Drush integration" section below for more information!

While it uses a different data source, it continues to report usage information back to Drupal.org, so the community won't lose that valuable resource. This will let us know how many people are still using Drupal 6 in the next months and years!

Refer to "Getting accurate 'Available updates' for Drupal 6" for a related article about it also.


Is there a way to find out how many registered users logged in a given time period?

You could count all User table rows in the database where the fields for "Last Access" and or "Last Login" are newer than one month old .  You'd need to compare those timestamps to a timestamp for the start of the current month. You can find that with something like this or maybe it's as simple as:

$this_month_start = strtotime("-1 month");


Where is the base domain stored in database D7

I think you're looking for $base_url in /sites/default/settings.php.  As far as I know everything in the database works off this value, and it is not explicitly set in the DB


How do I cache a custom module that has points?

Yes, you can use the Drupal cache API to set and get the data from cache.

Assuming D7, The following resources have some good information on that:

https://www.lullabot.com/articles/a-beginners-guide-to-caching-data-in-drupal-7
https://www.drupal.org/docs/7/managing-site-performance-and-scalability/caching-to-improve-performance/caching-overview

For example:

function MYMODULE_function() {
  global $user;
  $user_point_data = &drupal_static(__FUNCTION__ . $user->uid);
  if (!isset($user_point_data)) {
    // User per user cache id for points.
    $cid = 'user_point_data:' . $user->uid;
    if ($cache = cache_get($cid)) {
      $user_point_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $user_point_data
      // with the correct stuff..
      cache_set($cid, $user_point_data, 'cache');
    }
  }
  return $user_point_data;
}

You can then clear the cached data, based on specific user id or all items, with:

cache_clear_all

// Clear all user point data from cache
cache_clear_all('user_point_data', 'cache', TRUE);
// Clear specific user point data from cache
$cid = 'user_point_data:' . $GLOBALS['user']->uid;
cache_clear_all($cid, 'cache');


How to share Drupal code across multisites that are each in subdirectories?

Drupal come with already a multi site feature, you ca read more about it here.

After, if for some reasons you don't want install Drupal with multi-site and keep the both separate in your server, you can still use Git or SVN and co.

The idea is simple, you've the same codebase for development and multiple clone or checkout in your server. For example, in your case it will be drupal1 and drupal2.


How to change the query value using hook_views_query_alter?

function zed_views_query_alter(&$view, &$query) {
  if ($view->name == 'questions_home' && $view->current_display == 'rates_related') {
    foreach($query->where[1]['conditions'] as $idx => $condition) {
      if (!is_object($condition['field']) && $condition['field'] == 'node.title') {
        $query->where[1]['conditions'][$idx]['value'] = '%whateveryoulike%';
        // or you can unset this condition and write down a new one
        // unset($query->where[1]['conditions'][$idx]);
        // $query->add_where_expression('1', "$field LIKE %" . db_like("california") . "% OR field LIKE %" . db_like("somethingelse") . "%");
      }
    }
    dpr($query->where[1]['conditions']);
  }
}


Preventing spam registration /url redirect

If you don't need user self-registration then just disable that functionality.

To do this go to :
/admin/config/people/accounts (Admin > Configuration > People > Account Settings)

And for the Who can register accounts? setting choose Administrators only.

If later on you decide that you need that functionality, you can enable it back and then just add a captcha to your user registration form, or integrate something like honeypot or logintoboggan.


How to set If-Modified-Since HTTP header in my drupal site

As you can see in drupal_serve_page_from_cache function, Drupal knows and uses this headers. Exact quote is:

  If the request is conditional (using If-Modified-Since and If-None-Match), and the conditions match those currently in the cache, a 304 Not Modified response is sent.

How can you test? Obviously you can forge HTTP request in your user agent and see. Or you can believe in built-in tests.

Of course if you will not turn any cache on, there is no reason to react to If-Modified-Since, because you have no cached data to serve if content is not modified. Default cache is located under http://example.com/admin/config/development/performance, and you can use other cache modules and mechanisms, too. Then, it's up to them to react to cache-related headers properly.


Advanced conditions in Database Abstraction Layer?

You need to use the 'where' method for complex conditionals:

db_delete('table')
  ->where('UNIX_TIMESTAMP() - date > :date', array(':date' => 7780000))
  ->execute();


Why all dates columns in drupal are type=int and not type=date/timestamp/time?

I guess the main reason its that you cannot have two columns with TIMESTAMP and default NOW() value in MySQL according the documentation (see that answer). So seems to be the easier way to workaround it its to use int.


How do I validate the term title in hook_taxonomy_term_presave()?

I assume you should be looking at hook_form_FORM_ID_alter instead of hook_taxonomy_term_presave for validating the term title before saving.

/**
* Implements hook_form_FORM_ID_alter().
**/
function mymodule_form_taxonomy_form_term_alter(&$form,  &$form_state, $form_id) {
  // Check for tags bundle.
  if($form['#bundle'] == 'tags') {
    // Apply custom validator.
    $form['#validate'][] = '_mymodule_custom_term_validator';
  }
}

My custom validator.

/**
 * My custom validator for tags.
 **/
function _mymodule_custom_term_validtor() {
  // Check for term name is test.
  if(form_state['values']['name'] == 'test') {
    form_set_error('name', 'Title cannot be "test"');
  }
}


How to update cart after deleting line items?

instead of using $item->delete() this works:

  $cart_manager = \Drupal::service('commerce_cart.cart_manager');
  foreach($items as $item) {
    //$item->delete();
    $cart_manager->removeOrderItem($cart, $item, TRUE);
  }

the 3rd parameter is 'save cart' and setting it to TRUE updates the cart Total.


How do I build the node title from field values when saving the node?

Could be a job for Automatic Entity Label. Actually I'm using it that way – in production (though it has no stable release yet it works just fine).

  "Automatic Entity Label" is a small and efficient module that allows
  hiding of entity label fields. To prevent empty labels it can be
  configured to generate the label automatically by a given pattern.

You can define tokens from which the title will be built. An you can optionally set the title field to be always hidden on the node form. I'd also recommend to make the fields mandatory (required) that you use to build the title.


Edit your argument for configuration
Add validator options for your argument by selecting PHP Code from the select box
Add following code in it

 $usr = user_load(array(uid => (int)arg(2))) //Check the appropriate position of uid
 $view->display['page_2']->handler->handlers['argument']['date_argument']->options['title'] = $usr->field_first_name . "'s content";

Here page_2 is views identifier and date_argument is argument identifier.


Per the Filter API docs:

  Every filter plugin must specify a filter type in its annotation. Filter types were added specifically to support in-place editing. There are four filter types:

  FilterInterface::TYPE_MARKUP_LANGUAGE — Non-HTML markup language filters that generate HTML. The filter converts something that's not HTML to HTML in a way that is not compatible with WYSIWYG editing.
  FilterInterface::TYPE_HTML_RESTRICTOR — HTML tag and attribute restricting filters to prevent XSS attacks. The filter restricts the HTML allowed, for example, to protect against XSS.
  FilterInterface::TYPE_TRANSFORM_REVERSIBLE — Reversible transformation filters. The filter performs a transform for which a WYSIWYG plugin exists to perform the same transformation (and its reverse) client-side. For example,  may be (reversibly!) transformed to

Druplicon

.
  FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE — Irreversible transformation filters. The filter performs a transform for which a WYSIWYG plugin does not exist to perform the transformation client-side (especially, the reverse of it); instead, the WYSIWYG editor displays the unfiltered text. For example, Token Filter.

The type examples given are pretty descriptive of when to use them.

If you CAN take the filtered output and put it back into its original form via a WYSIWYG plugin (e.g. structured markup like XML -> JSON -> XML), use FilterInterface::TYPE_TRANSFORM_REVERSIBLE because the filter output can be reversed.

If you CANNOT take the filtered output and put it back into its original form via a WYSIWYG plugin(e.g. a token filter that prints the node title), use FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE because the filter output cannot be reversed.


problems with contextual filter backtracking node references

Under the contextual filter, check 'Provide default value' under 'When the filter value is NOT available' and select 'Content ID from URL' as the type. Your view should work.

Conceptually, you wish to list 'Packages' in the Context of the Account you are displaying.


How do I hook the stock status message to the product page?

System Messages are printed to the page via a block (Block: Messages, Category: System).

If the messages block isn't aren't appearing on a particular page:

Check to make sure the block is added to a region in the active theme for the page in question.
Check to make sure any visibility settings for the block are configured correctly for the target audience
Make sure that your theme actually renders the region that you added the block to.

If you're still not seeing the messages block:

Create a static custom block (something that should always appear) and place it in the region.
Test with the block added to a region you know is rendering, i.e. the main content region.
Inspect the source html of the page to make sure the html is actually missing and isn't just being hidden by css.
Enable twig_debug and verify that the page is built with the templates you think it is. Check each template (Page, Region, Block, potentially others, but it would likely be one of these that's the issue) and make sure the template is properly rendering what it needs to.


Rules governing views-based free text search

The rules controlling exposed text field filters are various SQL operators. To give you a good indication of what's happening, navigate to admin/structure/views/settings and enable Show the SQL query option for the Views UI then preview various views with different operators. As you enter different text, you can see the SQL keywords used to filter the view.

For Search: Search terms filter its based off the core Search index. The search module crawls node content, breaks it into text tokens, weights the score according to your settings (see admin/config/search/settings), and builds an index for terms to content.

In terms of fuzzy search technology Drupal's is pretty basic, but it works most of the time. If you're looking for more robust search options there are more advanced solutions out there (Google CSE, Apache Solr, etc.).


NotFoundHttpException after changing webiste hosting, sub-domain

Check database connection through drush sql-cli and show tables, I got the same error because of an empty database once.

If the data is of no importance, you can run drush site-install to re-install Drupal from scratch.


What do I do after I merge feature files with a remote server?

You will have to revert the feature, So that the configurations in the remote server would be same as that in the code. Feature overridden means, the config in the Code and that in the server is not the same. So by reverting the feature you make the code and the db config the same. Please be cautious while reverting the feature, Sometimes the changes which you have done directly in the server would be lost. It'd be best if you test reverting the feature in your staging environment first.


Try using the Pathologic module to help with this. Excerpt from the documentation...

Rule Order

Note that the order in which you include the rules may be important. In a scenario with three servers (for example, development on http://local.example.com/drupal, testing on http://example.com/drupal, and production on http://example.com) and using a WYSIWYG editor (as noted below), the following rules (paths to be matched) will work in order:

http://local.example.com/drupal/
http://local.example.com/
http://example.com/drupal/
http://example.com/
/drupal/
/

Pathologic works by stripping out the path as defined above and ensuring that what remains will work as a path relative to the site's $base_url (the URL you see in the location bar when looking at your  page), no matter which server it is on. It works down the list in order and only applies the first rule that matches a given link. Placing http://local.example.com first in the list, for instance, will rewrite http://local.example.com/drupal/about as /drupal/about, and this will NOT be rewritten further by the /drupal/ rule, so all possible permutations should be included in order of deepest to shallowest matching path. Some of the example rules may not be necessary for your situation, but it is safe to include even unlikely paths that you would like corrected (removed).

Now sit back and enjoy the fruits of Pathologic’s labor."


Can payment be done in pop-up rather than using redirect?

If your gateway tells you to redirect, you redirect.
If you need a modal-based gateway, choose another gateway.
Changing the flow recommended by your gateway puts you firmly in unsupported waters, and definitely exposes you to additional risk.
This is especially true since redirected gateways require PCI A compliance, while modals require the slightly more complex PCI A-EP compliance.

I would also expect most gateways to have protection against this.


Make a from element visible when a radio button is clicked

No need to write JavaScript for that; if you are working in PHP, you can use #states on the form element.

Example: form_example_states_form.

  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),

    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );


How do I add a node add link ( for a different content type ) in the node add form (drupal 7)

The module your are looking for is References dialog.

Also, you can use contextual administration. It's a more general approach, that won't put the link exactly where you want, but is much more flexible on the other hand. It allows you to use the same rule set as Panels, such as "Selection rule: Node type", for example to node/add/[other-type]. Fits like a glove together with Panels.


Create View Block.

Go to Home » Administration » Structure » View

Add New View.

Create a Block with View (Not Create a Page)

Then, Select that block on the specific page.

If you have created that page with Panels or Node Template (By Adding New Variant)
You can set View Rule.

Add Visibility Rule in View Block

Select String: URL Path as an Option

Then, set path to your page where you wanted to display your block.

I hope this will help you..


Prepopulate a field in a Reference Dialog Box

Yes, you can.
What you need for this?
1) references_dialog
2) entityreference_prepopulate
3) your custom_module.
For example field that you want to make with prepopulated field in url is entityreference.
Here is link to youtube how to use entityreference_prepopulate and URL https://www.youtube.com/watch?v=z9C4Uf6euLY.

After this you should override your "Create ..." link. How to do this?
Easy. Just implement hook_references_dialog_widgets_alter in your custom module and change name of function that generate add link

/**
 * Implements hook_references_dialog_widgets()
 */
function mymodule_references_dialog_widgets_alter(&$widgets) {
  $widgets['entityreference_autocomplete']['operations']['add']['function']
    = 'mymodule_references_dialog_entityreference_add_link';
}

And than you can define your add link function:

function mymodule_references_dialog_entityreference_add_link($element, $widget_settings, $field, $instance) {
// blah blah from original function
// Here you can catch field what you need and define url with $_GET parameters for it.
}

That's all. Enjoy reference dialog with get params in url.


There are a few different cache entries for the schema, schema:, schema:runtime, schema:runtime:1, and so on.

To clear the lot, try using a wildcard:

cache_clear_all('schema', 'cache', TRUE);


During updating translation: Fatal error: Maximum execution time of 240 seconds exceeded

Open sites/all/modules/l10n_update/l10n_update.locale.inc; at line 28, change the code to the following one:

drupal_set_time_limit(840);

It will increase the execution time and will work. The original code set the time limit to 240.


Organic Groups - define content type to be of Group type

On the create content type page you should have a vertical tab named Organic Groups. If this tab is missing, make sure you have enabled the Organic groups UI module. Clicking the Organic Groups tab reveals a couple of check boxes. Check the one for Group and hit save to make this content type a group which you can associate content with.

The other check box Group content defines that the content type can be posted into a group, i.e associated with the group you previously created.

To get you started you can also enable the OG example module.

The above is mainly for OG 7.2.


I would simply use content types (cck if you're in d6), views in blocks, taxonomy and some theming. I'm sure there are other ways to do it, but this would maybe be one.

Create a taxonomy 'category' and add all the 'categories' to it.

Create the content types category_page and category_sub_page (or something along those lines).

Create the fields you need for each content type:
For the category_page add a taxonomy tag field (to add the category from your 'category' taxonomy vocab) and if you wish to have images as headers different on each cat page add an image field etc ..

For the sub_page you need 2 or 3 image fields (depending on how many different images you wish to show (1 on the teaser, 1 or 2 on the main page?) and another taxonomy field.

Create your category overview page - tag it.
Create your subpages pages for that cat - tag them too.

Create a .tpl file for your node type:
In d7, copy the node.tpl.php file in your theme/template/ directory twice and name them node--category_page.tpl.php and node--category_sub_page.tpl.php (that's if you used naming conventions like above).

Create a node view that displays node type = category_sub_page and filter them by category, so only display category = 'SOMETHING' - or go even further and use arguments to get tax term of page and show only subpages with the same term (this way you could only use 1 view for multiple category pages). Create a block view from that showing teasers, add it to the content reagion using the blocks page. It should be displayed below the actual page content - if you don't have a region there you will need to add a block region. You'll have to add it to your theme in the page.tpl.php and the theme.info file. Read up about it.

Now edit your theme files for sub_pages .. node--category_sub_page.tpl.php - start it with

<?php if (!$page): ?>

anything in  between here will be shown as the teaser - that's you're menu block with text image - then

<?php endif; ?>
<?php if ($page): ?>

now anything in between is your sub_page full view.

To help you add items use to display the different items called.

 <?php dsm($node); ?>

then add them with php, defining your layout and style classes. Now theme it using css to get your desired look

Now you've create a node that displays sub-nodes in a block below the content.


I am pretty sure you have to update "node_revision" too.

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

  Note that the node_revisions table in the database will always have one record associated with each record in the node table, which it keeps track of as the current revision. This will happen even if you do not have revisions enabled.


How to loop through field deltas of an object?

Entity reference fields have a method called referencedEntities().

Usage example:

$addresses = $entity->get('address');
foreach($addresses->referencedEntities() as $delta => $address) {
  // Do something with the $address entity
}

P.S.
If you only want the field then as @Clive mentioned you can just iterate over $addresses.


Missing "operation links" from all content list page

The solution was to re-install the latest version of Drupal.


Filter by taxonomy parent using Json api

The term-ID 2 belongs to "Term B", not to "Term 4" or "Term 5". To check if term belongs to Term B you may include the term parent and check if it has id 2:

https://www.some-api.com/jsonapi/node/test?
_format=api_json&
include=field_regio.parent
filter[taxFilter][condition][path]=field_regio.parent&
filter[taxFilter][condition][operator]=IN&
filter[taxFilter][condition][value][]=2 (=> id of term B)

This should work at least for the simple example provided it the question.


how can i remove 'create new account tab ' from login page and show 'access denied' for 'user/register' in drupal  6?

Under admin/user/settings, change "Public registrations" to "Only site administrators can create new user accounts."


User select the filter criteria current_salary_range is 20000. I will show the results also salary range below 20000

In your Content type Manage Fields, what you need to do is make the Current_Salary_Range FIELD TYPE be a (number) Integer field and not a text field.

  Note: You will have to delete and create a new field, as you cannot change field type after the field has been created

Then when you add it as a filter in your view, you should get the option of less than or equal to

Note: picture is from Drupal 8, but should be the same in Drupal 7.


You can use flippy.tpl.php template. Copy this template in your theme and modify it what ever you want.

$image_arr = array(
        'path' => $file->uri,
        'style_name' => '<Style Name>',
        'alt' => '',
        'title' => '',
      );

print theme('image_style', $image_arr);


The easiest idea I could come up with would be to define the paragraph type through the UI. Then you'd have 2 options:

whether make a custom form with similar fields and create a new paragraph entity on form submission.
define a content type which has reference field to the paragraph type. Then you could simply render the node form which would handle all the logic of displaying the fields and saving of the paragraph it self.

I would prefer option number 2 since paragraphs are not meant to be stand-alone entities. They are meant to be parts of content. IMHO I don't think one paragraphs entity should be reused on multiple nodes.


Migrate files with directories and sub directories

How is destination_file mapped in your file migration? See https://www.drupal.org/node/1540106 for information on how the file options interact to determine the full destination filespec.


Which PHP file would a custom theme_link function go into?

theme_link() doesn't use a template file. You can override its output by placing your own theme function in your theme's template.php file:

function MYTHEME_link($variables) {
  //Alter this as you see fit
  return '' . ($variables ['options']['html'] ? $variables ['text'] : check_plain($variables ['text'])) . '';
}


How is a variable passed to theme_hook (theme_item_list, FacetAPI)

It is not necessary to create a new theme function. You could use the existing theme_item_list and extend it with double underscore. Rename item_list_aggregate to item_list__aggregate in FacetapiWidgetLinks::execute. And implement theme_item_list and theme_item_list__aggregate in your theme.

Look at node_title_list in core, this function uses the same pattern.


Import CSV, converting repetitive fields to taxonomy terms

It's not clear whether you're looking for a front-end tool, or help with implementing this using the migration APIs. If the latter, in Drupal 8 you can use the migrate_source_csv source plugin with the entity_generate process plugin provided in migrate_plus. Your migration YAML file might look something like

id: food
label: 'Import food nodes'
source:
  plugin: csv
  path: directory/my_csv_file.csv
  header_row_count: 1
  keys:
    - NAME
process:
  type:
    plugin: default_value
    default_value: food
  title: NAME
  field_type:
    plugin: entity_generate
    source: TYPE
  field_color:
    plugin: entity_generate
    source: COLOR
destination:
  plugin: 'entity:node'

The entity_generate plugin will lookup the incoming value in the appropriate vocabulary, create it if it doesn't already exist, and return a reference to the (possibly new) term.


How to print all values of a multi-value field, except the first?

In field preprocessing this while loop which fills the field items doesn't get started if the first delta is removed:

  $delta = 0;
  while (!empty($element[$delta])) {
    $variables['items'][$delta]['content'] = $element[$delta];
    $delta++;
  }

So if you bypass the field template to print the 0 delta do the same with the other deltas:

{# print first field value #}
{{ content.field_foo.0 }}
{# print something else #}
<hr>
{# print remaining field values #}
{% for key, item in content.field_foo if key > 0  %}
  {{ item }}
{% endfor %}


Are shared user tables still supported and working?

Don't.

Per table-sharing is a relict of the past, deprecated and will be removed in Drupal 9. With all the layers on top that dynamically create tables for fields, cache invalidation and so on, this is never going to work.

If you want to have a shared authentication system, then look into an actual single sign on projects.
These are some links to get started; I don't have a lot of experience with either yet.

https://www.phase2technology.com/blog/implementing-cas-single-sign-on-in-drupal-8/
https://dev.acquia.com/blog/drupal-8-module-of-the-week/drupal-8-module-of-the-week-simplesamlphp-authentication/05/04/2016/10246