Cache clearing takes too long: What can I do to improve it?

I have a pure MySQL approach to clearing the cache_page table quickly.

use dbname
ALTER TABLE cache_page RENAME cache_pageoff;
CREATE TABLE cache_pagenew LIKE cache_pageoff;
INSERT INTO cache_pagenew
    SELECT * FROM cache_pageoff
    WHERE expire > 1370891317
;
ALTER TABLE cache_pagenew RENAME cache_page;
TRUNCATE TABLE cache_pageoff;
DROP TABLE cache_pageoff;

This script will do the following:

take the cache_page offline
create a new cache_page
load the new cache_page with the most current data
put the new cache_page back online
remove the old cache_page

Give it a Try !!!

BTW the reason the process is taking long has to do with the range of the delete and the storage engine is use.

If your cache_page tables is using the MyISAM storage engine, the DELETE query would be traversing almost the entire table and deleting each row.
If your cache_page tables is using the InnoDB storage engine, this is orders or magnitude worse that MyISAM. Why? All the rows you are deleting are stored in the Undo Logs within ibdata1.

When the DELETE query has completed successfully, all the Undo Logs for the cache_page table are purged.
If the DELETE query is interrupted by a rollback operation, all the Undo Logs are used to restore the cache_page table in its original state. If cache_page is InnoDB, I strongly recommend not interrupting the DELETE  query. Let it goes its full course.


Multiple pagination of arbitrary array of objects

See Drupal Pagination with a Custom Query for full code example


As @No Sssweat points out in a comment on your original post, there is no Commerce 1 for Drupal 8, so if you're upgrading your site to Drupal 8, Commerce 2 is your only option.

But even if that weren't the case, Commerce 2 is stable and it's where all the current improvements in Commerce are happening. While Commerce 1 may have a larger contrib ecosystem at present, I find that once developer energy has moved on to the latest version of Drupal, it's frustrating to try and solve contrib problems on the old version. So my advice is always to go with the more recent version, once contrib has progressed enough that they key functionality you need has been developed and is reasonably stable. I believe Commerce 2 is there.

Finally, the migration process is kind of a bear (especially if you're migrating historical order data), so personally I'd only want to do that once, D7 Ubercart directly to D8 Commerce 2, rather than the two step process of D7 UC -> D7 Commerce 1 -> D8 Commerce 2. I think you'd be creating a lot of extra work for yourself without much benefit.


* Updated *

You can do this by overriding theme_button() in your theme. Note that the code here is copied from theme_button(), with the return value adjusted accordingly:

function THEMENAME_button($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled']))
  {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  if(isset($element['#search_button']) && $element['#search_button'])
  {
    return '<button' . drupal_attributes($element['#attributes']) . '><i class="fi-magnifying-glass"></i></button>';
  }
  else
  {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

Then you need to add #search_button = TRUE to the button in hook_form_alter()

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'MYFORMID')
  {
    $form['actions']['submit']['#search_button'] = TRUE;
  }
}

Note: This will render the button as requested. No guarantees that it will actually work with the Form API. That needs separate testing.


Returning the form in form_alter function

You can use it, sure. But it won't do anything.

The $form is passed by reference, precisely so that it can be altered in-place. Core never does anything with the return value from form alters, so there isn't much point doing it.

Your code looks right, put a drupal_set_message/dpm in the submit handler to confirm whether it's actually being called or not, or whether it's your one-liner that's not doing what you're expecting.


Views and CSS : how to exclude the exposed filters from CSS?

You could use the "Exposed form in block" setting under Advanced settings to get the exposed filter out of the masonry markup and put it a region above or beneath your masonry view.


Missing FieldItem properties while in entity::preSave()

I will answer my own question...

I am not sure when the property initialization comes to play but adding this code into my field item solved it. The get method will look for the property and initialize it if it does not exists with existing value which will result in the field returning correct data.

  /**
   * {@inheritdoc}
   */
  public function preSave() {
    $this->get('value');
  }


How to specify Google Chart API options for altering generated charts when using the views integration?

Finding an appropriate charting module

To create charts in Drupal, consider the Comparison of Charting Modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module (confusing names, I didn't invent them). Though there are other alternatives in that comparison that might be a better fit for this specific case.

Selection criteria

The license that comes with the related charting library (engine) in each of these modules, should be considered also (open source or not, license fee, etc). It is one of the (important?) selection criteria for deciding on the module to go for.

Some other typical items to consider are:

Possible privacy concerns.
Yes or no support for saving charts in PDFs (usually supported by PHP based libraries, and not supported by JS based libraries).
Flash based libraries should be avoided if charts are to be displayed on mobile devices.
Some libraries (like the Google flavors ...) require a working internet connection (not always available in local DEV environments ...).

Available options specific to the Charts module

The Charts module is possibly one of those "other charting modules" that you experimented with. For the Charts module, the currently closest answer (solution?) you can find is described in issue #2209467. And the closest solution to get this to work, is as described in comment #4 (which also includes an interesting patch). Be aware of the current status of that issue, i.e.:

the patch only works for Highcharts (as charting engine), the Google Charts counterpart of it is still missing (and prereq for adding this feature to the Charts module).
it is related to the Charts API (which is different from the Views integration). So after the Charts API feature gets delivered, some more (minor?) work is needed to also make it available within the Views integration of the Charts module.

So only considering the Charts module as an alternative, and applying the suggested patch is not sufficient. But at least it should help somehow to understand what the missing pieces are. And maybe inspire somebody to submit 1 (or more) additional patch(es) to make it complete?

Disclosure: I'm the author of the comparison and charting modules mentioned above, I hope this does not violate the site's policy on self-promotion.


How do I add unique page titles and meta titles to paginated views pages?

There are actually two modules:

the Meta tags module that is used to add meta tags to any pages

  The Meta tags module allows you to automatically provide structured metadata about your website. In the context of search engine optimization, when people refer to meta tags, they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of your site in search engine results.

the Page Title module that is used to set the title visible with the <title> tag

  This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.

the Title Overrides module

  Title Overrides is a module to provide title overrides for any page in as simple as an interface as possible. This module differs from the Page Title module in that this overrides both the <title> meta tag as well as the <h1> tag. You also have the option of entirely removing the page title from any page, which will remove the <h1> tags as well as remove the piping from the meta title. This improves search engine optimization for pages that have been overridden.

As far as I recall, there were some problems using the Meta tags module to set meta tags for views, but it can be they have been resolved, now.

The Title Overrides module seems the one you are looking for, as it overrides the content's title for any page.


Yes, make it a block. Assign it to a region on a particular page. When the user clicks the Apply button the view will be displayed.


cannot remove $base_url address from a link

You need to prefix http:// with your link. If you will not add prefix http:// with your link, Drupal will treat this as internal url of Drupal site.

So, you should add url http://www.google.com in your content.

Or you can use Link module to create a link field.

  With link module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


How do Pressflow Drupal sites handle user Cookies?

Cookies/sessions are handled by both Drupal and PHP. Drupal register some functions that PHP will call, when certain things need to happen, like destroying a users session. PHP handles most of the basic stuff and Drupal override some of it, store users sessions in the database.

I'm not familiar with Omniture but if it's anything like GA, a users session/cookie wont effect tracking at all. Cookies are used to identify the user, so they don't have to type in their username/password at every page. Without cookies, Drupal wouldn't be able to tell the users apart and would need some other form of identification, like a login for every new page load.

This is why, some people try to steal cookies, as that is the same as having the user log in and leave the computer, given the thief full access.


How can I escape the brackets so they are seen as literal characters

The problem wasn't the brackets—I was able to set the rule by referencing the nested #name and #value keys:

_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );


How do I sort by taxonomy term parent, and then by post date?

I think I found a way to do this--I added the "content: taxonomy terms on node" and "taxonomy term: parent term" relationships to the view.

The key is the "taxonomy term: name" criterion has a checkbox where I selected "parent", which appears only after you add the relationship.  I added the post-date sort criteria after that, and it appears to be working the way I want.


How to push form values to database in Drupal

You're not far off, a couple of things:

Creating a table like that in an init hook is definitely not recommended; Drupal provides hook_schema() so you can describe tables to the system. Uninstall and install your module again after implementing it and you'll see the table appear.
The reason your insert is failing is because you have a NOT NULL integer field which you're not providing (achvmntID). Drupal has the serial field type rather than an AUTO_INCREMENT key to get a serial field:

'achvmntID' => array(
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),


Drupal commerce display VAT exclusive unit price & subtotal for line item in cart and order

Finally I find this module: Commerce price by components

This is perfect for my requirement.

  Extension to Drupal commerce that provides a price formatter to enable/disable price components such as discounts or taxes when
  displaying prices. This gives the admin absolute control over which
  components should be displayed and which shouldn't. It also provides
  two Views handlers to display/hide price components in cart totals and
  order totals. Additionally it has basic rules support that gives to
  the commerce administrators the ability to do conditions using price
  components such as discounts or taxes and react accordingly.

  Example use case

  If you want to customize your cart or checkout views, you may want to
  display prices with taxes and without discounts (or viceversa) in your
  line items but the total amount should be displayed. Then you enable
  this module and choose at formatter level (both display fields and
  views) which components you want to hide or display.


Where to start for implementing user roles/levels?

Have a look at the Group module (a new module as of D7). It should address most (if not all) of your requirements. And it offers a potential alternative to the Organic groups module. Here is a quote from its project page:

  Organic groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).

  Group instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Some major differences between these 2 modules are:

Group started in D7 only, taking full advantage of entities introduced in D7.
Organic Groups is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases.
A D8 version of Group is in the pipeline and actively being worked on these days (expectation is "only a few months from now").

Additional Group sub-modules

Extra features can be enabled via these sub-modules:

  Group Add: Add members to a group without their consent.
  Subgroup: Make group to belong to another group.
  Group Invite: Allow group members to invite people into their group.
  Group Node: Enables Group functionality for the Node module.
  Group member profiles: Create multiple fieldable member profiles, which can be attached to a member.

Have a look at my answer to "How to create basic Organic Groups functionality with flags and references?" for way more details about it, such as available integration with other (commonly used) modules.


Force users to always log in and show no content

On the Structure > Blocks page, configure the Main Content block.  Within the Roles section, check Authenticated User.

Move the User Login block in the Content region.  This allows the Login screen to appear even if they are not logged in.

If you want to redirect them to the login page, you can install the Rules module and create a rule that whenever an anonymous user loads a page, and the page path is not user*, then redirect them to /user.


How can I embed the YouTube field module in a specific page?

Fields are designed to be attached to pieces of content (entities), especially the main content entities (nodes). Using youtube field, would mean you can attach a different youtube video to every type of content. This likely results in a textfield on every node edit page (of that certain content type) where you enter a URL or something.

If that is what you want, proceed happily. If you go to the manage display section of your content type you can alter the teaser view mode (switch in the right top) and remove the field from display so it does not show on the front page.

If that is not what you want and you only want one block to appear in a sidebar or something, go to the blocks page, create a new block and just paste the embed code there. Make sure to set the content filter to full-HTML so it does not get sanitized. Each block allows you to specify the URL's on which it should be displayed. (There is no need for this module)


How do I install the latest release of Drupal with Composer

composer create-project drupal-composer/drupal-project:8.x-dev \
  YOURDIRNAME \
  --stability dev \
  --no-interaction


How to change taxonomy term in field with Rules?

Question clarification

There is something in this question that I find bizarre: the requirement relates to "when an administrator downloads the file", but then the Rules Event mentioned is "content type viewed" (and combined with a Rules Condition "User has Role of Administrator").

Therefor I'm going to assume that "Content is viewed by a user who has the admin role" is an acceptable translation of "when an administrator downloads the file". With that in mind, read on about (a) what the reasons (multiple ...) are why it doesn't seem to work and (b) how to make this to work anyway ...

Mistake 1 - Use the correct token

The node:field-status is clearly a term reference field, which can, obviously, only have 1 possible value, which is one of these: uploaded, processing, admin hold, error, closed.

When you're using the Rules UI, in this case you should just use the token  [node:field-status], and NOT (repeat: NOT) [node:field-status:parent:1]. That explains '... when I test it, it changes the status to "none" ...' (as in the question).

Mistake 2 - Rules Condition 'Entity has field' is missing

From the Rules Conditions mentioned (only "user has role admin"), I'm about sure that there is a crucial additional Rules Condition that you would need ALSO to make this work. I.e. you need to tell the Rules module that you want to do something with the node:field-status field. I.e. you need to add a Rules Condition of "Entity has field" (related to that node:field-status field). Even though there are variations (other Rules Conditions), this "Entity has field" is what for me always seems to work when I want to do something with a field in Rules.

Using this Rules Condition is like ringing a bell for the Rules module to prepare for that, and have Rules already go retrieve the existing data about that field, so that you can (eg) test the existing value it contains (in a subsequent Rules Condition).

Mistake 3 - Rules Event 'Content is viewed' may be too late

Whatever you want to happen (via Rules), if you're using Rules Event 'Content is viewed', that you may simply be too late: the content is already being shown, so if the Rules Conditions or satisfied, what else do you want to happen. That is what 'Content is viewed' is all about.

If you didn't want to content to be visible at all (which does not seem to be the case here though), sorry, you're too late. If you did want something to happen BEFORE showing the content, then you should have used Rules Event "Drupal is initializing". Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this. And if you want the user to see the result of your Rules Action(s), a page refresh is needed for that.

Possible alternative

Here is a rule (in Rules Export format) that might possible be an acceptable alternative (solution) to answer this question, using field_demo_tags as the machine name of the term reference field and which I labeled "Demo tags" (adapt to fit your own machine name of your field before trying to import this rule):

{ "rules_update_taxonomy_term_of_a_node" : {
    "LABEL" : "Update taxonomy term of a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } },
      { "data_is" : { "data" : [ "node:field-demo-tags" ], "value" : "1" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "This is a node with value \u0022[node:field_demo_tags]\u0022 for field \u0022Demo tags\u0022 ..." } },
      { "data_set" : { "data" : [ "node:field-demo-tags" ], "value" : "2" } },
      { "drupal_message" : { "message" : "Be aware: the value of the \u0022Demo tags\u0022 field just got updated to [node:field_demo_tags] (refresh the page to see the updated version ...)" } }
    ]
  }
}

