Update a block from another block I want to write a page that works like this:
http://www.albemarlegallery.com/artists.php

i.e. when I hover over a link from one block, an image in another block updates

How can I do that?

Thanks

You can use javascript and ajax to update your image
just when hover your link replace src of image It is javascript only
it is not drupal all your html in the same page so it is easy to change any block when hover over another block


Programatically upload a page in D7 I'm certainly a noob, so sorry for this if it's very basic.

I had an installation of D6 and the following code was working perfectly. But when I upgraded to D7, the page was posted, but the body wasn't being uploaded. I see that the location of the body has changed in the MySQL structure, but how do I address it in the code? Here's what was working in D6:

    $node->name = rand();
$node->title = $content->title;
$node->created = time();
$node->status = 1; //published
$node->promote = 0;
$node->sticky = 0;
$node->body = $content->data;
$node->type = 'page';
//$node->path = $content->path;
$node->revision = 'true';
node_save($node);

Interestingly, when I try to specify the path, the node_save returns an error, but when I specify body, it fires, but the body never shows up.

Can anyone help? I've spent a lot of time on this... much appreciated.

<?php
//Create node
    $node = new StdClass();
    $node->type = 'game';
    $node->title = t('@date-@time', array('@date' => format_date($om__result->date, 'short'), '@time' => format_date($om__result->time, 'custom', "h:i A")));

    //Date
    $node->field_date = array(
      0 => array(
        'value' => format_date($om__result->date, 'short'),
      ),
    );

    //Location
    $node->field_location = array(
      0 => array(
        'value' => $om__result->location,
      ),
    );

    //Home team
    $node->field_home = array(
      0 => array(
        'value' => $om__result->home,
      ),
    );

    //Visitor
    $node->field_away = array(
      0 => array(
        'value' => $om__result->visitor,
      ),
    );

    //Division
    $node->field_divsion = array(
      0 => array(
        'value' => $om__result->divisoin,
      ),
    );

    //Program
    $node->field_program = array(
      0 => array(
        'value' => $om__result->program,
      ),
    );

    //Time
    $node->field_time = array(
      0 => array(
        'value' => $om__result->time,
      ),
    );

    //Field
    $node->field_number = array(
      0 => array(
        'value' => $om__result->field_nuber,
      ),
    );

    node_submit($node);
    node_save($node);
    drupal_set_message(t('@node has been created', array('@node' => $node->title)));
?>


