How can I modify the 'has_js' cookie? I am trying to modify the 'has_js' cookie that is set by Drupal. I need to modify this cookie so it becomes both  Http-only and secure in response to a site security review.

I attempted to add the following to the html.tpl.php file so the cookie would be modified before any output was rendered:

setcookie('has_js',null,null,null,null,true,true);
setrawcookie('has_js',null,null,null,null,true,true);

This gave me 2 has_js cookies, one with the desired modifications and one without.

I next attempted to grab the value from the original has_js cookie and then destroy it and replace it:

if(isset($_COOKIE['has_js']))
{
  $has = $_COOKIE['has_js']; //save cookie's value (i.e., '1')
  unset($_COOKIE['has_js']);
  setcookie('has_js','',time()-3600); //destroy old cookie
  setcookie('has_js',$has,null,null,null,true,true);
  setrawcookie('has_js',$has,null,null,null,true,true);
}
else
{
  print_r("Not set");
}

This demonstrates (by the output I get) that at the start of html.tpl.php, the cookie isn't set -- which might explain why there are 2 cookies (perhaps I was creating a has_js cookie at one point in time and after that Drupal creates its own). Confusingly, if I simply do

print_r($_COOKIE);

at the same place in the file, 'has_js' cookie does show up with an assigned value of 1.

So my question is:

How can I find out when Drupal is setting this 'has_js' cookie and how can I add these attributes to it?

I am answering this formally so other people can see one possible solution that will work if they have this same question, but the answer is actually found in the comment by @thumbson above: in order to modify the cookie, I did indeed find success in creating a custom js file that ran when every page loads.


How to translate only the interface back to English? My site default language is Hebrew (RTL), the problem is that it's all the site, and I want my sites admin-interface to be in English (American). how could I re-translate it to English?

There is a module for that: Administration Language.

This module lets the administrator see all administration pages in his/her preferred language.
You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).
You can use the standard Languages page to choose the language of the admin pages.


split/divide main content region to columns or create another custom layout I am building a theme and I want my main content region to be divided in 3 fixed columns. I have produced all my .css code and I just want to dynamically produce the markup (3 columns) and attach my styles to them. I know 'use panels or display suite' is the easy answer but I haven't till found a way to use them effectively.

Ideally I would have regions: content-left, content-center, content-right and when I create content I can choose where to place it. this <?php print render($page['content']); ?> needs some tweaking! Anyone?

After hours of searching, I was lucky (and persisent enough!) to come across this: http://www.youtube.com/watch?v=gmX2jnH9Kdg which describes how to achieve what I am after using panels indeed. I feel covered by that excellent video. I can leave my Q up for anyone frustrated as to how to translate his/her layout to dynamic drupal code


Authcache settings for blocks or views in panels I am setting up Authcache ESI and Varnish on Drupal 7. My site has panel pages that incorporate personalized blocks and views. Authcache allows caching parameters to be specified for blocks or views, and also on panels.

What is the recommended approach in this case? For example if I am placing a view in a panel page, should I:

Specify Authcache settings for the view only?
Specify Authcache settings for the view panel within the panel page only?
Specify Authcache settings for both the view and the panel -- and if I specify settings
for both, which takes precedence?

Note that each fragment which is loaded from the server results in an additional request. Hence it is beneficial to minimize the amount of fragments and it follows that you should pack all your personalized panes into one request if possible.

Note also that you only can load panels/panes if you place them with page manager. Neither Panelizer nor Mini Panels are supported at the moment (see these issues)

You should not nest authcache fragments. If you do then, the outer most wins. Authcache will not add any fragment placeholders inside fragments loaded via Ajax/ESI.


Customized node edit page How to customized the node edit page?
i was created one cart site for online education.
here i need one button to while edit the  node one of the content type?
how to create an button in node edit page?
how to add function for specific function for that button.

You can add a button to the node form, with a submit function for that button, using hook_form_alter()

function hook_form_alter(&$form, &$form_state, $form_id)
{
  $content_type = 'page'; // change as necessary
  if($form_id == $content_type . '_node_form')
  {
    $form['actions']['my_button'] = array
    (
      '#type' => 'submit',
      '#value' => t('Do something'),
      '#submit' => array('my_submit_function'),
    );
  }
}

function my_submit_function($form, &$form_state)
{
  // Do stuff here
}


How to alter field values on a display page? I am trying to alter field values in a page display.  I can get the field values easily using field_get_items(), but depending on the values of other fields, I may need to manipulate the text and/or display based on some PHP logic in my template file.  I am trying to do it using either hook_page_alter() or hook_preprocess_HOOK().

I cannot get the text to be altered when the page is displayed using hook_page_alter() or hook_preprocess_HOOK().  I can confirm those 2 functions are working and that I can pull the values from the DB ($page['content']), but I cannot override the variable to set them.  For example:

function standard_submission_page_alter(&$page) {
    $node = menu_get_object();
    $page['content']['system_main']['nodes'][$node->nid]['field_title_nickname']['#items'][0]['value'] = 'A new nickname title!';
}

function standard_submission_preprocess_page(&$vars) {
    $vars['node']->field_title_nickname['und'][0]['value'] = 'A new nickname title 2x';
}

Any ideas on why my altering of this field_title_nickname text field value isn't being accepted and displayed?  It keeps reverting back to whatever is originally in the database.

If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook_node_view() in a custom module, not in a template file.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( some conditions here ){
            $node->content['field_title_nickname'] = array(
                '#markup' => '
A new nickname title 2x
'
            );
        }
    }
}


Certain js File Not Working in Drupal I'm trying to render one div before another.

I've tested the js on my local machine to make sure it works by creating a simple page. The code is as follows:

<!DOCTYPE html>

IMAGE

BODY

I've added the following code to a js file on my Drupal site:

(function ($, Drupal, window, document, undefined) {

    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

})(jQuery, Drupal, this, this.document);

My .info file links to the js and it is loading. Other elements that require javascript are working too. I've even tried adding the script in the html.tpl file, but that did not work either.

The divs I am trying to affect are nested deep within the html markup, and have several classes applied to them, compared to the simple version I have made. Could that be the reason? Am I not being specific enough?

This will help you

(function ($) {

Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
  $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

}

};
})(jQuery);

Read this https://drupal.org/node/756722 It will definitely help you.


Field type date bad formatting i have a strange issue with a field "date".
First i save it programatically this way :