Some more details about it:

Rules Event: Content is viewed
Rules Conditions:

Entity has field, for field field_demo_tags.
The term id of the current value of the term must be the one for uploaded (adapt this term id to fit your case).
Current user has role Administrator.

Rules Actions:

Show a message (to confirm we have a hit, mostly for demo/debugging purposes).
Do your thing, i.e. update the term id to the value of the term corresponding to processing (adapt this term id to fit your case).
Show a message (to confirm we did our job, and suggest a page refresh).

For short: if a node is viewed by a user who has role admin, and the node has been tagged with the term with Term Id = "1" (which could be the equivalent of uploaded in the question), then the term will be changed to the term with Term Id = "2" (which could be the equivalent of processing in the question). Additionally, an informational message will be shown similar to this:

  This is a node with value "uploaded" for field "Demo tags" ...
  Be aware: the value of the "Demo tags" field just got updated to processing (refresh the page to see the updated version ...)

Voilà, 2 mistakes corrected, and a workaround for the 3rd mistake, which is hopefully acceptable ...


How to handle session for anonymous users for CSRF tokens?

So the solution to this problem is that something has to be saved into the session :)

  if (\Drupal::service('session')->isStarted() === FALSE) {
    \Drupal::service('session')->start();
    \Drupal::service('session')->set('foo', 'bar');
  }
  \Drupal::service('csrf_token')->get('baz');

Also, there is no need to call save() method.


How to hide a view if it has more than 1 row and also show some block if this is true?

Part 1

Enable the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

Part 2

As per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the number of rows returned by your view" (so that the block is only shown if the view has more then 1 row).

For that, perform these steps:

Use the Views Bulk Operations module to create a variation of your view in which you add a VBO field to it.
Create a Rules Component with a Rules condition "Check number of results returned by a VBO view". And select the VBO view created in the previous step.


Image field: mark an image as a "cover photo" with a radio button

One approach would be to use file entity and add a field to the image file entity, but that would require re-working your current solution quite a bit.

Another approach would be to use the

Field Attach API

e.g:

field_attach_form
field_attach_submit

to attach the additional field to the image. The field would then need to be checked during output to show/hide that image as the cover image.

Update:

Here's an example to add a checkbox to an image field. I had some settings on the instance form to show/hide the extra fields, removed for conciseness here. You may be able to use hook_field_attach_form though I used a element process hook instead.

/**
 * Implements hook_element_info().
 */
function MODULE_element_info() {
  $extra = array(
    '#process' => array('MODULE_element_process'),
  );

  $elements = array();
  // Add our process function to all managed_file elements
  $elements['managed_file'] = $extra;

  return $elements;
}

/**
 * An additional preprocess callback to append the form.
 */
function MODULE_element_process($element, $form_state, $complete_form) {

  if (!isset($element['#entity_type']) || !isset($element['#field_name'])) {
    return $element;
  }

  // You can get the field data, settings etc.. like this
  $item = $element['#value'];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
  $settings = $instance['settings'];
  $widget_type = $instance['widget']['type'];

  // Add element, only if file id available
  if ($element['fid']['#value']) {
    // Note default value selects from cache / db table TABLE_file_data
    $element['cover'] = array(
     '#type' => 'checkbox',
     '#title' => t('Cover'),
     '#default_value' => MODULE_file_data_value($element['fid']['#value'], 'cover', '')
    );
  }

  return $element;

}

/**
 * Implements hook_field_attach_presave
 *
 * Saves a files additional field data.
 */
function MODULE_field_attach_presave($entity_type, $entity) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $supported_widgets = array('image_image', 'imagefield_crop_widget');
  $instances = field_info_instances($entity_type, $bundle);
  foreach ($instances as $field_name => $instance) {
    if (in_array($instance['widget']['type'], $supported_widgets)) {

      $settings = $instance['settings'];
      // I have some settings I check as well, if enabled on field instance..
      //if (empty($settings['display_cover'])){
      //  continue;
      //}
      // Find all of the field items.
      $items = field_get_items($entity_type, $entity, $instance['field_name']);

      if (is_array($items)) {
        // Loop over and save extended field values
        foreach ($items as $delta => $item) {
          $fields = array();
          if (!empty($item['fid'])) {
            if(isset($item['cover'])){
              $fields['cover'] = $item['cover'];
            }
            $fields['changed'] = REQUEST_TIME;
            db_merge('TABLE_file_data')
              ->key(array('fid' => $item['fid']))
              ->fields($fields)->execute();
            // Need to clear entity cache for this file
            // as update was not with api but direct query
            cache_clear_all($item['fid'], 'cache_entity_file');
          }
        }
      }
    }
  }
}


Theres a widget called "OG members" that could help you.

When in a space, you have this button to personalize the display. Click it then you can add widget (the '+' button). In the new window, you can find widgets that you can add and configure as you need.
Theres one called 'OG Members' in the category called (I think) 'Panel panes'.
I think this widget is meant to display members of the space you visiting


It looks like your predecessor used jotform to set this up, see this screenshot:

If I am right, then you should be able to edit these values via the related jotform account.
Hope this does it for you, it seems you need the get those jotform credentials for the linked jotform account!


Backup & Migrate: Restored changes lost after clearing cache

Sorry, but your approach is wrong.

If things gets to disappear after cache clear, you have some serious bug in your implementation.

You should exclude all cache tables from migration.
After migration, you should clear cache of recipient site.

If your procedure is different, it's buggy. Details may vary but these two points are pretty much needed for consistent workflow.

If one of your sites generates different menu than the other after cache clear, then you failed to migrate some files that provide hook_menu or hook_menu_alter, or you have a problem with migrating menu data in database. Either way, disable cache for migration, don't ever try to rely on migrated cache.


This explains how I did something similar. You'll just need to adjust your selectors to hide the price as well as the add to cart button...

Step 1 – Create New “Product Status” Field

Go to  Administration > Store settings > Product settings > Variation types and select “Manage Fields” for the variation type you want to modify (I just use the default “Product” variation type for my site). Add a new field called “Product Status” of the type “List (text).” For “Allowed values list,” I entered the following because it occurred to me the client might want similar display-but-don’t-sell functionality for upcoming releases…

soldout|SOLD OUT
comingsoon|COMING SOON
Of course you can just include the sold out line if you prefer. The string before the pipe is the machine name and the part after the pipe is what will display. Save your changes. Now go to “Manage Display” for the product variation type and add the new field for any display types you use for your products. I just use the default and teaser display types on my site. Remember to adjust the label settings (I’m guessing you want “hidden”) and to order the field so it displays relative to other fields as you desire. Save your display changes.

Step 2 – Set Products to Product Status = SOLD OUT

Go to Products > Manage Products and edit your sold out products, setting the new status field to SOLD OUT as appropriate. Note: this is the only step the client will need to do in the future whenever he runs out of a certain product…

Screen Shot 2013-09-24 at 4.59.24 PMSave your changes.

OK – we’ve created a mechanism for indicating when something is sold out, but this doesn’t prevent site visitors from adding sold out items to their carts. Probably nobody would try to put these items in their cart, but you never know. I certainly don’t want my client to have to hassle with issuing PayPal refunds, so I’m going to make sure these products can’t be added to the cart. It seems to me the easiest way to do this is to use jQuery to remove the add-to-cart button for sold out products.

Step 3 – jQuery to Remove Add-to-Cart Button From Sold Out Product Displays

The following jQuery script simply looks for the class that wraps my Product Status (“field-name-field-product-status”): if it finds the class, it removes the Add-to-Cart form for that product. This works because Drupal’s default behavior is to not render the field and its wrapper classes if there is no data to display. In other words, only products I set to “Sold Out” (or “COMING SOON”) will have this field and class. I reiterate this technique because there are two possible display pages for products on my site (full and a teaser view), and each has a different DOM that needs to be traversed differently. You will almost certainly need to adjust my selectors for your particular needs (browser developer tools, firebug or just viewing the page source will guide you)…

/*Script for Gench product pages - removes add-to-cart button/form if product is sold out*/
/*wrap everything in a safety  "no-conflict" function so dollar sign works*/
(function($){
/*wait until page is fully loaded before firing script*/
$(document).ready(function(){
        /*remove add-to-cart button if product has status of sold out - for product display page*/
        $(".field-name-field-product-status").closest("td.views-field").find("form.commerce-add-to-cart").remove();
        /*remove add-to-cart button if product has status of sold out - for product teasers page*/
        $(".field-name-field-product-status").closest("div.content").find("form.commerce-add-to-cart").remove();
    });
})(jQuery);
Because I was already using javascript on my product pages, I just added the above script to the existing script, so I don’t have to do anything additional to call the new script. If you write this as a stand-alone .js file in your sites/all/themes/themename directory, you’ll need to reference the script which can be done globally in your theme’s .info file, or for select content, in your theme’s template.php file. For example…

function genchstyle_preprocess_page(&$variables, $user) {

  if(arg(0) === 'productdisplay' || 'store') {
    drupal_add_js(path_to_theme().'/js/soldout.js');
    $variables['scripts'] = drupal_get_js();
    $scripts = drupal_get_js();
  }
}

Here is what a product looks like when it is in stock (full display)…

And this is what it looks like when it is no longer in stock…

Again, you probably want to go with an actual inventory control module/approach for bigger/busier sites, but this kluge works pretty well for my purposes (and doesn’t preclude adding the Commerce Stock module later should the need arise).

Cheers


How to show each type of content-types just one time?

I hope I understand your question. Do you want to use the Type of the node as header for a collection of nodes?
So:

Sport
Node 1
Node 2
Node 3

Health
Node 4
Node 5

Economy
Node 6

What I would do is use the Views field view module. First make a view for all three groups, so you have three views one for Sport, one for Health and one of Economy. Give them all a header with the Type name. Then add all these views to one view with this module.


Drupal 8 how to show entity reference field in views exposed filter as select list?

How about the Views Entity Reference Filter module? The module is also capable of showing the values of the referenced entities in a filter instead of the IDs.


I have solved the problem by reverting to a older version of the database. I haven't been able to trace the real cause of the problem.

It had something to do with "Backup and Migrate" module, because that was the only real change between the versions.


You can create a node reference view. Check this answer for more information:
Display language in entity reference field

You can either limit your entries in the reference field or show the language in every entry.


What can I do to remove this entity definition from the database?

First solution (the best one if you can) (thanks @Clive) :

Put the deleted code back
Uninstall the module
Reinstall the module with the new code

Second solution (ugly, but worked for me)