How to delete file using drupal_form_submit? I'm using rest services with a custom resource on node update, i want to build the correct variable node structure to delete one of the files on a file image multiple fields.
I removed the file element from the form_state['values'] but isn't working.
I know i can do it manually but is it possible altering form_state['values]  ?

You can use this code in your form submit function

$file ='public://not_imported_longanswer.csv';
$path = $base_url . '/sites/default/files/not_imported_longanswer.csv';
if (file_exists($file)) {
    file_delete($path);
}


How to implement Commerce USPS Shipping? I have installed the following modules:

Commerce Shipping module (7.x-2.2)

Shipping UI
Commerce USPS module (7.x-2.0)
Commerce Physical Product (7.x-1.x-dev)

Checkout without shipping is working fine.Now in checkout settings I have enabled shipping service and info.

I am able to see USPS shipping method config and rules which are set to default (for now). I tried using different rules but can't see any shipping method in the checkout screen.

I have set production account username and url of the USPS.com (this probably isn't the problem).

I want to know step by step procedure to configure the shipping method and rules to add USPS shipping service.

I have 3 products types from which only one will have shipping service,I can see "Shipping" line item type but how to implement it to the product type so that shipping is shown on the checkout screen or is it optional?

Have a lok at the README.txt that comes with the Commerce USPS module, here is the content of it:

About this module
Commerce USPS module provides shipping calculations from the USPS
WebTools API
Dependencies
This module depends on the Commerce module
(http://www.drupal.org/project/commerce).
In addition, the following modules are required:

Commerce Physical - http://www.drupal.org/project/commerce_physical -  this module is used to define the physical properties (weight and  dimensions) of each product. This information is necessary to
determine  a shipping estimate.

Commerce Shipping (7.x-2.x) -  http://www.drupal.org/project/commerce_shipping - this provides the
infrastructure for Commerce UPS to fully integrate with the Commerce
module.

Installation

Install and enable the module and all dependencies (be sure to use  the latest versions of everything). Add dimensions and weight fields
(new field types via the Commerce Physical module) to all shippable
product types. Populate dimensions and weight fields for all products.

Configure the "Shipping service" checkout pane so that it is on the  "Shipping" page. The "Shipping service" checkout pane MUST be on a
later  page than the "Shipping information" pane.
(admin/commerce/config/checkout)

Configure the USPS settings  (admin/commerce/config/shipping/methods/usps/edit). You'll need to
create USPS WebTools account and obtain a username via
https://secure.shippingapis.com/registration/.

Limitations
Eventually, all of these limitations may be addressed. For now, be
warned.

Single "Ship from" address for all products.

Doesn't ensure product dimensions are less than default package size  dimensions. In other words, if you have a product that is 1x1x20
(volume=20) and your default package size is 5x5x5 (volume=125), even
though the product won't physically fit in the box, these values will
be  used to calculate the shipping estimate.

Doesn't play Tetris. For example, if you have an order with 14  products with a combined volume of 50 and your default package size
has  a volume of 60, the shipping estimate will be for a single box
regardless of if due to the packaging shape they don't actually fit in
the box.

Doesn't limit the weight of packages. If you're trying to ship a box  full of lead that weighs 600lbs, this module will let you
(instead of  breaking the order into more packages).

Doesn't account for packing material. If you need to account for  packing material, then you may want to adjust product dimensions
accordingly.

Methodology
Calculating estimated shipping costs is a tricky business, and it can
get really complicated really quickly. Knowing this, we purposely
designed this module with simplicity in mind. Here's how it works:

Every order must contain at least one package.

The number of packages is determined by calculating the total volume  of all products in the order, dividing by the volume of the
default  package size, and rounding up.

The weight of each package is determined by dividing the total weight  of all products in the order by the number of packages.

If you need custom functionality, you have several options:

Determine if it is something that can be generalized to suit a number  of users and submit it via the issue queue as a suggestion for
inclusion  in this module.

Hire one of the maintainers to create a custom module that interfaces  with Commerce UPS to add your custom functionality.

Break open a text editor and start coding your own custom module.

Apart from that, the module's project page contains this extra info:

Please refer to the README.txt file for additional information about how this module works and how to set it up.

Install and enable the module and all dependencies.

Add dimensions and weight fields (new field types via the Commerce Physical module) to all shippable product types.

Populate dimensions and weight fields for all products.

Configure the USPS settings (admin/commerce/config/shipping/methods/usps/edit). You'll need to create USPS Web Tools account and obtain a username https://secure.shippingapis.com/registration/ and call USPS to have the account moved into production (tell them you are using 3rd party software).


How to add a view tab to node edit form? I have two node bundles: events and registrations. Registrations have an entity reference field pointing to a given event.
I have a view, that list registrations with  some event and registrant information and a contextual filter for given event. I would like to add this view as a tab to Event node edit form so, that it would list current registrations to given event.
I managed to display the view on the edit form easily by adding the view to form render array with event nid as an argument for the contextual filter, but not sure, what are the possible ways to add view to a node edit form as a tab.

I'm assuming you mean "Drupal tab" when you say you want to display Views as a tab on the Event edit form. "Drupal tabs" are the "View | Edit | Translate | Etc" links that are usually visually styled as tabs.
Although, a Drupal tab is an independent page, it will not be like a Block within the Edit form, it will be just a link on the "View | Edit" menu, you'll have "View | Edit | Registrations". This means you won't see registrations listed when you go to Edit (unless you add a Block to that page through regular procedure), you will see your Registration results when you visit the "Registrations" link/page.
Display a Views Page as one of Drupal tabs
You will need to have the "Page" Display in your Registrations Views. Page Displays have special Page settings that include the Path and Menu options. Additionally, you'll need to adjust the Contextual filter too, to only appear on Event type nodes.
You can combine these two settings to make that Views Page appear among the Drupal tabs of a set of links.
The Path needs to follow the logic of the set of links. In your case you have drupal tabs /node/[nid], /node/[nid]/edit etc. You'll want to set your Path to node/%node/registrations.
On the Menu you should choose the Menu tab option, fill in what you want the tab text to say (into "Menu link title"), choose a Parent, it can some menu you're not displaying anywhere if you don't need this page to appear as a menu item elsewhere. The Weight will affect the order on the Drupal tabs, enter a larger number (e.g. 50) to make sure it comes up at the end, and not before "View" or "Edit".
You already have the Contextual filter configured and working, so you might not need to do anything else. Check that the Contextual filter ID from the "Content" Category with these settings:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type Event
Set the option for the case when the argument doesn't validate to something that makes sense to you.
When you save this View and reload some Event node page you should be able to see the Registrations as a Drupal tab. Rebuild Drupal cache if it doesn't appear.


Making a custom views field handler click sortable (getting an error when clicked) When I make my custom handler click sortable and subsequently click the label in the table heading of the view I get the following error:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unknown' in
  'order clause'

My handler is defined as below. This is a render only handler that performs a calculation on some other field data and outputs.

UPDATE:

Am I right in thinking that because this data is not stored in the database that I can't make it click sortable because there is no column to order by in the SQL statement that is generated?

Is there a way around this? Any help appreciated.

function rate_calc_views_data() {

$data = array();

$data['node']['rate_calc_handler_result'] = array(
    'title' => t('Standard Deviation'),
    'help' => t('Calculates the voting result standard devaition'),
    'field' => array(
      'handler' => 'rate_calc_handler_result',
      'click sortable' => TRUE,
    ),
    'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter',
     ),
);  return $data; }

Because this data is not stored in the database (it's just a dummy field that returns the result of some calculations) you can't make it click sortable as there is no database column to 'order by' in the SQL statement generated by the view.

There must be a way around this but it's likely quite complicated and beyond me at the moment.

If you have a custom handler that does something to change the way you display existing field data you can make it click sortable by overriding the click_sort($order) function in your handler class.

My mymodule.views.inc now looks like the below (where 'real field' is the name of the field included in the view, before the custom field created by my handler, but excluded from display)

<?php

function mymodule_views_data() {

    $data = array();

    $data['node']['mymodule_handler_myname'] = array(
        'title' => t('Score'),
        'help' => t('Makes score values human readable'),
        'real field' => 'value',
        'field' => array(
          'handler' => 'mymodule_handler_myname',
          'click sortable' => TRUE,
        ),
    );

    return $data;

}

?>

and my mymodule_handler_myname.inc looks like

<?php

class mymodule_handler_myname extends views_handler_field {

    /**
    * Loads additional fields.
    */
    function query() {

    }

    function click_sort($order) {

        $this->query->orderby[] = array(
            'field' => 'field_name', // here may be a field, or some SQL clause e.g. FIELD(str, str1, ...)
            'direction' => strtoupper($order),
        );

    }

    /**
    * Renders the field handler.
    */
    function render($values) {

        if (isset($values->field_name)){

            switch ($values->field_name){
                case 2:
                    $vote = 'Yes';
                    break;
                case 0:
                    $vote = 'No';
                    break;
                default:
                    $vote = 'Maybe';
                    break;
            }

            return t($vote);

        }
    }
}

?>

This wrecked my head for a full day so hopefully it's helpful to someone in the future.


Webform Drupal 8, node and form, how to pass node field info to form? I don't understand how node integration with webform works.  How do I pass data from a node with a webform field to an instance of that form?  I created a form with email and location.  Then I created a content type with location, description, date, and a webform field and then I added some content to it. How do I associate the location from the content type to an instance of a form?  How does the "Default submission data (YAML)" work?  I put "[current-page:title]" in there expecting it to populate the form, but I don't understand how to specify what form field it goes to or if I'm using the right syntax or what??

The location node is considered the 'source entity' and is automatically tracked.

You can use the [webform_submission:node] to pull information from the location node into the 'Default webform submission data (YAML)'. For example, to get the location's title you should use the [webform_submission:node:title] token.


Creating rollover tooltip for a view (Netflix Style) Here is my scenario: I'm trying to create a view that displays images, and some additional information on rollover -- Something similar to how Netflix does it, and I'm trying to determine the most feasible way to do this. I've found the Beauty Tips module, but since my view is inside a panel, I'm not really sure if this module will do exactly what I'm looking for. Any tips on how this could be implemented would be really helpful. (using Drupal 7 btw)

You probably want to use the Views Tooltip module, which allows you to do exactly that. It depends on the Tipsy tooltip module, and works with Drupal 7.


Conditional Field on Multiple Selects Module I have 1 Multiple Select field and 2 Select List fields:

I need to show those 2 Select field only when Multiple Select has a value of 1 (the first value of the list is selected). I made the dependency and the 2 Select lists are hidden, but when I select the first value of the Multiple Select field, the 2 fields are not appearing, nothing happens.

Is there something that I'm doing wrong? Any opinions why is this not working?

It work when I use these settings. See screenshots.


Get fields values in the view I am new on Drupal and I need to update an existing Drupal 7 website.

The website is multi-domains, multi-languages.

Getting the views fields values makes me a big headache!

The existing code of the website is like this:

In the folder templates:

Each template of the website has a file like: views-view-unformatted--some-name.tpl.php

And the to print the fields values, the code is similar to this:

<?php
$idInFieldCollection = $view->result[0]->field_field_a_name[0]['raw']['value'];
$item = $view->result[0]->field_field_a_name[0];
$value = $item['rendered']['entity']['field_collection_item'][$idInFieldCollection]['field_the_field_needed']['#items'][0]['value'];
?>
<?php print($value); ?>

This process seems huge!

And finding the path for each field value requires to use kpr() and explore the view object.

I don't understand so much yet all I read about Drupal, could you guys let me know if there is an easier way. With getters for example ?

You should use Entity module. in this module no matter what the language of the website is you can use entity_metadata_wrapper command to get the fields value. here is an example of my project where field_article_writer and title are fields of article content type:

function MYTHEME_preprocess_node(&$variables){
switch ($variables['node']->type){
    case 'article':
        $suggest = "page__node__article";
        $variables['theme_hook_suggestions'][] = $suggest;
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['title']= $wrapper->title->value();
        $variables['writer']= $wrapper->field_article_writer->value();
        break;
    }
}

Now in page--node--article.tpl.php, $title and $writer hold their correspondent value.


Why is the first visit to a rarely used site slow or even lead to timeout? I am looking for suggestions on Apache/Drupal/MySQL (localhost) configuration, to solve my issue. I use Ubuntu servers 8 LTS with classic Apache installation, and perform manual Drupal installation too. After publishing a site for customer review, I notice, that if a site is not visited very often or not visited at all for some time, such site response time increases significantly, up to situations with timeouts. Although, other vhost sites not on drupal on the same server run smoothly. E.g., if a site is rarely used, opening and navigating through out it takes very long times, or even timeouts. Each next page visit opens faster.

I use regular Apache settings and PHP memory up to 512MB, as sometimes Drupal module installations ask for more. Server is with 4GB RAM, and around 10 sites running on it at a time. Drupal for customer review is set without caching and performance settings turned on, thus I consider, that this can be a bottle neck in some cases, but still, if I work on the site, it is quite responsive, even without performance settings turned on.

I understand that there are very many ways of solutions and potential issue roots, but wondering, if there are some constructive ways to track this down to small list of tasks to accomplish better configuration. I've experimented with different Drupal performance tuning solutions found on the net, but it still does not solve issue, if a site is not used frequently. Restarting apache helps for a while.

There isn't a lot of information, and the answer is likely specific to your instance, but my first guess is that you are experiencing the effects of one or more cache misses.

If you are using APC, then your rarely used site may not have core files in the bytecode cache.  Subsequent visits will.

If you are using MySQL query caching, then your rarely used site likely doesn't have anything in the cache, so all queries need to actually run.

The Drupal cache entries themselves (ie, the variouls cache table) may also be stale, so initial slowdowns could be caused by this.

If you are using Poormanscron, then this could be running, too, on initial page loads.


Print views fields in a custom view page template I am trying to create a custom view page template which will be made of custom fields, which i am trying to print. I created a view page and added all the needed fields to it.

Next, I created a views-view--my-page-name.tpl.php template, which get's recognised, however when i try to print the fields, i get the errors below:

Notice: Undefined variable: fields in include...

Notice: Trying to get property of non-object in include....

Below is the full code of my custom view page template which i copied from the default view page template and modified it. Im trying to print the field with this code:

<?php print $fields['views_field_field_name']->content; ?>

I tried all variables of field name as: field_name, field_field_name, views_field_field_name, but none of them work, as they all give same error.

<div class="<?php print $classes; ?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  <?php print $pager; ?>

  <?php if ($header): ?>

      <?php print $header; ?>

  <?php endif; ?>

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

<?php print $fields['views_field_field_name']->content; ?>
<?php print $fields['views_field_field_age']->content; ?>
<?php print $fields['views_field_field_phone']->content; ?>

  <?php print $pager; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

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

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

<?php /* class view */ ?>

You are using template for display, here you will do theming for overall display, the $fields variable is not available here.

If you want to change how fields are printed relative to each other, row style, then you should use views-view-fields.tpl.php, in your case the name will be like views-view-fields--yourpagename.tpl.php.

but if you want to theme individual fields then you have to use views-view-field--yourfieldname.tpl.php.


Views 2: Combine two multi-value fields per row Creating a content type on D6 about short-listed books for a competition. Each entry (book) in the short-list is a node, with fields for book-title, book-description, author-names (multi-value), author images (multi-value).

So in order to create the short-list I'm using views. I thought I could combine multi-value fields using Views 2 but I can't work out how. I wanted to show:

Book title
Book description
Author photo 1 [image]
Author name 1 [caption]
Author photo 2 [image]
Author name 2 [caption]
...

etc

How can I achieve this using Views 2 on D6?

Ah.  I gotcha now.  Drupal has no internal automagic way of knowing any connection between your author name and photo fields.  But, for display purposes at least, you can show them together by hacking at the CCK field template.

If you go into CCK module's directory, you will find a content-field.tpl.php file.  Copy it into your theme's directory and then COPY it to content-field-field_author_photo.tpl.php, eg, based upon the field name of your author's photo field name.  It is imperative that you COPY it, not just rename it, CCK needs both the base template and the specific field one.

By default, this bad boy looks like this:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php print $item['view'] ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

and basically it wraps a CCK content field with lots of CSSable divs and so forth.  What you want to do is print out the author name under each photo, so you could do that by replacing the print $item['view'] (which is your photo) with something along the lines of this:

          <?php print $item['view']; ?>
          <?php if (!empty($node->field_author_name[$delta]['value']): ?>

               <?php print check_plain($node->field_author_name[$delta]['value']); ?>

          <?php endif; ?>

And now when CCK builds this field, it will also grab the author name and put it under the photo.  It will of course still build the author name field and display it, so if that's not what you want, you can go in the Display Fields section of the node type config and exclude it from the $content variable and then it will only show up here.

Clear caches/theme registry and style up the author-photo-caption class and you should be set.  And now wherever this field is displayed, it will grab its counterpart (assuming no typos above :)

(Other assumptions:  field_author_photo and field_author_name are the names of your fields on your system.)


Changing Drupal database How would you think if a designer extends the database of Drupal for a desired system? (for example adding field to some tables)

Would it be really PRACTICAL?

Bottom line: it's your database, you can add as many fields to whatever tables you like.

Drupal won't know anything about them, obviously, and it may cause unforeseen issues further down the line, as you're potentially changing the way the core system works. It's not possible to be any more specific than that without knowing pretty much everything about your application, so you'd need to test until you're happy you haven't broken anything.

The correct way to extend core entities is through the use of fields, I'd strongly recommend using those rather than hacking at database tables.


How can I get final URL of newly added node from hook_node_insert()? I have installed pathauto and implemented hook_node_insert in my module, the problem is when I use entity_uri to get new node's URL I will get node/xxx instead of pathauto url alias.

How can I get final URL of the node, after ALL other modules had their manipulations?

function HOOK_node_insert($node) {
    $uri = entity_uri('node', $node);
    $uri['path']; // this should be the final path
}

If you also implement hook_module_implements_alter then you can change when your insert hook fires, like this:

function mymodule_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'node_insert') {
    // Move my_module_node_insert() to the end of the list.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

So now when your insert code executes the path alias should be available.


How do I invalidate cache of an embedded view? I have a node type "Article" that contains a repeating Paragraphs field. One of the paragraph types let's the user embed a view using a entity reference field. When rendering an Article node containing a views reference I embed the selected view in hook_preprocess_paragraph like this:

$view_id = $paragraph->field_view->target_id;
$view = \Drupal\views\Views::getView($view_id);
$view->setDisplay('embed_1');
$vars['content'] = $view->preview();

This is working fine except when I enable caching. For example one of my views lists nodes of the type "Event". When I add a new Event it does not show up in the listing until I clean the cache. I could force clean the cache when inserting / updating / deleting an "Event" but I would much rather use Drupal 8's cache tag system and only invalidate the cached content that contains event lists. The problem is I cannot get it to work.

So far I have tried adding cache tags to the node, the view, and the paragraph  in hook_preprocess_paragraph and hook_preprocess_node like this:

$vars['paragraph']->addCacheTags(['node_list']);
...
$view->storage->addCacheTags(['node_list']);
...
$vars['node']->addCacheTags(['node_list']);

According to this page node_list can be used for node listings to invalidate the cache whenever a node is updated. But it has no effect. Maybe the preprocess hooks are to late to add cache tags?

What am I missing?

Edit:

After some more testing I found that if I edit an event, the changes can be seen in the listing and if I remove an event it disappears from the listing. The problem only occurs when adding new events.

Try to use buildRenderable(), that should ensure that the necessary cacheability metadata is added automatically.

$vars['content'] = $view->buildRenderable();

Hint: You might be interested in my Views Custom Cache Tag project. The node_list cache tag is invalidated every time any type of node is saved, even though your view only changes when an event changes. Using that module and a bit of custom code as shown on the project page, you have fewer cache invalidations and better performance.


External menu link within same domain Call me stupid, but I currently have a site that is using both Joomla and Drupal (long story). The site uses a number of sub-domains to represent different geographic locations.

For the main menu in Drupal, I have some items linking to pages within Joomla. However, Drupal doesn't allow to to specify a relative URL if the link is external to Drupal. This means I have to put the full URL including http scheme and hostname. Consequently, clicking these menu items results in a new window or tab being opened up, which is not what I want!

Does anybody know of a way I can have Drupal accept an external URL without needing to include the domain? For example: "/myJoomlaURL", instead of "http://www.mydomain.com/myJoomlaURL"?

Currently using Drupal 6.

Links opening in new window have nothing to do with the URL, relative or not, but with the target attribute of the <a> tag.


Is there a safer way to make preprocess changes? I recently made changes to template and node.tpl files for my theme. Is there a recommended way of implementing preprocess changes as to not hard code them into these files (in case of theme updates) or am I going to have to re-code them after theme udpates?

In an ideal world, you would create a sub-theme off of your master theme.  For example, most people don't use the Omega or Zen themes directly; rather they use the starter kit which is included as the basis for the sub-theme.

The sub-theme will inherit features from the base theme, but allow you to customize as needed.  When the base theme gets updated, the sub-theme doesn't get touched.

Whether you can retrofit your theme to actually be a sub-theme depends on your situation, but I suspect it is possible.


No Breadcrumb settings in Bartik theme? The breadcrumbs in my Bartik theme work perfectly. However, in my Zen subtheme are skipping a level!

I just noticed that there is no Breadcrumb settings section in the Settings for the Bartik theme.

I am using the Menu Breadcrumbs module for both sites...

Try using Custom Breadcrumbs instead.

  Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.


Can I get the relationships of a node using node_load()? I want to load relationships from the node_load(). So for example  getting the article content type and loading the author information with the same query.
How would I go about doing this?

The end goal is to make a computed field for Drupal Search API so that I can convert the field's name. The relationship fields are currently in the form table_name:field_name but I am indexing into Algolia and therefore need the field name to just be field_name.

As an option you can index the entire rendered HTML of your content.
Let's assume your index is called "default_node_index" and content type is "article".

Visit /admin/config/search/search_api/index/default_node_index/workflow
Enable "Complete entity view"

Visit /admin/config/search/search_api/index/default_node_index/fields
Enable "Entity HTML output".

Manage display of your content type /admin/structure/types/manage/article/display
Enable "Search Index" in "Custom display settings" fieldset.

Visit /admin/structure/types/manage/article/display/search_index
Add all the fields you want to render. You can extend this display using the regulat hooks, templates and preprocesses if needed.


AJAX change field is required I have simple form, two fields one is checkbox and second is text. When checkbox is checked.
Text field is required, and when checkbox is unchecked textfield shouldn't be required...

To perform this need with AJAX, i have my working example like below:

function mycustom_form($form, &$form_state) {

      $form['ask_required'] = array(
        '#type' => 'checkbox',

        '#title' => t('required'),
        '#default_value' => "",
           '#ajax' => array(
            'callback' => 'ajax_required_callback',
            'wrapper' => 'replace_reqired_div',
        ),
    );

       if (!empty($form_state['values']['ask_required']) && $form_state['values']['ask_required']) {
    $form['vin'] = array(
        '#type' => 'textfield',
    '#required' => TRUE,
        '#title' => t('VIN'),
        '#default_value' => "",
          '#prefix' => '
',
        '#suffix' => '
',
    );

  }else{

       $form['vin'] = array(
        '#type' => 'textfield',

        '#title' => t('VIN'),
        '#default_value' => "",
          '#prefix' => '
',
        '#suffix' => '
',
    );
  }

    $form['next'] = array(
        '#type' => 'submit',
        '#value' => 'Dalej >>',
        '#submit' => array('mail_form_submit'),

    );
    //    dpm($form);
    return $form;

}

function ajax_required_callback($form, $form_state) {

     return $form['vin'];
}

Is there any more elegant way e.g. to change attributes of field not whole VIN field?

Second thing is that when i place above code in ...form_alter, its not working..., there are fields there is ajax callback but required star is not changed

function module_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'user_register_form') {

        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');

        $form['ask_required'] = array(
            '#type' => 'checkbox',
            '#title' => t('required'),
            '#default_value' => "",
            '#ajax' => array(
                'callback' => 'ajax_required_callback',
                'wrapper' => 'replace_reqired_div',
            ),
        );

        if (!empty($form_state['values']['ask_required']) && $form_state['values']['ask_required']) {
            $form['vin'] = array(
                '#type' => 'textfield',
                '#required' => TRUE,
                '#title' => t('VIN'),
                '#default_value' => "",
                '#prefix' => '
',
                '#suffix' => '
',
            );
        } else {

            $form['vin'] = array(
                '#type' => 'textfield',
                '#title' => t('VIN'),
                '#default_value' => "",
                '#prefix' => '
',
                '#suffix' => '
',
            );
        }
    }
}

why?

You can use Form API #states attribute. This will allow you to trigger something based on another fields information. Below should be a working example.

$form['vin'] = array(
  '#type' => 'textfield',
  '#title' => t('VIN'),
  '#default_value' => '',
  '#states' => array(
    'required' => array(
      ':input[name="ask_required"]' => array('checked' => TRUE),
    ),
  ),
);


Aegir+ Ubercart + Freetrial + ARB. Not working I'm trying to set an automated approach to do the following:

Customer signs up for a 30-day trial. Enters CC#, but is not charged for 30-days until free trial converts.
CC# is verified (but not charged) on initial registration.
CC# is NOT stored in cleartext in my database (need PCI compliance).
IF account is active (i.e. I don't manually delete account), the account will automatically recur a monthly transaction every 30-days .

I have Aegir and store Admin set up with Authorize.net. I just signed up for Auth.net ARB, but I'm unsure how I set this up to accomplish what I'm describing above. As you can see in the screenshot below, I can manually charge the CC through the Admin interface, but that would imply that I would need to go in and charge the CC# in 30-days, and then manually every 30days thereafter.... That will become unmanageable quickly... As I said, I signed up for Auth.net's ARB, but the documentation on setting this up with Drupal is pretty poor.
http://screencast.com/t/kB0xixRAerIo

Secondly, and perhaps a bigger problem with Drupal, is the fact that as the admin, I can see the customer's full CC# right there in cleartext when I click "view card details". Yikes. There must be a big mistake in all this, but don't know where.
http://screencast.com/t/Kj46n17spnRq

Should I sign up for Auth.net's CIM to capture/store/hold customer's CC# throughout free-trial period, and then charge and and convert to ARB for automated monthly charges? If so, I'm stumped on how to set this up.

And... lastly the primary issue I have is that orders are being rejected due to no Bill-to address being populated with Auth.net. The order page shows no bill-to data was recorded, but when I look at the registration side, I can see that the bill-to address info was indeed captured.
There seems to be some missing link where the bill-to address data recorded at registration is not being passed through to Auth.net (but CC# and name is being passed through). So it's the missing Bill-to data that is causing the rejection on Auth.net side. Any thoughts on why this address data is not being populated on Auth.net's side?

Thoughts/leads? we have a couple SyAd guys stumped on this. Thanks!

While this question is now 6 years old, the way to go about this nowadays is via Aegir Site Subscriptions, which isn't quite ready yet, but is on the way.  So far, there's code for Recurly, but no other recurring billers.


Clearing cache causes nginx error Whenever I clear cache from the admin panel (or hit the url directly) I receive an nginx error (but nothing specific is being logged).

There are no PHP error logs being created for this either.

I've narrowed it down to the /includes/menu.inc _menu_router_build function.

The strange thing is, that if I add an echo to line 2365:

// Apply inheritance rules.
foreach ($menu as $path => $v) {
   echo $path; // echo added
   ....
}

The cache clears, it doesn't error out, BUT it doesn't seem to complete because all the values are echoed but I'm never redirected. Completely lost on this one.

We had a similar issue and traced it to the nginx fastcgi_read_timeout option. Because the code to clear the cache doesn't send any output to the browser until it finishes, nginx doesn't receive anything from PHP for 60 seconds. At this point, the default fastcgi_read_timeout is reached, so nginx aborts the request.

When you added the echo $path, you forced PHP to output something, which meant that nginx had something to read, so it didn't reach the timeout.

You should try increasing the fastcgi_read_timeout to, say, 120s and see if that helps.


hide node from user roles? I want to hide a node from our site for users with a specific role. I.e I have a section of my site that should only be accessed by logged in users, and I want to hide the node and the link to it in the main menu for anonymous users.

This seems like a very easy task but I'm having a hard time finding an easy way of doing this. I'm using Drupal 7.

-I've tried to do it with Rules but have not succeeded, (main problem has to do with not getting any relevant selections to choose from in the data selection.)

-I'v tried to create a new context in Context and everything looks good, but it has not the desired effect.

Is there a module for this?
Something like the equivalent of node access since it is not developed anymore.

Surely you can easily do it by using roles.

Create a role for the users you want to be able to access the node type.
in /admin/people/permissions set the permissions for the roles - disallow access to the node type for roles apart from your specific role that should be able to access it.

For the menu simply create a copy of your menu with the link you wish to hide for other roles and show it only for your specific role and hide the other menu instead. Since you usually assign menus as blocks this can be easily done.


How do I modify the _trackPageview output of the Google Analytics Drupal 7 module? I am working with the Google Analytics (googleanalytics) module in Drupal 7 and I need to get search categories added to the code. The module itself doesn't seem to offer any hooks in for an operation like this. I am considering trying to go into the storage of drupal_add_js to modify it. But I don't like how hacky that is.

So my next thought is to modify the module. But I would rather not do this to a contrib module. So any thoughts? I have been also wondering if I can push _trackPageview twice to Google on the same page, with the second time being with the search query and category. But I don't know how Google Analytics will work with that option.

If your question is "how to pass custom values to Google Analytics ?", then why wouldn't you use the Custom Variables feature of Google Analytics, populated by custom tokens ?

Create custom token containing search categories (via hook_token_info() and hook_tokens())
In Google Analytics Module interface, in the "Custom Variables" fieldset, add your custom token


How to display a flag to anonymous users? I'm using the Flag module, but I have a problem in displaying a flag to anonymous users.

I have 2 flags called "make feature" and "add to Favorites". I want to display this flag to anonymous users too. Currently it is displayed only to the users who are logged in (authenticated user).

I want these flags to be displayed to all users (whether logged in or not). But when an anonymous user clicks on flag than such user should be redirected to the login page. After login the user should be able to set flag.

Is this possible?

You can do this in your 'node.tpl.php' by something like below, if user is logged in display flag as normal and if is not logged in redirect user to logging page with destination parameter

global $user;
if(!$user->uid) {
    // $flag: bookmark or make_feature, $action: flag, $content_id: $nid.....
    $flag_link = flag_flag_link($flag, $action, $content_id);
    $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {
        $flag_url .= '?'.$flag_link['query']['token'];
    }
    print l(t('bookmark'), 'user/login' , array('query'=> array('destination' => $flag_url)));
} else {
    print render($content['links']['flag']);
}


How can I get the complete query? I am displaying a Drupal 8 view. I see that all of the fields that are displayed in the view are not in the query.

How does this work?

For query tracing you can use devel module. Devel module include the Web Profiler module which shows many options. Even you can see the all queries executed for page.

Following are the sample details of web profiler.

UPDATE: So how you can see your view query in web profiler?
Well, follow this steps.

For tracing purpose disable view cache. "Select 'No Cache' from advance section".
Then Clear all drupal cache.
Open views output page.
Click on database link from web profiler.
Now search in page(Ctr+F) your field name.
E.g: Here I added one field in my view, that is field_image. So I search that and I get view query..
Once you found out your query, you will see there is no parameter in query, Well to see which paraters query is taking click on "Info" tab of query. And you will see all parameters of placeholder.


Webmail Error due to Emoji A site I'm working on came across the following error in Drupal based on the addition of an emoji flex graphic put into the form field.

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: ‘\xF0\x9F\x92\xAA e…’ for column ‘data’ at row 1: INSERT INTO {webform_submitted_data} (mid, sid, cid, no, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder3, :db_insert_placeholder_4);
     Array ([:db_insert_placeholder_0] => 64
    [:db_insert_placeholder_1] => 10
    [:db_insert_placeholder_2] => 11
    [:db_insert_placeholder_3] => 0
    [:db_insert_placeholder_4] => Need multiple 250 ton Jacks, force not strong [AndroidFlexEmoji] enough) in drupal_write_record() (line 7239 of E:\webserver\Inetpub\wwwroot\includes\common.inc).

After digging around for a while on this site and others, I came across the following suggestion:

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

I'm not 100% sure if this will fix the issue I'm having, however, I'm not sure where to alter this to test it. The link below states that in Drupal you can find it under /includes/database/mysql/database.inc around line 53 but no luck.

Reference link: How can I remove emoji from all user input?
Any clarification would be great.

Do not hack the core (change any of the files in the initial Drupal download) unless you are using a patch in the issues queue or making one for a registered issue, /includes is part of that core.

The reason for this is that you will not be able to reliably upgrade your Drupal site as new versions are released and it is very important to keep it updated for security reasons.

Do always test new things on a development copy of your site, never on your production site (at least not after launch).

That being said, the best part of the answer you referenced is:

  All in all, I would prefer to just switch my MySQL to utf8mb4 charset, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

To elaborate:

MySQL allows various different encodings in its storage engine.  Latin1 (often the default) stores all of the data in one way and allows a limited set of characters.  UTF8 is a much larger library of characters.  Characters that exist in UTF8 that don't exist in Latin1 (for example) will make your database cry because it doesn't know how to read them.

The solution is to tell your database to use UTF8 instead of Latin1.

There are instructions online for doing this in-place but I personally prefer to do a mysqldump and import the database into a fresh database that has been specifically set to use UTF8, then tell Drupal where to find the new database.

As Molot said in his answer, you need MySQL 5.5.3 or higher to use UTF8, so you may need to upgrade your version of MySQL.  If you're on shared hosting this could be difficult, you should be able to see your MySQL version in CPanel or Plesk, otherwise ask your hosting provider for support.


page "/node/add" that I would like to programmatically limit the links that are displayed based on the users role I have a page "/node/add" that I would like to programmatically limit the links that are displayed based on the users role.  Is using either hook_form_alter or hook_form_ID_alter the way to do this?
I just figured out that "/node/add" is not a form so I can't use hook_form_alter or hook_form_ID_alter but in doing a little research it appears that I may be able to user hook_page_alter() instead to filter out some of the links.

If you set node creation permission (Node Module on www.yourhost.com/admin/user/permissions) to specific roles, the existing form should take care of this automagically by itself, eg, if the user accessing www.yourhost.com/node/add can't create a specific node type, it won't be presented on that page.

Based upon commentary, node/add is built via:

function node_add_page() {
  $item = menu_get_item();
  $content = system_admin_menu_block($item);
  return theme('node_add_list', $content);
}

/**
 * Display the list of available node types for node creation.
 *
 * @ingroup themeable
 */
function theme_node_add_list($content) {
  $output = '';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
'. l($item['title'], $item['href'], $item['localized_options']) .'
';
      $output .= '
'. filter_xss_admin($item['description']) .'
';
    }
    $output .= '
';
  }
  return $output;
}

so you most certainly could create a new YOURTHEME_node_add_list() function that filters the links based upon a user's role realizing that if the user entered the link directly it would nonetheless still work.

You could also create a node-add-list.tpl.php in your theme's directory with basically this in it as a start:

<?php

  $output='';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
'. l($item['title'], $item['href'], $item['localized_options']) .'
';
      $output .= '
'. filter_xss_admin($item['description']) .'
';
    }
    $output .= '
';
  }
  print $output;

