You have installed the development master branch of Drush. To continue using commands such as drush dl, drush pm-update and so on, you should install the 8.x branch of Drush.

However, your basic supposition is correct. The Drupal community is moving towards Composer and away from drush make and the drush pm-* commands. The reason for this is that more and more Drupal modules are depending on code that is distributed via Composer libraries. When using modules with Composer dependencies, the most convenient way to manage your Drupal site is through Composer. See drupal-composer/drupal-project for an example of this.

All of the other Drush commands are still relevant and remain useful.


Next link on node page based on its taxonomy term

It's only in Alpha but the Treewalk Previous / Next module appears to have that functionality:

  Previous/Next (Back/Forward) links for entity and other pages, that allow to visit them in a sequence.

  Unlike with the existing back/forward module, the sequence of items (entities etc) is not based on a view, but on hierarchical information already present in your site.

  It provides a configurable block with prev/next links based on menu trees. The block is named "Treewalk Prev/Next (Menu)"
  It provides Display suite fields with prev/next links based on entityreference / taxonomy_term_reference fields. The ds fields are named as "Treewalk Prev/Next (...)".

I've never used it but it might at least be a starting point to implement the logic yourself.


Have Select Dropdown of Taxonomy but allow user to enter new term

Install the Select or Other module

You can use the Select or Other module to add a dropdown with an Other option.

Selecting Other prompts the user to enter the new value in a separate field.

Your question asked to add the new business type directly; this module adds it to a separate field (however, an admin can later add the business type as a taxonomy term if you wish).

Advantages of this approach

You get admin approval of user input.  This way a bad user can't enter something like Sex sex sex which then appears as a business type on your site.
You have control over how long the list gets instead of letting users add an unlimited number of terms.

Coding it yourself

You can also code this yourself pretty easily using the States API instead of installing the Select or Other module.

Add a new text field, field_businesstype_other, to store the Other values for field_businesstype.

Create a taxonomy term named Other in your "business type" vocabulary.

Then, in hook_form_alter(), add something like this:

  $form['field_businesstype_other']['#states'] = array(
    'visible' => array(
      'select[name="field_businesstype"]' => array(
        array('value' => '123'),
      ),
    ),
  );

Replace 123 with the term ID of the Other term you created.


You can use entityQuery:

$fid = 13141;
$usedIn = \Drupal::entityQuery('media')
  ->condition('field_media_image.target_id', $fid)
  ->execute();

Example response:

Array
(
    [15105] => 13109
)


Using cache tags for a particular node list

Starting Drupal 8.9.0, there is a new ENTITY_TYPE_list:BUNDLE cache tag added (see the change record).
So in your case you would simply need to tag our list with node_list:book.
https://www.drupal.org/node/3107058


I thought there was already support for translatable pane titles in Panels with the i18n_panels submodule. However, looking at Issue #117934 which is currently marked fixed, there are still people providing patches. Though that issue title states it is for translatable Panel PAGE titles, the patch on comment #106 actually modifies code to make pane titles translatable.

Note that from an architectural perspective the approach in comment #106 is frowned upon because you are not supposed to pass dynamic text through t().  I would consider this a small permissible hack to get you across the finish line without wasting too much time.


I had the same issue with CKEditor. the h1,h2,h3,h4,h5,p tags and color picker were available to the user But we wanted every available tag to has a custom color. To do so I put the CKEditor output which was body inside a DIV with some ID,say node-body-wrapper, then added styles like this

#node-body-wrapper h1{
     color : red !important;
}

...

In this way I solved the problem. I recommend you to do the same.


How do I print results after submitting a Drupal form?

The normal way to handle this is to implement a multi-step workflow. See drupal_rebuild_form() for more information, but basically you set $form_state['rebuild'] = TRUE; in your submit handler, and in the original form function add a check to see if the form's been submitted. If it has, you have access to the submitted values and can manipulate the form as you see fit.

A very basic example:

function MYMODULE_some_form($form, &$form_state) {
  // If the form has been submitted, output something related to the submission
  if (!empty($form_state['values']['some_field'])) {
    $form['submission'] = array(
      '#markup' => function_to_get_markup_from_value($form_state['values']['some_field'])
    );
  }
  else {
    // Otherwise build the normal form
    $form['some_field'] = array(
      '#type' => 'textfield',
      // ...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


This is the only thing I recall seeing, at DrupalCon San Fran in 2010. Sam Boyer, a maintainer of Panels, discusses benchmarks a bit in this video:  http://sf2010.drupal.org/conference/sessions/state-panels-3-and-more-what-you-love  at about the 29 minute mark.  It's not really a great benchmark test, but gives some idea into what page manager is running/processing.


Metatags trimmed body in description/summary

You can use any field with Metatag, so simplest way would be to use Computed Field, that

  lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields

In your custom php code for field computation, use code like this:

$body = $entity->body['und'][0]['value'];
$width = 160;
$body_trimmed = substr($body, 0, strpos(wordwrap($body, $width), "\n"));
$entity_field[0]['value'] = $body_trimmed;

It will truncate on the word boundary, giving you no more than $width characters. More about truncating on StackOverflow.

Then, simply feed this computed field to Metatag.


Why doesn't a certain block appear on "view" pages of my site?

I think you have got issue with the rendering of that particular region into the page.tpl.php, where this block doesn't show.

Follow this steps to identify the issue --

Find the machine name for the region where you are putting your block from the THEME.info file.
Open your all page*.tpl.php file in the theme one by one. May be your theme contain different page.tpl.php for different kind of content display. If it not done by you then this step can be hectic as sometimes we declare the custom page.tpl.php structure in template.php too. But initially you can check all the TPL files starting with page.
Check for the rendering of the content by searching the machine name which you have got in .info file for the region where you are placing the block. I think somewhere it's not rendered.
Render the region into the TPL file where it is not. Clear the cache & check you display.


Implement parallax effect on Header image from Content type field

Where do you need to add that code? Into field.tlp.php, node.tpl.php or page.tlp.php? Is it D7 or D8?

If you need to extract src atribute (/path/to/image.jpg) from some HTML code (for example from the node.tlp.php field) then use Google. When you will have src then you can create desired
 element in your template files.

As universal answer as detailed question was.

Update:

I found that you have attached your site so I suggest this:

Create block in Views for header image field

NID as Contextual Filter
Enable cache per page
Output header image field as src (only image url) - there is such option in views or use this module
Override that field (rewrite the output of this field) with something as

enable block in proper region only for "Basic-page" CT


Custom module for adding CSS file in admin section

Unless you use the same theme for front and backend, that's not the right approach.

If something transcends the theme layer, e.g. you have functionality that you need to apply to two separate themes, it belongs in a module.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module for instructions to actually accomplish that, specifically the section on Attaching a library to all (or a subset of) pages which contains a contrived code example:

function contextual_page_attachments(array &$attachments) {
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
    return;
  }

  $attachments['#attached']['library'][] = 'contextual/drupal.contextual-links';
}


Send email with html template programmatically

In the mimemail-message.tpl.php info you can read

  Copy this file in your default theme folder to create a custom themed
  mail.
      Rename it to mimemail-message--[module]--[key].tpl.php to override it for a
      specific mail.

Try to change your tpl name from
mimemail-message.tpl.php to mimemail-message--system.tpl.php


Drupal has only a very course access control structure for viewing content.  For the uthenticated use role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

For more fine-grained access control, you need a node access control module.  There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module.

One particular module, named Flexi access, allows you to create access control lists consisting of a single user.  This may be what you're looking for.

Disclosure: I am the maintainer of Flexi access.


How do I manage the meta tags 'title', 'description' and 'keywords'?

Nodewords module will help in this regard. This module will help to add meta tags on nodes and custom pages as well.


If you are using the libraries API module, the correct place for the JS code is actually sites/all/libraries, not \sites\all\sites\all\modules\libraries (why do you have sites/all in the path twice?)

What slideshow module are you using, views_slideshow? I don't think you will actually need to add a jquery library if that is the module you are using, but that will depend on the actual module you are using. If you are trying to build a slideshow from scratch with jQuery cycle, here is info from the handbook on getting your js added to Drupal http://drupal.org/node/304255


This is can be done using TMGMT, from the TMGMT domain setting you can set up configuration per domain. You can also check out this module => https://www.drupal.org/project/domain_site_settings


How to get absolute url with different domain language prefix

This was pulled from my theme file, but as long as you have access to $node and $language, it will do the trick:

<?php
    if (isset($node))
    {
?>

        <?php
            $nodes = translation_path_get_translations("node/" . $node->nid);
            $path  = "";
            if ($language->language == "en")
            {
                if (array_key_exists("nl", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["nl"], "nl");
                }
        ?>
        <a href="http://nl.example.com/<?php print $path; ?>">Change to NL
        <?php
            }
            else
            {
                if (array_key_exists("en", $nodes))
                {
                    $path = drupal_get_path_alias($nodes["en"], "en");
                }
        ?>
        <a href="http://en.example.com/<?php print $path; ?>">Change to EN
        <?php
            }
        ?>

<?php
    }
?>

The URL's are hard coded with the path information calculated.


The examples module will provide you some custom code to implement this, have a look at the API documentation which add a vertical tab to the node form.

The only restriction I can think of is that this code is for forms so if you want to theme a node output you should use jQUery UI tabs. The tutorial you linked seems fine, but you'll need to change a little its CSS classes in order to output vertical tabs, compare its code tho this demo.


Timefield [entityform:field-name:value_formatted] token not working in Rules

Since this problem seems to be a bug, and just in case someone else runs into this issue, there is a workaround you can do within Rules to get the formatted value of the time field. It involves:

Enable the module PHP filter
Use the action Execute custom PHP code to run a PHP snippet that calculates
the formatted value using the raw value provided by the token


In your view, change the contextual filter to the following:
change:
Hide view
by
Provide default value
In Type, select the option that applies.


Use the References module:

  This project provides D7 versions of the 'Node reference' and 'User
  reference' field types, that were part of the CCK package in D6

or Entity reference:

  Provides a field type that can reference arbitrary entities

or Relation:

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.


Problem trying to create a views with tabs. Link of tab doesn't point to the path I set

I've not had the pleasure of Views 3, but I think I can see what's wrong. I believe you want to have three displays:

Articles, which has a default menu tab (and you want Views to provide the parent menu item)
Blog, which has a menu tab (but not default)
Events, which has a menu tab (but not default)

(Currently the displays are set up as default tabs, which is why they point to the parent item - just like the path for the View tab on a node view doesn't point to node/x/view but points simply to node/x.)


I was having the same troubles. Seems to me as far as my limited debugging skills go, that when drupal_process_form calls

$form = form_builder($form_id, $form, $form_state);

the values for $form_state[‘input’][‘og_group_ref’] don’t get passed through into $form. So I suspect I need to understand form_builder better to figure out why the values coming in aren’t getting transferred through. Ultimately when we get to og_form_group_reference_validate, $form_state['values’][‘og_group_ref’] doesn’t exist.

So, what I’m going to try for now (and seems to be working) is let og_form_group_reference_validate look in $form_state[‘input’] in addition to $form_state[‘values’], as og_group_ref still exists there.

Here’s a gist of my patch:

https://gist.github.com/housser/ba03c50f670dc5310520


How does DrupalGardens.com setup a new website?

Yes, Drupal Gardens sites are multisites. Modules inside either /modules or /sites/all/modules are shared by all sites in a multisite installation. If we installed an entire instance of Drupal for each individual Gardens site it would be a serious waste of disk space.


Display edit link for a node in a view when user has permission

In Views, there is a field you can add called Node: Edit link that will display a link to the edit page for the node, taking into account the user's permissions.


Somebody is trying to brute force the password

I have two ideas to help with this problem.

There are tools and services you can use to look for brute force attacks. The security review module and droptor tools both look in your watchdog (at Administer > Reports > Recent log messages) to see if you have a lot of failed logins for one user. You can also do that manually.

In Drupal 7 the "access rules" feature was removed from core but moved to a contributed module - User Restrictions. Using that module you can block users from a specific IP address. Apache deny rules will be slightly faster if you have relatively small number of rules but the Drupal rules are easier to add/update/remove.


Different urls for front page depending on language

Use this code in your template file then you can page accoding to your choose language

  function yourtheme_preprocess_page(&$vars) {
        if ($vars['is_front']) {
            $langcode = $GLOBALS['language']->language;

            if ($langcode == "en") {
                drupal_goto('home');
            } elseif ($langcode == "fr") {
                drupal_goto('front-page-for-france pt');
            }
        }


I was having a similar problem (Rebuild Permissions failing) and tracked it to Organic groups.

Go to Administration > Configuration > Organic groups > OG field settings
Under Bundles select the Group content type
Under Fields select Group visibility
Click Add field


How do I theme my module output (specifically the nodes coming out of EntityFieldQuery)?

Instead of doing a full node view you can make a custom node view like

return node_view_multiple($nodes, 'module_name');

That will enable you to create custom logic for this view type and setup field display as well if needed.

To define your own view mode you need to add it using hook_entity_info_alter

/**
 * Implements hook_entity_info_alter().
 */
function hook_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['module'] = array(
    'label' => t('Name'),
    'custom settings' => TRUE,
  );
}


Problem with remote sync because of wrong UUID

I was synchronizing the configuration between local environment and remote repo, and after doing the Pull and drush cr, when using drush cim, I got a similar error.

In my case, the UUID (unique identifier of Drupal element), of the configuration entity was in NULL value. Since I didn't know the origin of this, I went to the remote repository and I saw that it was pushed like this. In origin, it seems an export failure (drush cex).

I solved it by getting the number and writting the UUID (it's the same one that announces the error of drush cim by console). I edit the field configuration file and change NULL for this value of the UUID and again drush cim works again. Next, it is important to commit this change to remote (git push) so that it can be modified there, otherwise it can be lost locally after a global "pull".


How to hide the unflag link text once the flag is set?

In Drupal 7 you can use The Flag API (JavaScript) for this

  The flagGlobalAfterLinkUpdate event : This event is triggered immediately after a flag link has been updated. (Flag links appear in
  two flavors: "Bookmark this!" and "Unbookmark this!", and when we
  speak of "update" we mean this change in appearance).

    (function ($) {
        $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
            if (data.flagName == 'yourFlagName' && data.flagStatus == 'flagged') { //dont forget to add your flag name
                var flgName = '.flag-'+data.flagName;
                $(flgName).hide('slow');
            }
        });
    })(jQuery);


Embed video code from third party providers

I looked at the embed code from aparat and it reminded me of Slideshare's code. I tested it by entering its embed code the same way I do with Slideshare (copying the embed code into a non-rich text editing window) and it worked.

As with Slideshare, sometimes the video doesn't appear even after loading. The fix if that happens  is to refresh. It will show the second time.


Do not translate the admin area / How can I set the language of the admin area to English?

You could try the Administration Language module. There's only a dev version for the Drupal 7.x branch out currently, but it seems to work well enough (used it in a project myself).


If it is related to database queries you can use Devel module.  You can configure this module http://www.example.com/admin/config/development/devel this will show you a list of slowest queries.


Assuming this is what you are talking about Godaddy Application for Drupal

I would highly suggest to install Drupal on your own. That version is two releases behind with Drupal 7.34 addressing another recently found security issue with HTTPS websites.


How to add a new line item to existing recurring order?

It works even with:

if (!empty($order->data['lis'])) {
  foreach ($order->data['lis'] as $key => $li) {
    $line_items[$li->line_item_id] = $li;
  }
}

However, to avoid re-adding new line item every recurring cycle, the hook_commerce_order_update should be used instead as recommended on https://cgit.drupalcode.org/commerce_license_billing/tree/commerce_license_billing.api.php#n129:

  Modules that need to respond to a license plan or recurring order
  changing should use hook_commerce_order_update instead.


META tags module description [node:summary] doesn't work

I can confirm, that the token [node:summary] works in metatag. But only for the original "body" field with exactly that name. Did you change the field name? Because the original "body" field is not "field_body".


I guess it should be form, so you can try the following on VBO page, if it workds.

   function  mymodule_form_alter(&$form, &$form_state,$form_id) {
      dpm($form_id);
    }


Get all databases name present in Postgres Server in Drupal 7 Form API

One solution can be configurate the external database as a second database in settings.php.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'postgres',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute db_set_active('external');

When you want to switch back to the default database you execute db_set_active();

Example code to switch to and query the external database:

db_set_active('external');
$result = db_query('SELECT something FROM {sometable}');
while ($row = db_fetch_array($result)) {
  drupal_set_message($row['something']);
}

db_set_active();

And here are the queries that I have used for a similar project.

Getting the Databases:

SELECT datname
FROM pg_database
WHERE datallowconn = true AND NOT datname = 'postgres' AND NOT datname = 'template1'
ORDER BY datname

Getting the Schemas:

SELECT schema_name
FROM information_schema.schemata
WHERE catalog_name = 'DATABASE_NAME' AND schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema'
ORDER BY schema_name

Getting the Tables:

SELECT table_name
FROM information_schema.tables
WHERE table_catalog = 'DATABASE_NAME' AND table_schema NOT LIKE 'pg_%' AND table_schema <> 'information_schema' and table_type = 'BASE TABLE'

Getting Fields and Field types

SELECT ordinal_position, column_name,
CASE
WHEN character_maximum_length > 0 THEN concat(data_type, ' (',  character_maximum_length, ')')
ELSE data_type
END
AS data_type, is_nullable, column_default
FROM information_schema.columns
WHERE
table_schema = 'SCHEMA' and table_name = 'TABLE_NAME'

Reference

How to access the external database in drupal?
How to connect to multiple databases within Drupal


You can use {{ directory }} for the path to your theme. Then you just need to add /img/yourimage.jpg.


Override theme function inside module, template_preprocess_field

Hook functions are named like so: MODULENAME_hook.

In your case that's:

function MODULENAME_preprocess_field(&$variables) {

}


Printing out path from views - /drupal/ appears twice

<?php print l('',
'node/' . $view->result[$id]->_field_data['nid']['entity']->vid,
array ('html' => TRUE)); ?>

Here is the final solution.

It will add the NID on the end of node/ and create the internal path "node/x". If you're using Pathauto this will still work.


Generally speaking, only alter hooks can be implemented by themes, which means hooks like hook_form_alter() and hook_menu_alter(), or in short all those hooks that are invoked through drupal_alter() in Drupal 7 and lower (ModuleHandler()::alter() or ThemeManager::alter() in Drupal 8).

Other hooks, which are invoked by module_invoke_all() (ModuleHandler::invokeAll() in Drupal 8), don't get invoked for themes simply for fact the code doesn't check if the currently enabled theme defines any hook.

  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

In Drupal 8, where the ModuleHandler class invokes hooks implemented from modules and the ThemeManager class invokes hooks implemented by themes, only the first class implements invoke() and invokeAll(). This means that in Drupal 8 theme hooks aren't invoked, by Drupal core.

This is valid for Drupal core hooks, and mostly all the hooks used by third-party modules. It is then up to a module to verify a hook is implemented by a theme too, and invoke it. This is what the Views module does.

  // Let modules modify the view just prior to rendering it.
  foreach (module_implements('views_pre_render') as $module) {
    $function = $module . '_views_pre_render';
    $function($this);
  }

  // Let the themes play too, because pre render is a very themey thing.
  foreach ($GLOBALS['base_theme_info'] as $base) {
    $function = $base->name . '_views_pre_render';
    if (function_exists($function)) {
      $function($this);
    }
  }
  $function = $GLOBALS['theme'] . '_views_pre_render';
  if (function_exists($function)) {
    $function($this);
  }

For hooks used by third-party modules, you need to check the code used to invoke them. Chances are that only alter hooks are invoked for themes, but in some cases also other hooks could be implemented by themes.
Keep in mind that in the case of themes, not all the enabled themes are checked for hook implementations, contrary to what happens with modules. Only the currently used theme and the base themes are checked, as done from the Views module.


allow user to set some css settings through UI

Since the solution I reference in my first answer was created, I have learned new things. If I were to do the same things again, I would base it on a similar principle, but I would use Panels per pane "CSS Settings", to add CSS classes instead. See: How does one theme a panel (or add a style)

This should allow for much broader customization of content.
A problem with this approach is that Panels UI is hardly "customer friendly".
I would solve that by a custom form, on a dedicated admin page, that simply loads the pane settings from the database, overwrites them, and saves them back.


How to use node reference to link images of referenced node?

I'ld suggest you use References. Add a node reference field into your blog content type. Finally when creating a blog node you'll reference a basic page (the one with your image).

Then check the display settings of your node reference field. Check the field formatters where you can choose

Title (linked)
Rendered Node
NID
etc...

Exactly there you have to add a field formatter now. Best by writing a small custom module. You may take the following code as a starting point:

/**
* Implements hook_field_formatter_info().
*/
function MY_MODULE_field_formatter_info() {
  $info = array(
    'linked_image' => array( // Machine name of the formatter
      'label' => t('Image (linked)'),
      'field types' => array('node_reference'), // Scope (this one will only be available to node reference fields)
      'description' => t('Display linked image if available'),
    ),
  );
  return $info;
}

/**
* Implements hook_field_formatter_view().
*/
function MY_MODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
    foreach ($items as $delta => $item) {
      // get the nid,
      // do a node_load(),
      // get your image,
      // rework it
      // $linked_image = what ever you got
      $element[$delta]['#markup'] = $linked_image;
    }
  return $element;
}


is it possible to have multiple access callback for a menu item

No, it isn't. Drupal wouldn't know how to treat contradictory results*.

On the other hand, nothing stops you from calling original function inside your own. If you are unsure what is it, copy it's name to access arguments and use it inside your callback. Don't forget to back up original access arguments in sub array, if needed.

* Or rather Drupal devs would need to agree how to treat them, and have a will to bother at all.


How can I set up a "many to many" relation with an entity

You can set unlimit cardinality, some like this:

->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

This create a intermediate table to reference two entities.

Check api documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetCardinality/8.6.x


What is the difference between using drupal_goto('$path') and header('Location: $path')?

I had an exposed filter with identifier named destination. Since drupal_goto() takes care of the destination parameter sent in URL with the following code, it was overwriting my code.

  // A destination in $_GET always overrides the function arguments.
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }


The cURL HTTP Request module was built for exactly that:

This is a module intended for developers, as it provides just one API to call: curl_http_request().
The function curl_http_request() is an alternative implementation of Drupal core function drupal_http_request() using cURL.
The function intends to be backwards compatible with drupal_http_request(), by accepting the same parameters in the same form and by returning the response in the same format.

I can't comment as to the decision the original developers took, but don't forget that cURL isn't necessarily available on every system either.


How to rearrange views PHP sorting criteria?

You can go for hook_views_query_alter.

  Alter the query before executing the query.

function module_name_views_query_alter(&$view, &$query) {
  if ($view->name == 'Viewname') {
    //dpm($view->query->orderby[0]);
   // put your modified sorting criteria
  }
}


Drupal 7 stopped working 500 internal Server error

For some reason under PHP selector in Plesk dom and gd was disabled. after enabling those two the site return back to normal.


Background CSS images won't be changed after reuploading & Cache flushing

Since all caching aren't able to fix, let's try narrowing down the issue.

First, try to delete the image from your theme. Flush all caches and see if the background image is still there. If it is, open your browser development tool and check the background image URL and try opening it in a new tab, check the URL of the image and follow it in your server's directory if it really still exists.

Second, try restarting the server or any related running services you have in your server.

Hope this can at least give an idea on where to find what's causing the issue.


First : download the view slideshow model ;
second : add the field you want
third :from the setting you can add controller and pager
to display the item like this you have to use it in css to display it as for item


So here is the corrected code. I've changed some variable names to make it easier to understand.

$option and $pages became options
$page became $pages
$paged was retired

As @Sujith-Nara mentions you don't need array_unique as the keyed approach will make them unique by default. This does presume that the page titles are unique across the site (which is not enforced). You could replace the key with $p->nid or $p-name if the titles aren't unique.

Because the keys are now strings you can use ksort instead of sort to order them on the key.

$pages = $sql->execute();
$options = array();

// Populate page dropdown
foreach($pages as $p)
{
    $options[$p->title] = $p->title;
    // $options[$p->name] = $p->title;
    // $options[$p->nid] = $p->title;
}

// Sort the array alphabetically in ASC Order
ksort($paged);

$form['group_owner_filter']['select'] = array(
    '#type' => 'select',
    '#title' => t('Filter by Name'),
    '#default_value' => t('Make a selection...'),
    '#options' => $options
);


Single quote in in filter return exception querySelectorAll

I found a solution for this by using patch.
https://www.drupal.org/project/drupal/issues/2902769
Because this is a core funtion patch, I marked it as can-solve but not plan to use it myself, because the filter works still only some annoying console log.


Getting different terms from different rows for the same node with Feeds

In the end, I ended up with a custom php script placed inside the Drupal root. The script reads the csv line-by-line, checks the node if the term exists, if it doesnt exist, adds it to taxonomy term reference field table and taxonomy index table. Taxonomy nidex table is important because views, etc uses it to generate output.


Does anonymous can access current node? How to check it in my module?

Also, for development especially, Devel module's Devel Node Access submodule provides a block that you can display that shows, on any given content page, all the user access permissions/grants provided, and even displays a few users and the access they would be given if they tried accessing the page, editing, deleting, etc.

Check it out: http://drupal.org/project/devel

Also, just a short bit ago, Larry Garfield posted an excellent overview of node access in Drupal 7 (applies almost without any adaptation to the Drupal 6 systems as well).


Drupal Commerce variations missing when creating content

Upgrade to Commerce 1.14. This is a well-known issue with an artificial options list introduced in prior versions. While you're at it, make sure you're running the latest version of Drupal core and taken care of any security releases, too.


I solved the problem in the meantime.

In fact, there wasn't even a problem. I was adjusting the skins for the node, when I tought I'm doing that for the whole page. What I didn't notice at the time is that there is a contextual link icon in the top righ corner, and you have to use that in order to adjust the skin for the whole page.


There are a few ways of going about this... and I have literally done dozens of formulas for it since Drupal 6.

The way I usually go about this is with Bean (Drupal 7). Create a new Bean that will represent your banner, add some fields - then let the admin create the bean. Since it is based on blocks, you can set content type visibility or path visibility, and if you add Context (if you need that muscle) you get a lot more options.

Another way to do it, which is hard to describe in a comment, is to setup an entity type for banners (since they are not content), add the fields you need, and then on the node level, add an entity reference field. Create a view that displays the entity type in a view mode of your choosing, and base it on the ER relationship value. As you said, this won't solve Views pages, which is why you might want to stick with the block route. This formula is a little similar, as it entails relating whatever banner entity the user wants to the given node, and, you can set a default value to one banner if you need that option.

Yet another way to do it is to put a Field Collection representing banner components (title, link, image), and hide the Field Collection from the node rendering. Create a View, feed it the node id contextual filter, and have it render the node in a 'Banner' view mode, which will only hold the field collection. Then just theme that level of templates, and you're good to go.

The first way (with Bean) seems like your best option, whereas the second two put the creation aspect in the node form, but you lose a way to set them on non node pages (since the Views arg will fail). Blocks won't care what the page is made up of, as long as the path or visibility rule matches.


Menu does not set active trail when generating tree in theme file

Set the active trail in the MenuTreeParameter object per MenuTreeParameters::setActivityTrail. This requires knowing the menu link plugin ids, which can be retrieved using MenuActiveTrail::GetActiveTrailIds (linked from the previous API page).

  $active_trail = \Drupal::service('menu.active_trail');

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();
  $parameters->setActiveTrail($active_trail->getActiveTrailIds($menu_name));


How to set up Media module with image editor?

Take a look at the article "Crop, rotate, and scale embedded images".

You have to install Media crop module. Some details about this module (from its project page):

  Adds cropping, rotating and scaling to the media module's image embed
  function. Only available for images local to the server (not for
  remote images), and only when adding media via CKeditor.


How can I display custom data from the database in a View?

Ok, yeah, I feel a bit silly now and was making this too difficult. There is a module for this for Drupal 8!

I was able to accomplish what I needed with Views Custom Table.

Thank you prkos for the comment.


Programmatically alter a field collection field item not yet saved in the database

I might try removing $library_wrapper->save(). Calling $entity_wrapper->save() within hook_node_presave() is problematic for the exact reason you're stating -- the field collection item doesn't exist yet so it doesn't have the data needed to allow it to be created/saved. Calling $entity_wrapper->save() inside of hook_node_presave() can also sometimes cause issues on its own. By setting the value but not saving it, it should act as though you entered the value in the field on the edit form and should be saved when the parent node is saved.

Alternatively, you might try hook_node_update() or hook_node_insert() instead of hook_node_presave(). These fire later in the saving process, at which point your field collection item may already exist, in which case you won't have any problem saving it


Why is BaseFieldDefinition::getDisplayOptions($display_context) returning NULL

The getFieldDefinitions() method returns NULL if the field is not displayed. From the docs:

  Return value

  array|null The array of display options for the field, or NULL if the
  field is not displayed.

The code below is responsible for returning the correct value:

  /**
   * {@inheritdoc}
   */
  public function getDisplayOptions($display_context) {
    return isset($this->definition['display'][$display_context]['options']) ? $this->definition['display'][$display_context]['options'] : NULL;
  }

As you can see the $this->definition['display'][$display_context]['options'] array has to be set. If it isn't set the method returns NULL.


How to add call a js file in custom module that are added in libraries folder in drupal 7?

That code just registers the library with the system. To use it, you need to add it to the page with either

drupal_add_library('mymodule', 'mymodule');

or as part of a render array:

$build['#attached']['library'][] = array('mymodule', 'mymodule');


Settings contains a dot which is not supported, but module gets enabled properly

Okay, classical scenario, 30 seconds after I open a bounty for the question, I find the answer myself ...

I was looking into the wrong file. I started the skeleton of my module by following this tutorial.

In the "Basic Structure" section of the tutorial, dots are used in keys for the .schema.yml file. It is actually forbidden to use that, but the tutorial said you could anyway.

/config/schema/loremipsum.schema.yml :

loremipsum.settings:
  type: config_object
  label: 'Lorem Ipsum settings'
  mapping:
    loremipsum:
      type: mapping
      mapping:
        page_title:
          type: text
          label: 'Lorem ipsum generator page title:'
        source_text:
          type: text
          label: 'Source text for lorem ipsum generation:'

I removed the dot at the key, and the problem disappeared.


Configuration management export blocks from Dev to Staging

Another approach for synchronizing content that is added as part of development to test and live environments is to use the Default Content module to export the content. It is built for the content to be exported to an installation profile's 'content' folder, and then the module, if enabled, automatically brings the content in when the site is installed.  It is also possible to import the content one item at a time, such as in an update hook, with the below code in your example.install or example.profile:

<?php
/**
* Import a piece of content exported by default content module.
*/
function example_import_default_content($path_to_content_json) {
  list($entity_type_id, $filename) = explode('/', $path_to_content_json);
  $p = drupal_get_path('profile', 'guts');
  $encoded_content = file_get_contents($p . '/content/' . $path_to_content_json);
  $serializer = \Drupal::service('serializer');
  $content = $serializer->decode($encoded_content, 'hal_json');
  global $base_url;
  $url = $base_url . base_path();
  $content['_links']['type']['href'] = str_replace('http://drupal.org/', $url, $content['_links']['type']['href']);
  $contents = $serializer->encode($content, 'hal_json');
  $class = 'Drupal\\' . $entity_type_id . '\Entity\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $entity_type_id)));
  $entity = $serializer->deserialize($contents, $class, 'hal_json', array('request_method' => 'POST'));
  $entity->enforceIsNew(TRUE);
  $entity->save();
}

Export a custom block with an ID of 8:

drush dcer block_content 8

(If you don't set your profile path in Drush settings you'll have to specify it above.)

And use the resultant export in your example.install file like this:

<?php
/**
* Add the footer block content.
*
* Implements hook_update_N().
*/
function example_update_8001() {
  example_import_default_content('block_content/136efd63-021e-42ea-8202-8b97305cc07f.json');
}

See easily add default content with update hooks for more.


form with taxonomy autocomplete widget throws error upon submit: Invalid argument supplied for foreach()

I'm pretty sure this error will be coming from the following loop in taxonomy_autocomplete_validate()

 // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);
    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }

which is collecting the vocabularies allowed for the field, check:

Field is set to be a term reference
Field has at least one allowed vocabulary set
field_city is the correct machine name of the field in question


How to alter command being run by drush_invoke?

Drush calls command hooks via the function _drush_invoke_hooks, which unfortunately does not provide any facility to alter the arguments list from a pre or validate hook.  We are looking to provide a more flexible mechanism that would allow this in Drush 9. Currently, only the command alter hook can change the parameters to a command. Ideally, Drush commands should invoke other Drush commands via drush_invoke_process; this will also go through the command alter hook.  If a command uses drush_invoke, though, you are stuck, as drush_invoke bypasses the alter hook.


Rather than using Entity Reference to Block, we went with using Viewfield module. It has worked as expected with and without exposed filters.


Add class to ul element in views 3 unformatted list using templates or module code?

You could use the rewrite option in views to get the exact html output you need. Rewrite enables you to override the output of this field with custom text or replacement tokens. I use the last field, since the replacement tokens should be above the field you are rewriting. Make sure to go through set the field, label, wrapper html to None

In Views

Click on a Field
Click on Rewrite the output of this field
Add your code with the desired html output

Code

[field_degree]

[field_major]

Output

Certificate

Supervision

OR you can

Click Advanced
Click CSS class
Add the name of your class "unstyled" to the entire view.