Open your favorite SQL client (adminer in my case)
Search for your entity id in all tables
Remove all matching entries
Clear the cache


How do I create a form in a modal dialog with Drupal 7?

A good example for using forms on modal dialogs is in Ajax Login/Register module. You could see the module code and understand how it works(ajax_register is using ctools_modal).

Or you can render the form manually and use ctools only for the responses. For example:

mymodule.module:

function mymodule_form($form, &$form_state) {
  ...
  ctools_include('ajax');
  ctools_add_js('ajax-responder');

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'container',
  );
  ...
}

function mymodule_ajax_callback($form, $form_state) {
  if (!form_get_errors()) {
    $commands   = array();
    $commands[] = ctools_ajax_command_reload();

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

  return $form;
}

Now, you can anywhere render this form and show popup (using Twitter Bootstrap or Lightbox):

Show Form

<?php print drupal_render(drupal_get_form('mymodule_form')); ?>


You can check for a certain type of line item on an order using one of the two following methods.

Given an order, let's look for a shipping line item.

// Load your order.
$order = commerce_order_load(/* Order ID */);

Without Metadata Wrappers

if (!empty($order->commerce_line_items)) {
  // Iterate over the line items.
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item_data) {
    $line_item = commerce_line_item_load($line_item_data['line_item_id']);
    // Check the type.
    if ($line_item->type == 'shipping') {
      // Shipping line item found. Do the things.
    }
  }
}

With Wrappers

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Iteration is a bit simpler here.
foreach ($order_wrapper->commerce_line_items as $line_item) {
  // We have to access it using ->value().
  if ($line_item->type->value() == 'shipping') {
    // Shipping line item found. Do the things.
  }
}


Clearing Acquia Varnish Cache when any content gets updated

Not sure if this module would work for you, https://www.drupal.org/project/acquia_flush_varnish

Another module that you could check, https://www.drupal.org/project/acquia_purge

If neither one works, you can leverage Acquia's API.

Here's some info on Varnish from Acquia, https://docs.acquia.com/cloud/performance/varnish
Here they talk about the endpoint, https://docs.acquia.com/cloud/performance/varnish/purging#api

  DELETE /sites/:site/envs/:env/domains/:domain/cache

An example from them,

  curl -s -u user:pass -X DELETE \
  https://example.com/v1/sites/site/envs/prod/domains/example.com/cache.json

A example that only resets a specific page is listed here, https://docs.acquia.com/cloud/performance/varnish/manually-purge

  # Replace 'sitename' below with the appropriate value.
  curl -X PURGE -H "X-Acquia-Purge:sitename" -H "Accept-Encoding: gzip" http://example.com/path/to/page

A module that executes that when saving nodes, or a particular content type, should be easy.


Need a textfield required only when selectlist is set to 'Approved' within custom content type

Field Conditional States will help you modify the look of the field: it will make it appear or disappear, or will add the red asterisks to make it look required. But as you noticed, making it look required is not the same thing as making it required. What I have done is using a combination of Field Conditional States to change the look of the field, AND Field Validation to actually make it required (so that the form returns the "Field required" error message when submitted). Field Validation has a way to return the error by checking that the field is not empty, AND checking if a different field in the form has a particular value. You need the "PHP code" type of validation for this. Take a look at the documentation for this module's PHP code option.


Well, what you want to achieve ... Eg, output a horizontal list of links with "pipes" between them can be done in Drupal with the HTML and CSS drupal provides you.

What you need to refer to is a book on CSS.

A random Google of this technique yields:
http://jamesowers.co.uk/css-tutorials/50/horizontal-css-list-menu/

In a nutshell, you want to set the list-item as relative and to display inline in CSS. Give them some spacing and for instance add a right-border to every list item with your color choice. Then if you really want using a CSS/Jquery selector of :last-child remove the trailing right border if it bothers you.

If you are intent on rewriting and bending the HTML and CSS to your will because the above approach elludes you .... you can do 1 of 2 options:

1) using the http://drupal.org/project/devel_themer you can find the specific block in question within your theme. You can then alter the necessary template file(s) in drupal to alter the HTML produced from Drupal to meet your criteria. Menus are shown in blocks on the page. So you could find the theme function for the menu in question and override its output in your theme. Devel_theme should be able to tell you the correct function to override if your's isn't working.

Or you could create a really silly function like below in your template.php file and call it as needed from your .tpl files. The below code relies on the http://api.drupal.org/api/drupal/includes--menu.inc/function/menu_tree_all_data/7 function to pull a menu's items by the menu-name. See the linked API page to find out how to find out what specific menu in drupal you want to load ... then we simply create the HTML from the menu links as in the function. I really really dont recommend you do this. Either learn CSS and Jquery to render the default content drupal provides you with to appear as you want, or learn how to change the template files gracefully ...

/*
What does menu_tree_all_data() return ... well let's see below:

$ drush eval 'print_r(menu_tree_all_data("main-menu"));'Array
(
[49950 Home 240] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 240
                [plid] => 0
                [link_path] => <front>
                [router_path] =>
                [link_title] => Home
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 1
                [has_children] => 0
                [expanded] => 0
                [weight] => -50
                [depth] => 1
                [customized] => 1
                [p1] => 240
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] =>
                [access_arguments] =>
                [page_callback] =>
                [page_arguments] =>
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] =>
                [title] => Home
                [title_callback] =>
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] =>
                [type] =>
                [description] =>
                [in_active_trail] =>
                [access] => 1
                [href] => <front>
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

[49951 Student Login 239] => Array
    (
        [link] => Array
            (
                [menu_name] => main-menu
                [mlid] => 239
                [plid] => 0
                [link_path] => student/login
                [router_path] => student/login
                [link_title] => Student Login
                [options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

                [module] => menu
                [hidden] => 0
                [external] => 0
                [has_children] => 0
                [expanded] => 0
                [weight] => -49
                [depth] => 1
                [customized] => 1
                [p1] => 239
                [p2] => 0
                [p3] => 0
                [p4] => 0
                [p5] => 0
                [p6] => 0
                [p7] => 0
                [p8] => 0
                [p9] => 0
                [updated] => 0
                [load_functions] =>
                [to_arg_functions] =>
                [access_callback] => 1
                [access_arguments] => a:0:{}
                [page_callback] => _dew_auth_login_page
                [page_arguments] => a:0:{}
                [delivery_callback] =>
                [tab_parent] =>
                [tab_root] => student/login
                [title] => Student Login
                [title_callback] => t
                [title_arguments] =>
                [theme_callback] =>
                [theme_arguments] => a:0:{}
                [type] => 6
                [description] =>
                [in_active_trail] =>
                [href] => student/login
                [access] => 1
                [localized_options] => Array
                    (
                        [attributes] => Array
                            (
                                [title] =>
                            )

                    )

            )

        [below] => Array
            (
            )

    )

)

*/

function i_dont_advise_this($menu_name) {
  $data = menu_tree_all_data($menu_name);
  $links = array();

  foreach($data as $MenuItem => $item) {
    $links []= l($item['link']['title'], $item['link']['link_path']);
  }
  return implode('|', $links);
}

print i_dont_advise_this('main-menu');
# yields =>
# Home|Student Login


Domain Access and mother website arguments

If you have installed the Domain Access module, you will have the Domain Access Views module available. First thing you want to do is enable that module if you haven't already.

Once you've done that, you can use the current domain as a filter:

Under Filter Criteria, add "Domain Access: Domain ID"
"Operator" is one of "Current Domain"

Now the view will only return nodes for the domain that the block/page is loaded from.


Why Calling the theme path in a multinlingual site adds a language prefix?

You can use base_path() and drupal_get_path('theme', 'yourthemename') functions to get correct path.

Example:

$output = base_path() . drupal_get_path('theme', 'yourthemename');

Result:

/sites/all/themes/yourthemename


How to use Services to create new node with Entity Reference field?

I figured out the solution from comments on this issue.

To set the field via services, you can set the field's widget type to "autocomplete" and instead of just sending the nid, send a string with the title of the referenced node, a space, and the nid inside parenthesis.

'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 'Title of Node (123)'
        }
    ]
}


There is a field available in views called "Comment count" - just add this field and your done.


Problems creating a custom blank page with my custom module

You can output the html of one twig only in a symfony response:

use Symfony\Component\HttpFoundation\Response;