and then modify it however you wanted.

Just flush caches after either to make drupal's theme system see and pick up the changes.


How can we divide the price if the customer select certain attributes? I am working on a magazine site where the magazine can be subscribed. When users subscribe, we want to allow them to choose between full payment and monthly payment. I have used a "payment_type" attribute for the payment option, and I want to divide the total price by the number of months when user selects the monthly payment option.

How can I achieve this?

Why dont you try the Rules module? It is great for that kind of automation.


Does an ajax callback work within a Views style plugin? My module has a custom Views style plugin. In the style settings form, I want to implement an ajax callback, such as described here: https://www.drupal.org/docs/8/api/javascript-api/ajax-forms

However, I haven't had any luck. I can get a spinning effect, but nothing happens afterward. Here's an example of what I've tried:

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

  public function TestCallback(array $form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $text = 'Text to see if this is working';
    $ajax_response->addCommand(new HtmlCommand('#foo', $text));

    return $ajax_response;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['test'] = [
      '#title' => t('TEST!'),
      '#type' => 'select',
      '#options' => [
        '' => t('None'),
        'foo' => t('Bar'),
      ],
      '#ajax' => [
        'event' => 'change',
        'callback' => '::TestCallback',
    // having the line below uncommented seems to help
    //'url' => views_ui_build_form_url($form_state),
      ],
      '#prefix' => '

',
      '#default_value' => '',
    ];
  }

