texts:
I found this error repeated several times for two of the pages on my website.
    Warning: Cannot modify header information - headers already sent by (output started at
/home/customer/www/mydomain.com/public_html/includes/common.inc:2800) in user_cookie_save() (line 4041 of
/home/customer/www/mydomain.com/public_html/modules/user/user.module).

I checked a bit around and found other similar errors with "Headers already sent" but none of them on the user_cookie_save function.
How can I debug fix it?
I'm running on Drupal 7.78, PHP 7.3.2.7 and as modules that could influence the cookies, I'm running just the EU Cookie compliance module.
What I find strange, is that I do not recall having seen this error before. There is a small chance that the error was there ad I did not see it because the logs are filled with page not found, and access denied errors by nice persons from the internet :) I would say though that that is a small chance as I've checked many times the logs in the past and did not see this error.
I have no idea what changed, and also no idea of what is the impact of this error, it's a warning, but I can't reproduce it.
Many thanks


texts:
I'd like to be able to print the block id/number of my custom block in its template. I feel like these must exist because Display Suite has a token for it: [block_content:id].

Like a url to edit a block is, it goes to the edit form: block/17

How do I get that 17 in the twig template? Looking in block.html.twig, I don't see anything about a block's number.


texts: update user's profile field from another form

texts:
Here is what I need to achieve:

There is field "linkedIn url" in user's profile entity.
There is Event registration form on the website.
In the Event Registration form I would like to render field "linkedIn url" with value from the user's profile entity.
When user submits the Event Registration I want to save a value of the field to the database (to user profile entity of course).

Any suggestions? thx!