public function my_page_controller() {

  $build = array(
    'page' => array(
      '#theme' => 'videoPage',
      '#content' => $content,
    ),
  );
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response = new Response();
  $response->setContent($html);

  return $response;
}


How to write a WHERE clause with the '=' operator using db_select()?

db_select('field_revision_field_innostream_state', 'innostream')
  ->fields('innostream')
  ->condition('innostream.field_innostream_state_tid', 187, '=')
  ->range(0,30)
  ->execute()
  ->fetchAssoc();


Is it possible to remove Route objects from a RouteCollection object?

There is also a RoutingEvents::ALTER event, which runs afterward.

You can think of the difference between RoutingEvents::DYNAMIC and RoutingEvents::ALTER as similar to the difference between hook_menu() and hook_menu_alter().

There is a Views issue that discusses replacing routes, as opposed to removing and adding them, perhaps follow their example.


I am trying to create user registration form in js which beautiful and flexible

You can do it by using these modules :

Fancy Login

  Fancy Login adds javascript based, lightbox-style login functionality
  to your site. When the user clicks on any link that links to
  /user/login, they screen dims and a login box is created in the center
  of the screen.

Better Login

  Styling Drupal login/password/registration forms are a mission most of
  the time because they form part of the theme... This module removes
  that issue, it is slightly inspired by the way Wordpress login forms
  work, and uses three page templates to change the style of the forms.
  It is very simple to use, just install the Better Login module and it
  starts working immediately.

Model Form

  Modal forms make use of the modal feature in the ctools module to open
  some common forms in a modal window.


Node access doesn't consider translation

You can just call getTranslation like this:

$node_translation = $node->getTranslation('LANGCODE');


Import xml with Feeds from a folder outside site directory

yes you were right the correct way is to add in file system configuration (/admin/config/media/file-system) a private file system path that you need "/var/lib/jenkins", and then use it in your feed fetcher with prefix private://.

Please if it is possible move yor files form /var/lib to a user subfolder to avoid security problems.


Drupal commerce payment callback endpoint

so - this sounds like an IPN (instant payment notification), commerce payment does not handle that, so you have to pass the ipn url defined in hook_menu to your gateway in the specific parameter when submitting the _redirect_form, or setting it in your gateway configuration - depends on the gateway ..

/**
 * Implements hook_menu().
 *
 * adds the callback uri
 */
function YOUR_MODULE_menu() {
  $items = array();

  // Define an always accessible path to receive IPNs.
  $items['some_uri/IPN/%'] = array(
    'page callback' => 'your_module_process_ipn',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

so - your ipn looks like this httpx://example.domain/some_uri/IPN/What/ever
maybe that the What/ever is set by the gateway. if nothing is set, adjust the item in hook_menu !

then your callback function does take the action, like:

/**
 * Processes an incoming IPN.
 *
 * @param $uri
 *   dynamic URI
 * @param $debug_ipn
 *   Optionally specify an IPN array for debug purposes; if left empty, the IPN
 *     be pulled from the $_POST.
 *
 */
function commerce_postfinance_process_ipn($uri = NULL, $debug_ipn = array()) {
  $ret = 'IPN failed';
  if (ipn_valid($uri, $debug_ipn)) {
    $ret = 'IPN OK';
  }

  print $ret;
  exit(0); // hook_exit will not be invoked !
}

and in the ipn_valid function you access the $_POST array.

  don't forget to create a commerce payment transaction if the ipn is
  OK.

refer the paypal wps module for this (see funciton commerce_paypal_wps_paypal_ipn_process)


Need tags to update taxonomy list terms automatically?

A path is the name for the term or article.  Giving a tag an alias that matches an article (or vice versa) is not creating an override to reroute the display. To link a term to an article, you will want to add a field to the content type (article) that is based upon the vocabulary. You access this through admin/structures/content type/manage fields/add.


hook_tokens_alter() not applying to [user:one-time-login-url] Token

You cannot alter it because that token is not returned from user_tokens(). You get that token only with code similar to the following one.

$text_with_tokens_replaced = token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));

The problem is that first the implementations of hook_tokens_alter() are called, then the callback passed to token_replace() is called. The effect is that every value you set for that token is then changed from the callback.

This is the code used from token_replace().

  $replacements = array();
  foreach ($text_tokens as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

token_generate() is the function invoking the token hooks (including the alter hooks).

  $replacements = module_invoke_all('tokens', $type, $tokens, $data, $options);

  // Allow other modules to alter the replacements.
  $context = array(
    'type' => $type,
    'tokens' => $tokens,
    'data' => $data,
    'options' => $options,
  );
  drupal_alter('tokens', $replacements, $context);


Remove choice for user delete from Roles which can adminster the Users

I would start by creating a custom module and try using hook_form_alter.

function MYMODULE_form_alter(&$form, $form_state, $form_id)  {
  switch ($form_id)  {
    case 'user-multiple-cancel-confirm':
        // ALTER STUFF.. user dsm($form) to show available fields.
        break;
   }
}

Using

global $user;
$roles = $user->roles; // Array with user assigned roles

you can check the array for the Supervisor role.


You shouldn't query the database directly for entity data, there are APIs for that.

In this case you need an EntityFieldQuery:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'team_member')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_last_name', 'value');

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}


Allow users to use embedded HTML tags in custom blocks

The W3C specs (https://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#the-button-element) show that a button allows phrasing content (https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content), e.g. a <span> to be placed inside a <button>, but not a <div>, so your WYSIWYG editor is correctly rearranging the elements.

Perhaps you could rework your code to allow for a <span> to be used inside the <button> and style that instead.


Override specific routing from a core module

You can override route details in a route subscriber:

src/Routing/RouteSubscriber.php:

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('forum.index')) {
      $route->setRequirement('_user_is_logged_in', 'TRUE');
    }
  }

}

example.services.yml:

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

See Altering existing routes and adding new routes based on dynamic ones

If you want you can also replace the core classes with your own classes. You can have multiple routes for one class. Then you don't need a redirect.


Use custom module template for content type page?

page.tpl.php doesn't know, by itself, anything about node types so you'll have to make your module preprocess the page with hook_preprocess_HOOK() to add an alternative theme hook suggestion.

function MYMODULE_preprocess_page(&$variables) {
   if (isset($variables['node']->type)) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
    }
}

Once done, you can have your module evoke hook_theme() to advertise processing for your custom page node type template and its location. For example:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['page__mynodetype'] = array(
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
    'template' => 'page--mynodetype',
  );
  return $theme;
}

When the module is enabled (and theme registry cache cleared), the theme engine will look for page--mynodetype.tpl.php within the templates directory of your module.


restrict profile field to module and admin in drupal 6

Yep, you got it right.

Inside the profile.module's profile_view_profile() function, it uses the following logic when modifying $user to include the additional fields for viewing...

// Show private fields to administrators and people viewing their own account.
if (user_access('administer users') || $GLOBALS['user']->uid == $user->uid) {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
}
else {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE, PROFILE_HIDDEN);
}

...so yes, settings fields to PROFILE_HIDDEN will show them only to users with the administer users permission and/or to the user who is viewing his/her own account.

When editing a user, the module calls upon the _profile_get_fields() function to present the fields to be edited on the resulting form, and there, it uses the logic...

if (!user_access('administer users')) {
  $filters[] = 'visibility != %d';
  $args[] = PROFILE_HIDDEN;
}

...to restrict the editing of these fields to just users with the administer users permission by filtering out those fields from users without that permission.

And, of course, if your module or theme wants to edit anything in the database directly, there is nothing to really stop it.


"The website encountered an unexpected error." on front page only

Your subquery is returning null, that's why the main query is unable to find entity_id from it. I think you have a wrong query somewhere in your some function, with wrong condition.. Look at this line - WHERE (node.nid = :db_condition_placeholder_0) and actual placeholder - [:db_condition_placeholder_0] => -1 - entity id can not receive negative value. You can install Devel module, enable query log from devel settings page, log in as authenticated user and see what function calls this query..


How do I remove the site name from the head title in drupal 8?

Until metatag's module port has not finished you should code a bit for doing that.

If I were you I'll edit YOURTHEME.theme file and add this:

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function YOURTHEME_preprocess_html(&$variables) {
    unset ($variables['head_title']['name']);
  }


Invalid argument supplied for foreach() error in a custom view