If I uncomment the commented 'url', I get this error:

Uncaught TypeError: Cannot read property 'settings' of undefined
at resetSize (<anonymous>:34:32)
at later (debounce.js?v=8.6.3:20)

If I keep it commented, I get:

Failed to load resource: the server responded with a status of 500 ()
/admin/structure/views/ajax/display/view_name/page_1/style_options?
_wrapper_format=drupal_ajax&ajax_form=1&_wrapper_format=drupal_ajax:1
Uncaught Drupal.AjaxError
ajax.js?v=8.6.3:500

What's missing and/or incorrect?

From what I understand seeing the AJAX docs, I think you're not supposed to return an AjaxResponse object. You're supposed to return a renderable array from the Ajax callback.

Sample Code

public function buildOptionsForm(&$form, FormStateInterface $form_state) {
  parent::buildOptionsForm($form, $form_state);
  $form['test'] = [
    '#title' => t('TEST!'),
    '#type' => 'select',
    '#options' => [
      '' => t('None'),
      'foo' => t('Bar'),
    ],
    '#ajax' => [
      'event' => 'change',
      'wrapper' => 'ajax-output-container',
      // Since views style options forms are complex, they're built by
      // Drupal in a different way. To bypass this problem we need to
      // provide the full path to the Ajax callback.
      'callback' => __CLASS__ . '::testCallback',
    ],
    '#prefix' => '

',
    '#default_value' => '',
  ];
}