EDIT:
I implemented this functionality.
For those interested, complete source code is below:
(Note that I'm saving data to profile2!)

/**
*
* Implements hook_form_alter
*
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id == 'registration_form') {
            $profile = profile2_load_by_user($user->uid); // Load profile2 data
            if ($profile['main']->field_linkedin_url) {
                $linkedin_url = $profile['main']->field_linkedin_url['und'][0]['value'];
            }
            $form['linkedin_url'] = array( // Add field to form
                '#type' => 'textfield',
                '#title' => t('Your LinkedIn profile'),
                '#default_value' => isset($linkedin_url) ? $linkedin_url : '',
                '#maxlength' => 255,
                '#size' => 60,
                '#description' => t('Please enter your LinkedIn profile URL'),
                '#weight' => 10,
            );
            $form['#submit'][] = 'entity_registration_custom_registration_form_submit'; // Call custom submit handler

    }
}

/**
*
* Custom Form Submit Handler
*
*/
function  MYMODULE_MYFORM_submit($form, &$form_state){
    global $user;
    $profile = profile2_load_by_user($user->uid); // Load profile2 data
    $profile['main']->field_linkedin_url['und'][0]['value'] =  $form_state['values']['linkedin_url']; // Set new value for Profile2 field
    profile2_save($profile['main']);
    drupal_set_message(t('Submit handler works!'));
}


texts: Site gives 500 error or malformed page in place of WSOD and useful error reporting

texts:
I don't think I have encountered this before. Generally if there's a php error on page, I'm met with a WSOD. With error reporting on, the error, file, line number, etc are displayed on the page.

With this site, the site either returns a 500 error (if the error is in hook_form_alter, for example), or the page will load partially up to the point of the error and display sans stylesheet/other resources (if the error is in a template file).

Any ideas why this might be and how to change it over to expected behavior?


texts: How do I get the content of a Panel variant to display on as Content?

texts:
I've made a module that you can add to a Panel Variant's Content section by clicking a region's gear icon and selecting 'add content'. This seems to work fine and I can view the module's output if I set the Selection Rules to a certain url.

However, I want to add this module to a Node (by this I mean the sort of content where you can select Basic Page, Blog Post, Article, etc). When I click 'Add Content' I don't see where I can add the module - there's no Regions with little gear icons, unlike panel variants. It just seems like a page with a text field.

Would anyone know how I can actually add my Module to a new Content/Node page?


texts: views slideshow jquery interfering with nice menus

texts:
Building a site for my friend who is a lawyer. Every time views slideshow changes slides, it resets the hover state for views slideshow. I tried calling the nice menu javascript at the bottom of the page but that did not help.

http://www.tripodi.devserver2012.com/


texts:
I have a boolean field ( field_rejected ) in my custom comment implementation ,I need to set this field to false if this comment is published

I tried hook_comment_update and hook_comment_insert, This didn't work as it says in the documentation :

  "Note that hook implementations may not alter the stored entity data."

Then I tried doing this using hook_entity_presave but this also didn't work as it results in an infinite loading or error code 500.

This is the code I used:

function custom_comments_notification_comment_presave($comment) {
  if ($comment->isPublished() && !$comment->original->isPublished()) {
    $comment->set('field_rejected', 0, $notify = true);
    $comment->save();
  }
}

Note that this is implemented in custom module's .module file.

How can I solve this? How can change the boolean 'field_rejected' after publishing a comment?


texts: Hi every one I have exposed taxonomy terms dropdown. I need to search term name from the other text field if any term is selected from the dropdown.


texts:
I have Drush installed on my Inmotion hosting server.
For one Drupal 7 site, it works just fine but for the other one, which is nearly identical, it doesn't work so well.
Some commands it allows (like my favourite drush sql-dump or drush cc followed by 5) and but when I do a command drush cc all it throws an out-of-memory issue as shown below:
Drush command terminated abnormally due to an unrecoverable error.                                                                         [error]
Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in
/home/myAccount/public_html/mysite.net/sites/all/modules/views/includes/base.inc, line 129

The issues stemming from the base.inc file are:
after command: drush cc all: on line 129:
$storage[$option] = isset($definition['default']) ? $definition['default'] : NULL;
The issues stemming from the view.inc file are:
after command: drush cc all: on line 2244:
$this->$field = unserialize($info['serialized default']);
after command: drush cc all: on line 2312:
$this->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
The php.ini files are identical on both sites.
The settings.php files are not identical and I thought it would be resolved by adding the same lines to the ending of the file
ini_set('memory_limit', '512M');
error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

but this didn't solve the problem (even after clearing the cache).
What could cause this problem?


texts:
I'm trying to display my nested form in my twig template. But I can find how to display the subchilds values (not the input, the value).
As the tree form item is like this, I don't no how to loop over that. They should probably add a children keys so that we could loop over that :
'#tree' => true,
0 => [...] //first period,
1 => [...] //second period,
"attributes" => [...]

This is the hierarchy :

Categories (Sections) > Periods > Element

In order to have a result like this (period X and y are in #default_value):
| Table name (from category data)                             |
|-------------------------------------------------------------|
|Main column name | Period X (need this)| Period Y (and that) |
|-------------------------------------------------------------|
|Element          | Value period X | Value Period Y           |
|Element 2        | Value period X | Value Period Y           |

This is my code (I'm getting some values from function, useless to show that code here).
$form['sections']['#tree'] = true;
    foreach($categories as $key => $category) {
      $id_category = $category['id_category'];
      $slug = $category['slug'];

      $periods_section = $periods[$id_category];
      $form["sections"][$id_category]['#tree'] = true;
      foreach($periods_section as $period) {
        $form["sections"][$id_category]['periodes'][] = array(
          '#type' => 'textfield',
          '#title' => "periode",
          '#required' => TRUE,
          '#default_value' => $period,
          '#attributes' =>
            ['class' => $classes_input,
              'data-periode' => $period],
        );
      }
    }

And this is my twig. I'm gettin the twig variable "categories" from a function, then I do my logic to display section by section.
{% for category in categories %}
              {% set current_category_id = category.id_category %}
              {% set current_section = form.sections[current_category_id] %}
              {% set section_name = category.name %}
              {% set main_column = category.name_column %}
              {% set slug_section = category.slug %}
              {% if loop.first %}
                {% set last_section = slug_section %}
              {% endif %}
              {% set new_table = last_section != slug_section or loop.first %}
              {{ vardumper(current_section.periodes) }}
              {% if new_table == true %}
                {% set last_section = slug_section %}

                  {{ section_name }}

              {% endif %}

                  {{ main_column }}

                  {% for period in current_section.periodes %}
                    {{ vardumper(period.value) }}
                  {% endfor %}

              {% if new_table != true %}

              {% endif %}
            {% endfor %}


texts: How to create a Category Article listing with subcategories?

texts:
I am new to drupal 7 and I want following page:

  Main Category

  (1) Subcategory1
    - post1
      Details
    - post 2
      Details
  (2) Subcategory2
    - post1
      Details
    - post 2
      Details

How can I do that? I think I can use Views but I need some further details.


texts: How to make a theme'd table that is sortable and has pager?

texts:
So I get an array from another function and now I need to style it into a table and make the headers sortable and have a pager on it.

I've been able to do this when querying the database directly but when receiving the info in an array from an external API I'm unsure of how to do this.

http://alvinalexander.com/drupal/drupal-7-table-sortable-headers-pager-paging

Has an example of how I've done it in the past but cannot do it this way this time.

Is it possible to do this without completely rewriting my own theme table function?


texts: How can I add a title to a field in the checkout page?

texts:
I am wondering if there is a simple way (dropdown option or checkbox) to add a title to a field in the Drupal Commerce checkout page.  Specifically, I want the second field for Street Address to have the label: Address line 2.

I was unable to find this field in Admin > Structure > View that allows the option to "Manage Display" or "Manage Form Display" and make a label for a field "Hidden" or otherwise.

I also looked in the Commerce sections to no avail.

Next step is to find out if there is a Billing Information > "Manage Form Display menu somewhere.

Not in
Home > Administration > Configuration > People > Profiles > Profile types  > Edit Customer > Manage fields
either.


texts:
I am creating a module that is outputting a static php page into my Drupal install. Here is my module file:

<?php

function mymodule_menu() {
$items = array();

$items['live_amplified/hello_world'] = array(
'title' => 'Live Amplified',
// describe the page for the menu system.  site visitors will not see this
'description' => 'Simple custom hook_menu() implementation.',
// function that is called when visiting the new path
'page callback' => 'drupal_get_form',
'page arguments' => array('static_page_form'),
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
 );

return $items;
}

/**
* Implements hook_form().
*/
function static_page_form($form, &$form_state) {
// Add CSS and JS
drupal_add_css(drupal_get_path('module', 'mymodule') . '/static_page.css');
// Import your static HTML page
$form['html'] = array(
'#type' => 'item',
'#markup' => file_get_contents(drupal_get_path('module', 'mymodule') .'/static_page.php'),
);
return $form;
}

In my static_page.php I have written my HTML, but when I try to add any PHP the browser doesn't recognize it. It doesn't output anything. I have tried just echo test and still nothing.


texts: How do I display inline content with the Colorbox Module?

texts: I understand that I need to add the class "colorbox-inline" to the link and build the url like 119 this "?width=500&height=500&inline=true#id-of-content"... but how do I do that? Do I need to edit a .tpl file?


texts: What is the Drupal 7 version of FILE_STATUS_TEMPORARY?

texts: My use case is that I want to set an uploaded file as FILE_STATUS_PERMANENT until I know it has been processed correctly by my custom module. Once that is done, I'm happy for Drupal to delete it. There used to be a FILE_STATUS_TEMPORARY in D6 but no more. What should I use?


texts: What are best practices for backing up settings files?

texts:
I have a Drupal 8 multisite with a few different hosts for production, staging, and local dev. Certain important files like settings.php and .htaccess are excluded from git, making it complicated to push to staging and production from my local.
How are people getting around this? Is putting them in .git such a big security risk?
For some time, I've been excluding .htaccess from .git and creating a .htaccess-loca, .htaccess-prod, etc., putting them in .git and copying them to the .htaccess files on the difference hosts - but these also contain the same info. Not sure why these are a security issue. The .env files I can understand. The problem with settings.php is the contain database passwords; can I move them to .env and consider settings files safe for git? Can Drupal console be used for synchronizing these files? I'd rather not use sftp, and like git so I can roll back to known stable versions.
I used composer to build the site, can Composer be used to manage settings, env, and other config files?
How about Docsall, would that make things easier?


texts: Why can't I see the settings for the customfilter module in the Drupal admin?

texts:
I'm following this tutorial to add a custom filter using the Custom Filter module. I've installed and enabled the module.

However, when I try to navigate to /admin/settings/filters like it suggests, there is nothing there nor can I see any settings for the Custom Filter module anywhere in the admin interface.

What do I need to do to get this module working?


texts: When using custom twig expressions to rewrite view title, the breadcrumb shows the twig expression without replacing it

texts:
In some of the views, I needed to customize the title using twig. For example {{ title }} which would read the title of the first row in the view result and place it in the page title. This works fine.

The problem is with the breadcrumb. It shows as Some Parent page > {{ title }} without replacing the {{ title }} with its actual value.

I guess a solution could be something along the lines of placing some code in THEME_preprocess_breadcrumb, but I am not sure what to write there exactly. But shouldn't this functionality be something out of the box?

P.S. Not all my views are using {{ title }}, actually some of them are a little more complex, and some views are parents of other views path-wise. So solutions like in this Q doesn't help.


texts:
The view mode per node option in DS Extras is great. But I want to give my editors only the 2 view modes they need, I don't want to burden them with the complete list of some 20 view modes I use all over the site. Is it possible to configure this?

Thanks for any help
Kind greetings
Frank


texts: On the the main content page: mysite.com/admin/content we are allowed to sort by a few criteria. Sort by content type, published date etc. but is there a way to sort by taxonomy? It seems like previous versions of drupal could do this. But not so in 7? I know you can create a view to handle this, but i am curious if its possible to accomplish the functionality via the content admin page.


texts: Three level menu: How to show only the children of the current page?

texts:
A three level menu:

  Item 1
    Item A
        Item X
        Item Y
        Item Z
    Item B
        Item Xx
        Item Yx
        Item Zx
    Item C
        Item Xy

When viewing the "Item 1" node,  I'd like to display the sub-menu items in the template: Item A, Item B, Item C

When viewing the "Item B" node,  I'd like to display the sub-menu items in the template: Item Xx, Item Yx, Item Zx

While I would like to rely totally on the menu structure, the output will not be displayed as a traditional menu.

This code does what I need:

function subpages($nid=null) {

$nid = 'node/'.$nid;

$menuItems = menu_tree_page_data('main-menu');

foreach($menuItems as $key => $m) {
    if ($m['link']['in_active_trail'] && $menuItems[$key]['below'] && $m['link']['link_path']  == $nid) {
        $menu = menu_tree_output($menuItems [$key]['below']);
        } else if ($m['link']['in_active_trail'] && count($menuItems[$key]['below']) > 0) {
            foreach ($menuItems[$key]['below'] as $k => $third) {
                if ($third['below'] && $third['link']['in_active_trail']) {
                    $menu = menu_tree_output($third['below']);
                //foreach ($third['below'] as $item) {
                //  echo $item['link']['link_title'].'<br>';
                //}
            }
        }
    }
}
return $menu;

}


texts: How do I dynamically change the title of a menu link?

texts:
I made a menu in administration, structures, menu. I want to change the title, as it appears on the menu, of one of the links based on the gender of the currently logged in user.

I have found several answers to similar questions but I can't figure out how to implement the solutions. Some of them suggest using hook_menu_alter(&$items) and a separate callback function, but I don't understand the structure of $items. I was hoping to just print out the value of $items, find the string I wanted to change, and change that value in $items in the hook. Apparently, though, you can't debug the $items variable because hook_menu_alter is rarely called. I tried to figure out the structure of $items from a bunch of other questions and answers and I found stuff like this:

$items['user/%user_category/edit']['title']

Why is 'title' a property of a path? Does this mean that every menu on your site that has a link to that path will display the title that you set the above variable to? What if you wanted a link to a specific path on one menu to have a different label than a link to that path on another menu? Isn't there somewhere I can access and change the title of a menu link like this

$allMenuData['My Custom Menu']['an item on my menu']['title']


texts:
I have a View with a Page display that only allows the returned data to be linked if the user is authenticated/logged in. I'm not using any extra modules that I can see (inherited site) that would enable access like this.

I simply want to remove that restriction. There is another view that looks the same except it's for Public and shows all the same data but not linked. (the data are pdf files).

On the authenticated display, next to Access in the Basic Settings it has authenticated user. If I click that user role (not the gear for options), then I'm shown a list of user roles to use for access restrictions. I click "None" and save, but the links are not there as an anon visitor. Same if I try by changing the user to Anonymous User. Note: In the permissions, anon has the right to see webfm attachments.

I noticed the URL is documents-public or documents-auth; so I made it just documents. No luck.

I visited the actual custom-page-type which puts the View in a content pane. I re-ordered the variants, removed all Selection Rules and that didn't do anything either.

I flushed all caches.

Somewhere, the view is still only showing a view based on whether a user is authenticated or not even though I've removed the access (it says "unrestricted" next to access) on both displays and removed all selection rules on the actual page.

I'm stuck on where else to look.


texts:
Is it possible to use several variants in a page?
In the page I made only one variant is shown.


texts:
I am building a site using Drupal 7 and the Mollom module

Mollom really helps me to block spam on my site.
Even spam bot that succeed on passing the captcha module and register to my site, never post any content on my site - so that's great!

But, the problem is when a quality user try to write relevant good content in the site - Mollom is "unsure" and shows the user a captcha to validate that he is a human. This is a quality content without any spam words (e.g. "Viagra").

I tried writing by myself good content as an authenticated user, Mollom was "unsure" and showed me the captcha after I tried to save. I tired it again few times, and always mollom display the capatcha after I am trying to save.

Is there any way to make Mollom less strict? Am I missing something in the settings?
Can I use also the Honeypot module together with Mollom (and even remove mollom)?


texts:
I'm looking to make a Drupal 7 table with collapsible rows. I'm really looking to do what was asked in https://stackoverflow.com/questions/801082/how-to-implement-collapsible-table-rows-in-javascript

I'm just trying to bend Drupal 7 into shape to do it. Do far, I have created a table which has the extra "section" rows, and I've assigned an HTML class and id to the rows that are to be collapsed. My problem is the Javascript and CSS required to do this.

My rows are created something like this:

foreach($results as $row) {
  ...
  if($row_needs_section_header) {
    $section_number++;
    $rows[] = array(
      'data' => array("Section $section_number"),
      'class' => (array('class' => 'collapsitablesection')),
      'id' => "collasitableheader$section_number",
    );
  }
  $rows[] = array(
    'data' => array(
       $column_1,
       $column_2,
       ...
    ),
    'id' => "collapsitable$section_number",
    'class' => array('class' => 'collasitable')),
  );
}

This seems to generate suitable HTML, with each of the rows that are to be collapsed being in an "id" with the section number in it, and also having a class of "collapsitable".

I'm now trying to replicate "misc/collapse.js", but instead of working with fieldsets, make it work with my special table rows. I'm at something of a loss with this. Has anyone got any ideas about where to go next?


texts: Edit the token values submitted by webforms

texts:
I am using webform for user registration and confirmation page as profile page.
I have included the token as follows
" [submission:values:name]
[submission:values:email]
[submission:values:country]
[submission:values:date]
 "
Now the submitted values are displayed in profile page but my requirement is the user should be able to edit and save only few fields but view all fields.
How i would include edit option for displayed data using tokens.
Please help me on this issue. Thanks


texts: how would i go about creating variable menu links

texts: I would like to display different menu links on each page depending on the content and relevance of each page. How would I do this?


texts: Google OAuth 2 authentication in custom module

texts:
I've created a custom module to use the Google MyBusiness (GMB) API to get reviews etc for a specified location.

The issue I am having at the moment is authenticating. All the examples I have read suggest a two step process, first, get an access token, then make actual API call to request reviews.

The above requires setting up a redirect URL for google to send the authentication response, as far as I understand it. The questions I had were

After setting up the Google client library how do you handle the RedirectUrl in the context of http://localhost:81 (My local dev server which I doubt is possible considering google wont know who localhost is)
....or is it possible to have . permanent AccessToken for this which is stored in the config and simply make immediate calls to the Google API, much like Twitter allows for posting tweets automatically.

It would be nice to simply be able to do a Guzzle request to a Google API endpoint with attached accesstoken and skip the handshaking and requestAccessToken step.

Regards and Thanks
John


texts: Can my site's administrators bypass required profile fields during user creation?

texts:
I have two separate roles on my site, one for regular users, and one for site administrators.

The regular users must fill out more details about themselves than I need admins to do, such as name, gender and address.

How can I allow the site administrator to create new site administrators without needing to fill out these extra profile fields?


texts:
I am searching how to add price values to existing product attributes in Drupal Commerce 2.X

For Example:
T-shirt price = $10.00

A product variation/color = Red = +$2.00

A product variation/size = Large = +$3.00

Choosing the Red would increase the price to = $12.00

And Choosing the Large would increase the price to = $15.00

Is there a way to accomplish this in Drupal 8?

In Drupal 7 there was a module called Commerce Product Attributes that allowed the Admin to add ADDITIONAL pricing after choosing an attribute to the already set pricing.

Ex. Set Price = $10.00 // Selecting a Product Attributes with a price value of $5 would then increase the total cost due at checkout to $15.00


texts:
I'm adding some FB functionality for Drupal 8. Now I'm trying to add FB like button for articles.

I have a twig template fblikebutton.html.twig, which looks like this:

<iframe src="//www.facebook.com/plugins/like.php?href={{ link }}&amp;width&amp;layout={{ layout }}&amp;action=like&amp;show_faces={{ show_faces }}&amp;share={{ share }}&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:80px;" allowTransparency="true"></iframe>

I'm trying to bind it somehow with my fblikebutton.module file:

<?php

/**
* Implements hook_node_view();
*/

function fblikebutton_node_view(&$build, $node, $display, $type, $lang)
{
  $build['fblikebutton'] = [
    '#theme' => 'fblikebutton',
    '#link' => 'http://example.com/',
    '#layout' => 'standart',
    '#show_faces' => 'false',
    '#share' => false,
    '#weight' => 100,
  ];
}

/**
* Implements hook_theme().
*/
function fblikebutton_theme() {
  return [
    'fblikebutton' => [
      'variables' => [
        'link' => NULL,
        'layout' => NULL,
        'share' => NULL,
        'show_faces' => NULL,
      ],
      'template' => 'fblikebutton_link',
    ],
  ];
}

I feel I'm doing something wrong and would appreciate if someone could help me.


texts: Certain block code processes correctly for anonymous user

texts:
I have installed the BlueMasters theme on my Drupal 7.41 site.  Within this theme I have created several new regions and added new blocks to those regions, all of these regions are on the home page available to any visitor.

I have found the home page is not the same when I am viewing it as an authenticated user vs anonymous user.  As an anonymous user I have 4 separate blocks of text which are on top of each other and out of place, but when I login this text is all in the proper place.

I have found that if I grant the following roles to the anonymous user then the page appears correct:

Use contextual links,
Translate interface texts,
Administer menus and menu items

Within my block here is the code I am using

    <img src="<?php print base_path() . drupal_get_path('theme', 'bluemasters') . '/images/prod_go.png'; ?>" >

    "Safety"

    The App connects individuals...

    Features:

    Community

    Emergency

    Secure

    Map GIS Data Viewing

Here is the CSS:

.go-txt-head{

position: absolute;
top: 200px;
text-align: center;
width:50%;
font: 36px 'Lato';
}

.go-txt{

position: absolute;
top: 250px;
text-align: center;
width: 40%;
font: 18px 'Lato';
padding-left: 5%;
}

.go-list{

position: absolute;
top: 425px;
width: 25%;
font: 16px 'Lato';
padding-left: 15%;
}

Some of this code works fine as anonymous, the prod_go.png image is in it's proper place all the time.

Any ideas on why the text in the div is placed differently and the image is ok when a person is logged in vs anonymous?


texts: Use content field as data attribute in Views html

texts:
I have a piece of content with an 'Asset Type' field value of Vidyard.  I am using the Views module to render this content on another page.  I have added those fields to the View, but is it possible to add them as a data-attribute to the HTML.  For example, the Views module outputs:

    etc.

How can I add my "Asset Type" field as a data-attribute to the list item.  Making my output:

Is there a way to do this without altering the template?


texts:
Goal here is to just open my Nodes in a Lightbox.
Following is what I have tried at it is not working for me, any clue would be great:

In my View, I am rewriting the node title as following:

[title]

All I see that the title is output as a link to the node. Clicking on the title just opens the new node.

I followed the instructions at https://drupal.org/node/252260

  Basic example:
  Search google

I am using Drupal 6! (D6 Version: 6.22 & lightbox2 Version: 6.x-1.11)

Update: I tested this works in my D7 installation - but not in my D6 site. :S


texts: Show facets on non-search pages - not working?

texts:
I have Apache Solr search (not Solr for search api) set up and working but I can't get it to show facets on non-search pages.

I've tried every imaginable configuration of "Show facets on non-search pages not working" and "path" on the facet settings page but nothing seems to work.

Does this feature actually work? And if so how?


texts: How can you use multiple lines in a text area?

texts:
I'm probably missing something really simple here, but I can't seem to find it at all!

I want to have a text area for lyrics in my "Songs" content type.  Naturally, lyrics should be displayed one line per line, and with a space to distinguish verses, choruses etc... e.g.

  I got my head checked By a jumbo jet It wasn't easy But
  nothing is No

  Woohoo!

When I put the above in a text area, I get:

I got my head checked By a jumbo jet It wasn't easy But nothing is No Woohoo!

How do I get this to display correctly?  I am using Drupal 6.


texts:
I've got a few pages on my site that need to be accessed via https.
I need to pull some information about the current logged user on those pages.
The problem is, users log using http mode and the session is not kept when switching from http to https.
I've looked into secure login module but it brings some other issues (with facebook connect...)

Is there any way we can tell the cookie to persist ?
Thanks in advance


texts: Running ajax callbacks on custom composite field

texts:
I am using a custom composite field("test") in drupal8 webform in a webform_form_alter() hook. Two select fields-"out_part" and "out_serial" are added to this composite field("test"). "out_serial" is dependent on "out_part" i.e. upon selecting an out_part value from the dropdown, the dropdown values of out_serial are generated. I was able to achieve this with ajax callbacks.

    $form['elements']['test']['#element'] = array(
    'out_part' => array(
            '#type' => 'select',
            '#id' => 'out_part',
            '#options' => array(
                '80002192'=>'80002192',
                '80002191'=>'80002191'
                ),
            '#ajax' => array(
                'event' => 'change',
                'wrapper' => 'serialNumber_wrapper',
                'callback'=> 'populateOutSerialNumbers',
                'method'=> 'replace'
                )
            ),
    'out_serial' => array(
            '#type' => 'select',
            '#id' => 'out_serial',
            '#validated' => TRUE,
            '#attributes' => [
                                'id' => ['serialNumber_wrapper'],
                              ],
            ));

    function populateOutSerialNumbers($form, $form_state){
        $partNumber = $form_state->getValue('test')[1]['out_part'];
        $partNumber = isset($partNumber) ? $partNumber : 'Onboard';

        // Update the $result with dynamic database query results with respect to selected out_part
        Drupal\Core\Database\Database::setActiveConnection('***');
        $db = Drupal\Core\Database\Database::getConnection();
        $query = $db->query("select distinct T1.serialnumber from assets T1 where T1.dbid <> 0 and (T1.manufacturerpartno = :partNumber)", [':partNumber' => $partNumber]);
        $result = $query->fetchAllKeyed(0,0);

        $form['elements']['test']['#element']['out_serial']['#options'] = $result;

        db_set_active();
        return $form['elements']['test']['#element']['out_serial'];
    }

This callback works only on the first set of values of the custom composite field. When I click on "Add", the ajax fails to work on the second set of values. Any suggestions on how to overcome this? Do I need to add the ajax to
    $form['elements']['test']['items'] ?


texts: How to logout a specific user programatically?

texts:
I need to logout a specific user programmatically whose uid is known to me.

I think I need to destroy the session. Is there any table in drupal store that value?


texts: AJAX added form element disappears after failed validation?

texts:
I have a form field which uses the #ajax element. When a user interacts with this field a function is called and a new form element is added to the form and then the new form is displayed to the user.

However, if validation fails the added element disappears? Of course, I want it to remain.

How do I solve this problem?


texts: Conditionally add class to a webform component

texts:
I have a webform with a few "formula" components performing simple math calculations using the webform calculator module.

I am trying to theme the output of the webform in order to add a class to the formula component, depending on the value of the component being calculated.

In my webform-form-[formid]-tpl.php, I have something like this.

 <?php
if ($form['submitted']['mycomponent']['#value']==0) { ?>
    <?php print drupal_render($form['submitted']['subtotal']); ?><?php
}

else { ?>
    <?php print drupal_render($form['submitted']['subtotal']); ?><?php
} ?>
?>

which obviously doesn't work, since I probably miss the whole point :)

Any clue about what can I do in order to accomplish that?

Thanks.


texts: Need clarification Rebuild Registry instructions

texts:
From the module page:

You can just drush dl registry_rebuild and drush will download it
into your .drush folder. (Alternately, you can obtain the package
another way and copy the folder into .drush yourself.)

----I have no drush folder that I am aware of, I am using Xampp on a different drive (E:), using the built in Drush from Aquia Desktop on C: drive, not clear about that step.

On a multisite install, cd into the site you're rebuilding, as in cd
sites/mymultisitestrong text

---- This is not a multisite, so what command should I use?

I followed the steps and it seems like it worked by showing success, however, the site still has errors, like it didn't work....

Did this actually work? Any way to check in logs or something?


texts: db_query select nodes created this month

texts:
I need to query the database directly using php. I am getting my head around this an how to do this using the Drupal database abstraction layer (using db_select and db_query). I need to limit my query to nodes created in the current month. I know that the node table contains the date the node was created in the 'created' column and that this contains a date as a timestamp.

I am not sure how to get the current month and express it as a range of timestamps and return only nodes that were created between the two timestamps.

This code is working to return nodes limited by title:

    $result = db_query("SELECT nid, title FROM {node} WHERE title = :title", array(':title' => $node->title));
    foreach ($result as $record) {
      // Do something with each $record
      $mynode = node_load($record->nid);
      dpm($mynode);
    }

Going to the similar question I have tried to adapt that code to fit my query so I've ended up with:

    $year_month = "2014-04";
    $date = date_parse_from_format ("Y-m" ,  $year_month);
    $num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
    $first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
    $last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);
    $entity_type = 'node';

   $result = db_query("SELECT nid, title FROM {node}  WHERE created = :created", array($first_minute, $last_minute), 'BETWEEN'));
   foreach ($result as $record) {
     // Do something with each $record
     $mynode = node_load($record->nid);
     dpm($mynode);
   }