I would use the following code, to render a field.

render(field_view_field('node', $node, 'field_test1'));


What is a front page in drupal ($is_front)?

$is_front is set on any template from _template_preprocess_default_variables() (itself called from template_preprocess()). It uses the result of the drupal_is_front_page() function.

drupal_is_front_page() will returns TRUE, if the path of the current page matches the site_frontpage configuration variable. This variables can be set from the "Site Information" configuration page.

Usually there is only a single front page on a Drupal site. If you use the Variable translation module (part of the Internationalization project), then you could translate the site_frontpage configuration variable and have a different front page for each enabled language.

It may also be possible to have other module alter the value of the variables on each request to have multiple front pages. Additional module may also alter the value of $is_front in all or only a few specific templates. However, I cannot think of any useful use case for this, except torturing the template developer with inconsistency.


How do I add a span "wrapper" to all required form fields?

I'd suggest you create an implementation of the theme hook form_element, to add a new class at the top level rather than an extra div which is simply redundant. That way you don't have to recursively process every form on the site looking for required fields. Unfortunately the standard form_element implementation is not designed in a very helpful way, so you have to duplicate a lot of code:

  function mymoduleortheme_form_element($variables) {
    $element = &$variables['element'];
    // This is also used in the installer, pre-database setup.
    $t = get_t();

    // This function is invoked as theme wrapper, but the rendered form element
    // may not necessarily have been processed by form_builder().
    $element += array(
      '#title_display' => 'before',
    );

    // Add element #id for #type 'item'.
    if (isset($element['#markup']) && !empty($element['#id'])) {
      $attributes['id'] = $element['#id'];
    }
    // Add element's #type and #name as class to aid with JS/CSS selectors.
    $attributes['class'] = array('form-item');
    // extra code here --->
    if(!empty($element['#required'])) {
      $attributes['class'][] = 'form-element-required';
    }
    // <---
    if (!empty($element['#type'])) {
      $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
    }
    if (!empty($element['#name'])) {
      $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
    }
    // Add a class for disabled elements to facilitate cross-browser styling.
    if (!empty($element['#attributes']['disabled'])) {
      $attributes['class'][] = 'form-disabled';
    }
    $output = '
' . "\n";

    // If #title is not set, we don't display any label or required marker.
    if (!isset($element['#title'])) {
      $element['#title_display'] = 'none';
    }
    $prefix = isset($element['#field_prefix']) ? '' . $element['#field_prefix'] . ' ' : '';
    $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';

    switch ($element['#title_display']) {
      case 'before':
      case 'invisible':
        $output .= ' ' . theme('form_element_label', $variables);
        $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
        break;

      case 'after':
        $output .= ' ' . $prefix . $element['#children'] . $suffix;
        $output .= ' ' . theme('form_element_label', $variables) . "\n";
        break;

      case 'none':
      case 'attribute':
        // Output no label and no required marker, only the children.
        $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
        break;
    }

    if (!empty($element['#description'])) {
      $output .= '
' . $element['#description'] . "
\n";
    }

    $output .= "
\n";

    return $output;
  }