/**
 * This is the AJAX callback.
 *
 * It generates the output for the AJAX request. The output REPLACES
 * the "wrapper" you define in #ajax.
 */
public function testCallback(array $form, FormStateInterface $form_state) {
  // This element will replace the DIV#foo you have in your #prefix.
  $elem = [
    '#type' => 'markup',
    '#markup' => '
Is it not working!>
',
  ];
  return $elem;
}

Debugging

Make sure that on page load, you're getting a div with the correct ID in your field prefix. You can put some default text in the prefix so that you can see it on page load?
If HTML tags are being stripped from your #prefix markup for some reason, then try injecting a separate item in the form with #markup.


Notice: Undefined offset: 1 error I get this Notice:

  Notice: Undefined offset: 1 in
  custom_context_section_condition->_get_url_section() (line 110 of
  modules/custom/custom_context/plugins/custom_context_section_condition.inc).

  **
  * Get section by url
  */
  function _get_url_section() {
    // get the correct URL
    $path = $_GET['q'];
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $path = drupal_get_path_alias($_GET['q']);
    }
    $path = explode('/', $path);

    // Remove reserved part from path when defined as constant (see custom_context.module)
    if (in_array(arg(0), unserialize(URL_PATH_PART))) {
      array_shift($path);
    }
    // Remove reserved string from path when defined as constant (see custom_context.module)
    else if ($new_path = _custom_context_strpos_replace_arr($_GET['q'], unserialize(URL_PATH_STRING))) {
      $path = explode('/', $new_path);
    }

    // Get section by path
    $value = str_replace('-', ' ', $path[1]);
    $terms = taxonomy_get_term_by_name($value);

    // make sure we are getting the right section under the correct city
    // check if city context exist
    $city = NULL;
    $contexts = context_active_contexts();
    if ($contexts = context_active_contexts()) {
      foreach ($contexts as $key => $context) {
        if ($key == 'city') {
          $city = $context->conditions['custom_city']['city']['term'];
          break;
        }
      }
    }
    else {
      $city_context = new custom_context_city_condition(this, array());
      $cities = $city_context->_get_city($node);
      $city = array_shift($cities);
    }

    // check parent tid here
    foreach ($terms as $key => $term) {
      $parents = taxonomy_get_parents($term->tid);
      $parent = array_shift($parents);
      if ($city->tid != $parent->tid) {
        unset($terms[$key]);
      }
    }
    return $terms;
  }

This part:

if ($city->tid != $parent->tid) {
  unset($terms[$key]);
}

Also says: Notice: Trying to get property of non-object

Any idea whats wrong in my code?

In the code above $parent is an array so $parent->tid is illegal. I am not sure what you are trying to find in the $parent but you should also note that the parent array has numeric indicies. So you probably have to do it this wat $parent[45] or $parent[$city->tid] depending on your requirement


Sending email to hidden field using webform after calling hook_form_alter? Drupal 7.14, Webform 7.x-3.17 : I built a webform that has a hidden field "lt_email", and I'm assigning a session value to it using hook_form_alter -

function wbl_form_webform_client_form_1_alter(&$form, &$form_state) {
   $form['submitted']['lt_email']['#default_value'] = $_SESSION['Some']['Email'];
}

When I var_dump or dpm the ($form) I see the session value for lt_email, but after I hit submit on the webform, the value goes away, it doesn't get assigned.

Since %session[id] didn't handle multi-dimensional session arrays, I used the hook_form_alter workaround. I was under impression hook_form_alter would grab the session value, assign it to hidden field, and once submitted, the hidden field would retain the value, which I then use as the email component for the webform that gets triggered automatically. THe hidden field is blank upon submit.

I'm logged in as root, and all the other fields retain value upon submit (ie, name, address).

The problem is probably caused by the hidden field having the #value property set which overrides #default_value (even if the former is NULL or a empty string).

To get the desired result you have 2 options:

1) Override #value instead of adding a #default_value:

$form['submitted']['lt_email']['#value'] = $_SESSION['Some']['Email'];

2) Unset #value then add #default_value:

unset($form['submitted']['lt_email']['#value']);
$form['submitted']['lt_email']['#default_value'] = $_SESSION['Some']['Email'];

If you are wondering which option is the right one for you then #default_value means that Drupal will accept client-side changes to the field value (via javascript for example). If you don't need/want that possibility then #value should be used (Drupal will ignore any client-side changes in that case). It's mentioned in the documentation as well.


What's the purpose of the authmap table? I'm trying to create multiple websites with Drupal Multi-site feature, and I need to understand how the authmap table is used.

What's the purpose of the authmap table?

The "authmap" table is used when a user is authenticated using an external site, for example an OpenID server.
For example, in my test site I have used OpenID to create an account. In that table, I then found the user ID of the user account created by Drupal, and the OpenID URL used to authenticate the user (the one provided by the OpenID server).

The comment in user_external_login_register() gives a short explanation of how that table is used, and which functions the modules integrating with an external authentication server should use.

  Helper function for authentication modules. Either logs in or registers the current user, based on username. Either way, the global $user object is populated and login tasks are performed.

Keep in mind that in Drupal 8 the "authmap" table, and the functionality provided by the functions using it have been removed. Any module providing the integration with an external authentication server will need to use its own database table, which is what the OpenID module did in Drupal 8, before being dropped off.