So I worked it out, but as this question has been marked as a duplicate i cannot provide this in an answer, but here we go:

I needed to get the syntax of the between part of the query correct. Working code is:

    $year_month = "2014-05";
    $date = date_parse_from_format ("Y-m" ,  $year_month);
    $num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
    $first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
    $last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);

    $args = array(':first_minute' => $first_minute, ':last_minute' => $last_minute);

    $result = db_query("SELECT nid, title FROM {node} WHERE created BETWEEN :first_minute AND :last_minute", $args);
       foreach ($result as $record) {
         // Do something with each $record
         $mynode = node_load($record->nid);
         dpm($mynode);
       }


texts: how to make a custom module that has three forms on one page

texts:
I know how to make a module that has one form : http://www.wdtutorials.com/2012/04/26/drupal-7-how-create-forms#.U_YI1WNab3s

But how can I make a module that contains three different forms on the same page?


texts: Manipulate texts before rendering to frontend

texts:
I'd like to have two text fields in back end and programmatically manipulate the texts in these two fields before displaying the result in the front end. The text fields need to be WYSIWYG/CKeditor - preferably the standard editor.

How would I go around this? Should I create my own custom field or use hooks? Can you provide a not too complex example?


texts: Commerce form refresh: 500 error on /en/system/ajax