$now = new \DateTime();
$node->set('field_paiement_date' => DrupalDateTime::createFromTimestamp($now->getTimestamp());
$node->save();

Then when i come on the content type in the back office i've got this value :

And finally when i dump the field in question i got this value :

My current timezone is 'Pacific/Noumea', so the correct value i want to show to the users is the one when i dump the field. What is the best way to do that ?

Regards,

Datetime values in storage are UTC, if you are storing datetime values by your own, you have to pay attention on this and display datetimes to users considering your timezone ('Pacific/Noumea' probably declared in your php.ini or user's timezone present in user profile).

Storing 2018-05-02T08:23:25 as your current datetime in caledonia in database is a nonsense considering timezone, because the format DateTimeItemInterface::DATETIME_STORAGE_FORMAT do not include timezone.

$date = strtotime($node->field_paiement_date->value);
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', 'Pacific/Noumea');


How to register and create a node in the same form? I am trying to make a form that registers the user and creates a node at once. Is there a module for that? What is the best way to code that (if there is no module).

You're looking for the Inline Registration module.


Display a view in an overlay? I want to create a view of display type page with a path of '/%/bookmarks'. Whenever this view is linked on a page clicking on the link will open the view in an overlay instead of a new page. How can I do this?

The best solution I can think of for Drupal 6, would be to add some custom JavaScript to that page that scans all the links and attach a click handler on the links that matches the desired URL. Something like this:

$("a").each(function(){
  if (this.match('/bookmarks$/')) {
    $(this).click(function(){
      $.get(this.href, function(result) {
        $(result).find('#some .element').dialog();
      });
      return false;
    });
  }
});

The above code is written from memory, so is untested and probably flawed, but is can give you an idea of how to do it. The code requires jQuery UI dialog plugin to be loaded.


Add referencing entities into this entities renderable array Lets say I have a taxonomy called bands, and a taxonomy called band_members.

Band_members have an entity reference field relating each band member to a band.

When I view the bands taxonomy term page the band_members will not be listed.

I can modify the taxonomy term template and manually add them in there, however the bands need to be shown in popups, and the content for each popup is returned via AJAX using drupal_render(taxonomy_term_view($term)). This means any template changes won't show up. What I need to do is use a hook like hook_taxonomy_term_view_alter to add the band_members for that band into the renderable array.

However that will be quite a lot of work, and I though it seems like a fairly standard task to need to displayed referencing entities, so is there an easier way to do this?

In this example I've used taxonomies as an example, however this could apply to nodes, users or any other entities that reference each other.

Seems custom code was the easiest thing here after a bit of research...

function HOOK_taxonomy_term_view_alter(&$build) {
    if($build['#term']->vocabulary_machine_name=='bands') {
        $units = load_bands_members($build['#term']->tid);
        $build['units'] = array(
            '#markup' => theme('bands_members', array('members' => $members))
        );

    }
}

The function load_band_members returns an array of taxonomy terms and looks like this:

function load_band_members($tid) {
    $tids = db_query("SELECT tid
        FROM taxonomy_term_data td
        INNER JOIN field_data_field_band b ON b.entity_id = td.tid
        WHERE td.vid = 6 AND b.field_band_tid = :tid", array(':tid'=>$tid))->fetchCol();
    return $tids ? taxonomy_term_load_multiple($tids) : false;
}

I'm sure it would somehow be possible to get Drupal to render my band members for me, like it does on their own taxonomy term page, as opposed to me having to call my own custom render function but that will do for now...


User reference and Views 3 and Panels 3 i have the follow installation:

Drupal 7.12
Views 3
Panels 3

I have an content type with the follow fields:

User name (textfield)
Job Function (textfield)
User reference (Reference Field)

I filled the content type with: Username: Test Job function: CEO, user reference: demo

I have 3 users at mom, admin, demo and normal

What I'm trying to do is when I change the User reference field on this content type to other user like, admin or normal:

It will update on the views page or panels page the nodes that this user has created

I have setup a View and put on the Contextual Filters: Author ID and pressed Apply (all display)

Then I created a panel page and Add a Content, selected Views and selected this view I created, then I have an option there called Author ID, and a select list that has this field called User Reference, I selected it and update and saved the panel

But when I visit the panel page, it does not show anything

The question is how can I do this that I'm trying to do?

There are several things you can do to make your site work with Drupal a little better.

First,  it is a bit unclear how you are using your user reference field.  When I add the labels Admin and normal it sounds a bit like you are duplicating The users functionality already built-in.  Go to admin/people and look at the definition of roles and permissions.  It will allow you to define categories of users and assign them access to specific categories of content and activities on the site.

Next.  Define your view to achieve what you want, ignoring the panel.  'Taming the Beast' at nodeone.se demonstrates doing exactly what you are looking to do.  I recommend watching the entire series to understand exactly how Views works.
Note that applying contextual filters can be a little tricky.  I recommend you do not use path aliases when using them.

Only after you have your view displaying should you add the additional complexity of placing it in a panel.  Once again, nodeone has an excellent series for understanding how panels works.  Panels works closely with Page Manager and the videos show them working together.


Would Drupal send to an alternative email address for reset password? I am very new in Drupal.
I have an installation of Drupal 7 with LDAP authentication and LDAP user provision, this LDAP is linked to corporate mail system too. Users have 2 mail accounts (a corporate account and an alternative account), if a user forgot his password, I need the password reset send mail to both email addresses not only to the corporate account.

You'll want to create a custom module, please see https://www.drupal.org/node/1074360

You can then implement hook_mail_alter().

/**
 * Implements hook_mail_alter().
 */
function my_module_mail_alter(&$message) {
  // Alter password reset
  if ($message['id'] == 'user_password_reset') {
    // Load the user by email address
    if ($user = user_load_by_mail($message['to'])) {
      // If you have another user field with their alternative email address, add to the $message array
      if (!empty($user->field_user_alt_mail)) {
        $message['to'] = $message['to'] . ', ' . $user->field_user_alt_mail[LANGUAGE_NONE][0]['value'];
      }
    }
  }
}

edit: changed 'password_reset' to 'user_password_reset' as per Paul's comment.


What is the difference between $container->get('current_user') and global $user? I've been looking at symfony's implementation of dependency injection, and it seems like a service locator pattern.

It appears, at first blush, that the service container is not entirely different from a global namespace, and that any of the objects located within could be requested and modified in unexpected ways by some other module.  It seems like symfony has built in a way around these Action at a distance anti patterns by setting Scopes on the container, (addScope, enterScope, leaveScope), but I only see one example of addScope in CoreServiceProvider.php with a 'request' namespace.

Should module developers be encouraged to scope their interaction with the container if they plan on modifying services?

The general idea is to not use service location but define the dependencies directly in the container. There are edge cases where you need to pass along the full container, but really, try to avoid them. For objects like plugins and controllers we use a static factory pattern, on which you get the container to get your dependencies. Note: There aren't any objects which depend on those.

On top of that you also should avoid having to change services. As much as possible! Instead you should build a wrapper service which has a method like the \Drupal\Core\Session\AccountProxy ... you can set the current user on there
using setAccount.

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  public function doSomething() {
    $this->currentUser->setAccount(new UserSession(...));
  }


Ctools content type- How do I access a context that is provided by a panel page? I'm trying to add a ctools custom content type to the user profile override provided by panels.

I have added a context, Logged-in user.  I can access the values of this variable in my custom content type like this:

dpm($context['context_user_1']);

However, I also want to access the values for user-being-viewed, which is available in the user profile page by default.  With the devel module, I can see the variables are in $context under argument_entity_id:user1, but I can't access them like this:

dpm($context['argument_entity_id:user1']);

How can I access the variables of a context provided by default in Panels?

There might be a more elegant way, but here's what I came up with:

$user = reset($context);
$user = $user->data;


'You must declare "ids" as a unique array of fields in your source settings' I am trying to learn about importing images with migrations using this tutorial and this custom module (c11n_module). When I install and try to run 'drush ms' I keep getting an error.
In CSV.php line 105: You must declare "ids" as a unique array of fields in your source settings.

The id looks like this:
keys:
  - ID

The helper thought I found shows this:
ids:
  id:
    type: integer

However, if I change to this:
ids:
  keys:
    - ID

I still get the error. I have spent a few hours trying to figure this out. I am assuming it is in the YML file that I have to correct this. Any ideas for solving this issue?
Or am I thinking about it all wrong?
Here is the whole YML:
# Migration file for creating "image" for academic programs.
#
# Detailed explanations for various elements of a migration
# YAML have been provided in migrate_plus.migration.program_data.yml

id: program_image
label: Image associated to academic programs.
migration_group: c11n
migration_tags:
  - academic program
  - file
  - image
# Source.
source:
  plugin: csv
  path: 'public://import/program/program.data.csv'
  header_row_count: 1
  ids:
    keys:
      - Image file
  # Source field definitions.
  fields:
    Image file: Name of the image file associated with the program.
  constants:
    file_source_uri: public://import/program
    file_dest_uri: 'public://program/image'
# Destination.
destination:
  # We will be creating entities of type "file" this time.
  plugin: 'entity:file'
# Mappings.
process:
  file_source:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_source_uri
        - Image file
    -
      plugin: urlencode
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - Image file
    -
      plugin: urlencode
  filename: Image file
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
# Dependencies.
dependencies:
  enforced:
    module:
      - c11n_migrate

The way you're currently doing it doesn't look familiar, with keys and the way the fields are mapped; might just be it's a method I haven't come across though.
Either way I've always had success processing CSVs like this:
ids:
  - image_file
fields:
  0:
    name: image_file
    label: Image file

That assumes the first column in the CSV contains the unique image file name.


Why would single-use (harcoded) tokens not validate in the Message module, when the dynamic version does? In the Message module, why does the following dynamic token validate nicely [message:field-message-content:body] but the single-use (harcdoded) token does not @{message:field-message-content:body}

Basically changing [token] to @{token} doesn't work.

Note: I know I have to create a new message and just can't change the template on the fly to back-propagate existing messages.

For reference from the module's readme.txt:

  Tokens

  "Dynamic" tokens   When defining a message type, it is possible to use Drupal tokens in any of the   message fields, in order to inject
  certain content into the field on the fly.   E.g. Entering the string
  "[current-date:short]" to the message text will   display the current
  request time instead of the token.   E.g. [message:user:mail] will be
  replaced with the message author's username   (When displaying the
  message).   If the message has fields (e.g field_node_ref), its
  contents will accessible   by the token system as well under
  [message:field_node_ref].   (For instance:
  [message:field_node_ref:title]).   This relies on "Entity token"
  module that ships with Entity API.   Enabling "Token" module is also
  recommened, as it provides more tokens   and shows a token browser in
  the message type creation page.
  "Single use" tokens   The single-use tokens are similiar to the dynamic tokens, excepet they're   being replaced by their content as
  the message is created; Meaning this   content will not get updated if
  it's reference gets changed.   E.g. "@{message:user:name}" - Will be
  replaced by the message author's name   (When creating the message).
  You can use this for example when you know the user's name is not
  going   to change, so there is no reason for re-checking all the time
  the user   name -- hardcoding it makes more sense.

Note: There is nothing in the error logs. Essentially when I use the dynamic token, it works and if I change it to a hardcoded token, then it doesn't. Basically changing [token] to @{token} it no longer works. I know I have to create a new message and just can't change the template too.

Provided you're using Rules to send the message, i'll suggest you to manually save the message entity after having set all required fields but right before sending the message.

Single Use token are evaluated at save time.


How to Display a pdf, rft, doc, txt on a overlay? I collect user resumes by using a file field. That field is been display it on view and when you click on it it would download the resume file (either pdf, rft, doc, txt). I would like to open that document a overlay instead of downloading the document.

How can I achieve this ?

You chekced pdf or pdf_reader modules? in order to display it on an overlay open its link in lightbox


Is there a difference between "Clear cached data" button on the performance page and drush cc all? Is there a difference in what caching is cleared between

drush cc all

and

Admin > Site Configuration > Performance > Clear cached data button

?

Short answer:  There is no significant difference.

Drupal:

function system_clear_cache_submit($form, &$form_state) {
  drupal_flush_all_caches();
  drupal_set_message(t('Caches cleared.'));
}

Drush:

function drush_cache_clear_both() {
  drush_cache_clear_drush();
  if (drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL)) {
    drupal_flush_all_caches();
  }
}

Both end up calling drupal_flush_all_caches, which clears the standard Drupal caches, cached CSS/JS files, and everything declared by a hook_flush_caches.

drush_cache_clear_both is what is called by 'cc all'.  drush_cache_clear_drush clears some drush caches that have no effect on the Drupal site.


Get value of field attached to the file entity in a view I extended the file entity of type video, which ships with the media/file_entity module, with an extra field "tags". How can i get the values of this attached field in views?

You should just need to add a relationship with your file field, then the fields on your file entity should be available when adding fields to your view.


Form timing out with drupal_set_message I am getting some type of timing out error and not sure how to fix it or even where to begin, the error looks something like this http://pastebin.com/M8Wz4KEY

/**
 * Block info
 */

function zillow_block_info(){
    $blocks['zillow_block'] = array(
        'info' => t('Zillow Block'),
    );
    return $blocks;
}

function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = drupal_get_form('zillow_form');
    break;
    }
    return $block;
}