Connecting to the database and writing your own SQL, outside of the Drupal framework, while possible will put you in the dark ages. Drupal handles a lot of the heavy lifting and abstraction for you. If you are used to writing your own PHP to do DB queries it can be tempting to go with what you know. but  in the cases where you need to use custom queries use the Drupal DB API  like  Berdir suggested.

However often there are ways to use forms, without having to write your own database methods. Depending on what you want to do with the data there are several options.

Webform may be what you are after. Which will allow you to create custom forms with simple data management at the back end. Again fairly simple to implement but in this case you won't have the overhead of new nodes and the data is easily exportable.

In both of these cases you can use hook_form_alter to customize the form if you wish.


required modules to develop a ecommerce website

For Drupal, it's Drupal Commerce that worth consideration now. I worked with it couple of months ago, it takes some time to get used to it, but once you get it, you can create a lots of things with contrib modules and other tools that you can't do without custom development with other CMS.

You will find lots of how-tos, contrib modules and other informations about Commerce http://www.drupalcommerce.org/

Also make sure to check out Commerce Kickstart, which is an installation profile for Drupal stores and it's coming with basic configurations like set up product - product display, and it contains all required modules and dependencies for Commerce http://drupal.org/project/commerce_kickstart


How to limit flagging of articles to users with sufficient userpoints using Rules?

Here are the headlines of a possible solution to answer this question:

Step 1 - Create a designated role

Create a new "role" corresponding to users with (say) 150 points, assume you name the role UsersWith150Points.

Step 2 - Limit access to the flag

Secure the access to the flag to users with role UsersWith150Points.

Step 3 - Create some Rules logic

Any time a user gains points, use a rule to check if the user has at least 150 points. If so, have the Rules module grant access to the UsersWith150Points role.

Similarly, if a user looses points, also use a rule to check if user no longer has at least 150 points. If so, have the Rules module remove access to the UsersWith150Points role.