texts:
Where can I find more information about this error? Nothing is appearing in logs, the error message itself has no useful data.

An AJAX HTTP error occurred.
HTTP Result Code: 500 Debugging information follows.
Path: /en/system/ajax
StatusText: Service unavailable (with message)

Some background info:

Just grasping at straws this point, and may actually completely rework how this feature will work, but just in case anyone has any bright ideas:

Product variations exist in Commerce, certain options refresh the form via Ajax (this is a built-in commerce function), and on refresh any attribute/field that is no longer available is not included with the refreshed form. Again, total standard Commerce function.

I have used a few modules to help me create variations, such as Bulk Product Creation, and as recently has 1 month ago used the exact same process to do this successfully. That product is still working.

When I inspect the ajax call itself there's nothing really unique to this vs. the other working product(s).

I have tried eliminating variations, increasing PHP memory/POST stuff, etc., and have also turned on full error reporting.


texts:
How can I explicitly close a MySql Connection in Drupal 7?
I have a requirement of inserting back to rows to a DB table in Drupal..
I tried using db_insert/db_update and db_query.. In both cases I got the error Max number of SQL connections reached..
I am speculating that Drupal is maintaining these connections one per query and not closing them..
Hence I need to know if there is any way I can do it explicitly.


texts: Is upgrading MySQL to MariaDB seamless for Drupal sites

texts:
My server has an outdated version of MySQL (5.5, which EOL'd in December). The WHM panel has an update option and the recommended upgrade is MariaDB 10.3.

In theory (with all usual "test first" caveats), should a major upgrade like this be seamless for the Drupal sites running on the server?


texts:
According to http://www.drupalcontrib.org/api/drupal/drupal!core!includes!theme.inc/function/theme_table/8

I created a table in my custom page in Drupal 8.

$build = [
  'table' => [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ],
];

return $build;

Example of the first row.

$row = [
    'billing' => [
    'data' => $invoice . '<small>' . $label . '</small>',
  ],

In my page the <small> tag is displayed as it and not rendered as HTML tag. I tried to add attributes => ['html'] or this kind of option but it does not work.

How can I render HTML markup in theme_table()?


texts:
What I need is to add menu item to some menu, but it should have different parameters (title and url) depending on language. So I created new module and added links.menu.yml like:

my_menu_item_id:
  title: 'Dummy Title'
  description: 'Dummy Description'
  url: http://www.google.com
  parent: mainmenu
  menu_name: mainmenu
  weight: -100

And item appears well. Then I added menu_links_discovered_alter hook like:

    function mymodule_menu_links_discovered_alter(&$links) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $links['my_menu_item_id']['title'] = 'Title:'.$language;
    }

And title really get's altered, but that renaming is cached. So when I visit some page in other language previous title remains until I clear the cache. How to solve this. How to make Drupal execute this code with every page instead of using cached value?


texts: Any way to customize default nomask used in file_scan_directory() to allow Node.js modules?

texts:
I would like to use Node.js modules (such as grunt-contrib-imagemin) in my Drupal theme, but that adds *.info files which confuses Drupal.  If there were some way to change the default value of nomask used in file_scan_directory() to include 'node_modules' or some way to tell Node.js to use a local folder other than node_modules then the problem would be solved.

There is a post here that suggests patching Drupal core, but I'm hoping there's a more elegant solution.


texts: How to display different content in a panel page depending on device screen width?

texts:
I have a custom panel page (admin/structure/pages). It has a sidebar region. I also defined a View with two content pane displays: "news-teaser" and "news-teaser2".

How to show "news-teaser" content pane in the sidebar region on desktop devices and "news-teaser2" on other devices?

Each content pane inside page has "Visibility rules". It would be great to add a rule which would return true only for desktop, but there is no such rule.

By the way, I have Adaptive Theme, so I chose adaptive layouts for the page, but this is not doing what I need. With adaptive layout, I can choose different layout for different devices. But I want basically the same layout for all devices, only with different content in it.


texts: How do I programmatically generate a menu based on field values?

texts:
I'm working on a site where I want to have a menu that displays links based off of the content of a certain field.

For example, lets say it is int field_apples. I want to automatically generate a menu that will have links to lists of articles with each value of apples (or a range of apples such as ≤9 apples).

Apples menu

1 apple
2 apples
3 apples
7 apples
9 or more apples

Each link above will show a list of articles for that particular value of apples.


texts: views contextual filter based on post form data

texts:
I'm hoping someone can steer me in the right direction here.

I have view based on a content type. The content type contains a 'keyword' field and pieces of content all have keywords, say for example 'cars', 'trucks' or 'vans'.

The user fills out a form and submits to a page that displays the view in a block. I want the view to retrieve the keyword from the form, and filter the content based on that.

I thought I would be able to do this with PHP validation code in the contextual filter, but now I find that it must return only 'true' or 'false', I can't pass the value from the form and match it to my keyword field.

Can someone point me to a tutorial or useful posting on this? Is it even possible?


texts:
I have a view that returns JSON-serialized content. When there is a link to a file embedded in the content, the response includes the embedded file as  tag, rather than regular HTML. My front-end app is loading the JSON response directly into the DOM, so a link to the file is obviously not appearing.

How can I modify the JSON response so that it presents a link to the file in regular HTML? Thanks.


texts: When might a module's weight in the system table not affect its hook order?

texts:
I am trying to implement hook_menu_alter in my module, but I am finding that revisioning_menu_alter is always being called after my hook, regardless of what I set my module's weight to.  It seems that this is because the revisioning module does not appear in the system table at all, even though it is enabled.

What is going on?  How can I make my module's hook get called after revisioning's hook?  Don't modules always have to have an entry in the system table?


texts:
I have a 'Link' field that is entered in plain text by user. I am trying to display the raw value of this field in my views template. I did dsm($fields); in the views template.

For the field, the raw data shows as a node id, not the url the user entered. The content attribute shows the url but it is wrapped in html. This is also the case when using ->content or ->raw in my views template.

I need to only print the plain url text the user entered in the template. How can I do this?

Here are the results for content and raw value:


texts: All redirects suddenly not working (404 Not Found)

texts:
I have no idea why this suddenly isn't working. Drupal 7, with the current Redirect module (7.x-1.0-rc1). The redirects are set as 301 Default. They are all now returning a 404 error instead of redirecting.

Deleting the redirect and creating it anew doesn't resolve the problem. I'm not sure what to do next. I haven't updated the core or any other modules lately. Help!! Any idea where I should look next?

Thanks in advance.


texts:
I have a Taxonomy Vocabulary as People. In it there are two terms Board and Staff.
I've created a view with two displays, to display the people content with respect to taxonomy terms. The view title is Board Members.

When I access the  board page http://example.com/people/board the title is Board Members.
When I access the  Staff page http://example.com/people/staff the title is Board Members too.

I want to change the staff display title to be like Staff Members? How to change it?

I've filtered by using Contextual filters.


texts: Bulk action on views only works for the administrator role?

texts:
I have a view with a VBO field to execute a bulk operation over nodes.

The bulk operation for this VBO field is a rule component (which I have created) Get Voucher

This component execute some actions.

Now in the view I can execute the VBO only if I'm logged as a administrator. But not with any other role.

I make sure that the permission of all action are enabled. But the action for the component Get Voucher is not listed here.

The button for the bulk operation is shown but when I click it nothing happens.

Which other permission do I need to enable?

UPDATE 1: I know that the problem is related to the actions executed in the compoment. Here is the exported component

UPDATE 2: trying with a more simple component (just one action to show a message)

{ "rules_test_registered_user" : {
    "LABEL" : "test registered user",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "DO" : [ { "drupal_message" : { "message" : " Hello" } } ],
          "LABEL" : "first rule"
        }
      }
    ]
  }
}