I fixed it..anyone using views hacks will need to nest the above statement in an php if statement to ensure there is data in the array.


How can I add multilingual taxonomy breadcrumbs?

You can do this by making a content pane in Views.  Here's what you need to do.

For hierarchical taxonomies, determine the maximum depth.  Example: United States -> Illinois -> Chicago (child, parent, and grandparent)
Create a view showing fields of taxonomy terms.  Add a contextual filter: Taxonomy term: Term ID.  For When the filter value is NOT available, choose Provide default value of Taxonomy term ID from URL and leave Load default filter from term page checked.
Add a relationship of Taxonomy term: parent term.  Do this as many times as you need to get to the maximum possible depth.  Do not require the relationship because the term may be a root term.  To make sure that you can keep track of all the relationships even though they will be of the same type, when adding the relationship, click More at the bottom of the add dialog and type in an appropriate name (parent, grandparent, great-grandparent, etc.) for the Administrative title.
Add the taxonomy term name field (the one provided by the Title module, since we are using Entity translation).  Don't use a relationship.  As the administrative title, set "current page term" or something easy to remember.
Now to get the parent and grandparent terms.  First, add a term id for each relationship (parent, grandparent, etc.)  Make sure to uncheck create a label and check Exclude from display.  Make sure to set the proper relationship for each tid.
Then, add the taxonomy term name field again as many times as necessary so that you have a name field for each relationship.  Again, make sure to set the relationship each time you add a new field.  Also, for each term name that has a relationship, make sure that Hide rewriting if empty is checked under No results behavior.  Under Rewrite results, check Output this field as a link and enter taxonomy/term/[tid] where [tid] is the replacement pattern for the appropriate relationship.
Reorder the fields from "oldest" (grandparent) to "youngest" (current term).
Under Format, click Settings next to Fields.  Check the boxes next to all of the non-tid fields to make them inline fields.  Add the separator of your choice and you're done!


How to set permission to ALWAYS be full on for administrator?

Did you try to set Administrator role /admin/config/people/accounts?


If you are exporting and importing your configuration, you can simply re-import config from your last export. If you are not doing that already, you should definitely learn how to do so.

If you don't have the view exported, one way to get it back is to create another Drupal 8 site in your local development environment and then go to the config single export page (/admin/config/development/configuration/single/export) and choose Configuration type View and Configuration name Glossary.

Then go to your other site and choose "Import" and import the code.

For reference, here is my export (Drupal 8.4-rc2):

uuid: 350860b2-753f-4774-b504-5cc14b62c099
langcode: en
status: false
dependencies:
  config:
    - system.menu.main
  module:
    - node
    - user
_core:
  default_config_hash: '-pCFOVfbt__jaohFffTLnVavh4OBC6CjREAnchiRomQ'
id: glossary
label: Glossary
module: node
description: 'All content, by letter.'
tag: default
base_table: node_field_data
base_field: nid
core: '8'
display:
  default:
    id: default
    display_title: Master
    display_plugin: default
    position: 0
    display_options:
      query:
        type: views_query
        options:
          query_comment: ''
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_tags: {  }
      use_ajax: true
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: mini
        options:
          items_per_page: 36
          offset: 0
          id: 0
          total_pages: 0
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: ‹‹
            next: ››
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: Title
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: title
        name:
          id: name
          table: users_field_data
          field: name
          label: 投稿者
          relationship: uid
          plugin_id: field
          type: user_name
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: user
          entity_field: name
        changed:
          id: changed
          table: node_field_data
          field: changed
          label: 前回の更新
          type: timestamp
          settings:
            date_format: long
            custom_date_format: ''
            timezone: ''
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: changed
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: default
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: default_summary
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          summary_options: {  }
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          plugin_id: standard
          relationship: none
          group_type: group
          admin_label: author
          required: false
      style:
        type: table
        options:
          columns:
            title: title
            name: name
            changed: changed
          default: title
          info:
            title:
              sortable: true
              separator: ''
            name:
              sortable: true
              separator: ''
            changed:
              sortable: true
              separator: ''
          override: true
          sticky: false
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
          order: asc
          summary: ''
          empty_table: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      header: {  }
      footer: {  }
      empty: {  }
      sorts: {  }
      filters:
        langcode:
          id: langcode
          table: node_field_data
          field: langcode
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value:
            '***LANGUAGE_language_content***': '***LANGUAGE_language_content***'
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: language
          entity_type: node
          entity_field: langcode
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  attachment_1:
    id: attachment_1
    display_title: 添付
    display_plugin: attachment
    position: 2
    display_options:
      query:
        type: views_query
        options: {  }
      pager:
        type: none
        options:
          offset: 0
          items_per_page: 0
      defaults:
        arguments: false
      arguments:
        title:
          id: title
          table: node_field_data
          field: title
          default_action: summary
          exception:
            title_enable: true
          default_argument_type: fixed
          default_argument_options:
            argument: a
          summary:
            format: unformatted_summary
          summary_options:
            items_per_page: 25
            inline: true
            separator: ' | '
          specify_validation: true
          glossary: true
          limit: 1
          case: upper
          path_case: lower
          transform_dash: false
          plugin_id: string
          relationship: none
          group_type: group
          admin_label: ''
          title_enable: false
          title: ''
          default_argument_skip_url: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          entity_type: node
          entity_field: title
      displays:
        default: default
        page_1: page_1
      inherit_arguments: false
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: glossary
      menu:
        type: normal
        title: Glossary
        weight: 0
        menu_name: main
        parent: ''
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }


Prevent users from including their username in their password

I found that the Password Policy module actually does have an option to prevent the user from including their username in their password. The broader issue about how to restrict arbitrary strings from a user's password still stands though.


Drupal 8: javascript not loading in theme

Change

$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

to

Drupal.behaviors.basic = {
   attach: function (context, settings) {
   (function($) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
   })(jQuery);
  }

};


How do I get the name of the content type?

Try calling this function

node_type_get_name($node)

  Returns the node type name of the passed node or node type string.


After submission of a webform block how to replace that webform block with thank you message in the same page?

If you have the webform set as a block, you can go to admin > structure > block. Look for your webform block. It should be named something like Webform: 'name of webform node'. Click on the configure link to the right. When the edit form for the block loads, look for the section Confirmation message. Select the option Display the confirmation page in the block on the same page (no redirect). Now when you submit the form from the block, it will redirect back to it and show the confirmation message on reload.

You may need to fill out a message in the webform settings. I have attached an image of the edit block page for you to compare.


Using node_view() to display a node doesn't print local menu items

Yes this is expected. The reason they are there, is because the path of view a node is at node/[nid] and the edit/view is at node/[nid]/edit. If you changed the default node path with hook_menu_alter the tabs on all nodes would disappear.

The reason they are there, is because they are of type, MENU_LOCAL_TASK, check out the documentation on hook_menu, if you need to know more.


View: How to make a list of article(in a block) related to the taxonomy term of my main article

i've just found the perfect solution for me.

I tried a lot of solution with some php code but without success.

The problem was : I had one view which display an article (with a taxonomy vocabulary) and i wanted to add a block with a list of link of another content type who are linked with the same taxonomy term.

URL: www.example/product/[nid]/[title]

Contextual filter

Contextual filter: Content nid
WHEN THE FILTER VALUE IS NOT AVAILABLE :  raw value from URL (path -> 2 to retrieve the node id)

RELATIONSHIPS

Content: Taxonomy terms on node (with Require this relationship)
(term) Taxonomy term: Content with term  (with Require this relationship) -> Relationship -> Taxonomy terms on node

And after you have to come back to the contextual filters:

And add a Relationship to Taxonomy term: Content with term

Now it works great, i have all my other content type with the same term of taxonomy linker to the term of the main article display by view on my page.