Sounds easy and pretty forward ... except ... there is no (easy) solution to have a Rules Condition to "check the current user points for a user" (unless you're willing to use custom PHP logic in your Rules Condition). However, the clue to make this rule work anyhow, is to use as a very first Rules Action "Load user points of a user". For an example rule, which is close that what you'd need, refer to "How to create rule to change user role based on points (using User Points module)?": you'd only have to add a Rules Action to grant or remove some role (and adapt the user points threshold to your '150').


How to merge two views block result to a single block

May be this can help you.

You can use  https://www.drupal.org/project/views_field_view module to embed view in another view as a field.

Or You can create a custom block and merge both views. To get the views in your custom code you can use views_embed_view() or module_invoke();

check for more information
https://www.drupal.org/node/1034524
https://api.drupal.org/api/views/views.module/function/views_embed_view/7


How to build drupal-twitter bot like the one on drupal.org

You can achieve this by using Twitter & Oauth module. You will have to create a twitter app & use Consumer key, Consumer secret to connect to your twitter account.

You will have to choose a content type for tweet & yeah don't forget to enabled import option on twitter account.


I wouldn't call it "hacking", but someone (person or automated script) is definitely trying if you accidentally "left the door open". They found out that you didn't. Don't worry about it... As long as you keep your site up-to-date with security updates!


Security issues concerning including external code for module

If your web server is set up correctly then both of the paths you've mentioned will have the same permissions (readable but not writeable by the server), so they would be equally secure/insecure depending on the rest of your server setup.

I must admit I haven't come across a path like the second one you mention, although I know most contributed modules that have been updated to Drupal 7 use the sites/all/libraries folder for storing external code libraries.


Avoid redirect to comment page if comment is invalid

You can do this, by using hook_form_alter and then change the $form['#action'] value to point to the current destination.


Have you got this sorted yet?

Ensure that you're using the "Geofield - proximity" field for output and not the Proximity - distance field. I've tried using the latter and not had it working (yet).


How can I disable default blocks in Drupal 7 without touching the Blocks Config admin?

hook_block_info_alter() can be used to alter the default configuration of blocks. From there you can set the status, region, visibility and pages settings that match the wanted configuration. But once the blocks configuration has been written to the database, changes made with this hook will have no effect.

Sadly there is no other hook to configure blocks. But you can write the needed information to the database yourself as part of a custom module or profile hook_install() or hook_update_N() implementation. The standard_install() function from the standard module provide example code for that. If this is done from an hook_update_N implementation or a module, rows for the blocks may already exists in the database. You can then use a merge query for each block to avoid having to deal with the "is this an insert or a an update" question yourself.


How to sort taxonomy terms by their tid?

Base on your code, I think the key for the $data is tid.

You can just add <?php ksort($data);?> before your foreach loop.


How to display the trimmed value and the full value of a field in a same node

i answer myself:

inside node.tpl.php, this is rendering a trimmed version of my field

<?php
     print render(field_view_field('node', $node, 'field_myfieldname', array(
        'label'=>'hidden',
        'type' => 'text_summary_or_trimmed',
        'settings'=>array('trim_length' => 30),
    )));
?>

and then i render my 'default' format field like always

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


Implementing a secure confirmation page for an entity form (D8)

In drupal there are several way to do the same thing.
What I suggest in this case (certainly different for another person) use a small custom module with Cookies or Session.

Create a custom module.
Add an extra submitter.

Save the new USER ID on session, cookie ...
Redirect to the page (Ex : $form_state->setRedirect('your.module.route.name');)

Create a small dynamic custom page (Like : http://www.drupal8.ovh/en/tutoriels/5/create-a-simple-module-for-drupal-8-step-2-create-simple-page)

Get the USER ID from session, cookie ...

You can change the confirmation mail template from back office.


How do I structure a simple Drupal 7 site/theme?

It sounds like most of the things that you need to do (i.e. creating and placing content on the site) are not related to a theme, but rather related to site building. Folks coming over from Wordpress are usually confused by the split between theming and site building in Drupal, it's very different from Wordpress.

I would strongly recommend reading Drupal's Site Structure Guide. Your homepage and "about" page will most likely be a combination of node content and blocks, while your "jobs" page will involve creating a custom content type and a Views page listing the nodes of that content type.

The majority of your work to set up the content of the site and it's output can happen before you even begin theming. Theming is usually a later step in site building and should be considered a very superficial aspect of building the site. There are few situations where you would need custom templates for each page or node type, most of the arrangement of content and even layout can be handled via the Drupal UI.

Once you complete the site build in Drupal and move on to theming, the Drupal Theming Guide will be your starting resource for learning how the Drupal theme layer works.


How to move commerce kickstart database to other domain

It is showing the install.php file because it doesn't recognize your settings.php file - you need to check that this is in the correct sites folder (ex. 'default') and has read permissions for your web user.


How to stop all the processes except by entering Linux via SSH?

If you can log into your hosting account control panel, you may have access to PHPMyAdmin to change the password. Also you might be able to reboot your server from there.


How do I define a computed field equal to the concatenation of two fields of my custom entity?

I found this in ContentEntityBase.php 499 (but you could show us the whole error log):

I think the case is the following: your field is translatable (you didn't set it's not, and I tihnk the default is TRUE).

else {
  $field_langcode = $langcode;
}
**$field->setLangcode($field_langcode);**
$this->fields[$name][$langcode] = $field;

What I don't understand here: how basefield definition allows you to add a class which doesn't inherit / implements the right class / interface. I think it's a core bug?

You should either:
- add set language method, with a languagecode property
- set your computed field untranslatable


How to use different entity info per entity bundle?

I don't really understand what you are asking, but it's not possibly to have different entity type definitions per bundle. The only exeption is the uri callback, that forum.module is using, as you mentioned yourself.

As I said, I don't understand/you don't explain what you're actually trying to achieve. Try to explain that, maybe there's a way to achieve your goal, just not in the way you imagined it.


To show custom user fields in a view does not work for user with uid 1

Try using "Access: Role" rather than "Access: Permission" and select all user roles (that you'd like to be able to see the view ...


How to show a field in views only when a checkbox is ticked?

You can do this with Views out of the box. No need for Views PHP here.

Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.)
Use the Key formatter - this isn't obvious, but I couldn't get it to work without this.
Select REWRITE RESULTS and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need.
On NO RESULTS BEHAVIOR check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)


If you look at it, you'll notice MODULE_render_field is not useful at all. Once you get the renderable array from field_view_value you can change the values in it and render it. If you're adding that to a template, it will look fugly, for sure. But it belongs in a preprocess call, where it will look just normal:

<?php

function MYTHEME_preprocess_SOME_TEMPLATE($vars) {
  $field_items = field_get_items('node', $vars['node'], $vars['field']['field_name']);
  $field_value = field_view_value('node', $vars['node'], $vars['field']['field_name'], $vars['field'][$delta], $display);
  // Alter the renderable array.
  $field_value['#item']['alt'] = 'alternate';
  $vars['altered_field'] = $field_value;
}

And in the template:

<div class="something">
 <?php print render($altered_field); ?>
</div>


REQUEST_TIME is in GMT eventhough site timezone is IST

As per the docs.

  The entries in this array are created by the web server.

Drupal has no control over this, and in fact, neither does PHP. (Though of course both of them are free to manipulate the value)


How to calculate margins based on JSON and ONIX (XML) input and calculate points based on them?

Calculations

You should definitely have a look at the (fairly new) Math Field module, to use it for:

calculating the margin price.
the calculations after order completion.

Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).
Math Field does not yet support Field Collections (#2573643: Support the Field Collection module).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

Dashboard

Depending on your actual requirements/expectations, you might be able to implement your dashboard with only the Views module, possibly complemented one of more add on modules for it. E.g... if you'd also want some sort of charts to be created, a module such as charts could be a good fit.

As an alternative (or possible complement?) you might also want to consider the Forena module (discosure: I'm a co-maintainer), e.g. because it comes with charting out of the box, and it would even allow you to integrate some of your data stored in XML (your ONIX data) without importing them.

Buyer points

These points could be implemented using the Userpoints module (that's obvious). And by using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of granting the appropriate number of userpoints. So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Bonus: even though your question doesn't seem to include that (yet) as requirements, it would be straight forward to implement some special reward(s) for your frequent buyers. Here is what it would take:

Goal = "New customer", with only 1 Task = "Buy 1 product" (say with machine name = buy_product).
Goal = "Silver customer", with Task = "Buy 10 products, on 10 different days, in a timeframe of 3 months".
Goal = "Gold customer", with Task = "Buy 100 products, on 25 different days, in a timeframe of 12 months".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = buy_product) to keep track of the progress of any user to become a new/silver/gold customer (check the video for a similar sample).


How do I add a basic FlexSlider to the body?

Just copying HTML-part won't work as the page needs FlexSlider java script. So add it either by calling drupal_add_js() or modifying the html.tpl.php file of your theme.


Linking to #targets when promoting to homepage

Use URL's relative to the site root. Suppose your node lives at http://example.com/node/123 and your named anchor is called "target", write your link like this:

Target

This should work on the home page and the node page itself.


How to disable webform select box with jQuery without resetting selection value to default

You can do this by removing the 'selected' attribute first, and setting the new selected attribute, prior to disabling.

e.g:

if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').prop('disabled', true);
}

Here's a jsfiddle link for tinkering: http://jsfiddle.net/AwUwt/

Edit: Alternatively, you can just hide the select box

if (age < 19) {
    $("#edit-submitted-bring-alcohol option:selected").removeAttr('selected');
    $("#edit-submitted-bring-alcohol option[value='no']").attr('selected', 'selected')
    $('#edit-submitted-bring-alcohol').val('no');
    $('#edit-submitted-bring-alcohol').css('display', 'none');
}


Insert node title in the message sent by contact form

The current node is available from the route match, \Drupal::routeMatch()->getParameter('node'). Make sure it really is an instance of NodeInterface before you continue or check the route name.

Then it's easy to use $node->getTitle() as the default value for the subject of the contact form. Depending on what you want to do, you can then also hide the subject field.


OK, finally got it working:

sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Thanks to Remy for putting me on the right track, and This drupal.org post.

Seems it was that I needed to make a directory first... Rookie move.


listing all the pages of a custom content type

The views module do that. There's many articles about this question. Take a look on existing answers


The D6 version of the module doesn't support filefield. You must use the drupal upload module. On the node edit form: Attach a file, set it to private. Switch to the tab "Protected downloads" and specify your settings there.
If you don't see the tab "Protected downloads" then it might be a bug. Consider opening an issue for this on the issue queue for the module on drupal.org.


Use field formatters instead of printing raw values. With Twig Tweak module it can be done as follows:

{{ item.content['#paragraph'].field_content_2_media|view }}


Is it possible to synchronize publish status between translations?

You can't control the translation configuration of base fields such as the publish status field from the content type configuraton, so go to

  Administration >> Configuration >> Regional and language >> Content
  language

and uncheck the publish status field for your content type:

  [ - ]  Published

Now the publish option will be available only in the original language of the node and is then applied to all translations.


How can I work on which particular pages a CSS rule is used?

You can see a list of selectors not used on a page using external tools, there is no way for drupal itself to create the list for you however.

You can find some suggestions here: https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website
I personally use the chrome developer tools as described in the above link.


In case this might be helpful for other (beginners): Using the session object in a custom controller class with dependency injection.

Drupal\user\PrivateTempStoreFactory;

class mymodule_Controller extends ControllerBase {

  /**
  * The user's private $tempStore object.
  *
  * @var \Drupal\user\PrivateTempStoreFactory
  */
  protected $tempStore;

  public function __construct(PrivateTempStoreFactory $temp_store_factory) {
    $this->tempStore = $temp_store_factory->get('mymodule_name');
  }

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

 // Now get and set values in tempstore
 public function foo() {
  $foo = "xyz";
  // Set a session object "bar" and give it value $foo
  $this->tempStore->set('bar', $foo);

  // Get the 'bar' object from the session object.
  $value = $this->tempStore->get('bar');
 }

}


How to execute VBO list of nodes in Rules on After updating an existing user account event?

What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

  You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
  However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
  You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
  The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from your VBO list of the unpublished nodes of the user. And for each node in the list you want the rules action to be "publish node" (instead of "remove sticky").

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in that video also. I'm assuming your VBO view also requires the userid already.

The Rules component that you create as described above, should then become the action to be performed by a rule that is triggered by the event "After updating an existing account". This is what differs from what is shown in the video, starting from 11:30 (in the video the Rules component is triggered daily, via the Rules Scheduler).

Should you need any other rules "conditions" (eg: only for selected roles), you can add them to the rules component you created.


Webform field default value + Profile field value

According to Make profile fields avalaible as tokens, tokens for Profile fields was added, but it was added to dev 4 months ago. Since the 8.x-1.0-rc1 version was released 9 months ago, it does not have tokens.

So either switch to dev version until they release it or apply the patch provided on #22 to 8.x-1.0-rc1.


You can send an image through resources using base64_encode(), or _file_resource_retrieve().

I don't remember the specifics of it all, but here is how I did it for Services in a project last year. You'll have to dissect the code yourself, but it definitely does work:

/**
 * Override of the Services module File resource, retrieve method.
 *
  * The original method does not allow for the retrieval of an image with an image style.
  * This override accepts an additional parameter, $image_style, which if set will return
  * the file data for the image in that image style. This allows for the retrieval of private files.
  *
  * @param $image_style
  *   If this value is set to an image style, the data for the image in that image style will be returned.
  *   Otherwise, the original File resource is invoked.
  *
  * @see _file_resource_retrieve()
  */
 function ba_api_file_retrieve($fid, $include_file_contents, $get_image_style, $image_style)
 {
    if($image_style)
    {
        if ($file = file_load($fid))
        {
            $filepath = $file->uri;

            if($image_style == 'raw')
            {
                $return = base64_encode(file_get_contents(drupal_realpath($filepath)));
            }
            else
            {
                $return = base64_encode(file_get_contents(drupal_realpath(image_style_path($image_style, $filepath))));
            }
        }
        else
        {
            $return = 'file not found';
        }
    }
    else
    {
        module_load_include('inc', 'services', 'resources/file_resource');

        $return = _file_resource_retrieve($fid, $include_file_contents, $get_image_style);
    }

    return $return;
 }


Deleting field collection bundle programmatically from core

So apparently what I needed was field_delete_field(), and then a field_purge_batch().


Drupal installed in the web root but not at the base of the domain name

It it impossible, unless you count .htaccess (or similar config file for your webserver) as Drupal config too. If you do, in Drupal UI change base URL to http://example.com/drupal and use mod_rewrite to remove "drupal" from URI before further processing.

Note that this will not disable direct access. Of course you can block any calls without "drupal" prefix, but it would mean nothing except Drupal can work there. So if your goal is anything more than marking it's Drupal in your URLs, it's not a way to go.

Note: your mileage may vary depending on web server used.


Email templates can be found in module subdirectories:
https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails

For D8,  commerce is not using rules any more, but states machine and event subscribers, check order workflows / checkout flows
https://docs.drupalcommerce.org/commerce2/developer-guide/orders/workflows


How do I get my accidentally disabled side menu back?

Go to: admin/structure/block

Then move to the bottom of the page and search Navigation and in the select you must select Sidebar First, then go to the bottom and click the Save blocks button

See this picture:


creating a new content type with a series of blocks

I think that what you are looking for is Drupal's Taxonomy feature.  I would start with that.  This lets you categorize your content.

After that familiarize yourself with the views module.  Items created in nodes that are associated with taxonomy terms can be listed in a views block.  So if you have a concert site you can create a "show" type with dates.  Then you can create a view/block that lists upcoming concerts.

Then when you get those two things I would recommend learning how to use panels.

For a great example of it all put together look here


How to filter views rows whose nid is less than nid provided by url?

You can implement the hook_views_query_alter() to alter your query and change the = operator by the < operator.

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW_NAME') {
    /* Using the following line dmp($query)
     * (you need the devel module to use dpm) you will be able to search
     * where is condition to alter, you will see that in the
     * $query->where[0]['conditions'][0]['field'] you will have:
     * node.nid = :node_nid
     * so your solution will be replace the
     * = operator by the < operator
     * at this moment you can't do this from the Views UI
     */
    dpm($query);

    $query->where[0]['conditions'][0]['field'] = str_replace('=', '<', $query->where[0]['conditions'][0]['field']);
  }
}