/**
 * Form Info
 */

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['rates']['state'] = array(
        '#type' => ('select'),
        '#title' => t('Choose One'),
        '#options' => array(
            'CA' => t('California'),
        ),
        '#required' => TRUE

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

/**
 * Api info
 */

function zillow_api_info($form, &$zinfo){
    $state_value = $zinfo['values']['state'];
    $zillow_id = 'Xx-xxxxxxxx-xxxxxx';
    $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&'.$state_value.'');

    foreach($xml->response->today->rate as $todays_rates){
        print $todays_rates;
        '
';
    }

    foreach($xml->response->lastWeek->rate as $lastWeeks_rates){
        print $lastWeeks_rates;
        '
';
    }

    return zillow_api_info();
}

/**
 * Submit Info
 */

function zillow_form_submit($form, &$zinfo){
        drupal_set_message(t('this is the info the form has submitted. zip=@zipcode, states=@states, todaysrates=@todaysrates',
        array('@states' => $zinfo['values']['state'], '@todaysrates' => zillow_api_info())));
    }

There's an infinite loop in your code...

The function zillow_api_info() returns a call to itself, which will result in an infinite recursion from which PHP can't escape. As you're calling this function during the call to drupal_set_message() I'd guess that's why you're getting the timeout.

FYI You're not passing the @zipcode replacement to the t() function, it shouldn't cause an error but it might be a bug :)


How to have postings in blog with custom teaser length and read more links I know this is a common request, but I have had no luck finding any answer. I am setting up a single user blog on my site. The blog has it's own page.

I have made a custom content type based on the Article content type. Then set up a View that displays these for the the blog page. The only thing I can't seem to make happen is to set up a custom teaser length with read more links that take you to each full Article node.

When I set the Row style: node/Page row style options/build mode to Teaser, I get the shorter teaser length, but no read more link to the full node.

I am using Drupal 6.

Can you use "Rewrite the output of this field" on the teaser (or the body) to limit it to a certain length? You can break on a word and show an ellipsis, and you will also be able to show the Read More link as usual. You have to use a row style that will let you use Fields for this, though. Otherwise, you could try to find the function that Views uses to do the same thing and add a template file and preprocess function to alter the teaser length in the same way.

Check the "Information" setting on the bottom-left of the Views 2 UI to see the available templates. You basically copy the base version of one of these to your theme directory, name it as specifically as is needed, and then change it to match your needs. In this case, you wouldn't change it, but you would implement THEMENAME_preprocess_PATTERN (<--- depends on which one) to style the field value appropriately.


How to add auto create feature to custom taxonomy_term field while creating custom entity I created a custom module which has an custom entity.
I added base field term_id to it using below code

$fields['term_id'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Category'))
    ->setDescription(t('Default Category.'))
    ->setRevisionable(TRUE)
    ->setSetting('target_type', 'taxonomy_term')
    ->setSetting('handler', 'default:taxonomy_term')
    ->setSetting('handler_settings', [
            'target_bundles' => ['question_category' => 'question_category']
        ]
    )
    ->setTranslatable(TRUE)
    ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => array(
            'match_operator' => 'CONTAINS',
            'size' => '60',
            'autocomplete_type' => 'tags',
            'placeholder' => '',
        ),
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

I have a YAML file taxonomy.vocabulary.question_category.yml,
which create question_category vocabulary, I can see it in admin too.

But when I try to add a new text in it. I get an error
There are no entities matching ||new enitity title||

I want user to create terms and add it to question_category taxonomy.

Please suggest, what might be the error.

--

Thanks

I did it using below handler setting

setSetting('handler_settings', ['target_bundles' => ['question_sub_category' => 'question_sub_category'], 'auto_create' => TRUE])


How do I set a specific image header for each page? I am trying to have a header with a different image for each page of my site. I believe I should be creating a block. I don't want to create x blocks for x pages, and I prefer to do it programmatically.

So I developped a block using in SubheaderBlock.php.

/**
 * Provides a 'SLS Block' Block
 *
 * @Block(
 *   id = "subheader",
 *   admin_label = @Translation("slssubheader"),
 *   category = "custom",
 * )
 */

namespace Drupal\subheader\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node) {
      $nid = $node->id();
    }

    return array(
      '#title' => '',
      '#description' => '',
      '#nid' => $nid,
    );
  }
}

Then, I can use the node ID in the Twig template and change the picture accordingly.
The node ID is well passed to the Twig template, but it is cached! So, whenever the page change, {{ #nid }} outputs the same ID.

I have also tried to change Twig template suggestion and have a Twig template for each page, but still there are same caching problem.

The code below is probably not the perfect one.

/**
* @file
* Code for the example module.
*/

/**
 * Theme hook
 */
function subheader_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    $twig = 0;
    // change the suggestion only for the block_id 'subheader'
    if(isset($variables['elements']['#plugin_id'])){
        if  ($variables['elements']['#plugin_id']=== "subheader"){
            // give the twig template the same ID as the NID
            $node = \Drupal::routeMatch()->getParameter('node');
                if ($node) {
                $twig = $node->id();
                }
    // suggestion pattern is 'block__subheaderID
    $suggestions[] = $hook . '__' .'subheader'.$twig;
}}
}

A

After some many headache...
I believe I got what I wanted, thanks to Ivan.

  SubheaderBlock.php

<?php
/**
 * Provides a 'Subheader' Block
 *
 * @Block(
 *   id = "slssubheader",
 *   admin_label = @Translation("slssubheader"),
 * )
 */

namespace Drupal\subheader\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

   // get the node id if exist
   $node = \Drupal::routeMatch()->getParameter('node');
   $nid = $node ? $node->id() : 0 ;

   $outpout['id'] = array(
           '#markup' => $nid,
           '#cache'=>[
                 'contexts' => ['url:pager_id' ],
                 ]

       );

    return $outpout;
  }
}
?>

I get the id in twig with

{{ content.id }}

I checked with a a random number rand(1,100) it works perfect. There is one different cache per nid.

althought it works, I am not sure about the best practice for #markup and url:pager_id


Check if there is already a valid one-time-password -reset link I am using drupal 7.
I have this functionality that when a user clicks the reset password he gets a one time link on which if he/she clicks then they gets to some page where they can change their password.

But this functionality is somewhat need to be modified.
Suppose if they don't click on one link sent to them and then again request forget password, i want to send the same on-time-password-reset link to them and not generate new one untill 24 hours or if they clicks whichever happens first.

So do we have any function which can tell us if there is already existing one-time-password-reset link in database or not and if yes how can we reuse that instead of creating new one.

Also if they clicks on the one-time-forget-password link then they should land on password reset page (it is working as expected), but they should not be able to click any other navigation icon and if they does then message should tell them that they need to reset their password first.

In D7 one-time reset pw links are generated using the normal hashing techniques (plus a timestamp) but they are not saved in the DB (see  user_pass_reset_url). This means that there is no way to resend a link (without doing some major work to store this on your own). I don't see why you would care about resending the identical link, but I'm sure you have your reasons.

If they do click a reset password link, I would recommend that you style the password reset page using a completely different page template that does not include your navigation links (etc...) rather than trying to disable them. Just be sure to add a message with a link to the homepage (or where ever) once they successfully edit their password, or even better, do a redirect upon success.


Prevent File Upload during an ajax call I have a form that includes a managed_file field as well as a data popup and select field.  When the user selects a date, an ajax call is made to populate the select field.  However, I noticed that each time the ajax call is made, the file is uploaded, causing multiple copies of the file to to exist (each subsequent file having a number appended to the .  If the user selects another date, the file is uploaded again. How do I prevent the file from being uploaded multiple times during the ajax call?

Here is my form code

function _timesdb_import_form($form,&$form_state) {

  $form['file_fid'] = array(
    '#type' => 'managed_file',
    '#title' => 'Import File',
    '#size' => 100,
    '#description' => 'Select an import file.',
      '#upload_location' => 'private://filelocation/',
      '#required' => true,
      '#default_value' => variable_get('file_fid',''),
    );
    $form['date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'm/d/Y',
      '#title' => 'Start Date',
      '#description' => 'Enter the start date of the meet. After changing the date, select the meet below',
      '#ajax' => array(
      'event' => 'change',
      'callback' => '_timesdb_import_meets_ajax',
      'wrapper' => 'timesdb-import-meets',
    ),
  );

  $meet_options = isset($form_state['values']['date']) ? _timesdb_import_get_meets($form_state['values']['date']) : array();
  $form['meet'] = array(
    '#type' => 'select',
    '#title' => 'Select meet',
    '#options' => $meet_options,
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#default_value' => 'Submit'
  );
  return $form;
}

The ajax callback looks like this

function _timesdb_import_meets_ajax($form,&$form_state) {
  return $form['meet'];
}

Drupal submits the entire form at every ajax call, I think you'd have to use hooks before submit, before send or similar to prevent it. Heres something to get you started. Or simply put the file field last or at least after the ajax form elements.

Disable all form elements when doing AJAX

Ideally drupal should allow you to specify what you want to submit. please share your solution if you figure it out.


Where can I add this jquery code to apply to a view block? I have some jquery that I need to apply to a view that's being displayed as a block. The only template we're using for this particular view is views-view-grouping--my-view.tpl.php. I've tried adding the jquery to the beginning of this file, but as expected (because it runs recursively for each group) it's being added to the rendered source before every rendered group, instead of just once.

Where is the best place for me to add jquery code so that it's only added to the rendered source once? It's just two lines of code aside from the document.ready declaration, so I'd rather not have to put it in a separate file and call it conditionally from various page templates.

One quick way could be to add it inline in a preprocess function.

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
      }
    }