texts: I am developing a custom module, where I need to disable future dates in the date pop-up. How can I do this?


texts:
I have searched a way to filter the taxonomy terms by language (as done for nodes), but I didn't find any way to do it.

Does the Views module support that filter in taxonomies too, or just in nodes?
How can I filter the taxonomy terms by language?


texts:
When trying to export my site configurations from one Drupal 8 site to other I keep getting the following error

  The staged configuration cannot be imported, because it originates
  from a different site than this site. You can only synchronize
  configuration between cloned instances of this site.

So in this context what are cloned sites? How can I override this error to import the configurations?


texts: Safe way to authentication users with REST

texts:
I can authentication and login user with below code in Jquery

$.ajax({
    url : "http://domain.com/user/login",
    type : 'post',
    data : 'form_id=user_login_form&name=' + encodeURIComponent("user") + '&pass=' + encodeURIComponent("password"),
    dataType : 'json',
    error : function(data) {
            //error code
    },
    success : function(data) {
      console.log(data);
        //success code
    }
});

But is seems this is not safe mode, and I think maybe someone can attack  bruteforce to find users password.I want to know is this method safe(I don't think so) and what is solution for make this safe against brute-force login attack.

This Ajax request don't return any Json output,It seems try to login and if authorized  then get /user/uid

Note "User login REST format" is similar, but it's not duplicate, and it doesn't have an accepted answer.


texts: Differences between 'Add existing field' and 'Add new field'

texts: It is possible to reuse the already created fields via Add existing field option. From optimization perspective and the way Drupal stores and manages such fields in database I would like to know, does adding fields this way cause any extra efficacy or not?


texts: How do I get JSON data from a custom entity

texts:
I would like to GET JSON data from drupal 8 custom entity.
I am using ubuntu 14.04 and vagrant.
For that i have done these steps.

I have taken reference to Create drupal 8 custom entity from this link.

Enable this modules:

HAL - Core module
HTTP Basic Authentication -Core module
RESTful Web Services - Core module
Serialization  - Core module
Restui - Contributed module

RESTui Configuration:

redirect to admin/config/services/rest
Enable content_entity_example_contact entity
GET Settings done for custom entity

Save.

Permissions given for Rest full web services

Postman Plugin is integrated in to chrome.
below settings is done for postman.

Above steps i have done to GET JSON from custom entity but getting error in postman. Any suggestion or starting point will help for me.

Interestingly when i perform similar steps for drupal 8 node entity i am able to GET JSON data.

Thanks


texts: Get views pager to page by taxonomy term and not content type?

texts:
I have a content type with a taxonomy term with a field. I have a view filtering by the taxonomy term and pager. The view style is set to table with the grouping field set to the taxonomy term. My output is a single taxonomy term with multiple fields.

taxonomy term
field
field
field

The pager is set to 20 and is displaying 20 fields per page. I would like to display 20 groupings per page by the taxonomy.


texts: How do I programmatically create a view?

texts: There is a set of products in Drupal Commerce. How do I programmatically create a view that would select products for a particular field?


texts:
I'm using Drupal 8.

What I'm trying to do is:

Access the active node
From the node get the value of field_test and assign it to a variable
Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a field_test field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the code I am using.

mycustomblock.libraries.yml

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

MyCustomBlock.php

<?php
/**
 * @file
 *
 */

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

/**
 * Creates a 'Foobar' Block
 *
 * @Block(
 * id = "block_mycustomblock",
 * admin_label = @Translation("MyCustomBlock"),
 * category = @Translation("Blocks")
 * )
 */
class MyCustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

  public function build() {

  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $test = $node->field_test->value;
      $variables['#attached']['library'][] = 'mycustomblock/custom';
      $build['#attached']['drupalSettings']['mycustomblock']['test'] = $test;
    }
}

custom.js

(function ($, Drupal, drupalSettings) {
  var testMe = Drupal.settings.mycustomblock.test;
  alert(testMe);
)(jQuery, drupalSettings);

How can I tell if the JavaScript file is being loaded from the block? I checked in the inspector, and do not see it being loaded when the page with the block on it loads.

Furthermore, how can I properly access the field value and pass it to JavaScript?


texts:
I get an access denied on the front page with a fresh install using drush. I can get to the user page fine and login as admin. I read that it might be permissions. Not sure why be default its set like this though. Any thoughts?

Update:

Let me clarify what I need to understand. So previous deployments of drupal using drush I get a fully working site with permissions set correctly. Now I am not sure what is going on wrong but when I run

drush si standard (database info)

I get a freshly installed site with no permissions on the front page. Now I guess what I am trying to understand what is causing this using drush. From what I know and experienced drush si should install the site to a state in which drupal has permissions of anonymous set correct.

I can manipulate the database after deployment but I'd rather not do that if I can make it work with drush right away.

So what could be causing this issue? Am I using drush incorrectly when deploying it?

update:
I think it was a timing issue between mysql and drupal. In any case this is solved.


texts: Search API- Force taxonomy terms to be indexed as one language

texts:
I have a non-multilingual taxonomy on a multilingual site.  All of the terms in the taxonomy are in English.

However, since this is a taxonomy of locations, some of the translations of the names of states/prefectures are in the database as part of the general interface translations.

I have a search index in Search API that indexes the taxonomy terms (field reference on a node) as type taxonomy term.  Somehow, Search API is sometimes picking up the translations when it is doing the index, so I get results like this:

Tokyo (50)
東京 (25)

These are both Tokyo, just some of the entries are converted into Japanese.  The only thing I can think is that the author language is set to Japanese for the nodes that are coming up as Japanese.  However, when I display the data in a view, all of it shows up in English.

So, how can I force Search API to ignore translations when indexing taxonomy terms?


texts: Multiple form buttons with AJAX, how to update form state storage data?

texts:
I have a form built with the Form API that has multiple button form elements. I don't want any of these to submit the form normally, I want them to utilize #ajax and callbacks to update the display. I feel like I run into this on every so often and can't quite remember how to make it work.

When the form first loads, I want half of the buttons to be disabled. When one of the buttons is clicked, I want to be able to detect this in buildForm so I can set form defaults and remove the disable property so other buttons can now be used.

I thought I could set storage in the callback and read it back the next time the form is built:

// Relevant bit of the form...
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['actions']['#type'] = 'actions';

$form['actions']['update'] = [
  '#type' => 'button',
  '#value' => $this->t('Start Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'update'],
    'method' => 'replace',
  ]
];

$form['actions']['reset'] = [
  '#type' => 'button',
  '#value' => $this->t('Reset Form'),
  '#ajax' => [
    'wrapper' => 'my-form-wrapper',
    'callback' => [$this, 'reset'],
    'method' => 'replace',
  ],
  '#disabled' => TRUE,
];

// The AJAX callback
public function update(array &$form, FormStateInterface $form_state) {
  $form_state->set('flag_1', TRUE);
  $form_state->set('flag_2', "Started!");
  $form_state->setRebuild();
}

The callback fires, and I see $form_state storage get updated with those arbitrary values, but when the form is rebuilt, I do not see them in $form_state anymore.

I looked at a few other similar form API AJAX questions, but did not have any luck getting unstuck.

Note: I do not want to have to juggle this with jQuery. I want to be able to update form data behind the scenes and rebuild the form appropriately with the relevant data.


texts: I have a view constructed with many fields, one of those fields is a date field.  I added a filter on my date field that is asking for a relative date.  OK, this is no problem, but I have a request to gather all results from month to date.  For example, I want to get the results from today's date, back to the beginning of the month.  I used for this filter, the operator, "is equal to", the relative date, "this month," and I get no results back, even though there is results between now and the beginning of the month.  I was thinking I am using the wrong relative date.  I looked up the documentation here: http://php.net/manual/en/datetime.formats.relative.php, and "this month" looks like the correct format, but maybe it is not. Can someone point me in the right direction.


texts: Match user based on multiple taxonomy field with Views

texts:
I'm trying to make a view that "match" users depending on what they look for and what they offer.

When a new user register, he chooses what he wants to learn.

Let's say he chooses the following:

1) Vocabulary: "language" -> Term: "French"
2) Vocabulary: "language" -> Term: "Spanish"
3) Vocabulary: "science"  -> Term: "Chemistry"