I test the code and in my environment it works as I want it to.

Here is my view for if you want test the code (in this case the view name is articulos):

$view = new view();
$view->name = 'articulos';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'articulos';
$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'] = 'articulos';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$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: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'articulos/%';
$translatables['articulos'] = array(
  t('Master'),
  t('articulos'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('All'),
  t('Page'),
);


Is this normal to have Drupal Commerce stuck in PENDING status after a completed paypal payment?

Orders aren't being "stuck" here so much as placed here for you to determine what to do with them. When you build a Drupal Commerce site, you should consider what needs to happen to an order after the checkout process has been completed / payment has been received and either implement a manual process or some form of Rules or code based automation to do it. Drupal Commerce leaves it here because we don't make any assumptions about the type of product a Commerce site sells or the business processes involved in taking an order from checkout completion to final fulfillment.

PayPal WPS and related payment gateways are a bit of a special case, too, in that you actually cannot use the "When an order is first paid in full" event to manipulate the order status. Because these orders may not have completed the checkout process when their payment notifications arrive at the site, the checkout router still depends on these orders being in a checkout order status to complete the checkout process after the payment has been processed.

Instead, if you need to update the order status based on payment receipt for PayPal WPS, you should use the "Order balance comparison" condition in conjunction with the "Completing the checkout process" event to update the order status on that event instead if payment has been received. Additionally you can use a "Data comparison" condition to check the order status on the "When an order is first paid in full" event and update the order status if the order is not still in a checkout order status.


Is There a Generic Theme Duplication Module or Drush Command

No but you can copy the theme folder and then replace the name of the theme in all hooks and of course rename yourtheme.info to yourcopy.info. in order not to miss any hook you may use a prog like wingrep and search-replace the yourtheme string


Getting all nodes that have a specific term id using EntityFieldQuery

Something like:

$query = new EntityFieldQuery()
  ->entityCondition('entity_type', 'node')
  ->fieldCondition('field_taxonomy_reference', 'tid', TERM_ID)
  ->fieldOrderBy('field_audio_weight', 'value', 'DESC');

$results = $query->execute();

Check these articles for more information:

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-1/

https://www.phase2technology.com/blog/entityfieldquery-let-drupal-do-the-heavy-lifting-pt-2/


Form Block module usage in multiple sections

You could use the context module to achieve this. With this module you can show the same block in different regions on different pages. You can add a condition (like path is "/frontpage") and a reaction like show block xy in region xy.


You can select the Boolean field and widget type as Single on/off check box...This should solve your problem...No need to use any modules


How to apply a sequential number pattern in Pathauto?

You need an additional module for this – Serial Field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

You then can use Serial Field + Token + Path Auto - to create serial numbers in urls, for example: http://www.example.com/issue/10 (where 10 is a type scope serial number).


Accessing Drupal core functions in object-oriented code: Call to undefined function

It happens because drupal_json_encode() is defined in includes/json-encode.inc, which is not a file that is normally included when Drupal boots. To use that function, you should use code similar to the one drupal_json_encode() uses, although you really should use drupal_json_encode().

include_once DRUPAL_ROOT . '/includes/json-encode.inc';
file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

The code I would use is the following one.

file_put_contents(drupal_json_encode($feed_array), $path . '/novel.txt');


Email-only subscription form with mailchimp module?

I haven't got a mailchimp enabled Drupal site in front of me, but from memory the simplest way to do it is to set the fields you don't want captured as optional in the Mailchimp interface (NOT the Drupal module) and then just hide the fields using CSS on your subscribe form.

If you don't need to capture anything other than email for your mailing list, you can remove those fields entirely from your list on Mailchimp's site, and (again from memory) they won't show up in your Drupal form.


Fatal error: Call to a member function difference() on string in error on tpl file

The error is calling a method (difference()) on a string, while just PHP objects and classes implements methods. format_date() is documented to return a string, not a DateObject.

  Return value

  A translated date string in the requested format.

The code I would use depends from what modules you have installed, and which PHP version you are using.

If you have the Date module installed, and you enabled the Date API module, I would use the following one.

$birthday = new DateObject($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->difference(date_now(), 'years');

If you don't have the Date module installed, but you have a recent version of PHP 5 (which means higher than 5.2.0), then I would use code similar to the following one.

$birthday = new DateTime($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->diff(new DateTime())->format('y');

If you are still using a PHP version lower than 5.2.0, or you just want code you can use without to worry about the PHP version, I would use the following code.

$birthday = strtotime($content['field_date_de_naissance']['#items'][0]['value']);
$age = format_interval(time() - $birthday, 1);

I am not using format_date() since it returns a translated string, which is not necessary to strtotime() (and probably, it would confuse it).
format_interval() consider a month made of 30 days; for this reason, the code shown above is probably giving a different value than the other methods.

Reference

DateTime::__construct()
DateTime::diff()
DateInterval::format()
format_date()
format_interval()


Update

If one needs to obtain "JUST" the filename for theme logo for the active theme for any given domain in a domain access environment (as the OP found he needed to do), then the following code provides the image file name for the theme logo as $img_file.

$global $base_url;
img_path = theme_get_setting('logo');
$str_to_remove = $base_url . '/sites/default/files/';
$img_file = str_replace($str_to_remove, '', $img_path);

Original

Pass "theme_get_setting('logo')" as the path for the first php script?

<?php print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo'))); ?>

or rather - an amalgamation of the two -

if (theme_get_setting('toggle_logo')) {
print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo')));
}


How can I print the vocabulary name instead of the referenced term in a node template?

The vocabulary machine name is the bundle ID of the term, which you can get through the node object:

{{ node.field_taxo.entity.bundle }}

To load the label of the vocabulary:

{{ node.field_taxo.entity.vid.entity.label }}

This works only when the field has content. For an empty field you would have to dig into the field definition you get from the same field object and check whether the field is restricted to a single target bundle.


Getting a node's status is quite simple:

// Get the node with node ID 123.
$node = node_load(123);
// Get its status.
$status = $node->status;

That said... I don't know what your function looks like or in which context it's running, so depending on your situation, there may be an even better way to get what you want.


Not sure how you are generating this dynamic page, but somewhere in the mix, you could put something along the lines of:

drupal_set_header('Cache-Control', 'public, max-age=0');       // set max age to 0
drupal_set_header('Expires', 'Sun, 18 Dec 1983 02:28:00 GMT'); // some date in the distant past

before any other output, eg, at the top/start of your page's menu callback or in right before you select its custom template if it has one.

If this doesn't work, a quick hack would be to do a drupal_set_message('Welcome to my dynamic page'); which would cause drupal's core functions to try not to cache the page :)


Create a responsive email at Drupal for phone

Okay, this issue is solved by this module https://www.drupal.org/sandbox/dmitriytrt/1939698.

The issue happens because default "mimemail css compressor" module has excluded @media rules in email, so we need a different way of converting css to inline styles.

Another possible solution is to use emogrifier https://github.com/jjriv/emogrifier. This library's latest version has supported @media rules.


How I get the name of the taxonomy term reference of the content type

You can refer to this article having detailed information about entity queries.

You should use ->entityCondition('entity_type',  'node')  rather than using ->entityCondition('entity_type',  'taxonomy_term')


This can only be done on the theme layer. Try taking a look at theme_menu_link().


How to add jQuery.LocalScroll to Drupal 7?

When you view the source are the js files you added in the head? If not you'll need to clear your cache. Changes to theme .info files do not take effect until you clear your cache.

If it's a js error then it would be helpful to have some more details.


The important thing to make this work is the theme that your using; the Views Responsive Grid doesn't do much by itself with regards to styling but it allows you setup you view to apply the appropriate CSS class from your theme to make your display responsive.

You are using the Corporate Clean theme but it's not a truly responsive theme from what I can see from its layout CSS. You can still have that layout that you want for one screen type so that will be what I will show you here.

Change your view's format to Responsive Grid

Next change the settings for the Responsive Grid format to have  2 column in horizontal alignment and the class grid_6 to every column. You can also use grid_4 if you have a sidebar on your page.

Then change the Format's Show options to fields.

Now in the fields section add all the fields that you want to display. For example, I have the fields title, body and post date.

The next step requires you to add some custom html/css; normally advanced view display formats such as Views Bootstrap would have different options to display your fields. For example, had you been using a Bootstrap based theme the Media Object format would have served you well.

However, since you are using something different, I would recommend you override the out of the fields as follows.

Hide all but the last one of your fields by clicking on each field and checking the "Exclude from display option".

For the last field override its display by clicking on it and going to the Rewrite Results section. In the text box provided add in your custom HTML markup with along your fields using tokens provided by views.

In you theme make sure to add proper CSS classes, i.e, in the example HMTL I'm showing you should have the classes clinic, clinic-thumb and clinic-details. These should have the styling in such a ways that the clinic class clear floats, the clinic-thumb and clinic-details classes should have floats and respective widths.
Example CSS:

/**

.clinic has a clearfix taken from this page
*/

.clinic:before,
.clinic:after {
    content: " "; /* 1 /
    display: table; / 2 */
}
.clinic:after {
    clear: both;
}
/**

For IE 6/7 only
*/
.clinic {
*zoom: 1;
}

.clinic-thumb{
 width: 35%;
 padding-right: 5%;
 float: left;
}
.clinic-details{
 float: left;
 width: 60%;
}

If you followed my example you should get something like this:

Hope this helps!


Probably you would just want to implement your own version of theme_nice_menus_build(), and add all your required divs/spans right there.


How to use text from a block view as a prefix to a node title

So this is what I did, in case anyone wants to accomplish the something similar.

You first have to add a new region just above the content region in your MY_THEME.info file which in my case was:

regions[manufacturer_prefix_title]    = Manufacturer Prefix Title

Then I overwrote the page.tpl.php which contained:

  <?php if ($title): ?>

<?php print $title; ?>

  <?php endif; ?>

to each node instance I needed page--MY-NODE.tpl.php which now contains:

  <?php if ($title): ?>
    <?php print render($page['manufacturer_prefix_title']); ?>
  <?php endif; ?>

(The above required a preprocess_page hook.)

Then I created a block view, with the contextual filter set to NID. I also added filter criteria to get only the desired content types.

I added the 3 Content: Manufacturer fields, ticked exclude from display on each, and ticked rewrite the output of this field on each so that I could use the replacement pattern for those fields and wrap each one in the span class I wanted:

[field_MY_FIELD].

I also made sure to tick hide if empty under no results behavior so that the span class would not get rendered when the field was empty, as these fields  are not required.

I then added the Content: Title field once, and ticked rewrite the output of this field  and used replacement patterns for each of the manufacturer fields, leaving one space in front of the title:

[field_MY_FIELD_1][field_MY_FIELD_2][field_MY_FIELD_3] [title]

Since the contextual filter was set to NID, the title will only grab the appropriate taxonomy reference field, as only one is allowed per node.

Then all that was left was to simply place the new view block @admin/structure/block into the new region that was created in the MY_THEME.info file. I also configured the block to only show on the same content types that i defined in the filter criteria of the block view.

Hope this helps someone! :)


Your code is correct, but nothing will happen when you install the module itself. It will only be invoked when you create a new field of type instagram_gallery.

But that is not all. The only module that will get's it hook_field_schema invoked, is the module that actually defined the field. This is done with hook_field_info, so you need to have the following code in your field_instagram.module file:

/**
 * Implements hook_field_info().
 */
function field_instagram_field_info() {
  return array(
    'instagram_gallery' => array(
      ...
    ),
  );
}

Since you are defining your own field, you also need to use

hook_field_is_empty
hook_field_formatter_info
hook_field_formatter_view
hook_field_widget_info (unless you can use an existing widget)

Update
It's hard to say way you have troubles. What the field module does is this:

module_load_install($field['module']);
$schema = (array) module_invoke($field['module'], 'field_schema', $field);

You can try to load the created field manually and run the hook to see if it works. You need to load the .install file like shown above. My guess is that you have something misnamed somewhere, but it's hard to say where exactly. The above could should with your info look like this:

$field = field_info_field('field_name_here');
module_load_install('field_instagram');
$schema = (array) module_invoke('field_instagram', 'field_schema', $field);

If the above works, you can try to debug the actual field creation, the code is from field.crud.inc line 134.


Add class to views (Advance -> Class) and then through css, do something like this:

.className .Alpha["value=1"]{
      border: 2px solid #0f0;
}
.className .Alpha["value=0"]{
     border: 2px solid #f00;
}

Value may slightly differ and you can simply check it through "inspect" of your browser's contextual menu.


How to make drop down field as mandatory field in views exposed filter?

In the Exposed Filter option check Required checkbox.. See attached screenshot below for select list field..


How to make "Time" part of a date field not required?

I'm not sure this is possible without some re-engineering of how the date module works, or at least writing your own custom date field.

The date_field_validate() function calls DateObject::validGranularity() which checks to make sure there are sufficient date parts for the granularity you've chosen. If the field instance is set to be required, it's necessary for that check to pass before you can save the field values. Obviously this check won't pass if you haven't provided all of the relevant date parts.

A simple way around the problem might be to use a field collection, to which you can add two fields: one for the date and one for the time. There is a Timefield module out there, I recommend the dev version as the alpha version has some weird problems.

That method would also help with your display issue as the date and time are now separate fields.


Load required libraries with content using ajax

So after playing with this for a while I figured out that Drupal only pulls in the js Assets through ajax, not the css. I guess this make sense on some level. But I figured I can easily pull in the necessary css in using js.


How to set the default value of remember me in the persistent login module to on?

It does not look like that module offers such a setting by default, so you'll have to change the option using hook_form_alter as well (in a custom module).

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  // I don't check for the specific form here, since we do have a specific element we can look for.
  if (isset($form['persistent_login'])) {
    $form['persistent_login']['#default_value'] = TRUE;
  }
  if (isset($form['account']['persistent_login'])) {
    $form['account']['persistent_login']['#default_value'] = TRUE;
  }
}

You will have to make sure that your custom module is run after the persistent login module:

How to update a module's weight
There's a module for that


SOLUTION

When developing I had the language set to English; it needs to be set to Danish, in order to get this to work.


It would appear to me that Drupal 7 has no built in way to delete grants by GID, only by $node. Because of this I'm advocating doing a simple database query very similar to the query in node_access_write_grants().

Original:

 if ($delete) {
    $query = db_delete('node_access')
             ->condition('nid', $node->nid);
    if ($realm) {
      $query->condition('realm', array($realm, 'all'), 'IN');
    }
    $query->execute();
 }

My code:

$query = db_delete('node_access')
         ->condition('gid', $address->aid);
$query->execute();

Perhaps there's something to be said for using the 'realm' field to circumvent this issue.  However, this seems to work.  I'd love to know what the community thinks.