If you prefer you could also add it as a file that you store in your theme. This would include a file called myfile.js under the folder for your theme /js

    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         global $theme_path;
         drupal_add_js($theme_path . '/js/myfile.js');
      }
    }


Show original price and discounted price? I'm using this module: Commerce Discount to create products discounts. In the products list view I'd like to show both prices: the original price and price with the discount. How can I do this?

I found this module:   https://drupal.org/project/commerce_price_savings_formatter but it doesn't seem to work with the Commerce Discount module.

It does work with the discount module. In fact the moudle was built with that one in mind. Install Commerce Price Savings Formatter and go to your product types's display settings and change it as per the screenshot.


Create node programmatically with menu entries I created an action in Rules, which generates a duplicate of a node. If I am creating a node of the type "basic", it will duplicate the node for every taxonomy term. So when I have a node with three taxonomy terms, the action will generate three nodes.

The only difference are the taxonomy terms, because the created nodes should get the URL '/taxonomy-term1/node-title', '/taxonomy-term2/node-title', ...

My problem: If I have the taxonomy terms Taxonomy_Term1, Taxonomy_Term2 and Taxonomy_Term3, I get the following result:

/taxonomy-term1/node-title

/default/node-title

/default/node-title-0

I am thinking the problem lies in the array which was created from the latest nid. But when I am printing each term_name (to know what it looks like), the results are the Strings Taxonomy_Term1, Taxonomy_Term2 and so on.

function autocreatenode_rules_action() {
$nid = db_query_range("SELECT nid FROM {node} ORDER BY nid DESC", 0, 1)->   fetchField();
$string = token_replace('[node:field_tags]', array('node' => node_load($nid)));
$terms = explode(',', $string);
$i = 0;
foreach ($terms as $term_name) {
    $i++;
}
    if($i >= 2) {
        foreach ($terms as $term_name) {
            $node = new stdClass();
            $node->type = 'basic';
            $node->language = 'de';
            node_object_prepare($node);
            $node->title = 'Title';
            $node->field_body[LANGUAGE_NONE][0]['value'] = 'Something in the body';
            $menu = array();
            $menu['link_title'] = 'Menu Link title';
            $menu['description'] = '';
            $menu['menu_name'] = 'main-menu';

            switch($term_name) {
                case 'Taxonomy_Term1':
                    $menu['plid'] = 5;
                    break;
                case 'Taxonomy_Term2':
                    $menu['plid'] = 6;
                    break;
                case 'Taxonomy_Term3':
                    $menu['plid'] = 7;
                    break;
                default:
                    $menu['plid'] = 1;
            }

            $menu['enabled'] = 1;
            $node->menu = $menu;
            $node->status = 1;
            $node->promote = 0;
            $node->sticky = 0;
            $node->comment = 2;
            $node->uid = 1;
            $node->date = 'complaint_post_date';
            $node->created = strtotime('complaint_post_date');
            $node = node_submit($node);
            node_save($node);
        }
    }}

The code you posted seems a bit frail at places, but if it works for you, we can focus on your specific question.

The main problem is that you are not adding the $menu array to your node object before saving it. You would only need to add it to the object before you save it, similar to this:

$node->menu = $menu;
...
node_save($node);

Cheers and good luck!

P.S.: You can check out this thread for some code examples https://stackoverflow.com/q/2603289/5875098
P.S.2: To get all the terms directly from the $node object:

$terms = array();
$language = 'und'; // or will be provided by some Drupal hooks
foreach ($node->field_tags[$language] as $delta => $value) {
  $termObj = taxonomy_term_load($value['tid']);
  $terms[] = $termObj->name;
}

You can replace the $terms = explode... in your code with this snippet.


How do I handle third-party API credentials in settings? I am building a module that will need to integrate credentials for the 3rd party service in Drupal 8. The module's admin panel should remember the credentials and use them to interact with the service, but still hold them secure. Storing the credentials un-encrypted or exporting them in config with drush cex can pose a threat. How are such cases to be handled in Drupal 8? What is a good way to handle secure 3rd party credentials with Drupal 8?

Details: A module integrating with the 3rd party online service. This service provides credentials, that the user inserts in the module's admin form, and then can use the services. It won't do to hard code the credentials in PHP, and saving them as config in Drupal 8 will result in them being exported with drush cex. So, there is a need to store secure data in the settings, and keeping it from export when config is exported.

The key module provides a framework for abstracting key storage from modules. The module provides 2 key providers (plugins) out of the box: config and file. It is possible to implement a key provider plugin for some arbitrary storage such as what the encrypt module provides.

Note that a web site's actual security risk for using a particular key provider depends more on security procedures and infrastructure.


Filter by color with exposed filters I have taxonomy list of color names(red, black, etc). If I create an exposed filter form, how can I show the color with corresponding coloring? I want to style each select option with background color, i.e for the option Red, the background should be red. Can we style that in the stylesheet?

I use view3 and views_hacks
thanks.

What you're asking is not necessarily Drupal related (although there is the Color module which also shows a color value in a select list, you could look into using the Color module to use its select widget or colorpicker instead of a taxonomy listing of colors by English name).

Anyways, if you want to stick with using a taxonomy select with like "blue" being the 3rd option in the select list -- you could reference this StackOverflow example using Jquery to style select items. You could make a call to drupal_add_js() in a theme function whenever your view and its filters are shown on the page to add the necessary jquery.

I would recommend looking into the Color module in the long run.


Does creating multiple tpl files affect site performance? I am creating different tpl file for each and every content type. (Including every view)

Is it a good practice? And does it affect site performance?

Any suggestions?

thanks

It won't make a noticeable difference as long as you disable rebuilding the theme registry on production, enable caching, and follow best practices (e.g. don't execute logic or queries in your templates, and never ever save PHP code in the database). There are quite a few other, more noticeable things you can tweak to improve performance and load time before you get to the level of worrying about the number of templates.


Invalid form POST data in AJAX Login form I am working on a drupal 7 website using an AJAX login form. I have a problem, the form work fine once and then doesn't work when I logout and try again. I need to empty cache and try again to have it work again.
I think this is something linked to the form_id not found in cache but I don't know how to fix it.

Any solution?

Thanks

short:
it should works if you disable "cache pages for anonymous users"

long:
When Drupal's core caching feature is switched on, forms are delivered to anonymous visitors from cache which results in the situation where one and the same form gets delivered more than once with the same form_build_id.

As soon as one of the anonymous users submits such a form, the record gets removed from cache.

The next visitor who is submitting the same form will potentially run into trouble because of the missing form record in cache.

The regular Drupal FAPI seems to be OK with that but if the form gets submitted via Ajax, the submission gets rejected, a watchdog entry gets issued ('Invalid form POST data') and drupal_exit() gets called.

The result of that is that the user would have to reload the page before being able to submit the form. This can be annoying i.e. if the form being used is the user login form. It seems as if just nothing is happening.

This issue arrises always when page caching for anonymous users and form submission via Drupal's own ajax mechanism get used in combination.

source:
http://drupal.org/node/1694574