Then, he chooses what he can offer in exchange:

1) Vocabulary: "language" -> Term: "English"
2) Vocabulary: "science"  -> Term: "Physics"

On another page, I want to display in a view all the users that "Match" his criteria.
Here, it could be :

User1: Look for "English" and offer "Spanish"
User2: Look for "Physics" and offer "Chemistry" and "French"

I can't figure a way to display all user that has the same taxonomy term as the user who did the research but with the learn / offer parts inversed. I hope this is clear.

Any Ideas?


texts: Restrict permission to custom modules in drupal

texts:
I am using drupal 6, and I have created a custom module. This module consists of a form that can be used for adding records to the database.

But I saw that the link to this form (http://localhost/drupal/my_module/form) is accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users. I want  only the administrator to access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module ?


texts:
I want to modify the userpages with some changes:

change the page-title
hide some or all of the local taks items (the tabs)
display some user-infos
insert a view

Here is how I want to solve it:

use THEMENAME_preprocess_page() to change the title
use THEMENAME_menu_local_task() to hide the tabs
use the user-profile.tpl.php to display user infos
create a view and use views_embed_view()

Is there a better way of doing that? Should I consider using page--user.tpl.php or a combination?

Edit: concerns Drupal 6


texts: Modifying target vocabulary when migrating taxonomy terms with migrate_d2d

texts:
I'm working on migrating a D6 site to a nice, shiny, new D7 site, and as part of that migration, I need to split one large vocabulary (approx 12k terms) into two new vocabularies. I have the mapping figured out (done manually, with mappings stored in a custom table), so the only thing left to figure out is how to modify the destination vocabulary as needed.  Here's what I have tried so far.

function nb_migrate_register_migrations() {
  // Define arguments used for all migrations.
  $common_arguments = array(
    'source_connection' => 'legacy',
    'source_version' => 6,
  );
  $vocabulary_arguments = array(
    array(
      'class_name' => 'NBPeopleOrganizationsTermMigration',
      'description' => t('Migration of People and Organizations terms from Drupal 6'),
      'machine_name' => 'PeopleOrganizations',
      'source_vocabulary' => '4',  // D6 Vocabulary ID
      'destination_vocabulary' => 'non_journalists',
    ),
  );
  $common_vocabulary_arguments = $common_arguments + array(
    'soft_dependencies' => array('NBUser'),
  );
  foreach ($vocabulary_arguments as $arguments) {
    $arguments += $common_vocabulary_arguments;
    Migration::registerMigration($arguments['class_name'], $arguments['machine_name'],
      $arguments);
  }
}
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }
    // Check to see if term is in $journalists.  If not, leave it as
    // non_journalists (as defined in migration registration), otherwise
    // change it to journalists.
    if (in_array($row->tid, $journalists)) {
      $this->destinationVocabulary = 'journalists';
    }
  }
}

So I've just defined one of the two new vocabs as the default when registering the migration, and then I want to modify the destination vocabulary if the source term is in my custom table.

The problem I'm having is finding what to modify to change the destination. As you can see above, I tried changing $this->destinationVocabulary, but that doesn't have an effect.  The only other place I can see to change it is in $this->destination->bundle, but that is a protected property of the MigrateDestinationEntity class, and there is no setter function for that property. Looking at the row, I'm seeing that prepareRow isn't the place to do this, since it just has the source data for the term, not where it's going.

All that being said, what do I need to do to modify the destination vocabulary for a term on the fly like this?

Thanks.


texts: Searching on Taxonomy terms with the Search API module?

texts:
I've been playing around with the Search API module for a little bit now, and it seems to be working fairly well, but I can't figure out how or why I am not able to search on terms even though they are selected among the search fields.

Does anyone have any hints or pointers on what I could be doing wrong?


texts: Keeping the URLs of download files to always be the same

texts:
I have a client that need the URLs of downloadable PDF files on their site to always remain the same, because URLs of the PDF documents are published in paper written documents.

If you remove a file and then upload a new one with the same name the system will automatically add an extension (_0, _1, etc) on to the end of the file name, and keep the old file name.

This happens in multiple places - if you have the file as a field in a node, or if you add them as links via the WYSIWYG editor in text fields. Is there any way around this, so that file names always stay the same?

I know (in Drupal 7 at least) that it's possible to set up redirects, but that is cumbersome when you have 100's of files. Does anyone know a solution to this?


texts: Why isn't my sub-theme using its CSS file?

texts:
I created a sub-theme of the Drupal8 W3CSS theme and followed their directions about copying and renaming files, and editing the info.yml file. I installed it, and set it as default theme. It works. (I can see my custom logo.) The styles.css file is not coming from my files, but from the default sub-theme, which I haven't enabled. When I view the source of a page, I see the following tag, which doesn't contain the path for the CSS file used in my sub-theme.

<link rel="stylesheet" media="all" href="/themes/d8w3css/drupal8_w3css_subtheme/css/styles.css?qbo25b" />

It could be I missed a step.

Do I have to do something with Composer after changing any .yml file of the theme? I did clear all the cache bins.


texts:
Coming from a different CMS, I am diving little by little into the Drupal philosophy and I have already bumped into a problem. (being a beginner sucks :/ )

I have installed the hierarchical select module to facilitate my user to add the taxonomies they want. But the user is not happy with the way that the list is displayed.

What I wanted to do is to find a way for the user to define the display (and thus the saving) order of the taxonomies on each node independently.

I thought of weights but that would have an impact on the taxonomy order and not the node.

I did a few searches on the fora and also googled a bit but I always go around the views related topics and I am not able to find a module that does this.

It might be impossible (I have no clue yet on how the taxonomies are saved and treated in the database) so I explain a bit more the situation as there might be a better solution or an alternative to what I am thinking.

In practice, my user wants to be able to choose out of a list of taxonomies one to be displayed before the others, and ideally to be able to arrange the rest of the terms at will.

eg.

node 1 -> Term3, term 2, term 5

node 2 -> Term1, term 5, term 6

The user suggested that could also "work" with 3 fields that define the order of the chosen terms but I find this solution very short term solution and will cause problems the day that I need to add a 4th or a nth field on the same node.

Any suggestion apart from creating my own module?

Thanks a lot for you input,


texts: How to configure drush command-specific archive-dump --tar-options in a site alias

texts:
The following command does exactly what I want — It dumps an archive, excluding all of the files and directories that I don't want:

$ drush archive-dump --tar-options="--exclude=.git --exclude=*.psd --exclude=sites/default/files/styles/ --exclude=sites/default/files/private/backup_migrate/manual/"

Can anyone show me how to set these extra command-specific archive-dump tar-options inside a site-alias array in aliases.drushrc.php?

I've tried every variation I can think of, but I can't seem to get the syntax right.

Update Here is a gist with my full test setup including verbose output and -debug info.


texts: Print the query results inside the submit function

texts:
I have a query wherein it fetches data from the database, a simple SELECT query which is processed when a certain submit button is clicked. What I want to achieve is to get the results of that query so that I can populate it on my form. So far my code looks like this,

function my_module_my_form_submit_go($form, &$form_state){
    $values_array = array(
        'week'            => $form_state['values']['week'],
        'employee_name'   => $form_state['values']['emp_name'],
    );

    $result = db_query("SELECT * FROM {time} WHERE week='".$values_array['week']."' AND employee_name='".$values_array['employee_name']."' ");
}

and my form looks like this,

// this is where I want to populate the data which came from the database
$form['week'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Week',
    '#value'    => $result['week'],
);

$form['emp_name'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Name',
    '#value'    => $result['employee_name'],
);

$form['go_btn'] = array(
    '#type'           => 'submit',
    '#title'          => t('Go'),
    '#value'          => 'Go',
    '#id'             => 'go_btn',
    '#submit'         => array('my_module_my_form_submit_go'),
);

I am pretty sure that the query has results because I ran it on the database. What I want is to echo/print the results in the form because later on they will be also used in another form submission. How would I do such thing after the submit button is clicked. I have only managed to display a text using drupal_set_message but any data which came from the database, I can't display any. Please help. Thanks.


texts: How can I get rid of Contribute 8.x-5.0-beta3 module?

texts:
What's wrong with Contribute 8.x-5.0-beta3 module?

After 8.6.10 update I have a problem with Contribute module.
First it's marked as outdated/not supported but on some sites I can not remove it fully as it lefts something in the db.

So finally I get the errors like

"The following module is missing from the file system: block_user bootstrap.inc:276"

even after the

drush pm:uninstall

It's a composer managed install.


texts: Multi-step form in Drupal 8 using Ctools

texts:
I am looking at examples and code out there for multi-page (multistep) forms in Drupal 8, and it seems there are two ways of approaching this:

Using raw Form API This Sitepoint tutorial
Chaos tools

I have not had much experience with using ctools, but I would prefer to use the simpler method, problem is that I do not understand how to use the ctools wizard to create a multipage form.

This issue started me off in the CTools direction, but the only example I have is the tests, and I am struggling!


texts: How to create block with unapproved comments for dashboard?

texts:
I have a question similar to this one: I'd like to add a block with an overview of unapproved comments on nodes to my dashboard and simply have the possibility to publish them (via a link or button).

How can I do that?


texts: Override theme template from module without implementing a theme

texts:
I have a project on D8 where I don't use any custom themes, I use default seven theme for everything because there is no need of any visual theming.

So My question: Is it possible to override theme template using module? without implementing theme at all?

I have a case where I want to add custom third party generated value in node's template.

This is what I have done:

Implemented custom template:

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'video_teaser' => [
      'template' => 'video_teaser',
      'variables' => NULL,
    ]
  );
}