check the (http://drupal.org/project/entity_translation) module   and also read this  https://drupalcommerce.org/discussions/820/how-do-i-setup-multilingual-products

https://www.drupal.org/documentation/modules/translation


Is it correct to directly modify a supplied Drupal theme?

No, it's not correct to directly modify a contrib theme (or Drupal core, or a contrib module). Once you start doing that, you cannot easily update the theme anymore. It a few months, you, or another, developers may forget the theme was modified, do what should be a easy update and break everything.

You have two options to change and existing theme. You can rename the theme before making any other change (ie. fork the theme to a custom theme). You can also create a sub-theme of your chosen theme. The sub-theme can override template and theme functions, and adds ins own process and pre-process functions. But it will inherit all non-overridden templates and theme functions and all process and pre-process functions.


How to create a custom payment page attached to a user account's form

I think that this site will tell you what to do:

Setting up payment methods

You shall download one of the modules to get a list of services.


Url component is not able to generate URLs with empty anchors, so you need  create an anchor on your page or use existing one.

use Drupal\Core\Link;
use Drupal\Core\Url;

$url = Url::fromUserInput('#main-content');
print Link::fromTextAndUrl(t('Link text'), $url)->toString();


How can I create a new user—with Profile 2 fields—programmatically?

I load the profile object:

$profile = profile2_by_uid_load($user->uid, '<role type here>');

Then I edit the $profile object.

I have a Rules component that saves the profile object. I forget why I have the rule but I remember that it requires quite a bit of code and database queries to get it right.

I set the Rules component to take the $profile object as an argument / parameter and invoke it like this.

    rules_invoke_component('rules_machine_name_this_is_the_component_url_too', $profile);


Form Validation. Ensure Placeholder is not submitted value

In your code these two lines may make issue. remove/comment these lines and try.

$form['field_first_name']['und'][0]['value']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'First Name';}";
$form['field_first_name']['und'][0]['value']['#attributes']['onfocus'] = "if (this.value == 'First Name') {this.value = '';}";


How to get block layout programmatically?

You can get the block layout programmatically from the configured blocks by going through each region defined in the current theme:

  $block_layout = [];
  $theme = \Drupal::theme()->getActiveTheme();
  $regions = $theme->getRegions();
  foreach ($regions as $region) {
    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block')
      ->loadByProperties(['theme' => $theme->getname(), 'region' => $region]);
    uasort($blocks, 'Drupal\block\Entity\Block::sort');
    $block_layout[$region] = array_keys($blocks);
  }

This is without checking if the blocks are visible on the front page. That would be difficult, because the visibility condition plugins are context aware and only provide a correct result when they are called in a real front page context.


Entity reference or viewfield for Drupal8: How to embedd views output in my node?

I solved the problem by myself:

I use the modules Twig tweak and Twig input filter

to solve the problem above in Drupal 8. Works fine.


10,000+ nodes vs. 1 node with 10,000+ field collection items

Loading 1 node with like 10,000+ field collection items sounds like performance suicide if you don't limit the amount of items being loaded and displayed initially. And having to open a node with 10,000+ field collection items only to maybe add or edit one item will be really big pain then.

With nodes, much likely you'll never display all of them at once. You very likely will have them organised in Views. Limited display, pagers, filters, lots of caching possibilities. When you want to add a node, you'll have a fresh node form, loaded in milliseconds. Plus you will have a much larger number of contrib modules available dealing with sortability, searchability, orderability and a lot of other -abilities that come in handy when organising content. Also when it comes to content import.

Go for 10,000+ or even 1,000,000+ nodes. That's what Drupal is made for.


How to create a controller that runs query?

@asrob,
Please refer the basic docs provided by Clive to create a controller in drupal 8 with route to access the same or
this link to create a custom module in drupal
and follow this sample code below to display your data in table format along with a pager:

  <?php

  /**
   * @file
   * Contains \Drupal\custom_module_name\Controller\DetailsController
   */

  namespace Drupal\custom_module_name\Controller;

  use Drupal\Core\Controller\ControllerBase;

  /**
   * Description of DetailsController
   *
   * @author aaditya.walawalkar
   */
  class DetailsController extends ControllerBase {

    const RECORDS_PER_PAGE = 10;

    /**
     * {@inheritdoc}
     */
    public function getRecords() {

      $records = $query_result_from_query;

      // total records
      $totalRecords = $total_records_count_from_query;
      $recordsPerPage = self::RECORDS_PER_PAGE;
      // initialize pager
      $page = pager_default_initialize($totalRecords, $recordsPerPage);

      $offset = $recordsPerPage * $page;

      $data = array();
      foreach ($records as $delta => $details) {
        $data[] = array('data' => array(
          $details['name'],
          $details['remarks'],
        ));
      }

      $recordsToDisplay = [];
      $recordsToDisplay[] = [
        '#theme' => 'table',
        '#header' => array($this->t('Name'), $this->t('Remarks')),
        '#rows' => $data,
        '#empty' => $this->t('No Records(s) Found.'),
      ];

      // Finally, add the pager to the render array, and return.
      $recordsToDisplay[] = ['#type' => 'pager'];
      return $recordsToDisplay;

    }
  }


How do I use and administrative form and save a message?

Yes, I found the bug.

In buildForm is says:

hello_world.adminsettings

But it must be:

 welcome.adminsettings


Probably not possible out of the box.

You'll need to implement access for them, see for example https://www.drupal.org/node/1140606 for some discussions/ideas.

In 7.x-1.x, categories are terms, in 7.x-2.x they are separate entities.

However,I doubt that simplenews, in either 7.x-1.x or 7.x-2.x fully respects whatever access you define there, but patches to improve that are welcome.


Acquia installation is up-to-date but requests update and reports errors

For the errors, I think you could continue developing your Drupal site with it but for me I wouldn't like those in my site. I myself don't know the cause of it thought but I found a recent issue in the Acquia forum: Errors on Clean Acquia Drupal Install which still has no reply on a fix.

Option 1: Use Acquia

Try uninstalling and reinstalling the whole Acquia Dev software and see if the issue still persists.

Option 2: Use XAMPP(I use)/WAMPP

I've been using this since I started web and its straight forward. You don't need to change any settings too. What you need to do is:

Download the .exe from the XAMPP page
Install the application
Download Drupal Core that can be downloaded here
Extract Drupal Core into C:/xampp/htdocs/[your drupal root folder] (if you just chose the default settings of XAMPP on installation)
Go to http://localhost/phpmyadmin and create your database there, just use the defaults too
Start the installation of your Drupal site by going to http://localhost/your-drupal-root-folder-name]


The solution for this is three modules.

http://drupal.org/project/token_profile

and enabling the core module profile.

Add any custom fields for a sales rep. Then enable rules. Rules will take any tokenized field based on certain events.


Is there a way to delete/purge all generated image style images without re-generating them?

You just have to do drush image-flush --all. Source : http://www.drushcommands.com/drush-6x/image/image-flush

Examples of using the drush image-flush command:

drush image-flush - Pick an image style and then delete its images.
drush image-flush thumbnail - 'Delete all thumbnail images.
drush image-flush --all - 'Flush all derived images. They will be regenerated on the fly.'


Why is my Ajax callback not returning anything?

there are a few things that could go wrong with this. Ajax callbacks can be a really hard thing to do and often requires a bit of trail and error. Hope this helps.

First of all, when your ajax callback function should not contain the "::".
This is only used when you are programming inside a Class, right now you're in a .module.
So you can change to.

'callback' => 'some_ajax_sample'

Furthermore you should check with a breakpoint if you even get inside the function. This should be resolved when removing the ::.

Second thing you should do is add the wrapper div to your element.
You can do it like this:

$form['elements']['name']= [
  '#prefix' => '
'
  '#suffix' => '
'
  '#type' => textfield,
  '#title' => 'sammy',
  '#ajax' => [
            'callback' => 'some_ajax_sample',
            'wrapper' => 'edit-name',
            'event' => 'keyup',
            'progress' => [
              'type' => 'throbber',
              'message' => 'loading.....',
            ]
          ],
        ];
}

When you added the wrapper, Drupal knows which element should be replaced and update.

Last thing you can try is to remove the response and to just return the $form['elements']['name'].

Hope this helps.


If you are creating a menu link from a custom module, you can check this

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

Quoting the documentation:

requirements (required): Determines what must be met in order to grant access to the route.
    _role: A specific Drupal role, eg. 'anonymous'.

Alternatively you can use this module: https://www.drupal.org/project/menu_item_visibility
"It exposes configurable and extendable visibility settings for menu links."


How can I specify inner elements template in custom login page?

See How to manipulate forms in Drupal 8:

  To make changes to the fields in your form, you have to change the specific twig templates. First check which twig templates correspond with the base theme of your Drupal application. It is important that you give new twig templates the same name as the original ones, otherwise your new templates will not be recognized.


Using one view for multiple Content Types