Configuring Kaltura module in drupal 7 I am trying to configure the Kaltura module in Drupal 7. If I try adding the partner ID, email ID, and password (which I have received from Kaltura's website), it gives me the following error:

  Class 'KalturaUser' not found

I also added the library but it's not working. Could anyone tell me how to configure the Kaltura module?

According to Kaltura module documentation here http://cgit.drupalcode.org/kaltura/plain/README.txt?h=7.x-3.2

You should download the php version of API from here   (http://cdnbakmi.kaltura.com/content/clientlibs/php5_16-12-2014.tar.gz) and place it under DRUPAL_ROOT/sites/all/libraries/KalturaClient directory.

Note: The directory name is case-sensitive.

Alternatively you can use drush for this.Here is a command for drush.

    Drush kaltura-client-install


Flag the node after login I am using flag module to bookmark the content. Authenticated user can normally flag the content. For anonymous user when they click on flag link it should go to login page. After successful login it should flag the node automatically.
I have the code for flagging the content, but I could find how to flag after login.
$flag = flag_get_flag('wishlist');
$flag->flag('flag', $nid, user_load($uid), TRUE);

You can try using hook_node_view for doing this.
What it does is:

  Act on a node that is being assembled before rendering.

Here is an idea to try out:

/**
 * Implements hook_node_view
 */
function yourmodule_node_view ($node, $view_mode, $langcode) {

  // use a one-timer boolean for this action
  if(user_is_logged_in() && !isset($_SESSION['autoflagging_once']))
  {
    $_SESSION['autoflagging_once'] = true;
    $flag = flag_get_flag('wishlist');
    $flag->flag('flag', $node->nid, user_load($uid), TRUE);
  }

}

Good luck!


how to find Profile module I cannot find Profile module in the core in drupal7, I want to create a registration page with multiple textboxes. Kindly tell how can I find the profile module.

The Profile 2 module isn't in Drupal 7 core yet. You can download it here.

If you'd like to set up user profiles without Profile 2, you can add more fields to the user profile at Administration > Configuration > People > Account Settings > Manage Fields and play around with Panels and Views afterwards.

You can find more information here too:

How can I create user profiles in drupal 7?
How to create a profile page?


How to fetch nearest node based on geofield? How to fetch nearest node based on location geofield,i want to fetch nearest node based on longitude and latitude of my current location ,for this i have installed and configured geolocation field module also created view enabled all settings,but its not giving desired result.

I have followed this tutorial https://www.drupal.org/docs/8/modules/geolocation-field/how-to-create-a-nearest-node-view-sorting-by-proximity

Can we fetch the data directly from database by something like below example of php in drupal .

set @orig_lat=122.4058; set @orig_lon=37.7907;
set @dist=10;

SELECT *, 3956 * 2 * ASIN(SQRT(
POWER(SIN((@orig_lat - abs(dest.lat)) * pi()/180 / 2), 2) +  COS(@orig_lat * pi()/180 ) * COS(abs(dest.lat) * pi()/180) *  POWER(SIN((@orig_lon – dest.lon) * pi()/180 / 2), 2) )) as  distance
FROM hotels dest
having distance < @dist
ORDER BY distance limit 10

By using this query i will try to alter views query for getting desired result

Something like this should do the trick to implement haversine :

/**
 * Implements hook_views_pre_execute().
 */
function YOURMODULE_views_pre_execute(\Drupal\views\ViewExecutable $view) {
//...
    $view->build_info['query']->join('YOUR_FIELD_LATLNG', '...', '...');
    $view->build_info['query']->addExpression(sprintf('3956 * 2 *
                                            ASIN(
                                                SQRT(
                                                    POWER(
                                                        SIN((%s - TABLE.YOUR_FIELD_LATLNG_LAT)*pi()/180/2)
                                                    ,2)
                                                    +COS(
                                                        %s*pi()/180
                                                    )
                                                    *COS(
                                                        TABLE.YOUR_FIELD_LATLNG_LAT*pi()/180
                                                    )
                                                    *POWER(
                                                        SIN((%s-TABLE.YOUR_FIELD_LATLNG_LNG)*pi()/180/2)
                                                    ,2)
                                                )
                                            ) * 1.60934', $lat, $lat, $lon), 'kilometers');
}

edit nearest :

$view->build_info['query']->orderBy('kilometers', 'ASC');
$view->build_info['query']->range(0, 1);

Note there is a contribution with views on geofield : https://www.drupal.org/project/geofield/issues/3012750


How to skip route if not user access I have two routes (from views module) with path "/test".

Route N1 required "role_1" user role, route N2 required "role_2" user role.

Rote N1:

class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_1"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_1"
    '_method' =>
    string(8) "GET|POST"
  }

...

Route N2:

class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_2"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_2"
    '_method' =>
    string(8) "GET|POST"
  }

...

How to skip route N1 if current user have "role_2" but does not have "role_1"?

You can't have multiple routes on the same path with different access checks, it just doesn't work like that.

If you want something like this, then you need to create your own route, check permission/role of the user there and then display the right view based on that.


How to check in Twig file whether node has a field? In my twig file i try to override the field. In the {% if %} clause I need to check whether a field has particular value, if yes then assign the value as a class.

{% for item in items %}
  {% if node.language.value == "English"  %}
    {% set example_classes = 'english' %}
   {% else %}
    {% set example_classes = node.language.value %}
  {% endif %}
  <div{{ attributes.addClass('field', field_name, example_classes) }}>
    {{ item.content }}
  </div>
{% endfor %}

the line {% if node.language.value == "English"  %} brings nothing, how can I get the value of the node's field_language in twig file?

In the field.html.twig a list of available variables is specified:

Available variables:
* - attributes: HTML attributes for the containing element.
* - label_hidden: Whether to show the field label or not.
* - title_attributes: HTML attributes for the title.
* - label: The label for the field.
* - multiple: TRUE if a field can contain multiple items.
* - items: List of all the field items. Each item contains:
*   - attributes: List of HTML attributes for each item.
*   - content: The field item's content.
* - entity_type: The entity type to which the field belongs.
* - field_name: The name of the field.
* - field_type: The type of the field.
* - label_display: The display settings for the label.

I'm a friend of template pre-processing, in order to keep presentation logic separated from (advanced) field processing.

Therefore, I suggest a hook_preprocess_HOOK() implementation in your theme's *.theme file and outline this approach:

/**
 * Implements hook_preprocess_HOOK() for nodes.
 */
mytheme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  $example_class = '';
  if (
    $node->hasField('field_language')
    && !$node->field_language->isEmpty()
  ) {
    $variables['example_class'] = strtolower($node->field_language->value);
  }
  $variables['example_class'] = $example_class;
}

So you could access the newly added template variable {{ example_class }} within your node template:

{% for item in items %}
  {%
    set field_classes = [
      'field',
      field_name,
      example_class,
    ]
  %}
  <div{{ attributes.addClass(field_classes) }}>
    {{ item.content }}
  </div>
{% endfor %}

If you'd like to stick to just altering your template, you can also access all fields of a node entity within its templates by using the {{ node }} variable.

Keep in mind, that unrendered/preprocessed fields of the original entity usually are FieldItemLists. So you'll access an array of field item instances keyed by their delta:

{% if node.field_language and node.field_language[0].value == 'English' %}
...
{% endif %}

The {{ dump() }} Twig function can help you to debug your available values.


How to display a specific form mode in a programmatically displayed form I have a custom entity type, property.  In admin/structure/display-modes/form I created a new form mode for this entity type, machine name is property.property_status.  It only shows one field on the form.

I am now trying to show that form mode on a custom page.  Right now I'm using:
\Drupal::service('entity.form_builder')->getForm($property, 'property.property_status') but I get the error:
Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "property" entity type did not specify a "property.property_status" form class.

Any ideas?  Thanks!

You need to specify a form operation in the handler section of the custom entity:

/**
 * @ContentEntityType(
 *   id = "property",
 *   handlers = {
 *     "form" = {
 *       "default" = "Drupal\mymodule\Form\MyEntityForm",
 *       "status" = "Drupal\mymodule\Form\MyEntityForm",

You can define multiple operations for the same form class. In this example I used status for the form operation, because this name usually doesn't contain the entity type name.

Then you should be able to use the form mode status in the entity form builder:

\Drupal::service('entity.form_builder')->getForm($property, 'status')


Delete cookie just before render I am trying to hide the fact that I have a Drupal site (as much as possible).

The idea is that if a would be hacker (I am not talking about some ninja that could break into the pentagon) looks at the site they would not be able to (easily) see it is a Drupal site.

Most of it is done - I just don't know how to delete some cookies set by modules.  In specific I want to do this for anonymous traffic (clearly someone that is logged in already knows they are on a Drupal site).  The cookies that I want to delete would not affect the site - it is related to two admin modules.

I tried a couple of hooks - the last one was theme_html_head_alter - but nothing works.  This is the code I need to insert somewhere - just not sure where?

if (!user_is_logged_in()) {
   user_cookie_delete('DrupalModuleFilter');
   user_cookie_delete('Drupal_tableDrag_showWeight');
}

Did not find the answer (I did try hook_page_alter) - but I realised I was not focusing.  I want to hide those cookies from anonymous users, but those users will never access the admin section, so the two cookies I am trying to delete, will never be set.


Enable/disable a menu item programatically depending on a variable value I need to show a menu item only in certain moments. Imagine that I've a form with some options. If 'A' is selected, I need to enable a menu item that has a form for adding information about 'A'.

I have done a module that has a hook_menu like this:

> function secciones_menu() {
>
>
>   $items = array();
>
>       $items['secciones'] = array(
>           'title' => t('Crear Sección'),
>           'description' => t('Crear Secciones'),
>           'page callback' => 'drupal_get_form',
>           'page arguments' => array('secciones_wizard'),
>           'access callback' = TRUE,
>           'type' => MENU_NORMAL_ITEM,
>           'menu_name' => 'main-menu',         'customized' => 1, // Must be 1 in order to not dispaly the link in any language
>           'language'  => 'es', // language is required in order to make the item translatable   );

return $items; }

And then have my form for 'A'. So how I can enable or disable the menu item, depending a variable value?

Thank you !

EDIT 1:

What I've done is change the access callback and the menu type:

function agenda_menu() {

  $items = array();

  $items['agenda'] = array(
        'title' => t('4. Crear agenda'),
        'description' => t('Crear agenda'),
        'parent'=>array('Configurar Revista'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('agenda_wizard'),
        'access callback' => 'agenda_access_callback',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'menu_name' => 'main-menu',
        'customized' => 1, // Must be 1 in order to not dispaly the link in any language
            'language'  => 'es', // language is required in order to make the item translatable
  );

  return $items;
}

And then I've done the next code:

function agenda_access_callback(){

    //db query
    //insert that query in $options array
    foreach ($result as $row) {
        $options[$row->id_seccion] = $row->id_seccion;
    }

    if(isset($options)){ //if the array is not empty
        return TRUE; //the menu item is visible
    }
    else{
        return FALSE; //otherwise, is not visible
    }
}

Ok, this is what I have done, but it doesn't work. Any idea? Thank you.

The usual way to enable a menu item only in certain circumstances is to use a custom access callback, in which you would evaluate whether this option is set. So:

'access callback' = 'my_module_access_callback',
...

function my_module_access_callback() {
   return my_module_test_option_is_true();
}

But it's a little hard to be sure if this will work for your case as you haven't given us much to go on.


Unable to access site after deleting an entry from the database The entry views.view.media from the config table in phpmyadmin was accidentally deleted. When visiting the site it giving the error The website encountered an unexpected error. Please try again later. I'm unable to login or access any page. What can I do to fix this problem? It's drupal 8.2.4.

You can try installing the views in a similar configuration to your current site, on another install, and then copy that row from the database in that install to your current site.


Add an boolean attribute to a text field? I need to add a boolean attribute in the form of a check-box to a ordinary multivalued text field attached to a node. In this case, the text field will be used to list arguments for functions, which can either be required or not-required. So, in a node-edit form, I envision it to look something like the screen below. What's the best way to go about this?

Edit: adding links to suggested options, and also some that I found while checking these out:

field collection - https://drupal.org/project/field_collection
field collection table - https://drupal.org/project/field_collection_table
double field - https://drupal.org/project/double_field
tablefield - https://drupal.org/project/tablefield
multifield - https://drupal.org/project/multifield (dev)

You can write your own field type and widget form. A good example can be either filefield or imagefield.

Or try Field collection module.

So you can create a new type of field in field_collection UI.

Here are tutorials: https://drupal.org/node/1353926


How does drupalxray.com find out the modules present on a thirdparty website? drupalxray.com gives an exhaustive list of the modules present in a third party website. How does it ascertain which are the modules present on a site?

Note : It also identifies the modules which are not enabled.

Based on How to determine the modules enabled on a third party website? but making it a separate question as others might find it useful.

I enabled access log on my site and then let www.drupalxray.com to review my site.

The entries in the access log looked like below.

HEAD /sites/all/modules/token_custom/LICENSE.txt HTTP/1.1
HEAD /sites/all/modules/active_tags/active_tags.js HTTP/1.1

As you can infer, looks like they have an exhaustive list of static files in all the modules that they can ascertain through their service.

They are using HEAD requests to save the bandwidth.
If the HEAD requests return 404 response code, the module is not present in the code base if it gets a 200 response code then it can ascertain that the module is present.

However it would be good to know if they have a list of modules with static files or if they have automated that to find the static files all the module on drupal.org.

The suggestion to enable access log was made by Clive.

Note : Currently the services only looks at the sites/all/modules folder only. But I think they can easily tweak a little to make it more generic.


Access Node in html.tpl.php in Drupal 7 I am trying to access the current $node variables in the html.tpl.php within Drupal 7. The problem is that I am running a Analytics software in the backend for which I've to record each page's analytics from html.tpl.php.

If there's a normal page, I have to record generic attributes but if it's a node, I need the following things in the html.tpl.php:-

Title of the Content (Node)
Content Type of the Content

I can do this in node.tpl.php through $node->type;, but unfortunately I need it in html.tpl.php.

Many Thanks.

You can get the current menu object with menu_get_object(). From there you can determine if that object is a node or not. Since it defaults to "node" it will be empty if you're not on a node page and will have all the normal node object stuff available if you are.

$node = menu_get_object()


Ambiguity of using '.' as a separator in the site directory name might have security implications? In a Drupal installation, which is served through the web server's default server config (i.e. it gets any request for an otherwise unknown domain) I have a settings file at DRUPAL_ROOT/sites/example.com.au/settings.php.

This site is normally requested as http://example.com.au/, but what's given that the request gets to the server (and the user agent may not follow the directives of DNS here), what's to prevent it being served as a response for http://example.com/au/ or http://example/com/au/?

The testing I've done suggests something blocks this from working (I get a redirect to the install page), but I want to be clear on what's going on, and to be sure that it's reliable.

If accessing a drupal installation through divisions of the domain name and path other than the expected one is possible, then there would be security implications.

EDIT:

In response to @tenken:

From https://api.drupal.org/api/drupal/sites!example.sites.php/7

This file allows you to define a set of aliases that map hostnames, ports, and pathnames to configuration directories in the sites directory. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. See default.settings.php to view how Drupal discovers the configuration directory when no alias is found.

It's not perfectly clear, but that sounds like the directory in the sites file will will still be used if a request arrives with a domain name that was not anticipated, in which case the problem remains.

Your virtual host rules are as secure as you've written them. If you want complete control on what URLs map to what multi-site installations then use the sites.php placed in sites/sites.php of your sites folder to explicitly set what URL(s) go to which Drupal installation using PHP.

The sites.php file resolves the URL -> site mapping after the webserver directs traffic to Drupal.

EDIT

Drupal can be run in multi-site or standalone. This is accomplished on how you configure your webserver. The "problem" you're describing is you want to use multi-site but not have Drupal try to discover invalid site addresses. This is purely dependant on how you setup your webserver.

An example of how to setup Apache for multisite might be:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com
  DocumentRoot /var/www/example.com
</VritualHost>

This will resolve example.com to the docroot and any subdomain site at *.example.com -- including "invalid" subdomains which may not exist and attempt to route to an invalid url as you've described. This is by design by Drupal when using multi-site installation.

How might this be fixed for Apache? By fixing Apache vhost entries to limit what valid domains the virtual host is used for. This is not necessarily fixable via Drupal (although I still like using sites.php personally).

For instance we can change our virtualhost to the following:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias site1.example.com abc.example.com xyz.example.com example
  DocumentRoot /var/www/example.com
</VritualHost>

This revised Apache virtualhost routes example.com and exactly 4 subdomains and no others to the docroot. No other domain traffic will be routed to this drupal installation from the webserver.

A similar technique should be available for most webservers. Your virtual host rules are as secure and as organized as you've written them for your own production servers. I use Nginx as a proxy for Apache on a few websites, and Nginx as the sole webserver for at least 1 site, but I haven't had to try to solve this problem myself using only Nginx (but I'm familiar with the Apache solution above).


how to add div tag to field collection I have a field collection named rmr_bar_li. I want to add a div to each line item of field collection, that is within field collection. How can I do that? Can any one help?

We need to write a hook_form_alter();
In my case ,

function mymodule_form_alter($form,$form_state,$form_id) {
  form['rmr_bar_li'][und][0]['anyfield']['#suffix'] =

;
}

Here anyfield is field inside the field collection below which you have to place your DIV tag.


How to autoexpand everything on a view translation edit form? To fully translate a view into one language I have to expand dozens of collapsed panels, most of them with only one or two subelements.

I've reported it here. But is there a quick workaround, like a module or setting that automatically expands all these panels?
I tried using hook_form_FORM_ID_alter but changing the #open value is ignored (note that it's a top-level Displays panel #open which is true by default):
 /**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_admin_form_config_translation_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  foreach ($form['config_names'] as $key => $config_name) {
    if (substr( $key, 0, 1 ) !== '#') {
      $display = $config_name['display'];
      $display['#open'] = false;
    }
  }
}

It's set to closed at
https://git.drupalcode.org/project/drupal/-/blob/8.9.x/core/modules/config_translation/src/FormElement/ListElement.php#L70
by
            '#open' => empty($base_key),

so I'll just add a patch to composer to change it to
            '#open' => true,


Webform confirmation message alternate source How can I override the default webform source for the form submission confirmation message and fetch it from a 'CCK' (I still can't remember what they are now called in D7) element instead?

You could use an approach similar to that outlined here: http://drupal.org/node/1245298

Steps:

Use hook_menu to create your confirmation page path
Set confirmation page in webform ( e.g path is confirmation/%nid/%sid to pass parameters )
Load relevant webform and/or submission in menu callback
Display confirmation message as required.


Theming the user registration form I want to theme the user registration form in Drupal 7 by adding new markup, etc. I cannot seem to figure out how to do it.

I've followed a few tutorials which suggested that you could simply invoke hook_theme in template.php, and use a corresponding theme function:

function mytheme_theme(){
  return array(
    'user_register' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mytheme_user_register($form) {
  // print, die, etc
}

But this is not doing anything, regardless of what I do in the theme_user_register() function, or how many times I clear the caches.

Any thoughts about how to do this in D7?

It turns out that I need a combination of changes:

I had to implement hook_form_alter()in a module and set the form's #theme property:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'user_register';
}

And then in template.php:

function mytheme_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
  );
}

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And then I added user-register.tpl.php with my desired markup, and

<?php echo $rendered; ?>

to print the form.


Display results of a form I am trying to find a simple way to display the results of a simple checkbox form on the same page after submit. I know you can use the drupal_set_message, but I want to display the results formatted on the page, not in the message box.

public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message($this->t('Your favorite car is @fav_car', array('@fav_car' => $form_state->getValue('fav_car'))));
      }
    }

Full code for form here;

/**
 * @file
 * Contains \Drupal\cars\Form\FavoriteCarForm.
 */

namespace Drupal\cars\Form:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\cars\CarsStorage;

/**
 * Class FavoriteCarForm.
 *
 * @package Drupal\cars\Form
 */
class FavoriteCarForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'favorite_car_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['fav_car'] = array(
      '#type' => 'radios',
      '#title' => $this->t('What is your favorite Car!'),
      '#options' => array('Toyota' => $this->t('toyota'), 'Ford' => $this->t('Ford'), 'Subaru' => $this->t('Subaru')),
    );

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your favorite car is @fav_car', array('@fav_car' => $form_state->getValue('fav_car'))));
  }
}