Implemented hook_theme_suggestions_alter:

function MY_MODULE_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if(in_array('node__teaser', $suggestions)){
    $suggestions[] = 'video_teaser';
  }
}

And this, works, instead of default template, my video_teser template is used.

BUT: I have a problem passing default node variables to my custom template, they aren't passed automatically and I couldn't find the way to do this using current approach.


texts: Drush downloading to an old version of Drupal

texts:
I am new to Drupal/Drush. I tried to learn Drupal last year with tutorial that was based on Acquia-drupal (which I downloaded and was using drush there).
Now, i decided to give it another go by installing Drupal on MAMP. I tried to download a few development modules and the operation was a succes, but the modules didn't appear in my list of modules. Than it dawned on me that they must ended up on the wrong location instead at my new MAMP/sites/all/modules...
How do I fix that - do I ought to delete the Acquia, or should I install another instance of drush?


texts: How to integrate JS / CSS only on specified Pages / custom content types

texts:
I would like embed my module JS / CSS files only in specified cases.
Like on a /url/ or if a custom content type is rendered?


texts: instant upload after select file in a file or image field (quit upload button)

texts:
In the normal fashion you have to select the file you want to upload in a file field or image field and then click "upload" button.

this is not very "user friendly"

How to upload the image or file just after the user selects it in the window without the necessity of click "upload" button.


texts: Ajax callback return 500 Internal Server Error

texts:
file mymodule.inc :

        $items['ajax/channel/%/get-program'] = array(
        'title' => t('get channel program by ID'),
        'type' => MENU_CALLBACK,
        'page callback' => 'get_channel_program',
        'page arguments' => array(2),
        'access arguments' => array('access content'),
      );

      return $items;
//channel program
function get_channel_program($channel_id){
  $channel_id = (isset($_POST['channel_id']) ? $_POST['channel_id'] : '');
  if (!is_numeric($channel_id)) :
    drupal_not_found();
  else :
    drupal_json_output($channel_id);
  endif;
}

file mudule.js :

Drupal.behaviors.ajaxProgram = {
        attach: function (context, settings) {

            // CSS Selector for the button which will trigger the AJAX call

            $('.channel-tv-tabs .tab .tabset .single-prog', context).click(function () {

                var channel_id = $(this).data('channel-id');

                $.ajax({
                    url: '/'+Drupal.settings.pathPrefix + 'ajax/channel/'+channel_id+'/get-program', // This is the AjAX URL set by the custom Module
                    type: "POST",
                    data: { channel_id : channel_id }, // Set the number of Li items requested
                    dataType: "json",          // Type of the content we're expecting in the response
                    success: function(data) {
                        var parsed_data = $.parseJSON(data);
                        console.log(parsed_data);  // Place AJAX content inside the ajax wrapper div
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        console.log(errorThrown);
                    }

                });

            });

        }
    };

Pls help me and tell what i do wrong?
When I try go to link http://hostname/ru/ajax/channel/25/get-program I recive page not found


texts:
i have a custom table created using .install file and in views.inc i am writing code to expose fields to views but i dont want to join that table with node. my code is as follow

function core_sms_views_data() {

  $data['core_sms_details']['table']['group'] = t('Core SMS Details Table');
  $data['core_sms_details']['table']['base'] = array(
    'field' => 'date', // This is the identifier field for the view.
    'title' => t('Core SMS Details Table'),
    'help' => t('Example table contains example content and can be related to nodes.'),
    'weight' => -10,
  );

  $data['core_sms_details']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'date',
    ),
  );

  $data['core_sms_details']['date'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),

    'relationship' => array(
      'base' => 'core_sms_details', // The name of the table to join with.
      'base field' => 'date', // The name of the field on the joined table.
      // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );

  // SMS failed field.
  $data['core_sms_details']['sms_failed'] = array(
    'title' => t('SMS failed field'),
    'help' => t('sms failed daily wise.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  return $data;
}

if i removed
$data['core_sms_details']['table']['join'] = array(
        'node' => array(
          'left_field' => 'nid',
          'field' => 'date',
        ),
      );
    then the field is not appearing in view what i am doing wrong here?


texts: Create a view with user filter by default and all users after reset

texts:
I come here because i want to create a view who display all content of type "Document" of my website, but by default i want to show the content of type "Document" of the user connected. And after when i click on the button reset of the view, i want to see all content of type "Document" of all users.

For example the view when i come on the page :

Me | document 1
Me | document 3
Me | document 4
Me | document 6

When i reset the view :

Me | document 1
Jean | document 2
Me | document 3
Me | document 4
Jean | document 5
Me | document 6
Mickael | document 7

this is possible ?

Thanks


texts: How to get the front page title in page.html.twig?

texts:
I'm trying to use the page title in my theme's page.html.twig. On normal pages, {{ node.label }} does the job, but that doesn't work on the front page. There, node is NULL, presumably because the font page is a view rather than a "real" page.

I have tried to dump all the available variables on page.html.twig using kint, but it seems that none of them contains the page title. Other questions discuss a similar matter, but either only for normal pages or for getting the title from PHP (and not from within a TWIG template).

I'm looking for an approach that works in any template, although page.html.twig is most important for me right now. It should also take a global title override into account. The ideal solution would also work on normal pages (i.e. not the front page).

TL;DR: I'm looking for a template variable/function X so that {{ X }} is the current page title, no matter whether I'm on the front page or on any other page.


texts: default value for entity reference field

texts:
I have a form with an entity reference field and I need to add a default value. I've tried

$form['field_op_product']['und'][0]['target_id']['#default_value'] = $product_node->nid;

but, that doesn't work. Any idea on how to do this?

The widget type is "AutoComplete"


texts: I've installed reCAPTCHA module but spam still bypass my security and leave nasty comments. What should I do? How to block them?


texts:
I am removing products from cart programmatically using such a code:

commerce_line_item_delete($line_item_id)

The problem is, I cannot find any hook, that would be invoked after removing product from cart.
I have tried hook_commerce_cart_product_remove, but this hook is not called when removing product with commerce_line_item_delete function.

How can I remove product from cart programatically, so I can use hook after it happen?


texts: How do I deliver variables to a theme function?

texts:
I'm struggling to complete my first Views display plugin. Currently I'm at a stage where the theming stuff is not working.

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'myfunc' => array(
      'variables' => array(
        'view' => NULL,
        'options' => array(),
        'rows' => array(),
        'title' => NULL,
      )
    )
  );
}

function theme_myfunc($variables) {
  // $variables are null
  $view = $variables['view'];
  $options = $variables['options'];
  $rows = $variables['rows'];
  $title = $variables['title'];
  // ...
}

The variables are obviously null in theme_myfunc(). I don't know how I'm supposed to deliver them from the view object to theme functions.

Should I implement any of the template_preprocess() functions by any chance?


texts: Blocks appearing inside the Content Nodes(Article)

texts:
I have added two blocks in my content page such as Most Popular block and Related Contents. I have also arranged these blocks to be appear in the lower in the Content section inside the Blocks. But, these blocks are appearing inside the articles after the Title field and then the main content of the article gets displayed as Here I would like to display these two blocks after end of the article(i.e after the comment). It would be great if somebody can help me out???

I have reordered it already in the following order Under Content in the Block settings:
Main page content
View: Most Popular:
View: Related Contents
But Still these two blocks embedded inside the content.


texts: I created a view that displays a content types images in a Jcarousel. When I first created the view with the images it was working. I then removed the images to eventually upload new images. When I did, the views stopped working. You would only see an empty white box where the thumbnail image WOULD have been. It scrolls and all just no image. Have the same problem with another view I created using the product images as well. I tried clearing the cache but that didn't do anything.


texts: Assign Node To Other Menus Besides Main Menu

texts:
Is there a module or technique which will allow us to assign a node to a menu -besides- the Main Menu. Users find it annoying that the only menu they can assign a new page to has to be based on the Main Menu. We have many custom menu blocks and it would be nice if the user could set up the page menu in one step rather than having to save the page, then go to the Admin/Structure/Menus and assign the page to the link.

BTW: We're using Kickstart 2 Omega theme if that makes any difference.

Can this be done?


texts: Feeds : creating a node dependencies at importation

texts:
The Excel file I'm trying to import is comprised of two part, the first three columns describe a node that might or might not exist currently, and the three last columns are my entity informations. To date I've created a Feeds plugin to provide a custom processor for my entity and I've explored Rules.

What I'd like is to import the three last column into a entity and before saving it, check if a node with the existing account number exists. If it doesn't, create one with the three first columns. After that, I'd store the nid into the entity as a foreign key (my entity has a n-to-1 relationship with the node).

I've tried to use Rules "Before saving an entity" event, but I can't access unmapped columns this way. I've tried adding mapping to non-existing properties of the entity thinking they would be set and simply forgotten once the entity goes out of scope, but I instead get an unknown property error at importation. I've even tried to override the setTargetElement function in my processor, but the error still occurs. It seems to me I've got little choice but to store the unwanted data in the table and duplicate it in the node afterward (exactly what I'm trying to avoid).

Does someone have either a way to create these non-persisted property, have a better way to create and store a node relationship in an entity (Entity reference maybe) or even another solution6

Thanks


texts: Rule to send out content of newly created forum-topic or comment

texts: I have a rule that will send me an email with the username of the person that creates a new comment or forum-topic. However, I would really like the URL and actual content to show up in the email. How can I accomplish this in that order of importance. Because right now I have to click on content on the site and look for the newest items to find the new content.


texts: How to alter paths, that are translated by i18n?

texts:
I am using language selection by language domain in Drupal 7. That has the side effect, that all internal Drupal paths being created as absolute paths by the i18n module.