Migration multibyte images file name issue I have a Drupal website that I transferred it from host A to host B. I have some images uploaded with its Arabic file name, it works fine on host A, but after zipping Drupal files into a zip archieve, sending it to host B, extracting it there and finally run my website there, I found that the file names have been corrupted. the following screen shot demonstrates the issue:

What's the cause of this issue? How could I keep correct multiple byte file names correctly during zipping and unzipping?

By the way, the two hosts are Linux.

The solution is, simply, to compress the folder or files as tar not zip. Tar does not encode file names so it keeps it as it is in the filesystem. This is the Reference


URL variable not respected when ajax call happens in user registration form There are some fields (some required, some not) I need to (conditionally) hide in the user creation form:

function hook_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
    case 'user_register_form':
        //variable_name is sent using hook_menu_output_alter()
        if ($_REQUEST['variable_name'] == 'variable_value') {
            $form['field_id'][LANGUAGE_NONE]['#required'] = FALSE;
            $form['field_id']['#access'] = FALSE;
        }
}

This generally works but not when I override a (required) entity reference field in the form to change its autocomplete path:

//in another module:
function hook_alter(&$form, &$form_state, $form_id){
    $form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#autocomplete_path']= 'custom_autocomplete';
    $form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
            'callback' => 'custom_callback',
            'wrapper' => 'custom_wrapper',
            'method' => 'html',
            'effect' => 'fade',
    );
}

function hook_menu(){
    $items = array();
    $items['custom_autocomplete'] = array(
        'title' => '',
        'page callback' => 'custom_page_autocomplete',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function custom_page_autocomplete($string) {
  $string = array(':s' => $string . '%');
    if ($string) {
        $results = db_query("SELECT title, nid FROM {node} as n WHERE type = 'custom_type' and title LIKE :s", $string);

        $items = array();

        foreach ($results as $result) {
            $items[$result->title.' ('.$result->nid.')'] = $result->title;
        }
        print drupal_json_encode($items);
    }
}

function custom_callback(&$form, &$form_state) {
    //if an entity reference field value is set, then find & assign values to some other fields, based on that entity:
    $entity_id = $form_state['values']['field_id']['und'][0]['target_id'];
    if ($selected_entity = node_load($entity_id)) {
        $form['field_somefield1'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield1['und'][0]['value'];
        $form['field_somefield2'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield2['und'][0]['value'];
        $form['field_somefield3'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield3['und'][0]['value'];
    }

    $commands = array();
    $commands[] = ajax_command_replace("#edit-field-user-somefield1", render($form['field_user_somefield1']));
    $commands[] = ajax_command_replace("#edit-field-user-somefield2", render($form['field_user_somefield2']));
    $commands[] = ajax_command_replace("#edit-field-user-somefield3", render($form['field_user_somefield3']));
    return array('#type' => 'ajax', '#commands' => $commands);
}

So, whenever an AJAX call is made by the overridden field and I then submit the form, all the (previously hidden) fields are visible again and the required fields become required again.

Any ideas why this is happening?

The AJAX callback shouldn't alter the form (that should be handled by the form constructor or a form alter). This tends to be a good thing, because it forces you to put all your form logic in form functions, and that means they can degrade gracefully if JS isn't available. When dealing with AJAX forms, the callback typically just decides what part of the form to return. Take a look at the example from the examples module:

/**
 * Basic AJAX callback example.
 *
 * Simple form whose ajax-enabled 'changethis' member causes a text change
 * in the description of the 'replace_textfield' member.
 *
 * See @link http://drupal.org/node/262422 Form API Tutorial @endlink
 */
function ajax_example_simplest($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#title' => t("Choose something and explain why"),
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element changes.
      'callback' => 'ajax_example_simplest_callback',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'replace_textfield_div',
      // There are also several optional keys - see ajax_example_autocheckboxes
      // below for details on 'method', 'effect' and 'speed' and
      // ajax_example_dependent_dropdown for 'event'.
    ),
  );

  // This entire form element will be replaced whenever 'changethis' is updated.
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("Why"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // An AJAX request calls the form builder function for every change.
  // We can change how we build the form based on $form_state.
  if (!empty($form_state['values']['changethis'])) {
    $form['replace_textfield']['#description'] = t("Say why you chose '@value'", array('@value' => $form_state['values']['changethis']));
  }
  return $form;
}

/**
 * Callback for ajax_example_simplest.
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return array
 *   Renderable array (the textfield element)
 */
function ajax_example_simplest_callback($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['replace_textfield'];
}

Note how the dynamic change of the form happens in the form constructor while the callback is minimal.


How to limit term reference autocomplete to a certain branch in hierarchical vocabulary (D7)? I would like to add a term reference field in my user registration form, where the users should enter or select the organization they are from.

Tags vocabulary:

  - Organizations
   -- Orga1
   -- Orga2
    -- Orga3
    -- etc.
  - other parent term
  - other parent term

I think i remember, that in D6 i found a way to limit the term search to a certain branch of my vocabulary, so in this case, i was able to select "Organizations" and only the children terms where handled through the autocomplete.

I played around with various modules, but still there is no way to configure a parent term, but only set a hole vocabulary for the reference while creating the field.

Of course, i could set up a single vocabulary for the organizations only, but i fear that i will end up with a mess of single-use vocabs, while i would prefere to keep those things in one hierarchical vocabulary.

Did i miss something? Was there a change in the vocabulary-use-philosophy?
Any hints appreciated.

I use Workbench Access for this. I think you need to use the dev release, but for me, it is stable on a production site. It allows you to define which user roles and individual users can see which parts of taxonomy.


Block not showing up I am building a fairly simple module, and I am trying to set up a block, but it doesn't appear. I can't figure out what is wrong with my code.

function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Links'),
    'status' => 1,
  );
  return $blocks;
}

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff':
      $block['subject'] = t('Quick Links');
      $block['content'] = quick_links_get_links();
      break;
  }
  return $block;
}

function quick_links_get_links($department = '') {
  return t('Hi');
}

Your implementation of the block hooks is wrong.  Try the below:

function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Links'),
    'status' => 1,
  );
  return $blocks;
}

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff':
      $block['subject'] = t('Quick Links');
      $block['content'] = quick_links_get_links();
      break;
  }
  return $block;
}

function quick_links_get_links($department = '') {
  return t('Hi');
}

I've namespaced the block, and changed the status from TRUE to 1, as per the hook_block_info() docs.  I've also removed the assignment of $delta, as this is passed through automatically.

REFERENCES

hook_block_info()

hook_block_view()


How to change default file system path in D8? In D8, where to change the Public File System Path to be :

sites/default/files/[nodeID]/

Do I need write a module?

You can't change the public file system path globally to include a nodeID because there are things that can store files that do not have a nodeID (such as non-node entities).

Instead, you can change where files are stored per file storage field (examples: File fields and Image fields).

To do so, go to Structure -> Content Types -> My Content Type -> Manage Fields and then choose Edit for the relevant field.

Then, in File directory, you can use tokens to set up the path however you like.  For example:

myfiles/[date:custom:Y]-[date:custom:m]-[date:custom:d]

There is a link below Help text that you can click to see a list of available tokens.


What else apart do I need enabled, apart from "block to region" in Display Suite Extras for the "block regions" vertical tab to appear? I've enabled "block to regions" in Display Suite Extras and I have enabled "Full Content" in "Manage Display".

But the "block regions" vertical tab still does not appear among the other tabs beneath the field table in "Manage Display".

Is there anything I should do to make the "block regions" appear?

You can't use the Default display view mode. You have to enable the Full Content view mode, which will then give you things like Block Regions and custom Page Title options.


Turn off Drupal caching without Access to admin panel I'm using Drupal 7 on WAMPP , Windows 7

Background: Drupal on my local box is copy of working project, but this local version I can not login like admin , because it doesn't store session. It doesn't give out any PHP Error.

So I guess I have to turn off cache to find out , is there any PHP Error appearing.

Read that there is such thing as drush , but is it possible to use from Windows ?

But the main question , is how to stop caching on Windows 7 without Admin access !?

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

drush en cache_disable --yes

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

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

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

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


Retrieve field value in a view twig I would retrieve the value of a field of the first row, like this:

rows[0].field_name..

but the 'array is too large and kint breaks.

You can look up the structure of the view result in your question Get result view with formatter programmattically. (there was no feedback, did it work?)

If you want to use this in twig, it would look like this:

{{ view.field.field_name.value(view.result[0]) }}


How to display messages from a block separately from $messages in page.tpl.php I have a webform which works as a newsletter subscription form: it displays a textfield for an email and a button. When the button is clicked, a notification message is displayed on top of the page where any other messages are usually displayed.

However because the webform is a block and it's displayed in the sidebar, it would be more usable if the message is displayed right above the block, where visitor's focus currently is, instead of top-middle of the page. Is this something possible to implement?

To generalise: is it possible to display messages from different blocks/modules in different sections of the page instead of the unified $messages variable?

If the notification is being set in the $messages variable used in page.tpl.php you can emulate theme_status_messages() by adding this to your theme's template.php file