This is not different from what is done in Drupal 7:

When building the form, you verify in $form_state a value is present; if it is present you show its value
In the submission form handler, you tell Drupal to rebuild it

What changes is the code you actually use, since Drupal 8 introduces new classes Drupal 7 doesn't have.

class FavoriteCarForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'favorite_car_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['fav_car'] = array(
      '#type' => 'radios',
      '#title' => $this->t('What is your favorite Car!'),
      '#options' => array('Toyota' => $this->t('toyota'), 'Ford' => $this->t('Ford'), 'Subaru' => $this->t('Subaru')),
    );

    if ($form_state->getValue('fav_car')) {
      // Show the value the user entered.
    }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }
}

Calling $form_state->setRebuild() causes Drupal to call buildForm() again, passing in $form_state the values the user submitted and the values added from validation and submission handlers.

I didn't add the code to write the submitted value. You could:

Show it as description of the form element
Show it in a #markup element

I would rather not implement such code for just showing the selected value, though. I would use it to show the result of an elaboration done from the input given from users, for example showing a map of the town entered from users.


Using token in page.tpl.php? I downloaded the social media module and I found this token: [socialmedia:sm-twitter_username]. I want to show it where the Read more / Add new comment section is, under an article. Since I can't find a block that is for that sections how can I just insert it into the code?