To get sub-domains working again I want to alter the paths that are translated by
i18n. Is there a hook I could use for that?

The function *hook_url_outbound_alter()* is triggered before the path translation by i18n, so it can't be used for that purpose.


texts:
a possibly stupid question. Why won't this form submit?

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

if I add the following

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

and a submit function:

function my_form_submit($form, &$form_state){
  dd('Submit ran');
}

The debug statement is never called. What am I doing wrong?


texts: Why does my selection gets only the last row?

texts:
I rewrote for Drupal 8 a Drupal 6 query on 3 custom entities (see here):

$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }

Unfortunately, I can retrieve only the last of each {datedistribution-role-nom}.
For each 'datedistribution', if I have more than one 'role' or 'name', I can get only the last one considering the sort order I put in place.
Strange, no?
Any idea why?


texts: Add comma in between the Tags Display in Drupal 7

texts:
Can any one help me how to add comma inbetween the tags in drupal 7.

I have inspect the code  for the following tags

Tags: Test bha

the code for this is

Tags:&nbsp;

                Test
                bha

I have used used the following code to add the comma inbetween the tags

              function fold__field_tags($variables) {

                   $output = '';

              // Subtract 1 from count to match $delta which starts at 0
               $count = (count($variables['items']) - 1);

              // Render the label, if it's not hidden.
              if (!$variables['label_hidden']) {
             $output .= '
' . $variables['label'] . ':&nbsp;
';
                 }

           // Render the items.
          $output .= '
';
          foreach ($variables['items'] as $delta => $item) {
          $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
          $output .= '
' . drupal_render($item) . '
';
         // If this is not the last item, print a comma and space
         if($delta < $count) {
          $output .= ', ';
         }
         }
       $output .= '
';

    // Render the top-level DIV.
      $output = '
' . $output . '
';

      return $output;

    }

Can Anyone help me where i made a mistake.


texts: How do I implement a reverse node reference using References?

texts: Using the References module (D7 version), implementing a new field in an article content type for node reference was very easy, but now I cannot seem to figure out how to discern the reverse reference. Just as there is a link shown in my article to the node I have selected in the node reference drop down, I am expecting that on the "linked to" article, I should be able to see a link back to the first article. Has anybody done this? My understanding is that it is part of the D7 version of this module.


texts: How to refresh entity from entity_load(), reloading the entity as it is now?

texts:
If an entity has already been loaded, entity_load() retrieves it from memory rather than reloading it. Makes sense.

But: what can you do when you need to reload an entity that has already been loaded - when the entity's data has (or, may have) been changed in the database since it was loaded by another function, and you need the changed version?

The closest I can find to a way to reload an entity is to call entity_load() with the 4th parameter of entity_load() to true - for example, entity_load( $entity_type, $entity_id, null, true ); - however, this does much more than just reload the entity.

It also appears to reset the cache on the server, which can have a lot of undesired side effects (for example, I'm finding that calling this as a step in the process of saving an entity causes a cache to be created for the entity's fields that is missing field data, and this faulty created cache persists even as the entity is saved, causing it to seem like the entity's fields failed to save and a blank entity was saved, at least until caches are cleared). From googling around, I get the impression that setting this parameter is generally considered to be A Bad Idea (posts I've seen aren't specific about why, but my experience offers a clue).

So, how can I re-load an entity that has already been loaded but which I suspect has been changed since being loaded, with minimal other consequences?

Drupal 7, and while core-based answers are best any answers that use the Entity API contrib module or other robust contrib modules are fine.


texts:
I'm trying to override the label of the picture field.  I've started with the code here:

How to change the field label on my registration form? Drupal 7

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
if ($form_id == 'user_profile_form') {
  dsm($form_id);
    $form['account']['picture']['#title'] = t('Profile Picture');
}
}

I just want to override the "PICTURE" title to something else.


texts: How to convert currency dynamically on Product Page?

texts:
I am using drupal 7 and commerce modules. I want a dynamic currency converter on product display page or cart page (priority is product display page). Suppose Product A is displayed with price 1 USD and user is from India or some other country then I want to give the user an option to change the currency before adding product to cart. If the user selects INR then the 1 USD will be converted to INR which makes it 67 and payment will be made in INR. How can I achieve this kind of functionality in Drupal ?

Suggestions are welcomed.

Thanks


texts: Create pagination in theme('table') when not using SQL query

texts:
I would like to create a pager in the table when there is fix amount of rows.

The method suggested on internet creates table, and it fetches data by using sql query, but i want to create a table from the data from the array.

visitedgroups = array('1','2','3','4');//It is an array of node id which are group entity
$header = array(
                array('data' => t('Group Name')),
                array('data' => t('Group Since')),
                array('data' => t('Join')),
            );
            $rows = array();
            foreach ($visitedgroups as $groupid) {
                $groupnode = node_load($groupid);
                $createdtime = format_interval((time() - $groupnode->created) , 2) . t(' ago');
                $joinlink = l('Join Group', 'group/node/'. $groupnode->nid.'/subscribe');
                $rows[] = array( l($groupnode->title, 'node/'. $groupnode->nid),
                                                t($createdtime),
                                                $joinlink,
                                    );
            }
            $output .= t('Recently visited groups by you, in which you are not member.');
            $output .= theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('group-visited-table')))).theme('pager');

The above code generates the table and working fine. But i want to add pager in the table.
From the references on internet i found that people adds,

  $query =
  $query->extend('TableSort')->extend('PagerDefault')->limit(10);

ahead of $query->execute(), but i don't have query.

So how can i apply pager in this scenario..


texts: Is it possible to add fields definitions in entity?

texts:
I created an entity using drupal console and now I would like to add fields to it. These should be references to other entities. I want these fields to be added programmatically, in the code. Ideally in the entity class so I can use entity methods to load referenced entities. How do I do that?

Thanks.


texts: Do custom theme suggestions execute on every page load and does that impact performance?

texts:
I've been working with Drupal for a little while now and one nagging question I've had is about whether or not logic in my *.theme or *.module files have any impact on server load.

Let's say I have this bit of code in my *.theme file:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MY_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if(\Drupal::routeMatch()->getRouteName() == 'entity.node.edit_form' && \Drupal::routeMatch()->getParameter('node')->bundle() === 'blog_general') {
    $suggestions[] = 'page__no_sidebars';
  }
}

This bit of code adds a template theme at the page.html level. I only need this for about 1% of my site and it bothers me a little that this would need to execute on every page load just so 1% of my site can templated correctly.

So my question is, would this code get executed on every page load? Or does the caching take care of it? If it does execute on every page load then this one bit of code might be trivial. However, I'm slowly building up a lot of these types of altering hooks and it's bugging me that they could be taxing the server.

I appreciate any insights. Thanks!


texts: Is there a way to know the type of output inside a template file?

texts:
I am making a website for both WAP and smartphone browser, and I am using two themes to display WML and HTML. Now I have a problem to show a <anchor> link. The pseudo-code for the code I would use in the template file is the following one:

if (HTML_THEME) {
  print 'BACK';
}
else{
  print '<anchor>BACK<prev/></anchor>';
}

Could anybody tell me how to implement this?


texts: Use user/register instead of default login page for anonymous users

texts:
This sounds simple enough but I can't make it work.

Only registered users can view the site content, but instead of the login block, I want users to go to the user/register page (with the 'login' and 'request new password' tabs also there), and after registering then be taken to the frontpage.

I've tried the login redirect and login destination modules, but they don't help setting user/register as the defult page for anonymous users. I tried setting 'user/register' as the homepage in config/system/site-information and force logged-in users to the actual frontpage, but not surprisingly that didn't work. I tried disabling 'view published content' permission for anonymous users, and then set the 403 page to user/register, but nothing. I tried creating a rule (first time using rules) as follows:

Event: drupal is initializing

Condition: user has anonymous role

Page redirect: user/register

And other variations I could think of, but to no avail.

I don't think it's that difficult and I'm probably missing something. Can someone please advise?


texts: Converting a Views SQL query with INNER JOIN to an EntityQuery

texts:
I'm trying to create a custom JSON:API resource that returns the entities that have been flagged by a user.  (The Flag module does not offer a way to get this out of the box.)
I used Views to build a query to show all terms flagged by the user:
SELECT taxonomy_term_field_data.tid AS tid, flagging_taxonomy_term_field_data.id AS flagging_taxonomy_term_field_data_id
FROM
{taxonomy_term_field_data} taxonomy_term_field_data
INNER JOIN {flagging} flagging_taxonomy_term_field_data ON taxonomy_term_field_data.tid = flagging_taxonomy_term_field_data.entity_id AND (flagging_taxonomy_term_field_data.flag_id = 'MY_FLAG' AND flagging_taxonomy_term_field_data.uid = 'MY_UID')

Then, I installed the JSON:API Resources module and configured a custom resource.
However, JSON:API uses EntityQuery, not regular SQL queries.
So based on my very limited knowledge of SQL, I wrote a basic query to get all the terms:
    $query = $this->getEntityQuery('taxonomy_term')
      ->condition($entity_type->getKey('bundle'), 'MY_VOCABULARY');

Now I want to restrict this to the terms that have been flagged by the user.  How do I implement the INNER JOIN in the Views query in EntityQuery?


texts: How to create page of multiple entity reference fields

texts:
I'm making a kickboxing archive. I would like to create a content type 'Fights'. But something isn't working.

A fight takes place between 2 fighters (content type 'Fighters'), at an event (content type 'Events'), in a venue (content type='Venues').

I need to select two fighters. I have added an entity reference of 'field_fighters'. Now I want to add another entity reference of the same field for fighter 2, but I can only refer to this field once. How can I do this?