If you are using the same field for all content types and want to display them all on the same view and grouped by content type. Here is the step by step.

Create a view for all content type in Unformatted list or table.
In Filter Criteria: Add the "Content: Type" and check the content types you wish to display
In Filter Criteria: Add the "Offer" is equal to "Yes"
In Fields: Add any field you wish to display, and add "Content: Type" set that exclude from display
In Format Settings: Set "Grouping field" by "Content: Type"

This way, The view will list all those node content type with Offer equal to yes, and grouped by content type.


Storage API + Services 3: How to work together?

replace uri with filepath
--> POST http://example.com/api/file http/1.1
Content-Type: application/json
Content-Length: 343901
Cookie: ..............
X-Csrf-Token: .........
{"file":"iVBOR.......Jggg==","filename":"myimage.png","filepath":"public://storage-field-images/myimage.png"}
--> END POST (343901-byte body)


How to display/hide a field only if has a certain value?

Hope youre feeling better! You should be able to achieve this by:

exclude the Date field from view.
in the Later Date field, under "rewrite results" check "Rewrite the output of this field. at the bottom of that fieldset expand Replacement patterns to see all the tokens available.  You should see somethine like [Date] to indicate the content from the Date field. Enter that into your text.
In the "no results behavior" section, enter "Date to Be Determined" in the "No results text" box. check Count the number 0 as empty (so when the box isn't checked it will show your "Later" message) and check "Hide rewriting if empty"
Save view and refresh caches


You are trying to render the twitter_url twice. First in then preprocess function and then again in the template.

If that's not the problem, start debugging. Install devel.module if you haven't already and add dpm($variable) statements on the relevant places, e.g. dpm($twitter_url) in the preprocess function.


To recognize a suggestion in a module, you need to explicitly specify it in hook_theme() of your module.

system_theme() for example has this:

// Normally theme suggestion templates are only picked up when they are in
// themes. We explicitly define theme suggestions here so that the block
// templates in core/modules/system/templates are picked up.
'block__system_branding_block' => array(
  'render element' => 'elements',
  'base hook' => 'block',
),

Copy the original definition and then change the key and set the base hook.


How to grant permission to FileSystem.php file

First of all make sure that the files directory (sites/default/files by default) has the right owner and permissions.
And also directory of temporary files, in general /tmp if you don't have create one and give it the right permissions.


How to show number of a views return results without submitting the view?

How about triggering ajax call on key-press of that input field. In the ajax callback programatically call the view to get total count of results populate this count in field.


How can I find what nodes are causing 404 errors?

Try a the "Recent log messages" report and apply a filter to show you only the "page not found" logs. You will then see a list of pages not found and you can click on the message to find out more details about it.

If the problem is that a lot of pages change their path then you might want to use the "Path Redirect" module (http://drupal.org/project/path_redirect) if you are using Drupal 6 or the "Redirect" module (http://drupal.org/project/redirect) if you are using Drupal 7 to let search engines know about the new path of the content.

Note: if you have clean URL setup make sure it is working and you are not missing the .htaccess file. It happen to me once when I move a site from dev to production and I didn't copy the .htaccess file.


Matching user accounts in views with taxonomy

From the create view wizard, you need to choose, show "Users."

In the filters section you'll create a filter for "I want" whose value is set via PHP to grab the current users choice for "I have." You'll need the Views PHP module for this.


How to display a list of nodes in a block?

Unless you have a specific issue not mentioned in the question, I would recommend using a view to create this block. This would mean that the criteria remained easily editable.

If you had specific need to output the list of nodes within a custom block, or would like to pass arguments to the view from custom code you could use views_embed_view.


Views generally gets node id from url when url format seems to be node/nid

For your case, select 'Raw value from URL' in Provide default value section and select path component as 3 as nid lies in 3rd url arg. Your views should be getting the desired nid now.

Hope this helps you. :)


How do I translate strings in Twig templates?

You need to visit the page in a language that is not English to have them picked up. That should be enough.


Overriding default hashing mechanism: cannot redeclare user_hash_password()

Everything in core uses

require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

so I would guess at the cause being a contrib module.

Also just check that the password_inc variable has been updated correctly and not deleted somehow.


get last element in URL(menu item) generated by hook_menu

array_pop(arg());

will return the last component of the current Drupal path.


How should I configure the wysiwyg filter to align the images?

Some people forget to turn off the built-in HTML Filter when they enable the WYSIWYG Filter.  If you double-filter, you will lose your img attributes.

For my part, though, I prefer to not put the float on the img; instead, I float the div that surrounds the image and caption, allowing them to float together.  (Example image, with floated caption "A battle...": http://www.westkingdom.org/content/new-members).  To give the content editors a good user experience, I allow them to set floats on images with ckeditor, but I move the markup to the div in a render hook when the content is displayed.  In this scenario, I don't need to allow floats on the image at all.

I have a writeup of how I achieved responsive images with captions using media 2.0, wysiwyg filter, and a couple other modules, and a couple of custom hooks.


I have found the answer of it since in render variables are passed by reference https://api.drupal.org/api/drupal/includes!common.inc/function/render/7

so i was passing $main_menu_expanded multiple times in render which was culprit.

Fix is

$variables['main_menu_expanded'] = render(menu_tree_output($main_menu_tree));
<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

Now i dont get extra ul


remove email field from registration form

Mean that you can set an account without e-mail, as admin or someone that have rights, in url '/admin/people/create'. But when a visitor goes to 'user/register', he must specify a e-mail, because someday an e-mail will only be used if you wish to receive a new password, as description says.

There are two types of accounts, one with e-mail (like a visitor that created a new account), and another without e-mail (admin created a new user). This is why AccountForm check if user have an e-mail and check if user is admin or have 'users' permission, to set e-mail field required or not.

There is no reason to a visitor create a account without an e-mail, there is no other way to admin/system contact him for any kind of situation. In other hand if an admin create a new user, somehow he will able to contact the new user.


Try setting the $base_url variable to the new site domain. This is in the /sites/default/settings.php file.


Why don't breadcrumbs appear on views generated pages?

Have you tried Views Breacrumb / Custom Breadcrubs / Views breadcrumbs modules?


How do I add menu items within a .install file

You can follow the example from the profiles/standard/standard.install file and use code like this inside your implementation of hook_install():

// Create a Home link in the main menu.
$item = array(
  'link_title' => st('Home'),
  'link_path' => '<front>',
  'menu_name' => 'main-menu',
);
menu_link_save($item);


Custom form from user registration form not showing new fields in D7

Is there a reason you need to use code? You could just add the fields to the user profile and check "required on registration" to make them show up during registration.


Exist any way to integrate Google Rich Snippets in D6?

Given the comments, I am thinking all you'd need to do is theme the fivestar summary with google's snippets.  To do that, I pulled the theme_fivestar_summary() out of the module and plopped it into my theme's template.php file like so:

function YOURTHEME_fivestar_summary($user_rating, $average_rating, $votes, $stars = 5, $feedback = TRUE) {
  $output = ''; // ADDITION #1
  $div_class = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= ''. t('Your rating: !stars', array('!stars' => $user_rating ? $user_stars : t('None'))) .'';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    $div_class = isset($votes) ? 'average-count' : 'average';
    $average_stars = round(($average_rating * $stars) / 100, 1);
    $output .= ''. t('Average: !stars', array('!stars' => $average_stars)) .''; // ADDITION #2
  }
  if (isset($user_rating) && isset($average_rating)) {
    $div_class = 'combo';
  }

  if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
    $output .= ' '. format_plural($votes, '@count vote', '@count votes') .''; // ADDITION #3
    $div_class = 'count';
  }
  elseif (isset($votes)) {
    $output .= ' ('. format_plural($votes, '@count vote', '@count votes') .')'; // ADDITION #4
  }

  if ($votes === 0) {
    $output = ''. t('No votes yet') .'';
  }

  $output = '
'. $output .'
';
  $output .= ''; // ADDITION #5
  return $output;
}

and commented where I added the snippet additions.


Form altered select field is submitting the wrong values

For dynamic list text no need of form alter for a content type.

You can achieve this goal using Content Construction Kit (CCK) module.

Install this module and configure field as below image

and define function statement like

function _options_english_side_menu(){
    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    return $english_side_menu_list;
}

Using this function you can assign dynamic list to list text.