The Read more link is added by node_build_content(), while Add new comment is added by comment_node_view(); other links like those can be added by any module implementing hook_node_view().

So, to answer your question, there aren't theme regions you could use to add links where you see Add new comment, and you don't add them in page.tpl.php. You need a module implementing hook_node_view(), for example using the following code.

function mymodule_node_view($node, $view_mode, $langcode) {
  $links['socialmedia_twitter'] = array(
    // Depending on what the token returns, you need to use one of these lines.
    'title' => token_replace(' [socialmedia:sm-twitter_username]'),
    'href' => token_replace(' [socialmedia:sm-twitter_username]'),

    'attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($node)))),
  );

  $node->content['links']['mymodule'] = array(
    '#theme' => 'links__node',
    '#links' => $links,
    '#attributes' => array('class' => array('links', 'inline')),
  );
}

Rather than calling token_replace(), I would look at the module code, and see which function generates the token, and use it instead of calling token_replace(), since you are replacing a single, static, token you already know which one it is.
In any case, you need to check the code implemented by that module, as some token require an extra parameter passed as $data; without that, they don't work, or they don't produce the expected output.

In a theme, you would implement hook_node_view_alter().


Can't group by year from a date row I have a field of date-time type. I added this field into a view and formatted the date-time field to show only year. When I switch 'aggregation' on in Views and try to group this field it didn't work as i expect and show all the dates again. I saw the Vies-query and there wasn't any preformatting. It was grouping by dis field only. I want the modify the query to get this fields formatted as i need(years only). Any advices would be appreciated. Thanks in advance!

I don't think (I haven't seen your view) you need to enable aggregation to group by year. This is a solution:

If you need to display the date field value add the field twice. You will use one for the display of the date and the other for the grouping by year. If you are not going to display the date, you still need the date field to be able to group by year.
On the date field you are going to use to group by year you need a custom format that will only show you the year and if you are collecting both start and end date set it to you only the start date or the end date, but not both.
To create a custom date format go to admin/config/regional/date-time in Drupal 7 or to admin/settings/date-time in Drupal 6. There you will create a date format that will only show the year and then create a date format type that will show that date format.
Back to the date field you want to use to group by year change its format to the newly create format that only show you the date and set you show only one date and click apply. Also if you don't want the year value to show on the view check the option to exclude it.
Depending on the view format you have chosen (Table, Unformatted list, HTML list, etc) you will click the setting of the format and you are going to set the date field with the newly date format as the grouping field. Click apply and you are done.
You might also want to visit the "sort" section of your view to set the sort order of the dates.


Hide Price by Role for a Content Type in Drupal 7 I am trying to achieve the following:
1> Hide Price Field for a Role only on a specific content type.

I am using Drupal Commerce.

Things I tried:
1> Field Permissions for the commerce_price field on a product. But because we using the same field across all product types the settings do not apply  to  just 1 product type.

2> preprocess_node
But could not access the price componenet. As it is a component inside the product reference field.

Could you please help me figure this out. Any help would be really appreciated!!

Links referred:
https://www.drupal.org/node/1496450
Is there a way to hide the price on a product using Drupal Commerce?

I have never used Drupal Commerce, however I understand that you want to hide a field according to a role. That is doable through hook_field_access().

hook_field_access($op, $field, $entity_type, $entity, $account)

  Determine whether the user has access to a given field. This hook is
  invoked from field_access() to let modules block access to operations
  on fields. If no module returns FALSE, the operation is allowed.

https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_access/7


Whenever new user registered, how to make them active based on some condition automatically I have a cloud driven drupal site. In the site one content type exists named as people it has email field. The content in this content type is around 5000. Whenever new user registered I want to check user email with the people content type email field that is around 5000 content i want to check. If user email matches with any one email in people content type I want to make them active automatically. How to do this.? Can anyone give me suggestions. I tried with rules but its not happening. Can anyone suggest some custom php code for rules module

Using PHP on admin end is not recommended. If you are interested in custom module here are the pointers

Implement hook_user_presave : Invoked when a user is created or updated.
Make sure your code inside presave hook is conditional for new account created but not updated. You can use in_new property of account object

if ($account->is_new) {...}
Use Entity Field query to find a node with email id of current account being created
if you found a result then Set $edit['status'] as 1.


Looking for a Menu Module on Node Page Out site has many, many nodes included in a number of menus. When creating a node, the Parent Item select box under Menu Settings is quite long.

Is there a module that provides a better, more usable interface to selecting the parent item? I've done some searching and couldn't find anything.

I can recommend you Menu Link Weight together with Client-side hierarchical select. The combination of those two modules allow you to separate each level in an own select field and makes sorting pages within a level very handy.

After installing both of them visit /admin/config/user-interface/menu-link-weight and select "Client-Side hierarchical select".

This solution works very well for a site where we use a lot of levels and menu items.


Ajax filter in exposed view not working I am embedding a view as such:

function theme_module_name_element($element) {
  $view = views_get_view('view_name');
  $view->set_use_ajax(TRUE);
  $output = $view->render();
  return $output;
}

The view is displayed then by the filefield sources module but when you try to search it won't use ajax. I'm assuming this has something to do with the js not being loaded but I just can't figure out how to get this going!

Any ideas?

Edit: This might be related to this: http://drupal.org/node/386388

Edit 2: The pager works and when it has been used the search works...

Edit 3: When the pager is pressed (and everything works fine) there is html added to the form so it goes from:

(Edit 3 update: If I had to guess I would say "Drupal.behaviors.ViewsAjaxView" from ajaxViews.js isn't being executed when the filefield_sources source is being chosen.)

                Search

                            <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="" class="form-text">

                    <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">

to:

    <form action="/" accept-charset="UTF-8" method="get" id="views-exposed-form-Filefield-Sources-Imagebrowser-default" class="views-processed">

                    Search

                                <input type="text" maxlength="128" name="image-title" id="edit-image-title" size="30" value="arnar" class="form-text">

                        <input type="submit" id="edit-submit-Filefield-Sources-Imagebrowser" value="Apply" class="form-submit">

        <input type="hidden" name="view_name" value="Filefield_Sources_Imagebrowser">
        <input type="hidden" name="view_display_id" value="default">
        <input type="hidden" name="view_args" value="">
        <input type="hidden" name="view_path" value="node/add/dagskrafaerslur">
        <input type="hidden" name="view_base_path" value="null">
        <input type="hidden" name="view_dom_id" value="655136b3027e2ef4608dfbaa7605db4c">
        <input type="hidden" name="pager_element" value="0">
    </form>

(Notice the addition of the form tag and input elements.)

Enable the Ajax in Views Basic Setting and remove $view->set_use_ajax(TRUE); and check.


How do I target a specific term or node in a toked? I am developping a site on a dev server, and I am wondering how to create hyperlinks not depending on the server the site is running on.

I have considered usig href="node/xx" and href="term/yy" but I would like to use the paths generated by pathauto.

But I cannot include the pathauto url as I am certain my client will change titles before I move the site to its final destination, and I might have to regenerate paths to do that.

So I am wondering if there is a way with tokens. Something like [node:nid:122] or [term:tid:122]

The link node module is doing this for you. Here is a quote about it (from the module's project page):

Once installed you (or any user who can post) can add an embedded href link to any node using the syntax (where N is a number, and NNN is a node id):
[node:NNN]
Parameters follow the part and are comma separated name="value" pairs:
[node:NNN,title="Original version of the picture"]
MultiLink supports Link Node, so if someone is viewing in another language it gets converted to [node:101] or whatever the correct node is for the translated version automatically.


drupal_get_messages always blank the drupal_get_messages() function is returning nothing when run from page--front.tpl in my custom theme. Do I have to add something to page.tpl.php to build this?

I have a print_r set up and it's always entirely empty even though in the admin panel I've got all types of messages

By the time your page template is built, drupal_get_messages() has already been called (by way of theme_status_message(), which is called from template_preprocess_page()).

Since drupal_get_messages() clears the message cache unless the second argument to the function is explicitly set to FALSE, and theme_status_message() doesn't provide that second argument, the next time it's called the $_SESSION['messages'] var has already been cleared.

You already have access to $messages in your page template file, but if you're looking to get hold of each individual message you'll probably have to do this in a preprocess function:

function MYTHEME_preprocess_page(&$vars){
  $messages = drupal_get_messages(NULL, TRUE);
  $vars['message_list'] = $messages;
}


Set up Drupal to use alternative nodes for different incoming urls? I have a Drupal website set up selling a single product. Currently the transactions are being processed with paypal with simple buttons set up on a specified node (e.g. www.website.com/buy).

I want to start a referral or affiliate system so that drupal will notice the different incoming links (www.website.com/referral) and will then always route (www.website.com/buy) to (www.website.com/buy_referral) once it detects the different incoming links. This is because I will set up different PayPal buttons for different referrals on different buy_referral nodes.

Is there a module available to do so? or is there an easier way to do things?

Thanks for the help.

You could use the mod_rewrite features in your site's .htaccess to redirect before Drupal even gets started. This would increase performance vs. using JavaScript.

Implementation details:

https://stackoverflow.com/questions/5151385/redirect-on-the-basis-of-referer-http-referer-htaccess

More about Drupal's .htaccess:

http://drupal.org/getting-started/clean-urls

Contents of Drupal's .htaccess:

http://drupalcode.org/project/drupal.git/blob/HEAD:/.htaccess


How to limit and enable Commerce shipping options based on the customer's country? Very simple use case, using only flat rate shipping, with version 2 of Drupal Commerce Shipping and Drupal Commerce Flat Rate. I have two shipping options customers can choose between if they are in one country (the UK) and two if they're in any other country. Let's call them:

UK standard
UK special
International standard
International special

I've looked for ways to switch shipping rates on and off using rules, but all I can find is rules that apply a particular shipping rate, not rules which enable or disable options that the customer can then choose between.

This related question gives a faint outline of how to apply rates, but not how to enable or disable options, and likewise this related question, where there are 12 options but all are chosen for the customer (and the answers simply say "use rules"). Under the Calculation Rules tab under admin/commerce/config/shipping/services/flat-rate, I can't see anything in the "actions" list that looks like it enables or disables a particular rate. Plenty that appear to apply a rate, but not giving the customer a choice or limiting the choice.

This is clearly common and possible, as it's referred to for example in this issue, but I can't find anything on how to do it.

I've tried adding a rule like this through "Configure component" for a particular shipping rate, but it had no effect, the international rate still appears as an option even if the country is "United Kingdom". Here's the rule:

Here's another I tried using "Calculation rules" which, also had no effect:

Everything I can find around enabling or disabling shipping by country is about disabling countries completely.

I couldn't find anything in the Commerce Shipping documentation, and there is no Flat Rate documentation.

The two crucial pieces of information:

The "Configure component" link alongside each shipping rate under admin/commerce/config/shipping (Store > Configuration > Shipping) is the place to set validation criteria for a shipping rate to appear as an option.
In these rules, countries need to be inputted as two-letter country codes not the full names.

In detail:

Set up the shipping rates and go to admin/commerce/config/shipping (Store > Configuration > Shipping)
For each one:

Follow the "Configure Component" link
"Add condition"
Commerce Order > Order Address Component Comparison
Address value = Shipping Address, Address Component = Country, and tick the Negate box at the very bottom if this is one for "everywhere but" (e.g. international rates)
Input the 2-letter country code under Value. You can see what this is by using Inspect Element on a country selector dropdown:


Starting with View Modes I have done a drupal theme and as of right now am only working with teaser and full view modes.  Both of which I have themed in the node--product.tpl.php file
I am interested in learning view modes to create different,  fully customizable layouts for different pages and products.

How and where to create a new view mode for a paticular node type ie. Node--product.tpl.php before themeing.  Is there a preferred module for this which doesn't limit themeing.
How and where to tell a given page ie. Page--front.tpl.php which view mode of a paticular node type to use.  Is there a module for this. As of now the product nodes appear under the content region.

How and where to theme the html of a view mode. Even if it's a template override. Right now I have the two view modes themed in a photo if else statement. The "if" being the teaser and the "else" being the full node.
Any tutorials or videos that stand out for this?

You should take a look at Display Suite.  It makes easy work of most template modifications without having to create .tpl.php files.  It has an easy to understand method of managing View Modes.

From the above link:

Use custom view mode

Enable DS UI module.
Go to Administration > Structure > Display Suite > View modes (admin/structure/ds/view_modes)
Click "Add a view mode"
Enter a label & define to which entities the mode will be made available
Click "Save"
Go to Administration > Structure > Display Suite (admin/structure/ds)
Click "Manage display" for the entity (e.g., "User") whose display you like to change
Choose the vertical tab "Custom display settings"
Enable the new view modes
Click "Save"
Flush all caches
Choose the custom view mode from the secondary tabs in the top of the page.


Select an Image style depending on external/dynamic factors (theme region or other field content) I have a Bean (bundle that generates blocks) which I display in one of 2 different theme regions. Either in the header, or the footer. This Bean contains an Imagefield, which is rendered through an Image Style.

I would like to be able to display the Image using a different Image Style, depending on which region the Bean is being displayed in. For example, if the Bean is being displayed in the header region, then I want the image to be rendered in style A. If it's being displayed in the footer then the image should use style B.

So - how can I select the Image Style that is used for an Image Field depending on which region the content is being displayed in?

One option would be to add another field to the Bean which would be a 'Style selector', however this introduces another step for the site owner as then then have to manually specify which style they want to use. It would be better if this were done automatically based on where the content is being displayed. However, if this can't be done, then how would I adjust the Image Style based on the value of another field?

You could use Viewmodes (Layout Plugin / Display suite) in order to use different image styles.

E.g. Use a view with rendered viewmode "Teaser-Big" in Header and "Teaser small" in footer and pass an context argument to the view.


Paragraph contextual filter I would like to create "related item" with paragraphs.

I have 2 content type using paragraph field. This paragraph field has different options, like "quotes, related items, slider" etc.

I want to get some fields from "related item". "Related item" field is a "Entity reference".

Inside paragraphs type I have one called "related item"

Inside this I have a field type "entity reference"

I have different pages where I can add this paragraph and choose the entity.

I want to get specific fields from this entity type.

I know I can acomplish this with a view, relationship and contextual filters, but I don't how to do this with a paragraph or if it is possible.

You may have to jump through several hoops to get the data from the entity reference field.

  // Query entity types
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'your_content_type');
  $entity_ids = $query->execute();

  // Query paragraph types
  $paragraph = \Drupal::entityQuery('paragraph');
  $paragraph->condition('status', 1);
  $paragraph->condition('type', 'paragraph_type');
  $paragraph_ids = $paragraph->execute();

  // Loop through entity IDs
  $paragraph_output = array();
  foreach($paragraph_ids as $pid){

    // Load each paragraph
    $paragraph = Paragraph::load($pid);

    // Load each entity reference field
    $entity_id = $paragraph->get('field_entity_identifier')->getValue();

    // Get entity parent Node ID
    $parent_node = \Drupal::entityManager()->getStorage('node')->load($parent_id[0]['value']);

    // You'll need to insert another foreach loop here drilling down further into the node that is being referenced.

  }

First you have to loop through the content types. Then you have to look to see if those paragraphs are set and have data. Then you loop through the paragraph types data and get the nodes they reference. Then you have to loop referenced nodes.

It's not an exact solution, but it's how I load data in modules and create my own API endpoints for some fairly heavy frontend javascript applications.


How do I print an image field value in views-view.html.twig? It seems I'm able to print text field values with {{ view.field.field_example.getvalue(view.result[0]) }}, but this same method doesn't work for image fields. Please help.

views-view.html.twig is not meant to be used for field printing.

You should use views-view-fields--[view-name].html.twig

OR

views-view-fields--[view-name]--[machine-name].html.twig if you want to be even more specific.

and there you just do

{{ fields.field_name.content }}

  For multi value fields, is there a way to print just one value within a field at a time?

{% set field_values = row._entity.get('field_name').getValue() %}
{% for field_value in field_values %}

{{ field_value['value'] }}

{% endfor %}

  By doing {{ fields.field_color_hex.content }}, I printed them all at
  once.

In your case:

{% set hexes = row._entity.get('field_color_hex').getValue() %}
{% for hex in hexes %}

{{ hex['value'] }}

{% endfor %}


Create a new template view for a specific vocabulary name I'm in need of some help for my Drupal 7 site. Right now I am using the stock taxonomy view (/taxonomy/term/%) that came with views to display a listing of some specific nodes. It works great.

Now I would like to create another page that will display a different view listing of nodes under a different vocabulary term. I'd like to template to be different also.

I'm having trouble wrapping my head around how to best do this. I am using Panels for some of my pages so could I use that? I've tried to activate the panels page that overrides the taxonomy, but I can't because I am using views already to generate a page. Can I clone my current view and set a filter for a specific vocabulary and use that?

I ended up using the Taxonomy Views Switcher module which allowed me to create a new views page. It's not the best solution, but for me it works.