function YOURTHEME_preprocess_block(&$vars) {

  $block = $vars['block'];

  if ($block->module == 'MODULENAME' && $block->delta == 'DELTA') {
  $output = '';
  foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
    $output .= "
\n";
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }

  $vars['messages'] = $output;
  }
}

Then in the template file for just your block (e.g. block-MODULENAME-DELTA.tpl.php), print the $messages variable.


Programmatically activate users I have a custom module that allows administrator users to review users, and then approve their registration. I can't figure out how to programmatically trigger the 'approve' process.

Changing their role, or doing a regular user_save() with the new status doesn't seem to trigger rules associated with activating the user.

I'm sure there's a simple function for this, but I can't find it.

You have to rely on user_load to load the $user object, edit what's appropriate, in your case $user->status, then user_save the modified object.

You could also use db_query to update the users table directly if you know what you're doing.

As for triggering the rule, this post explains how to do it.


How to get a list of Users as values for a select list field? How do I get a list of users of a specified role to populate a select list in node/add/* ?

For example when creating a piece of content I want a field "Select Your Moderator of Choice" and the options are a list of all users with the role moderator.

You will want to install a module that allows you to reference a user. A popular choice is entityreference.

With Entity Reference you can create a view of User's with a display type of Entity Reference. You can then add a filter to your view to only show users with the role that you are interested in.

Then you can setup a new field on your content type of the type, reference. Within that fields settings you can specify your view to be used as the mode for "Entity Selection".

You only need to setup the view if you want to limit the users that are selectable. If any user would be valid for your field, Entity Reference has some built in modes for entity selection that makes the process even easier.


How do I get the path alias without the language code? Suppose I have an alias like http://www.example.com/en/the-new-webpage.html.

I want to get the the-new-webpage.html part in hook_preprocess_html(). The language code might change into 'ja' or some other code due to the language availability. So I can't get the URL and pass it to str_replace() to replace the language part. Is there a function or a way to get the alias part without the language code?

Since you just need the last part of the path, you can use the following code in a hook_preprocess_html() implementation.

$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}


How can I let users rate content with half stars in Fivestar? This is a quite regular feature request on the Drupal website (see for example this article), but there hasn't been provided a full answer anywhere and the answers only cover Drupal 6.

Instead of rating content with whole stars, I'd like my users to be able to vote with half stars (0.5, 1, 1.5, 2, etc.). On my website, voting on nodes happens via comments.

How can I achieve this? Which CSS and/or PHP changes do I eventually have to make to the Fivestar module?

I've written a module that alters the fivestar module to allow halfstar voting:

Halfstar

After installing the module an option is added to the field instance setting form allowing half star voting:

Which then allows voting with half stars:

There is a rounding bug that occurs occasionally at the moment when using the Stars (rated while editing) widget. If you have 9 stars and then vote 5.5 is display as 5.6.


Object undefined in jquery, plus my links are pointing elsewhere I asked this question on stackoverflow earlier, not realizing this site existed.  Seems that this would be a better place for it.

In a nutshell, I've restored an existing drupal 7 site under the public_html/migrated_site folder on my hosted site.

When I browse that URL however I'm getting errors from jquery that the Drupal object doesn't exist, and all my links and images point to public_html/migrated_site/sites/someothersite...

..where someothersite is the name of the old subdierctory under public_html on the prior host.

I changed my settings.conf values to point to the migrated MySQL database, and that bit appears to have worked, in that the site is coming up, albeit unstyled and with the above jQuery and links errors.

However I'm not sure what could be going on above?  I've tried a few RewriteBase settings in .htaccess in both public_html and public_html/migrated_site (particularly, adding RewriteBase /~hisusersite/migrated_site) but nothing seems to have made a difference.

The Drupal JS object not being defined is a symptom of it not loading core JS files. His previous site probably enabled JS aggregation that places the aggregated file in sites/someothersite/files/XXX.js. The same goes for the missing images. Have you copied over sites/someothersite/ from the previous host?

It sounds like sites/someothersite/settings.php was what his original host was using and configured for DB & files. Since you're now viewing the site on  gator1111.hostgator.com Drupal is using sites/default/settings.php.

This primer on drupal multi-site settings might help to also explain what's going on.


How can alter the select options provided by Simple hierarchical select? Simple hierarchical select is used to display Taxonomy as a select field in my existing content type. So I'm trying to alter the value of it. Even tried using hook_form_alter but didn't work. So is there any way or hook using which I can alter the value of the select list?

Finally, I was able to resolve it by using the module handler "shs_term_data_response". Like below

function YourModuleName_shs_term_data_response_alter(&$content, $context) {
  $termList = json_decode($content);
  $filteredList = array();
  /..your logic to modify $termList and push it to new array.../
  $content = json_encode($filteredList);
}

Hope it may help someone :)


is it good idea to add js file for every page? I have some JS and CSS on my site that are very specific to some pages.  From a Drupal perspective, it is good idea to add them using drupal_add_js() instead of THEME.info?  Does such thing affect caching, or anything else Drupal-specific?

This question is borderline one, it's one of these topics where art meets science of software development.

Either way, drupal_add_js() should be avoided. Always favour #attached property, and if possible, add libraries, not single JS files.

For site-wide vs single page: you probably have some kind of JS and CSS aggregation enabled. Using different sets of files is wasteful - it means that for every page your client needs to download another aggregated file. Leaving the same set everywhere allows clients to use cached aggregated version - and this is (usually) the least time-consuming and least transfer-consuming way to go.

As Clive reminded, there are situations that are exceptional. Sometimes you need different versions of jQuery, or conflicting sets of libraries, and aggregating them can result in JS error, or create really big aggregated file. In situations like this you may not want to include all of them, or simply it might be impossible due to conflicts. Even then minimizing the number of "sets" is a good idea.

If you have a really big script used only on one rarely used subpage, some aggregation modules will allow you to exclude it from aggregation and always serve separately - a wise choice if you have 1kb of JS logic that you need in one place only, for example. This part is an art of profiling, not really knowledge and recipes.


Problem with Google Analytics module: "undefined index" I use "Google Analytics" module (version 7.x-2.1 = up to date) and I get the following error message:

  Notice : Undefined index: value in googleanalytics_page_alter() (ligne
  217 in
  .../www/sites/all/modules/google_analytics/googleanalytics.module)

Any idea how can I solve it? Perhaps some manual modifications in the googleanalytics.module file?

This is a support request on Drupal.org for this here.

Since it is not really a bug or feature request though it is technically on topic here so the summary of that issue is:

Make sure that you have run update.php.
If that didn't fix the problem then try re-saving your google analytics settings (it would be a good idea to confirm that they are what they should be before saving).

Also I would recommend that if you get error messages like that to search google and the drupal.org issue queue for the module(s) in question.


How to use domain access module for localhost I want to use domain access module for my xampp localhost.
Any one knows how to configure it for localhost.

Regarding module configuration, use your localhost address as domain alias for each domain. /admin/structure/domain/view/1/alias

Of course you need to have those aliases configured for your virtualhost on server too.


How do I send an email to the administrator users when a specific link is clicked? I'm working on a new site built with Drupal 6, and I have to program a specific action on the node pages.
I have a page that shows the product information for users. Following the information, I have a button labeled "order now"; when this button is clicked, two scenarios are possible:

if the user is not logged in, he is redirect to the login form
if the user is logged in, an e-mail is sent to the administrator with the current product information and the information of the user who clicked the button


Theme the progress bar when in batch API with AJAX I am looking to create a stylized theme for the progress bar for the batch API screen. I wish to alter the HTML and CSS being displayed in order to do so.

I know how to add the CSS to the page. I am aware of the hook theme_progress_bar, but according to the documentation "Note that the core Batch API uses this only for non-JavaScript batch jobs.".

What is the best method for overriding the HTML for AJAX driven batch API jobs?

Ultimately decided to use the hook hook_js_alter() in order to replace misc/progress.js with my own version. You can declare your own markup in this file, and also react on progress update (every 1500 ms out of the box).

In case anyone was wondering, this is the outcome of this http://drupal.org/project/nyan


How to change scheduler date format in *_node_form When I go to fill a *_node_form I find that Scheduler module only have this date format "Y m d" "H:m:s" and I would like to have "d m Y" "H:m:s".

I'm looking to the module and I don't find anyway, also , I have make a dpm with $form, And I don't find anyplace to change the date format.

Can be done this?

Thanks

Oskar

I find it the url is: admin/config/content/scheduler

The strange is that it doesn't have a "configuration" link in module page list.

Oskar


Get the current path in Views What's the best way to get access to the current path in Views?

My use case is I want to use the current page path in a text area (i.e. I want to have a text field like More).

At the moment I'm handling it by using hook_views_re_view to rewrite a "Global: Custom Text" field value with drupal_get_path_alias().

Ideally I'd like something more portable, i.e. the ability to add a "Global: Current Path" field to my view.

What combination of hooks/handlers/plugins do I need to use?

Thanks a lot. I did go down the Views PHP route initially, but it struck me as a bit un-Drupally, and even Views PHP says to use handlers where possible.

In the end I used hook_views_data and did:

function mymodule_views_views_data() {
  $data['views']['current_path'] = array(
    'title' => t('Current Path'),
    'help' => t('Provide current path.'),
    'field' => array(
      'handler' => 'concept2_views_handler_field_current_path',
    ),
  );
  return $data;
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function mymodule_views_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'mymodule') . '/handlers',
    ),
    'handlers' => array(
      // The name of my handler
      'mymodule_views_handler_field_current_path' => array(
        // The name of the handler we are extending.
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

With a handler file like:

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
class mymodule_views_handler_field_current_path extends views_handler_field {
  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE, 'bool' => TRUE);
    $options['hide_alter_empty'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    unset($form['help']);
  }

  function render($values) {
    // Return the text, so the code never thinks the value is empty.
    return drupal_get_path_alias();
  }
}


Change edit link URL in the content administration page I been trying to recreate something in the admin section of Drupal from a previous.

In the content, when you roll over the "edit" link. It shows the link like this: https://www.example.com/dolor-melior/edit?destination=admin/content

But I needs it to be: https://www.example.com/node/1/edit?destination=admin/content

I have Pathauto, Redirect and Global Redirect modules installed.

Go to YOUR_SITE/admin/config/search/path/delete_bulk check All aliases and click in Delete aliases now!


Count nodes that referenced current node in VIews How do I count how many nodes have referenced the current node In Views?

In the Advanced section of the view's configuration, there is a subsection Other. This subsection holds an item Use aggregation. Turn this item on. This allows you to configure the Aggregation settings for each field in the Fields section. One option is to use COUNT.

What remains is to navigate from the current node to the nodes that reference the current node. In Drupal 6, this could be done with the Reverse Node Reference module, which suggests the References module for Drupal 7. I think you have to add a Relationship then add a Node:Nid field that uses this relationship and is aggregated using COUNT.


Drupal Commerce input price formatting Presenting price with comma separator is working. But while editing product (or creating) I have to use price with dot separation, otherwise I'm getting warning, that field doesn't contain value. So right now I have to remember to use dot and after I see common - it's annoying. Does anyone deal with this with success?

I want to enter 24,43 as value, but it is not recognizable as value (which actually is).

Instead I have to enter 24.43, which is not accessible from num pad with current regional settings.

This issue is what you look for - currently it has a patch that needs work.
http://drupal.org/node/1450736


Add role when logged_in I want to add a role to the user when they log in for the very first time to their account. Any ideas of how to work this out? Rules maybe?

Thanks,

Rules only with module logintoboggan. Then you will have Event: when user account is active

With custom module hook_user_login and you must check for custom fields filled only once like timestamp.


Creating a new menu item that links to /user How do I format an array item using hook_menu() that links to /user but has a new title and is only accessible to logged in users?

Currently I'm using

    $items['user'] = array(
      'title' => 'Account Settings',
      'path' => 'user',
      'router_path' => 'user',
      'description' => 'Manage your username, password and contact information here.',
      'access callback' => 'user_is_logged_in',
      'type' => MENU_NORMAL_ITEM,
      'weight' => -20,
    );

Then end goal is to have a link that is titled 'Account Settings' that links to /user and that is only available to logged in users.

Edit: I guess to clarify, how can I incorporate the system menu /user item into my modules menu without using the UI?

To move an existing menu item to a different menu in code, you can implement hook_menu_alter() and change menu_name and weight for $items['user'].


Devel Krumo outputting all variables in a list format and not in an expandable clickable list When I do a dpm() on an array my devel krumo output is showing a list of the variables. Previously it was in a clickable expanding list where I can hide and show the child arrays. What settings did I miss to fix this?

If you are using bootstrap 3, you might encounter this problem. To fix this issue, add the following code to your template.php file.

function THE-THEME-NAME_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= reset($messages);
    }
    $output .= "
\n";
  }
  return $output;
}


How to add value on custom field using rule action I am new to Drupal. Trying to get it work with Rules module.
I have added new field (decimal type) to user: field_user_custom which I can see in DB as user__field_user_custom as a table.
I want to add value to this table on each article update.
I have setup rule as this:

Create a Reaction rule

React on Event: "After updating content"

Action:
a. Type: set data
b. Data Value: @user.current_user_context:current_user:field_user_custom
c. Value: 888

However, on article update, this value is not updated. I have tested if the rule is applied with having System Msg and it throws the msg but doesn't update the user field.
I doubt my Data Value is not correct. Which is why I have tried with this:

user:field_user_custom

but this didn't help either. What am I missing?

You were close. It's actually @user.current_user_context:current_user.field_user_custom, per "Set a data value"?.


Different payment methods for different product types Is there a way to have different payment methods available for different product types?

This is my scenario and what I've figured out so far:

I have two product types on my Drupal Commerce site, for selling bus travel passes. One type is just to book the bus pass where you select the date and times (custom line items) for your buss tickets. The other type is for actual payments, where you can choose a buss pass, add additional tours (with custom line items too) and then pay with Paypal.

I am using a customized version of the example payment module, for the booking payment type, and using the Drupal Commerce Paypal module for the actual payments.

What I need is to have the custom booking payment method available for one product type, and the paypal payment method for the other product type.

I have tried to add a condition for the product type and haven't been able to do this. We can add a condition for a particular product, but not for a product type. This would be ideal: https://skitch.com/ipwa/eywxa/add-a-new-condition-chasquibus

What I have done for now is to clone the Paypal rule for each payment product type, and selected that products SKU as a condition. This is not ideal, because if a user has more than one payment product, we get a duplicate Paypal payment method available for each additional payment product on the order. I guess this makes sense since we have a payment method rule for each one.

My solution would be able to have a condition for product type on the payment method rule, or be able to have the four payment products SKUs in a 'Order contains a particular product' condition.

The product's type is a property of the commerce_product entity, so you can use the built-in "Data comparison" condition to test it.

Just add a new condition of type "Data comparison", and make the data selector look like this:

When you continue you'll get a screen like this:

As you can see you get a nice drop down list of product types to choose from. I just tested that and it works a treat.

If that isn't working for whatever reason, it's pretty easy to implement your own rules condition in a custom module:

function MYMODULE_rules_condition_info() {
  return array(
    'commerce_product_is_type' => array(
      'label' => t('Product is a certain type'),
      'parameter' => array(
        'product' => array(
          'label' => t('Product'),
          'type' => 'commerce_product',
        ),
        'type' => array(
          'label' => t('Product Type (Machine Name)'),
          'type' => 'text'
        )
      ),
      'group' => t('Commerce Product'),
      'callbacks' => array(
        'execute' => 'MYMODULE_commerce_product_is_type',
      )
    ),
  );
}

function MYMODULE_commerce_product_is_type($product, $type) {
  return $product->type == $type;
}


How to alter standard.front_page in module links YML file? I have a menu with a "Home" link which was "provided by the Standard module. The title and path cannot be edited."

I am trying to alter the text/link using my module's links.yml file like so:

standard.front_page:
  title: 'Home Test'
  route_name: '<front>'
  menu_name: main

However this has no affect on the menu link. Other entries in this file work just fine.

Is it possible to alter the link in this way, or is the only option to use one of the menu hooks such as hook_menu_links_discovered_alter

I usually use this the hook_menu_links_discovered_alter() in this way:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function YOUR-MODULE-NAME_menu_links_discovered_alter(&$links) {
   // Changing the title.
   $links['standard.front_page']['title'] = 'Hi';
   // Changing the route.
   $links['standard.front_page']['route_name'] = 'block.admin_display';
}

But it seems that there are another ways in How to update a menu link created with MenuLinkContent::create()? and How do I programmatically update or delete menu items?


How do I send data using JSON as output format? There are separate web forms created on the basis of the Webform module (Drupal 7), sending by default goes to the required e-mail. Everything is within the module.

In addition, there was a need to send the data of the webform application (field) to various CRM (custom) based on JSON.

Request format

{
    "aCode": "zzz",
    "importdata": {
        "id": "zzz",
        "user_data": {
            "name": "zzz",
        },
        "contact": {
            "phone": "zzz",
        }
    }
}

How do I properly implement this functionality?

Process:

External url for accepting JSON lead requests (example): http://example-server.com:8083/api/submit

After the webform has been filled in, it is necessary to automatically send the field data in the raw postdata format to the external CRM with the JSON request format specified above in the code.

You will need to write a custom module that will select data from the webform tables in the database, encode your response and then call the URL

$crmurl = 'http://www.crmdomain.com/api/datafromdrupal';

if (isset($response)) {
  $json_response = drupal_json_encode($response); /* Pure json encoding */

  $options = array(
             'method' => 'POST',
             'data' => $json_response,
             'timeout' => 15,
             'headers' => array('Content-Type' => 'application/x-www-form-
             urlencoded'),);
  $result = drupal_http_request($crmurl, $options);
}


Drupal 7 aliases for a certain content type producing 404 I've got a custom content type ("charity listing").  Nodes in this content type should have the automatic alias charities/view/[name-of-charity].  They do indeed have this alias, when I try to edit a node the alias is there.  However, typing the URL alias into the browser gives me a 404 error.

I have tried re-generating all the automatic URL aliases.  Still doesn't work.

Help much appreciated!

Do you have any folder's in your root directory called "charities" or is there any rewrite rule in your.htaccess file? I know it's a long shot, but I had a very similar problem once and this turned out to be the cause.

Also, try putting "?q=" before the alias when you type in the url and see if that works (e.g., http://yourdomain.com/?q=alias/path). it will point to problems related to my other suggestions.