texts: How to bypass "allowed values" validation for a select field (list_string)?

texts:
At the user account form, I've created two select fields (of type list_string) for state and city.

The state field has a list of states for its allowed values config, and the city field has no values for its allowed values config (cause its supposed to have dynamic values).

The city field is being populated dynamically via ajax after selecting a state (it's a dependent dropdown mechanism).

It was all fine until I tried to save the entity and got an "Illegal choice selected..." error message.

I've tried all (decent) workarounds for this problem but none of them worked (including a dynamic values list).

For those wondering, this is how I implemented the dynamic values list when I tried it:

/**
 * Set dynamic allowed values for the city field.
 *
 * @param \Drupal\field\Entity\FieldStorageConfig $definition
 *   The field definition.
 * @param \Drupal\Core\Entity\ContentEntityInterface|null $entity
 *   The entity being created if applicable.
 * @param bool $cacheable
 *   Boolean indicating if the results are cacheable.
 *
 * @return array
 *   An array of possible key and value options.
 *
 * @see options_allowed_values()
 */
function module_name_cities_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, bool $cacheable): array {
  $options = [];

  if ($entity->bundle() == 'user') {
    $state = $entity->getState(); // Returns the value for `field_user_state`

    $cities = module_name_load_cities_from_state($state);
    $options = array_merge(['_none' => '- Select a city -'], $cities);
  }

  return $options;
}

As you can see it wouldn't work, since I am relying on the entity being filled with values by the time I try to load the list of cities from an another entity field (state). Is that clear?

In the ideal world, I'd be able to remove this "valid choice" validation, that is set through the AllowedValues constraint at some point. Unfortunately, I had no success trying to do it.

Does anyone know how to remove this validation constraint?

I can see it is set by inspecting the return value of \Drupal::entityManager()->getStorage('field_config')->load('user.user.field_user_city')->getItemDefinition()->getConstraints();

How to bypass this allowed values validation?


texts: How to make relation between user term and nodes terms?

texts:
I'm newbie to Drupal. I'm in a process to restrict the user based on the node taxonomy term, and the user taxonomy term. For the user's I have attached a custom field of type Term Reference. I have a Taxonomy Vocabulary called Company. Inside that vocabulary I have created two terms Tata, Infos.
There are totally 100 nodes, out of these 60 were belongs to Tata and the 40 belongs Infos.

Now these terms would be reflect to the user profile page as radio button. When admin select Tata for particular user, then that user might be able to see only the Tata tagged nodes and vice versa. I have tried tac_lite and content_access module before adding custom fields to user profile page, but not my requirement is getting finished. Is there any way to achieve this!!!

Thanks!!


texts: We are trying to do migration of joomla database to drupal 8. We are using migrate and migrate plus modules to accomplish this task. We took migrate example module(beer migration) which came with migrate plus module as reference and trying to customize it according to our requirements. But when we try using our custom migration names instead of beer_term the migrations are not registering. Is there a way that we can register them.


texts: Drop-down menu only works after clicking into the parent page first

texts:
I am using the Venture theme for Drupal 7.
I have a 'Products' page listed in the main menu with a drop-down list that is a separate page for each product. However, to get the drop-down list to show up, I first have to click on the 'Products' menu link, which will bring me to an empty page.

I would like the drop-down list to display if I hover over the 'Products' menu item so the user can select a child product page right away instead of having to go into the parent 'Products' page first and then having the option to select from the drop down menu like it is doing now..
Ideally, I would like to not have to display the parent 'Products' page at all, and have it just be in the main menu as a way to access the drop-down list items to other pages.

Any suggestions would be appreciated.


texts: Getting an email notification when a new Drush version is available

texts:
With standard Drupal modules, you get an email notification when there's an updated version.

How can we have this option with Drush?

I searched the official http://drush.org website and unfortunately there's no mailing list or RSS feed so that we know when there's a new version of Drush out.


texts: Access to a website only when I grant them access

texts:
I have made a registration form and a login form using PHP.

The registration form saves user's information to a database.

But as I am pretty new to PHP I want to achieve this think. I have also made a whole e-commerce website with Drupal commerce(commerce kickstart) but I want as an entrance page to be this registration form and when I grant them access to be able to see the whole content of my e-commerce website.While i say grant them access when they give me the fields of the registration form,they wont be able to enter the website until I send them a password. So my question is : How can I achieve not be able to see the entire website?What I need to do to protect it? I mean I need to add code on the registration form? on the login form or the template/theme?

I know that I have to use $_SESSION[] and $_COOKIE[]

For example

if($_SESSION['loggedIN'] ===false){ header('location:login_page.php')}

but I do not know where to put the code so as to work. In which part of the commerce kickstart do I have also to say that the e-commerce website would be on a sub-domain as the domain will be used for the registration form if this helps.

Thanks!


texts: How do I add the "onload" attribute to a script tag?

texts:
I need to add the onload event in jquery script tag as advagg does. I have done a bit of research, and I found that they are actually invoking hook_element_info_alter() and thereby add their hook_advagg_modify_js_pre_render() implementation into it. Then, they alter the child elements.

When I do the same in a hook_element_info_alter() implementation, type['script'] is not there.

Am I missing something?


texts:
I have a nodetype with a nodereference field but my references are not visible on my page. I can't work with the nodereferencefield in views either.

Edit:
I created a contenttype 'Building' with a referencefield to the contenttype 'person'. When I create a 'Building' and I refer to a person, the person is not listed on the buildingpage. I haven't changed display settings.

Version: Drupal 7


texts: entityfieldquery, return several results

texts:
I want get several entries of database. Im a entityfieldquery novice and I misunderstand how I do for get several results who contain certain fields (here, the fields that interest me are : delta, field_top_value and field_top_revision).

By example, I try this code :

$query = new EntityFieldQuery();
$query
    ->entityCondition('entity_id',$nid_device)
    ->entityCondition('entity_type','node');
$result = $query->execute();
dpm($result); //show just one only node...but I would like get the five entries, with field "delta, field_top_value and field_top_revision_id"

I "tried" to read the documentation, but my english reading isn't very good, and I don't find example for my case..

Thanks for help !


texts: How can I remove the %20 from a URL evaluted by a contextual filter?

texts:
I have a contextual filter that is set to evaluate the "Raw value from URL" against my taxonomy term name. The issue is that a few of my taxonomy terms are two or three words long. This results in a URL like:

https://example.com/category/my%20taxonomy%20term

What I want is for my url to be:

https://example.com/category/my-taxonomy-term (but this currently returns no results).

Is there a way to use dashes instead of the %20 in a views contextual filter that uses the "Raw value from URL" setting?


texts: Where to collect business logic for Entity models?

texts:
Thinking of entities as an MVC 'Model', where would the business logic for an entity sit? I have a custom EntityController, but that isn't attached to an instance and seems to be intended only for serialization logic. I need a Model class that has the same properties as the entity StdClass, but also has functions for operating on the data and presenting it.

I am currently wrapping the entity with a real Model class that is created by its static function Model::createFromEntity($entity)


texts:
I need to display field data for a given revision in a view for example the body.

To archive this I created a view which displays content revisions.

This view has a relationship by default: The revision ID of the content revision.

I then added the body field using this relation.

When i run the view the body field is empty for all revisions but the active one.

When I change the relation to The revision NID of the content revision. I get all fields filled out, but they are all filled with the data from the active revision.

I don't know if this a bug or the expected behavior.

Is there a way to get the field data for revisions that are not active or do I need to rewrite the queries?

I'm using the revisioning module, but it doesn't make a difference if it's active or not. The results of the views are the same.


texts: Can you tag individual searches per search in order to apply different filters to each?

texts:
I've got a site where we use solr to generate some menu items and other custom lists as well as running the default search. The issue I'm running in to is all the different hook_apachesolr_query_alter calls across several different modules seem to be getting applied on top of each other stopping everything from working as expected.

Is there an identifier I can look for, or that I can add, in order to identify which query is currently being altered so I can filter them appropriately?

This is what I want to be able to do:

<?php
if ($query->name == 'special_menu'){
  $query->replaceParam('qf', 'sm_vid_Colour');
}
?>

(This is a dupe of my post on Drupal.org at http://drupal.org/node/1976224 but I wasn't getting any love there and thought I'd try my luck here!)


texts: Exposed filter with "inverted" checkbox: Checked = view all, Unchecked = filtered

texts:
I have a view that shows commerce products, with an exposed filter to show only items with stock >= 0. So, if the checkbox is checked, it will hide out-of-stock items.

I would like to reverse this so that if the checkbox is checked, all items are shown, and if it is not checked, only the filtered items (stock >= 0) are shown.

The label could then be changed to "Reveal items that are currently not available".

Any idea how to do this?
I could probably do this with some hook_form_alter() and stuff, but I am more interested in something to configure with the Views UI.

(Not that I shy away from custom modules in general, but I like to avoid stuff that is hardcoded to one specific view name and display id and field name..)


texts: How can I reset render cache on an entity for current user in hook_entity_view_alter()?

texts:
I have Commerce products for which I'm showing or hiding the add-to-cart link, if that product is or isn't in the current cart.  In my code:
function mymodule_commerce_product_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
    $myservice = \Drupal::service('myservice');
    if ($myservice->isProductInCurrentCart($entity->id()) {
        $build['add_to_cart_link']['#access'] = FALSE;
    }
}

That works fine, however, when the product entities are rendered, they retain their cache and will continue to display, or not display, the add-to-cart link until the cache is cleared.
In my view_alter hook, how can I clear the cache for the current user for that entity before it's rendered?  Can I set a cache tag?


texts:
I want to add a custom link at the end of the loop of my view just like Pager More Link do. But I want to create a custom link. What I've tried so far:

I have created a Custom Text field, rewrote it to a link that I want and made it exclude from display. Then I group my this field and with css I place it where I want it. The only problem is that this grouped field is displayed with an <h3> tag that I don't want.

Is there any way to group field but not in tag <h3><h4>... or there is a module or something which can give me a option to create a link similar to the pager more link but with a custom url?


texts: Views Load More pagination causes duplication

texts: I am encountering an issue with Views Load More with Waypoints module. My question is more focused on the next contents that are retrieved. Because there are new contents added to the top, the page 2, for example, now contains items from page 1, thereby showing duplicates. Please see explanation below. How can this be addressed?


texts: Zip code in checkout pane in mobile displays to far right where users don't find it

texts:
Theme issue perhaps.

Commerece kickstart 2, sub-theme of Kickstart,
zip code is displayed to the far right on mobile screens (android) and the users can't find it to fill in.

Quick hack is added clear:both to class but this effects all displays to have city, state and zip on separate lines.  I'll post a better fix when I have time.

.form-item-customer-profile-billing-commerce-customer-address-und-0-postal-code {
   clear:both;
}


texts:
Anyone know of a way within the theme to redirect to a different url after login?

Theme #1:
Eg. User goes to www.examplesite.com logs in and is taken to www.examplesite.com/front

Theme #2:
Eg. User goes to www.examplesite.com logs in and is taken to subdomain.examplesite.com

I know of modules that allow us to do this for the entire site but have not found a way to do it just for a single theme.

Background: its for the mobile site UX.


texts: Tools to create registration site with calendar and jQuery/ajax

texts:
I belong to a volunteer organization that uses a painful .NET site for signing up for shifts (for example, you can change registrations for anyone, not just yourself), so I'm looking to create a Drupal site that can handle this process much easier and also allow admins to make changes without having to pay someone to make changes when needed.

You can see the current site below.  Each column is a day, the numbers (140, 148, etc.) are the stations, and the second column is the position. At one glance, you can see who is signed up on a given day and at which station. This is just one small part of the entire page, which is a calendar view of a whole month.

What I would like to do is create a "Register" button for each slot that uses ajax when clicked that would register the user for the shift and replace the button with the user's name (after doing some validation, such as making sure the user isn't signed up for another slot at the same time, they have permission for that slot, etc.).

The trickiest part is creating the custom form and then displaying it in the calendar.  As with any Drupal site that needs a calendar, I'm looking at the Calendar and Full Calendar modules.  Both seem to require nodes with date fields and Views displays to show a calendar, so I'm guessing I would need to create something like a Shift entity with a date field and then create the node via the ajax code.  The bigger question is how to create the custom form and display it in the appropriate date in the calendar.  Is it a matter of creating a custom Views display handler for the form, or is there a simpler way? Once I figure that part out, the rest will be pretty easy.

Thanks.


texts: Get this jQuery Youtube Playlist working?

texts:
Drupal 7.  I'm trying to get this to work - seems simple enough.  I added the .js file through my theme's .info file, and it's picking that up.  I selected "Full HTML" as the format for my block, and pasted the code in (both the js and the ul).  Just doesn't work.

http://www.geckonewmedia.com/blog/2009/8/14/jquery-youtube-playlist-plugin---youtubeplaylist

Any ideas?  I suspect the js needs to be loaded somewhere else, that maybe it's being stripped out from the block code?

Per SoftArtisans (thanks) this is now what I have in the Body of my custom block (set to full HTML):

Video 1

Video 2

Video 3

It's still not working.  I verified the other .js file is being picked up in the source.


texts: Copy taxonomy term name to another field

texts:
I need coordinates for each term in a cities taxonomy I got one a site for one of my clients. I found Geofield, which I use on nodes on that very same site, and it works as it should. However in my city taxonomy Geofield has a bug that makes it unable to get coordinates based on a title, which the term name is.

So I figured that I might copy the value of the title into another field for a term - like Title Copy field, and then base Geofield coordinates by that. Now, I don't know how..

I've found Computed Field which I find to complex for this, Tokens I don't get to work, Reference auto fill needs yet another source field so it goes away.

Any ideas for a simple solution that will work with terms created from both the taxonomy UI AND when nodes add new terms from a Autocomplete field?


texts:
if a user changes his email address, I want him to lose a specific role (if he had that role in the first place). To make matters more complicated, we have the "email confirm" module enabled and this bitchy little module uses user_presave() in a way that leaves no traces of an email change when it is called during the edit of a profile. So I wrote a module and gave it weight -1 to make sure it gets a chance to compare $edit->mail to the users current mail before "email confirm" begins to work.

My code looks like this (version with a lot of debug statements that will be removed in the live environment):

function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    // remove xyz role if the users changes his email address
    $user = user_load_by_mail($account->mail);
    $role = user_role_load_by_name('xyz');
    if (array_key_exists($role->rid, $user->roles)){
      drupal_set_message('In if-clause.');
      $return1 = print_r($user->roles, TRUE);
      drupal_set_message($return1);
      $user2 = user_save($user, array('roles' => array_filter($user->roles, function($item) use ($role) {return $item != $role->name;})));
      $user3 = user_load_by_mail($account->mail);
      $return2 = print_r($user3->roles, TRUE);
      drupal_set_message($return2);
      if (!$user2){
        drupal_set_message('User_save() failed.');
      }
    }
  }
}

If I log in with a test user that has role xyz and change his email address at the "edit profile" site, i receive these status messages:

In if-clause.
Array ( [2] => authenticated user [5] => abc [8]
=> xyz )
Array ( [2] => authenticated user [5] => abc )

The debug messages tell me that:

It has been found out, that the user has the role xy and therefor the if-clause was entered.
Before the call to user_save(), the user had the role xyz
After the call to user_save(), the user was freshly loaded and he did not have the role xyz anymore

Yet despite all this, the user does not lose the role, no matter how often I change the email address or flush the cache.

My question now is: What the hell?

Using user_save() in the user_presave() function seems to be odd, but when I put the $roles array in $edit without the xyz-role, I receive pdo exception that states, that the roles are already set for this user.


texts:
I'm trying to use the Disable Messages Module to hide some messages. For example the message Proposal has been updated. (because I'm using a wizard and updates every step).

These are my configuration settings of the disable messages module:

I've cleared my cache but the message is still showing. Am I doing something wrong?


texts: IP-numbers not found in database table ip2country

texts:
I am trying to hide a certain field in the product nodes for all visitors from other countries. I have installed the ip2country module and I am using this code snippet to fetch the language code in my module:

$ip = ip_address();
$country_code = get_country($ip);
dsm($ip . " " . $country_code);

The IP address is showing but not the country code. I am testing this on a web server and the IP printed by the dsm seems OK. I have also copied and renamed the ip2country_get_country($ip_address) function from the ip2 country module to experiment with different solutions in my own module:

function get_country($ip_address) {
  $ipl = ip2long($ip_address);
  if (is_long($ip_address)) {
    $ipl = $ip_address;
  }
dsm($ipl);
  // Locate IP within range.
  $sql    = "SELECT country FROM {ip2country}
             WHERE (:start >= ip_range_first AND :end <= ip_range_last) LIMIT 1";
  $result = db_query($sql, array(':start' => $ipl, ':end' => $ipl))->fetchField();

  return $result;
}

The thing is that the long ip produced by the get_country() function ($ipl = ip2long($ip_address)) is ten numbers, and as far as I can see in the database table no numbers for my country (Sweden) is made up of ten numbers... So it's not strange that the db query does not return the expected result ('SE'). There must be something obvious I am missing here... ? I have experimented with SQL queries directly in phpMyAdmin and I can confirm that the IP number is not to be found in any of the ranges given.


texts: Get the master parent node id for a node reference field

texts:
I have 3 content type "A" , "B", "C".
B has a node reference to A.
C has a node reference to B.

B->A
c->B

Using simple query I want to get the master parent node Id of C. which is A node id

c->B->A

How to do this.


texts:
Using CKeditor module I am trying to add a new template.

I have modified default.js in

\sites\all\modules\ckeditor\ckeditor\plugins\templates\templates\default.js

By adding a new entry, however after Flushing caches/restarting web server, I still don't see the new template when I edit content.


texts:
I'm creating a custom module in Drupal 8.4.4. I put several menu links under the Development menu.

scrape.scrape_form:
  title: 'Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_form
  description: 'Scrape content from ccad.edu'
  weight: 10

scrape.scrape_images_form:
  title: 'Images Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_images_form
  description: 'Scrape images from ccad.edu'
  weight: 20

...

This is working fine, but now that whole menu is getting a bit too long.

I wanted to wrap up all of my links under one 'header' link under the Development menu.  I added this at the top of mymodule.links.menu.yml:

scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  route:<nolink>
  menu_name: scrape.migration
  route_name: scrape.migration

But when I try to rebuild the cache, I get this error:

The website encountered an unexpected error. Please try again later. Symfony\Component\Routing\Exception\RouteNotFoundException: Route &quot;scrape.migration&quot; does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

How can I make a new, non-navigable parent link under Development, to put my custom links under?

Edit 4k4's comment is correct, but my parent link is very small and greyed out.

scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  menu_name: scrape.migration
  route_name: <nolink>

How can I get a full-height, dark-font header link?


texts: How to put site in 'Safe-Mode' to troubleshoot Drupal if site encounters problem?

texts:
If site goes caput. Quite a few modules have been installed. Site was running perfectly fine until you need to upgrade a few dozen modules now. (I have not been updating my drupal site for quite a few months - imagine how many modules needs updating!) Update was ran, site stopped working. I don't know where to start troubleshooting. Site would not even go to admin/structure pages. It just refuses to cooperate.

I feel there should be a way. Like, looking from the database itself what tables should I delete (should I delete module tables? Would this not entertain more problems?), or is there any specific tables I should look at only and safely delete the contents that should force Drupal to run in 'safe-mode'?

I guess there should be a safe-mode option for Drupal in cases like these but if none, what is the best course of action to put it into 'safe-mode'.

Notes:

I have searched in "advise for managing and troubleshooting modules" but this is not enough for me.
"Drupal error. Drupal safe mode possible?" also is closer but I don't know how to use drush or at least as far as I know drush is difficult on windows.


texts:
I am using Drupal 7, and I want to show the breadcrumb only on the forum, so I used the following code:

$node = menu_get_object();
if (arg(0) == 'forum' || $node->type == 'forum') print $breadcrumb;

The code works, but it gives errors when I visit the admin page.

  Notice: Trying to get property of non-object in include() (line 18 of /srv/www/lusciousanime.com/public_html/sites/all/themes/anime/page.tpl.php).

Does anyone know how to fix it?


texts:
I've installed contentaCMS and contentaJS. After installation I can directly access the CMS via contenta.ddev.site and the nodeJS proxy via contentajs.ddev.site. Out of the box the nodeJS proxy does know about the JSONAPI routes and when accessing contentajs.ddev.site/api I do see all resources (the module openapi_jsonapi is preinstalled for this). However, I want to access my core REST and custom REST endpoints via the nodeJS proxy too. Therefore I installed the module openapi_rest. I created a custom rest endpoint under /custom/test and return a simple "success" 200 message (accessible via contenta.ddev.site/custom/test). However, even after restarting the nodejs server, when trying to access contentajs.ddev.site/custom/test, I get a 404.
Any idea what I'm missing here? All the documentation about contentaJS, drupal+nodejs proxy etc did not give any details of how to set this up properly.
My question is kind of similar to this one (however, no answers given)


texts: How to cancel an order transition if failure is detected in Commerce 2 / State Machine

texts:
I'm trying to plug into order transitions in order to send my order to a custom fulfillment system.

I have a transition called "send_to_fulfillment", and order states "reviewing" and "sent_to_fulfillment".

I'm hooking into the commerce_order.send_to_fulfillment.pre_transition event. What I can't figure out is how to cancel the transition if the process fails. I can certainly just throw an exception and let the site die, but I'd prefer to be able to elegantly stop the transition and inform the user of the error.

Any tips? I've tried WorkflowTransitionEvent::stopPropagation which didn't do it, and I can't seem to find it documented anywhere.


texts: Best way to make an EntityFieldQuery query be case sensitive?

texts:
The case-sensitivity of queries created using EntityFieldQuery rely on the underlying database's collation [*]. So if the collation for a particular field is 'utf8_general_ci', then all the queries created with EntityFieldQuery are case insensitive.

Given that it's not always possible to change the schema (say, if you are developing a module that acts on third party fields) how can you ensure case sensitivity when using EntityFieldQuery ?

My solution so far consists of using a tag and a hook_query_TAG_alter hook to cast the value to a BINARY value (and EFQ allows us to create our own operator for this). Here is an example:

function mymodule_query_case_sensitive_alter($query) {
  foreach ($conditions as $index => $condition) {
    if (is_array($condition) && $condition['operator'] == '=c') {
      $placeholder = ':db_condition_placeholder_' . $query->nextPlaceHolder();
      $conditions[$index]['field'] = 'CAST(' . $conditions[$index]['field'] . ' AS BINARY) = ' . $placeholder;
      $conditions[$index]['value'] = array($placeholder => $conditions[$index]['value']);
      $conditions[$index]['operator'] = NULL;
    }
  }
}

Then one could run:

$r = (new EntityFieldQuery())
  ->fieldCondition('field_my_field', 'value', 'ExaMple', '=c')
  ->addTag('case_sensitive')
  ->execute();

Based on this, my questions are:

It is quite cumbersome. Is there really no simpler way ?
Does such a tag already exist ?
This is limited to MySql field storage backend - how could it be adapted to work on other field storage backends ?

[*] I am assuming a MySql field storage backend here.


texts:
I have a custom form with manage file input where users can upload their profile images. Upload looks like this:

 $acc = user_load($state['user_id'], TRUE);

 // upload profile image
 if ($state['values']['image'] != '0') {

   //check if this file is already in use, if not, save new file
   $res = db_select('users', 'u')
       ->condition('uid', $state['user_id'], '=')
       ->fields('u', array('picture'))
       ->execute()
       ->fetchAssoc();

   if ($res['picture'] != $state['values']['image']) {

     $img = file_load($state['values']['image']);

     file_usage_add($img, 'user', 'user', $state['user_id']);

     $img->status = FILE_STATUS_PERMANENT;
     $acc->picture = $img;
     file_save($img);

   }

 } else {
   $acc->picture = NULL;
 }

 user_save($acc);

This approach is piling up unused files if user's change their images multiple times. It is because of file_usage_add function that is logging  files in database, therefore drupal won't delete files that are logged in file_managed database.

I think I could manually change old file status in database before new log is inserted by file_usage_add and let Drupal automatically remove this unused file. Is this statement right?

Even if it is true, I have strong feeling this is not optimal Drupal way of managing files. Is there a better way?


texts: How to aggregate field results to a chart?

texts:
I installed the Chart module and I'm using it in my Views display.

I have a field: Score

I added a chart but it shows two different charts (see image) instead of just one with all the results from that field.

How can I put them together? If it's with aggregation, can you give me some guides?

Here is how another attempt looks like:

And this is how my View currently looks like:

The tabular format of its data to be charted looks like so:

Notes:

I'm using the Chart module because I need the "radar" type which only exists in that module.
I want to create a chart with all the scores displayed in the table, and not one chart per score.
I don't want all the fields to appear as data, as in the last pictures in my question. I want the text to be the legend and the number to be the data.


texts: How to render the same field twice but with different name/id attribute?

texts:
I have overriden user-register.tpl.php and in it I would like to render same checkbox twice (so that I can submit if either of them have been checked and they are the same I just need to display them twice).

Example:

   print render($form['field_add_option']);

   print render($form['field_add_option']);

But this gives same field with same id with same name which is to be expected. Is there a way to change name and id of field before rendering?

I have tried to change the name like (before the second one)
$form['field_add_option']['und']['#name'] = 'test1';

But the label for and name of checkbox are still the same.


texts:
I have a View which is a list of stores and for each store I have a list of products. This is a sample as it looks now:

Ken's Store

Products: Doodles
Products: Daddles

Joe's Store

Products: Acme Hammer
Products: Acme Nails

Stores are a content type and products are a content type. Products has an entity reference to stores. The view is set to Unformatted list and grouping by Content title(store). I'd like the view to group products like this:

Ken's Store

Products:
Doodles
Daddles

Joe's Store

Products:
Acme Hammer
Acme Nails

Setting Content Title (products) as the second grouping field only causes a repetitive title without grouping. How do I get the products to group under the store grouping?


texts: What is wrong with this drupal 7 preprocess function to output a fields value into the body classes?

texts:
I have the following preprocess function and was wondering what I have wrong here as its not working.

This is just to grab a fields value and insert it into the body classes.

/**
 * Implements hook_preprocess_html().
 */
function cotyhouse_preprocess_html(&$vars){
  $node = menu_get_object('node');

  // Check if on an article node page
  if ($node->type == 'article') {
    // Get field values
    if (field_get_items('node', $node, 'field_title_color') == 'black') {
      $vars['classes_array'][] = drupal_html_class('tblk');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white') {
      $vars['classes_array'][] = drupal_html_class('twhi');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white_shadow') {
      $vars['classes_array'][] = drupal_html_class('tsha');
    }
  }
}


texts: drush sqlc import causing Mysql 1045 (28000) Error Acces. How to resolve it?

texts:
I'm trying to move a live Drupal 7.39 site to my local Acquia dev set up which installs Drupal 7.41.

I follow what I think is standard procedure, which is to get a clean install, copy my site's sites folder, and then upload the database and run the update script.

I'm using the drush command drush sql-drop -y && drush sqlc < dump.sql. The first part of the command runs, the database tables are dropped, but then I get a 1045 error (28000) for my database user.

What perplexes me, is that the first part of the call works, but it fails in the second part. The sql file is too large to import through phpmyadmin, and I'm really dumbfounded here.

Should I update the live site to 7.41 before migrating it? I don't want to do this because I don't want to do updates on the live site.

What is causing this issue? I think it's a conflict with the SQL settings in the settings.php file, but they match the database user and authentication but I don't know enough about the guts of drush to figure out how to fix this.


texts:
I'm trying to better understand how Drupal 8 autoloading for classes is automatically mapped to the src directory in modules.

Basically, I'd like to know how the system knows to look in the modules/module_name/srс directory when searching for classes.

I can't seem to find any details on how it's done through the composer.json files or the autoload_psr4.php files. Perhaps I'm looking in the wrong place?


texts:
I want to pass down an array to my javascript. So that i could create markers on google map.

By doing this:

drupal_add_js('https://maps.googleapis.com/maps/api/js?key=AIzaSyDcl28Qcn9GTi02rRtQaLgVS4GWZbGcQ8E', 'external');
$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');
drupal_add_js('sites/all/modules/GoogleMapByDave/DGMap.js','external');

The javascript that is DGMap.js dosnt seem to work.

Here is the js in the DGMap.js:

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

  //var locations = Drupal.settings.myModule.locations;

 function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var locations = [
                    ['Mājas',56.956344, 24.197409],
                    ['Domina',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

     }

      google.maps.event.addDomListener(window, 'load', initialize);

   }
   }
)(jQuery);

But if I add it through the module as an inline it works! But I dont know if i can use the variables there?

drupal_add_js('jQuery(document).ready(function () { function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById(\'map-canvas\'),
        mapOptions);

    var locations = Drupal.settings.myModule.locations;

    var locations = [
                    [\'Mājas\',56.956344, 24.197409],
                    [\'Domina\',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][\'locationLat\'], locations[i][\'locationLng\']);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][\'locationTitle\']
      });
    };

  }

  google.maps.event.addDomListener(window, \'load\', initialize); });','inline');

EDIT//////////////////////

I got further in this. Adding script like this:

$path = drupal_get_path('module', 'GoogleMapByDave');
drupal_add_js($path . '/DGMap.js', array('weight' => 1));

And the script:

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

var mapOptions = {
    center: { lat: 56.9714744, lng: 24.1291624},
    zoom: 9
};

var locations = Drupal.settings.GoogleMapByDave.locations;
alert(locations);

var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

var locations = [
                ['Mājas',56.956344, 24.197409],
                ['Domina',56.966058, 24.162004]
                ];

for (var i = 0; i < locations.length; i++) {

  var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

  var marker = new google.maps.Marker({
      position: loc,
      map: map,
      title: locations[i][0]
      });
  };
}
};

Now the script is runned. But the problem now is that how can i get settings? I get unidentified from "locaitons" var.

Btw i changed the $settings['GoogleMapByDave']['location'] part.


texts: Ouput Node Reference Field Title in Drupal 7

texts:
When creating templates in Drupal 6 I can output just the title for the value of a node reference field like so:

echo $node->field_example[0]['safe']['title'];

I'm trying to do the same thing in Drupal 7 - I've tried many variations like the examples below but the output is always blank or throws an error:

print $content->field_example['und']['0']['node']['title'];

print $content['field_example']['#object']['field_example']['und']['0']['node']['title'];

Any help on how to grab the 'title' value is much appreciated.


texts: I have a view set up for the user OG Membership. In my page view the Users Group roles and system roles show up, but in the services view it will not display the field or the role name.


texts: How can I programatically remove/hide a menu item when the menu is displayed?


texts:
I am not a developer although I have been using Drupal since it came out 19 years ago.

I have an existing D7 Ubercart site that works well, but I want to move to Drupal Commerce.

I have installed Drupal 8 Commerce 1 at one site, and Drupal 8 Commerce 2 (commerce 8.x-2.16) at a second site.

I know that Commerce 2 requires composer, but at the moment I have set up the Commerce 2 site with the above module (commerce 8.x-2.16) with Ludwig and it seems to function just fine.

Here is my question:

Would it be advisable to start my new site with Commerce 1 or Commerce 2?

Commerce 1 is stable, and I am thinking that perhaps I should start there and eventually migrate to a stable version of Commerce 2.

Thank you for any insights or advice.


texts: How to clear cache only for users's field?

texts:
I have some cache issues on website when I run some process. I'm looking for a way for clear cache only for user's fields from a custom module. K dn't want clear all cache for save performances.

I read the documentation, but I didn't find any example for clear only user's fields cache.

Any help me?

How can I do that with the clear_cache_all function ? (which parameters?)


texts: Load external php library in custom module

texts:
I’ve read a lot of topic on this but i can’t figure why it is not working for me.

I’ve built a custom module. It is working fine since return $output; in my controller class is working : I can see in front-end a page with my custom html.

I’ve written a script outside Drupal in order to test. Basically, i connect to a webervice and retrieve all the datas. It’s working fine.

Now, i want to execute that script inside the controller class.

I need to load an external php library to instantiate an object.

In my test php file (outside Drupal) a simple require_once is working.

require_once('nusoap.php');

But it is not working in my controller class.

So, i’ve activated the library module and do :

$path = libraries_get_path('nusoap') . DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php';

require($path);

It’s still not working.

Error message indiquactes :

  Error: Class 'Drupal\webservices_dc\nusoap_client' not found

I’m sur the file path is correct because if i do this, i can see the content of the file.

echo file_get_contents(DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php');
die();

I’ve also tried this :

in nusoap.php (where there is the class i need to include),

namespace Drupal\webservices_dc;

and in module controller class :

use Drupal\webservices_dc\nusoap_client;

But it is still not working.

Finally, i’ve copied the content of the external php library inside the module controller and it is working.

So i’m nearly sure the issue is related to the loading of that external library.

What is the correct way to load external php library (and wait it is fully loaded) in order to use it in a custom module ?


texts: With search_api_solr, how can I apply an significant field based boost when using solr 6.x?

texts:
I am using the solr backend for search_api on a drupal 8 site.

I have added the value of a taxonomy term reference field (field_promoted_search) to the index.

If an item of content has field_promoted_search with value matching the search term, I would like it to get a significant boost (eg ^1000), pushing it to the top of the search results.

Adding a high 'boost' value at admin/config/search/search-api/index/content/fields worked as expected when the server was using solr <6, but since moving to 6.1.0, this does not work as expected. This may be because search_api_solr/solarium is using a multiplicative boost rather than additive. This is not seem as useful to me as this multiplies the relevance achieved by other fields, rather than solely privileging field_promoted_search, though I am uncertain of this aspect.

I have tried adding a boost query for this promoted search field to the solarium query using hook_search_api_solr_query_alter. This requires me to pass each search key as a boosted query, and the effect seem to be affected by the order of the keys (and also my result does not end up top).

$keys = $query->getKeys();
unset($keys['#conjunction']);
// Boost results where search term matches promoted search field.
$boost_keys = [];
$boost_value = 1000;
foreach ($keys as $key) {
  $boost_keys[] = '"' . $key . '"^' . $boost_value;
}
$solarium_query->getEDisMax()->setBoostQuery('ss_promoted_search:' . implode(' OR ', $boost_keys));

When I attempt to use a boost function instead, I get an error from back from Solr and the query does not run (I have tried several functions).

// Format is: "funcA(arg1,arg2)^1.2 funcB(arg3,arg4)^2.2"
$solarium_query->getEDisMax()->setBoostFunctions("ord(ss_promoted_search,1)^1000");

Any advice much appreciated.

My reference for additive vs multiplicative boost methods is this very helpful article.


texts: Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'?

texts:
Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'. Like using:

$GLOBALS['user']->uid

instead of

$account->uid

if it were avialable?

Thanks.


texts: Does cache-tag / cache context bubbling up mean core doesn't actually individually cache separate page components?

texts:
So I read that cache contexts and cache tags bubble up to the entire page they're in. Let's say I have a custom page template with 3 sections that are populated in the page's theme preprocess hook:

[A: The Current Time]
[B: The Logged in User Name / A link to login if not logged in]
[C: Node and Taxonomy data]

A and B are very simple and C is very complex and slow. The node/taxonomy data only changes when new content is added, so it also happens to update the least often and the one we'd want to cache the most. B is different between anonymous users and logged in users, and also unique to every user. A is the same for everyone but changes every minute.

Normally, I would have A with a max-age of 60 seconds, B with a 'user' context, and C with the node:id cache tags relevant to what it needs to show (which we invalidate when new content that affects those nodes is added).

It seems to me that including A and B severely limit the ability to cache C, because if the contexts bubble up then B will force the server to keep a cached copy of the page for every different user. And if the lowest max age bubbles up (not sure if this is a thing) then A will force the entire page to be invalidated every minute.

Does that mean that this specific scenario would force Drupal to clear the cache for C every minute? Does it depend on how the page is implemented?


texts: Drupal 8 theme showing Uncaught TypeError: $(…).find(…).once is not a function in console

texts:
New to Drupal 8.

I've created a demo theme. The .libraries.yml file is below:

global-styling-and-scripts:
 version: VERSION
 css:
  base:
   assets/css/font-awesome.css: {}
   assets/css/bootstrap.css: {}
   assets/css/slick.css: {}
   assets/css/bootstrap-datepicker.css: {}
   assets/css/jquery.fancybox.css: {}
   assets/css/theme-color/default-theme.css: {}
   assets/css/style.css: {}
  theme:
   '//fonts.googleapis.com/css?family=Tangerine': { type: external, minified: true }
   '//fonts.googleapis.com/css?family=Open+Sans': { type: external, minified: true }
   '//fonts.googleapis.com/css?family=Prata': { type: external, minified: true }
 js:
  assets/js/jquery.min.js: {}
  assets/js/bootstrap.js: {}
  assets/js/slick.js: {}
  assets/js/waypoints.js: {}
  assets/js/jquery.counterup.js: {}
  assets/js/bootstrap-datepicker.js: {}
  assets/js/jquery.mixitup.js: {}
  assets/js/jquery.fancybox.pack.js: {}
  assets/js/custom.js: {}
  dependencies:
   - core/drupalSettings
   - core/jquery
   - core/jquery.once

If I deleted all the .js from this file, I see no errors in the console however, the images, and slideshows etc are not properly rendering.


texts: When exiting views modal I am returned json

texts:
When I am in views UI and I edit an option a modal box appears. I edit some seetings then press save and am displayed with something like:

  [{"command":"settings","settings":{"basePath":"/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme_token":"SUIsCUisas2D3yeSiBkGNwaXtTMtlVVXouHWgoffCYA"}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons"},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-block","data":"\u003Cdiv
  id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv
  id=\u0022edit-display-settings-top\u0022
  class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket
  clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button
  ctools-dropbutton\u0022\u003E\u003Cdiv
  class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022
  class=\u0022ctools-twisty
  ctools-text\u0022\u003Eopen\u003C/a\u003E\u003C/div\u003E\u003Cdiv
  class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022horizontal
  right actions\u0022\u003E\u003Cli class=\u0022duplicate ...

What could be going wrong?


texts:
I'm attempting to replace the titles on my pages with images.
I've added an image field to my content type and have created a view that displays the image for the selected page with a contextual filter.

I am embedding the view in my page.tpl.php page with views_embed_view().

I'm having a problem with the conditional statement. If no image exists for the selected page, I want to show the regular page title. Currently, my code will print an empty
 tag on pages with no mages. Can I get some help with this?

I am using Drupal 7 and the Views module version 7.3.3.

<?php $TitleImage = views_embed_view('title_image', 'block'); //Embed View ?>

<?php if (!empty($TitleImage)): //Check to see of View is empty ?>

<?php print $TitleImage; ?>

<?php else: //Display regular title ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>

<?php print $title; ?>

    <?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

I need to replace the page title in the page.tpl.php file. There are 3 content types that have the field_title_image field. I thought that creating a view with a contextual filter would be the best approach, to not display on content types that do not have the field_title_image field.

I came across this comment that helped me with displaying the image.

Below is my revised code. Is there a better solution?

<?php if (isset($node->field_title_image['und']['0']['filename'])): ?>

<img src="/sites/default/files/images/<?php print $node->field_title_image['und']['0']['filename']; ?>" alt="<?php print $node->field_title_image['und']['0']['alt']; ?>">

<?php else: ?>
<?php print render($title_prefix); ?>
<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>
<?php endif; ?>


texts: How can I set a default value for the country in an addressfield?

texts: I'm trying to set the default value for a country in an addressfield (caught in hook_form_alter) and ensure that the associated fields (administrative area, etc.) are refreshed properly. How can I do this?


texts: How to use drupal_set_html_head in a page created though my module

texts:
I have my module like this

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

    $items['mymodule'] = array(
        'title' => 'mymodule',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('access content')
    );

    return $items;
}

function mymodule_form($form, &$form_state) {
    $form['text'] = array(
      '#markup' => 'mymodule content'
    );
    return $form;
}

Which will create a page mysite.com/mymodule.
I now want to add a meta tag to this page using drupal_set_html_head.

Anyone know where to place the drupal_set_html_head function call?


texts:
I grant my users userpoints with pending status, for some actions on my site.

I want to automatically approve the points after 2 weeks. Is there a function to change the status of the points?

Also I want to cancel the points if the users submit a form.


texts: How do I add a confirmation form after the user clicks on "Save" in an edit form?

texts:
On a site I'm building, a user can edit certain fields on a node that cause a chain reaction to happen (which I've implemented using hook_nodeapi() and its "update" operation).
Since this chain reaction potentially affects a lot of other content, I'd like to inform the user of exactly what other content will be changed, which depends on the changed field values, unknow until the user submits the node.  After the user has read the list of affected content, I'd like to give them the option to click on Yes, which will save the node and start the chain reaction, or click No, which will take them back to the node edit form (with edits intact).
How can I make a confirmation form appear after the user clicks on Save?


texts: add a shopping cart button to a list of nodes

texts:
I am creating a module that display a custom add to cart button for each item i fetch from DB. ( I don't want to use ubercart but rather a custom simple cart).

So my code looks like this:
mycustom_page() {

$sql = "SELECT nid from {nodes} n WHERE n.type = :type AND n.status = :status";
$result = db_query($sql, array(
'type' => 'products',
'status' => 1,
));
foreach($result as $row) {
$node = node_load($row->nid);
$page[query'][] = node_view($node, 'teaser');

return $page;

}

this will return a list of nodes of type products. All I need now is to add a form with a add to cart button and a callback with add to cart feature.

How do I add a form to each node? Also I need if is possible to display and handle the node fields  separately inside the foreach.

Many thanks


texts:
I'm utilizing the Field Collection module to allow me to associate objects of one content type (say, Authors) with another content type (say, Books).

When viewing the Edit page for one of my specific Book objects, whenever I try to use the "Add another item" or "Remove" buttons within the Authors section -- which operate via Ajax -- I'm getting an Ajax "403 Forbidden" error on the following URL:

field_collection/ajax

One key piece of information is that this happens with only one specific object; the functionality of those buttons works perfectly fine on the edit pages of other Books.

When I visit the Recent Log Messages page -- admin/reports/dblog -- it displays the following error message:

Notice: Undefined index: form_build_id in ajax_get_form() (line 320 of .../includes/ajax.inc).

I checked though, and the form_build_id does, in fact, appear to be included with the POST data being submitted to field_collection/ajax.

Is it possible that that form_build_id is somehow invalid?

I'm sort of at a loss here. Any thoughts?

UPDATE:

I set up watchdog to log the POST data, and it seems like there's absolutely no data available in $_POST once it hits the field_collection_remove_js function within the Field Collection module code...

Is there a chance I'm hitting some sort of POST length/size limit? The node in reference does, in fact, have a whole bunch of data associated with it.


texts: I need to add on condition to profile form submit handler profile2_form_submit_handler

texts:
I need to add on condition to profile form submit handler. I have wrote the condition to profile2_form_submit_handler function which is found under sites/all/modules/profile2/profile2.module location.
I have applied the condition in core file but now wanted to move this set of core to template.php file but it is not reflating.
Anyone please suggest me to make it from hook or something other.
My code is:

function THEMENAME_form_submit_handler(&$form, &$form_state) {
  profile2_form_submit_build_profile($form, $form_state);
  // This is needed as some submit callbacks like user_register_submit() rely on
  // clean form values.
  profile2_form_submit_cleanup($form, $form_state);

  foreach ($form_state['profiles'] as $type => $profile) {
    // During registration set the uid field of the newly created user.
    if (empty($profile->uid) && isset($form_state['user']->uid)) {
      $profile->uid = $form_state['user']->uid;
    }

    // check default image status
    // if there is not any then make first image as default
    $default = false;
    $images = $profile->field_user_image['und'];

    foreach($images as $image) {
        if(($image['field_profile_default']['und'][0]['value'] == 1)
         &&($image['entity']->field_profile_default['und'][0]['value'] == 1)) {
            $default = true;
            break;
        }
    }

    profile2_save($profile);
  }
}


texts: Uncaught TypeError: Cannot read property 'fn' of undefined

texts:
This occur after I added a Photobooth plugin in my hook_init function:

function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/photobooth_min.js");
    drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/website/js/script.js");
}

This needs JQuery(1.11.2) to work, but Im assuming that Jquery has already a default Jquery. So why does it doesn't work?

I had installed JQuery Update Module and finds out in the Configuration Settings was only limited upto Jquery 1.10, which is not sufficient for my Jquery Plugin. How will I update the Drupal's default JQuery library to 1.11.2?


texts:
I can't get the views slideshow to center in the div. I tried the following code but with issue:

#views_slideshow_cycle_main_content_slideshow-block {
  width: 100%;
  text-align: center;
}
#views_slideshow_cycle_teaser_section_content_slideshow-block {
  display: inline-block;
}

The image display in few seconds but disappear afterwards.

Can anybody please help me how to solve this problem?


texts:
I am writing a custom module for stripe payments and I need to declare constants for CLIENT_ID and CLIENTSECRETKEY.

is it good to declare them in hook_init because then they will available every where ?

module contains other functions like make_payment and add customer etc.


texts: Disabling Browse to Library in Media Upload Field

texts:
I'm on d7.2 with the included Media Module. I'm also using WYSIWYG if that matters at all.

I'm seeing that when a user clicks the image upload field, they have a choice of either 'web' or 'library'.  The Library option shows all files that other users have uploaded to be included in other nodes. How do I disable that so that they don't see all the other files?

I don't use galleries- just upload/attach images to nodes that the users themselves create. Guests and Registered Users BOTH can see the nodes and image files- but I don't want them to have access to all the images that have been uploaded previously.

I think this has something to do with Private/Public, but I can't figure it out. Any input?


texts: How change 1 line of code in a core module without hack?

texts:
Every time I update Drupal core I get the error message,

  Notice: Undefined variable: forum_term (line 764)

I've implemented this hack on forum.module to get rid of this problem.

How can I implement this change without hacking the core forum.module file?


texts:
I have a problem that I am not sure how to address. I am using commerce guys and Drupal 7. I have some products around 200. But each one will have updates or news of what it is going on with them. How could I accomplish this so each product will display its news. For instance

Product Name
Description
Origin

PRODUCT NEWS

Month 1
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 2
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 3
lorem Ipsum is simply dummy text of the printing and typesetting industry.

view all product news

The first part is easily done with view mode but I have no clue what it is the best way to integrate news to a product display. I have searching in commerce guys and display suite but still don't have an idea. Do you have any advice, experience or module or how could I accomplish this?


texts: Multiple contextual filters using or statements

texts:
I have a taxonomy which defines the sections of a site. One of the terms is "Global". What I am doing is creating pages with the site section term and also creating promo boxes which use the same taxonomy. By default the "Global" term is selected wherever the term relation is used.

I would like to have a block view using contextual filters. I have set it up to use one filter which is the term id from the url. This works great but when I have a page that has a specific section but does not have any related promo boxes I would like to load the "Global" set of promo boxes.

Is there a way to create multiple contextual filters using or statements? The default sets them up as and statements which will not allow me to load the "Global" plus the related to the page. I am sorting the view by taxonomy weight and have "Global" at the bottom so if I can get an or contextual filter I'll be in business.

Does anyone know of a module to do this or will I have to hook the view using hook_views_query_alter


texts: How to add "rel=nofollow" to ALL external links?

texts:
How to add "rel=nofollow" attribute to ALL external links....in Drupal 7?

So far I can find only with different filters and what not....

Before I was working with Joomla - I had a single plugin which was once set up - and wrapped ALL, completely all external links, wherever they would be - in Menus, articles, modules, social buttons, advertisements, etc....

I just cannot understand why would I need some Filter - the only Filtering option should be - it is an External link...

If I would know all external URL some scripts or users may add to my site - it would be great. But my experience shows - external URLs are almost always added secretly without me being aware of it; but it still should have "rel=nofollow"..


texts:
Using Views in Drupal 7 I can consume the output of a restful API. I want to take some of the data and dynamically create pages. For example I get the following return json:

$data = {'title':'This is a page title','alias':'pages/page-alias-name','content':'This is some content'}

I would want to dynamically create a page located at http://www.example.com/pages/page-alias-name which would have a title of $data['title'] and the content would be $data['content']. Is it possible to create pages dynamically like this. How can I go about doing this?

Additionally, if I had identical content stored in an external database that can be read by a custom Views module, can I do this and how would I go about it?


texts:
I am really new to drupal and struggle to find good tutorials
for the issues I have. One of those issues is as follows:

How do I obtain values from foreign nodes.
Specifically nodes that were created in a feature bundle.

As a concrete example I would like to load all Jobs from the Recruiter
distribution and then extract the field information from them.

After reading through the Book Pro Drupal 7 Development and
many online resource I still struggle to grasp how I am supposed
to do this other than to do direct Database Queries.


texts: Define a normalizer just for a specific use case

texts: I try to create a custom API with custom endpoints where API users can receive entity data from our page. We want to have flat arrays for most of the fields and some additional custom data added so I tried to implement some custom normalizer classes. I found out that supportsNormalization() is the place where the decision is made if my normalizer is used, but I have no context. I just have the object which needs normalization and the format on which I can say Yes, please use my normalizer. As I don't want to force all my entities everywhere in the project be normalized with flat array this is too restrictive for us. I want to use my normalizer only when the entities should be normalized for delivering it in a specific API. Is there a way to achieve this?


texts: How to add missing data selector in "Create new entity" rules action?

texts:
I have created an activity log using the Message module. It is about Statuses module (for which I'm using the DEV version). When someone comments on a status update, the activity is logged, but it should be logged for the status update owner and not the current user.

Currently, when I create the rules action "Create new entity" in the rules setup, the only replacement pattern available in the data selector for "User for which to log" is 'site:current-user'. Here I want 'status:status-sender' and not 'site:current-user'. The owner of the status update must receive the notification and not the user who commented.

Message export

{
  "name" : "status_comments",
  "description" : "Status comments",
  "argument_keys" : [ "@status_comments_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@status_comments_user commented on your status",
        "format" : "plain_text",
        "safe_value" : "@status_comments_user commented on your status"
      }
    ]
  },
  "rdf_mapping" : []
}

Rules export

{ "rules_posted_statuses_comment" : {
    "LABEL" : "Posted a statuses comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "statuses" ],
    "REQUIRES" : [ "fbss_comments_rules", "rules" ],
    "ON" : { "fbss_comments_save" : [] },
    "IF" : [ { "NOT fbss_comments_rules_on_own" : { "comment" : [ "comment" ] } } ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "status_comments",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:status-comments-user" ],
          "value" : "[comment:commenter]"
        }
      }
    ]
  }
}

Note: This is strange because I have another message type with the event "user saves a status" and in its rules action, it shows all replacement patterns for statuses in data selectors


texts:
How do you install Drush on WSL (Windows Subsystem for Linux) when the following command from Drush docs, doesn't work?

php -r "readfile('http://files.drush.org/drush.phar');" > drush


texts: How do I create a workflow that creates multiple nodes?

texts:
I'm recreating my pages in Drupal 8 for a platform upgrade. One thing I've identified for this upgrade is the need for a workflow that creates multiple nodes before it's actually finished. If a user creates node of type A, it automatically creates a second node of Type be and auto-fills an entity reference field with whatever nid Node A was given. I'm HOPING this is something I Can create easily, through a form builder or something like that.

I'm not sure what the best option is for this, but I do need to find a way to simplify this workflow. I think I'll need rules a part of it, but I'm not sure at all one way or the other.


texts:
Currently I'm learning drupal database command as I'm pretty new to Drupal, I'm more familiar with mysqli api. I want to check the role of user before they are logged in to the system, the role table maps rid with a role (for example 1 - admin, 2 - author, etc.), the users table and users_roles table are linked by uid, which is unique. The role i want to verify before user login to the system has rid (role id) = 2. This is what I have so far, but it doesn't really work:

function is_author($name) {
$query = db_select('users_roles');
$query->join('users', 'users_roles.uid = users.uid'); // JOIN users_roles with users
$query->fields('users_roles', array('rid')) // SELLECT the field rid from users_roles
    ->fields('users', array('name')) // SELLECT the field name from users
    ->condition('users.name', ':name');

$result = $query->execute();

while ($record = $result->fetchAssoc()) {
    if ($record == 2) {
        break;
    }else{
        return false;
    }
}
return true;

}

This is the users and users_roles table:

table users:

uid | name | pass | .....

1 | Michael | (encrypted password)

2 | Ted | (encrypted password)

3 | Mark | (encrypted password)

Table users_roles:

uid | rid

1 | 2

2 | 3

Please help!! Thanks in advanced!


texts: How can I detect if node is the last one from within node.tpl.php?

texts:
There are a number of variables for the node.tpl.php template, like $id that contains the current nodes index number, but how can I figure out if the current node is the last index or how many nodes there are in the current listing?

(I'm using Drupal 7)


texts:
I have read in a lot of sources that I should use the geofield_compute_values() when trying to programmatically save coordinates in Drupal, but it does not work for me. That function doesn't exist in Drupal 8.5.2.

I've installed the Geofield module using Composer and I can use it as usual in the admin area. There are no problems with saving.

This is the code I tried, which returns an error about a not existing function (geofield_compute_values()).

$geofield_data = geofield_compute_values(['lat' => $lat, 'lon' => $lon    ], GEOFIELD_INPUT_LAT_LON);
$cbisProduct->set('field_koordinater', $geofield_data);

I have also tried this out with no successful result and no errors.

$geofield = [
  'geom' => "POINT (" . $lon . " " . $lat . ")",
  'geo_type' => 'point',
  'lat' => $lat,
  'lon' => $lon,
  'left' => $lon,
  'top' => $lat,
  'right' => $lon,
  'bottom' => $lat,
];
$cbisProduct->set('field_koordinater', $geofield);

I also tried the solution given in How to save LNG and LAT progamatically in a geofield, but it didn't work either.

How can I programmatically save coordinates?


texts: How do I render an image with display options?

texts:
I would like to render an image, with responsive styles at the top of a view.

The approach I have been using is to try to access to the full array that you get when calling render($content['field_banner']) from the view template.

I am using:

The views-view-bvt-tables--class-timetable--page.tpl.php template
The Picture module to map images styes to screen sizes
The Profile2 module

I have found the image using this code.

$profile_row = $result[0];
render($profile_row->field_field_studio_banner);

It gives a different result, compared to the following code, used in profile2.tpl.php.

print render($content['field_studio_banner']);

I can't see display properties, such as #formatter = picture in the view array.

How do I set any display property?


texts:
At the content type i add some field:

if you want to include or embed block into the body of your node
https://www.drupal.org/project/insert_block

if you want to include or embed view into the body of your node
https://www.drupal.org/project/insert_view

How about webform?


texts: Use Javascript to Incrementally Add a Numer to a Selected Class

texts:
I am dynamically generating content using Drupal. I am running javascript that places a div before another div. The code works fine, and looks like this:

  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one');

   });

My issue is that because the content is generated dynamically, the class "views-row-#" changes incrementally. For example, if I have 3 elements of content on the page, Drupal will create the class views-row-1 for the first one, views-row-2 for the second, views-row-3 for the third.

What I have done (which is not ideal) is written out a line of code for each piece of content like so:

  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-2 .content .body').insertBefore('.views-row-2 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-3 .content .body').insertBefore('.views-row-3 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-4 .content .body').insertBefore('.views-row-4 .content .field-name-field-image-one')
   });

I will never know how many pieces of content there will be because it's dynamic, so I'm looking to have the javascript add the number to the class. Is this even possible?


texts: How to get only published revisions of a node?

texts:
I have several types of content that are moderated(content_moderation and workflows), in a custom validation process I need to know if a particular node has at least one published revision. Is there a way to obey only the revisions of a node that are only published?

I found this example on a node core module controller:

protected function getRevisionIds(NodeInterface $node, NodeStorageInterface $node_storage) {
    $result = $node_storage->getQuery()
      ->allRevisions()
      ->condition($node->getEntityType()->getKey('id'), $node->id())
      ->sort($node->getEntityType()->getKey('revision'), 'DESC')
      ->pager(50)
      ->execute();
    return array_keys($result);
  }

But this returns all the revisions and I am trying to avoid loading each of the revisions to search for the published ones and if I can bring the id of only the published ones it would be the best in my case.


texts:
i've wrote custom module for my site, but it doesn't work.
It should transform shortcode from my text field:

  Example text [gap=word,5] example.

to the input.

Here's the code:

<?php
function game_gaps(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'view':
    $subject = $node->field_gaps[$node->language][0]['value'];
    preg_match_all("^\[gap=(.*?)\]^", $subject, $fields, PREG_PATTERN_ORDER);
    $text = $node->field_gaps[$node->language][0]['value'];
    $text2 = str_replace("
", "", $text);
    $array = explode("
", $text2);
    $rows = count($array);
    $j = 1;
    $node->field_gaps[$node->language][0]['value'] = "";
    foreach ($array as $array2) {
      $gap = $array2;
      foreach($fields[1] as $value) {
        $fieldsVars = explode(",",$value);
        if (preg_match("^\[gap='.$value.'\]^", $array2, $matches, PREG_OFFSET_CAPTURE) == 1) {
          $gap = str_replace("[gap=" . $value . "]", "<input type=\"text\" size=\"" . $fieldsVars[1] . "\" value=\"\" data-for=\"" . $fieldsVars[0] . "\" />", $gap);
        }
      }
      if ($j < $rows) {
        $node->field_gaps[0]['value'] .= '
' . $j . '.&nbsp;' . $gap . '
';
        $node->field_gaps[0]['value'];
      }
      $j++;
    }
  }
}

Any ideas friends?


texts:
like what you can see in this site, I want to have 3 tabs for comments.

oldest first

newest first

sort by likes

I've tested creating views and show in tabs but this way in too heavy!

is there a better way?


texts: Small problem with Facebook Autopost module / Facebook App

texts:
I have installed the Facebook Autopost module after setting up my Facebook App. When I add a new content, my rule should post it to facebook, however I get the following message:

Facebook SDK threw an error: OAuthException (#200) The user hasn't authorized the application to perform this action

Do you know what I have or haven't done correctly and how I could resolve this? I think it's something to do with permissions or something in my Facebook App?

Thanks


texts:
I need to insert an html code into a content block.
As the html code has some javascript links and css, I've done a module to include all the references in the .info file.
The problem is that I don't know how to insert the html code in the .module file.

This is the html code:

    <link rel="icon" type="image/png" href="favicon.ico">
    <title>Aldizkari Elektronikoa</title>

  <meta charset="UTF-8" />

  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no">
  <meta http-equiv="cleartype" content="on">
  <meta name="description" content="Aldizkari Elektronikoa"/>
  <meta name="keywords" content="" />
  <meta name="author" content="" />

  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/stylesheets/style.css">
  <link rel="stylesheet" href="assets/stylesheets/secciones.css">
  <link rel="stylesheet" href="assets/stylesheets/mediaQuery.css">

As you can see most of the code are references to javascripts and css. But what I need is to include the  to the module, because this is the part that shows what I need form my page.

Do you know if the is any hook for this? Or can I do in an other way to add this html structure to the content block?

I hope you can help me,

Thanks


texts: How to apply Panels layouts for CiviCRM pages

texts:
For CiviCRM pages Events and Contributions that has paths of e.g.

www.site.com/civicrm/contribute/transact?reset=1&id=1
www.site.com/civicrm/event/register?id=23&reset=1

And so on.

Problem is that you need to copy paste custom .php files and folders in themes dir for each form to apply custom styling, e.g. have right side and left side columns and display custom content. E.g. left side column texts and infos, descriptions and right side column contains the registration form/payments.

I can't figure out how to do that without copying multiple folders for each form and editing it each time to match the page ID.

I'm looking at the Panels and it doesn't have CiviCRM content as nodes content type to be applied and filtered out in the panels variant and etc.

Or not possible?


texts: Sorting by linked node/entity reference fields

texts:
Suppose I am printing name tags for thousands of content nodes in one content type called "Attendee." Each of these nodes specifies a single "Attendee" for an event, (and their respective name tag). Suppose these attendees also needed name tags printed out for their “friends” who are attending with them. That is not a problem: These friends need their own node with the same fields to get their own name tag, so I keep them in the same content type and distinguish that they are a friend of an attendee with a simple checkbox.

When rendering the view, I need these friends of attendees to appear right after the attendee they are going with. So to link them, I used a node reference or a entity reference field. How do I get the Views module to sort the friends of attendees right after the attendee they are going with?

P.S. I am technically using the Views PDF module, but it has the basic views functions, so if it's possible with Views, it will probably be possible with this module.


texts:
EDITED
The excellent Privatemsg module provides a wealth of functionality but some sites might not need/want this degree of complexity. Rather than starting with something complex and disabling/removing features, I would like to think about ways to build something relatively simple from basics.
Using the basic infrastructure of D7 what are the ways one could create a simple messaging system that allows user A to message user B, and both of these corresponding users to delete this message individually (i.e. user A deletes message 1, but user B does not; therefore user B can still see message 1)?
How might message threads (i.e. successive related messages) be managed and displayed?
How well would the solution scale (e.g. 1,000,000 messages, 100,000 threads, etc.).
Thank you.


texts:
I want to add an add more button to an element in Drupal form (using Drupal Form API). Should I make it with javascript (append a new element) and check for $_POST in submission or is there another solution in Drupal API.

This is my code for that field, I want users to be able to upload more than one image:

$form['product'] = array(
  '#title' => t('product'),
  '#type' => 'managed_file',
  '#required' => TRUE,
  '#default_value' => variable_get('product', ''),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(0.6*1024*1024),
  ),
);


texts: How to resolve my 404 error when using hook menu?

texts:
I've a custom module named workingmodule. I get a 404 when  visiting domain.com/workingmodule.

My module is enabled, and I cleared the cache. This id the code I am using in workingmodule.module.

/**
* Implements hook_menu().
*/
function workingmodule_menu() {
  $items = array();
  $items['workingmodule'] = array(
    'page callback' => 'workingmodule_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
* Display the tagboard/custom content for page.
*/
function workingmodule_blank_page_callback() {
  print_r("test");
}

Why does domain.com/workingmodule return a 404 error?


texts: Some fields are not sorting properly in view

texts:
I'm trying to create a directory list in view. But some of the fields are not properly sorting.

See the below image for my view configuration.

And the output of the view.

Update:  Style setting

Update:  Field Settings

Grouping

Please anyone help me to get the correct output.


texts: Is there a way to display the current date on views? I just realized that I couldn't use global tokens nor could I get custom date created on Display Suite on views.


texts: Rules - New events inside code not shown in interface

texts:
I am trying to insert a new event inside an already existing module. The module is Nodeaccess https://www.drupal.org/project/nodeaccess it's used to grant users edit/delete permissions to single nodes.

inside sites/all/modules/nodeaccess i have made the file nodeaccess.rules.inc which contains this code:

/**
 * @file
 * Rules integration.
 */

/**
 * Implementation of hook_rules_event_info().
 */
function nodeaccess_rules_event_info() {
    return array(
        'nodeaccess_grant_permissions' => array(
            'label' => t('Permissions are granted to a user'),
            'group'=>t("NodeAccess"),
            'variables' => array(
                'granter' => array('type' => 'user', 'label' => t('The user who granted the permissions.')),
                'granted' => array('type' => 'user', 'label' => t('The user who got the new permissions.')),
                'node' => array('type' => 'node', 'label' => t('The node on which the permission has been granted.')),
            ),
        ),
    );
}

Looking at different guides on the web it looks like this is all you have to do to get a new event but in the events list i can't find it.
I have tried:

refreshing the cache
disabling/enabling nodeaccess module then refreshing the cache (and rebuilding permissions as it was requested)
disabling/enabling rules module then refreshing the cache
adding the rule entry in a *.rules.inc file i've seen it's being imported (namely the feeds.rules.inc file from the feeds module which already existed when i installed the rules module)

Nothing worked so far

EDIT: i have changed the function name and the entry name (both from "node_access" to "nodeaccess" ) but it's still not showing. I have discovered that if i add an entry on a file i know it's being imported and keep the prefix of the entry, then it shows up


texts:
I'm trying to add external JavaScript to my Drupal 8 theme. Can someone tell me what I'm doing wrong here? This function is in my MYTHEME.theme file:

      function MYTHEME_preprocess_page(&$variables) {
      $vars['ext_js'] = array(
        '#attached' => array(
          'data' => 'http://cdn.somelibrary.com/library/2.3.1/js/jslibrary.min.js',
          'options' => array(
            'preprocess' => TRUE,
            'every_page' => TRUE,
            'group' => 'NONE',
            ),
        ),
      );
}

Then in the theme I'm rendering it with:

{{ ext_js }}


texts:
Is there a path with which I can call the "Access denied" page?

I'm trying to implement a rule that redirects to such a page because I want to prevent users and search robots from visiting certain nodes.

This is for Drupal 6.


texts: How to export translated variables settings in code?

texts:
In a custom module I define several configuration variables by implementing the Variable module's API. The module is part of a multilingual site project, so some of these variables should be translatable.

In my hook_variable_info() implementation, these variables are defined as with 'localize' => TRUE so they are available in the Multilingual settings > Variables interface provided by the Variable translation module (part of Internationalization). But their default state is not to be translated. So, in order to have the variable translated, the site administrator needs to visit the page and select my module's variables.

I need my custom variables to be automatically translated when the module is installed.

The module already uses Features to export other configuration, so a solution based on Features would be nice. But it can be purely code based.


texts: Mix taxonomy and node title in ordering in a View

texts:
I have a View which lists books (nodes). They are sorted by alphabetical order (Title). Good. They are linked to taxonomies (categories). I could sort by taxonomy to group books of the similar theme together, and a second sort by title. Good.

Now the problem. My client want to list both taxonomies (categories) names and title books together, so we have the following beautiful omellete of data (imagine that the lists which are book titles beggining with prefix "-" are hidden after you click on the taxonomy they belong):

 Antologies (category)
  - Interesting antology (book) *hidden until you click Antologies*
  - More interesting antology (book) *hidden til you click Antologies*

 Book about everything the meaning of life (book) *visible*

 Cooking books (category)
   - A guide on cooking data (book) *hidden til you click Cooking books*
   - How to cook an alien (book) *hidden til you click Cooking books*
 Course of the pyramid (book) *visible*
 Decameron (book) *visible*

Nonetheless to say, I am completely at lost here. I have considered to use an extra field data to the content (node = book) to set an alias, which is the category. Then order by alias and to achieve  the " - " indentation, use some hook code to identify the taxonomy.


texts: How to include book traversal links on a custom twig template page

texts:
I use the Book module to create books with chapters.
When I use the default twig template node.html.twig to display a book chapter, a section titled "Book traversal links" is included, with links to the previous chapter, the next chapter, and to the book. The debugger says these links come from the book-navigation.html.twig template.
Instead of the default template, I'm using a custom twig template node--chapter.html.twig to display chapters.

QUESTION:

How can I get the same book traversal links onto my custom page?

NOTES:

I checked for a block containing the book traversal links that I could just insert in my twig template, but I don't see one.
I have checked the $variables array in the twig template to see if maybe a list of the chapter's siblings is already there, but don't see one.
I'm already using HOOK_preprocess_node(&$variables) to find the book parent book's id, so I can use it to find the chapter's siblings, if that's the way to go.


texts: Drupal 7 Custom Page shown only for logged-in users

texts:
My problem is that, I need to create a new Page (path f.e. //panel), but I want there only logged-in users. If user is not logged in, he should be redirected to login form. I was trying to do it with Custom Pages, but I dont know how to do it, I can create variant only with HTTP response code, and its working good, but I dont know how to show content of this page, it's simply redirected me if I'm not logged in or displaying, that page is not found if I'm logged in.
Do you know a solution for my problem?


texts: I know db_select and Drupal's Database Abstraction Layer work across database implementations as long as there is a driver (mysql, postgresql and sqlite drivers included in core). But what about db_query? Should I patch contributed modules to make sure they work with sqlite?


texts: Create a View Block that shows a taxonomy vocabulary applied to the current node

texts:
I have a news section of a Drupal 8 website that contains an ever-growing list of nodes. To avoid a messy menu in the long term, they do not have a menu position assigned but instead are shown via Views, which render News nodes tagged with certain taxonomy terms.
Because they aren't part of the main navigation, the regular Menu Block doesn't work here. Instead, I'm trying to replicate this part of the nav using the taxonomy term structure and exposing that in a View block. The terms IA matches the page IA, down to the News node level.
How can I expose the taxonomy term used on the Node, plus it's siblings and parent:
- newsroom
  - media release
    - 2019
    - 2020
    - 2021
  - records
  - blog entries

So a News node tagged with records should show this in the View block:
- newsroom
  - media release
  - records
  - blog entries

And a News node tagged with 2020 would show:
- media release
  - 2019
  - 2020
  - 2021

There are plenty of questions about exposing related Nodes to a certain term, but not related Terms on a Node...any help?


texts: Does Strongarm need to be enabled on Production site using Features?

texts:
I'm using Features in order to make my site content configuration exportable for purposes of staging my server. I'll be using Strongarm to make some of the site variables exposed for management in a feature.

Does the Strongarm module need to be enabled on my live production site in order for the active features to be able to present and set the variables which I have encapsulated within them?

Or, does Strongarm only need to be enabled on my dev server where and when I am creating my features components?


texts:
Through the code, I will wish my redirect the user to an absolute url.

I tested with drupal_goto () but it only works with relative urls. I wish to go to another domain that current_domain

thank you


texts: OG Subgroups - call function _og_subgroups_get_inherited_users

texts:
I am trying to create a custom rule for OG Subgroups to email the members of a subgroup when content is added to it.

In og_subgroups.common.inc I can see the function I wish to use to return the inherited users of a subgroup

function _og_subgroups_get_inherited_users($group_type, $group_id, $states = array(OG_STATE_ACTIVE))

In my custom rule action I'm not sure what I should be passing to the function as $group_type and $group_id parameters. I have tried things like "node" and the NID of the group:

$array = _og_subgroups_get_inherited_users("node", 27);

Once I get it working with a hardcoded node e.g. node 27 I will then try to pass the details of the parent groupd that content has been added to.

I'm using OG Subgroups 7.x-2.0-beta1. For the full background into why I'm creating this custom rule action you can see my original drupal answers question


texts: Allow authenticated users to create taxonomy terms

texts:
Currently I categorize content using nodes as categories, because authenticated users cannot create taxonomy terms.

What would be the way(s) to accomplish a term/add page for authenticated users?


texts: how to do mapping user to user in drupal

texts:
I created 4 user in my site.

1)contributor1
2)contributor2
3)validator1
4)validator2

Contributor can able to create a node  and validator can able to review the node

I am using workbench module for content moderation.

My question is?

When contributor1 create a node, then he send the node to validator1 for review
and  contributor2 create a node , then he send the node to validator2 for review

So please let me know, how can I do the user wise mapping

contributor1 create node1 through content type 1  , then only node1 access only validator1 user and he can publish the content   same as
contributor2 create node2 through content type 2 , then only node2 access only validator2 user and he can publish the content..

you have any idea please let me know


texts: How to enable tag moderation using rules?

texts:
I would like to create a rule where if a user adds a tag(taxonomy) which is not allowed (e.g. 'Sexy') the content which contains that tag is sent to be moderated to the site admin for approval before being published.
I am currently stuck on the data selector part as I do not know what to put there!


texts: Dynamically changing the href on a link with data-dialog-type = modal does not work

texts:
For reference I am working on this issue for the Focal Point module...

I have a link whose href is updated dynamically using js based on a particular user interaction (moving the focal point on an image). The link may start as /admin/focal_point/preview/10/21x68 but after a user moves the focal point to another part of the image it is changed to /admin/focal_point/preview/10/75x28. In attempting to open this preview page open in a modal (as opposed to a new window) I'm finding that clicking the link loads the preview as though the link had not been changed. Any idea how to tell the ajax logic that loads modals to acknowledge the changed href?


texts:
I want to add a description field to my menu and and use it in front.

I managed to have a text_format field for my description (in /admin/structure/menu/manage/main) but when I click on save, that field is empty.

function HOOK_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#format' => 'full_html',
  );
}


texts:
I am trying to load a PDF from a link using colorbox but although the colorbox window opens the pdf is just text characters. This is what the link looks like:

This is what my link looks like:

View

and when it's rendered out it looks like this:

View

which looks right to me but the pdf is just text characters. The pdf loads fine just as a link opened in your browser.


texts: How to make one view with different taxonomy terms in different rows?

texts:
I want to make a view with 3 rows of lets say fruits, with 6 fruits max for each row. Spring, Summer and Autumn fruits.

And I don't want them to be mixed in one array so I could style them in view-template. How can I do it correctly?


texts:
How do you allow a content type to publish an option that changes views options of that page?

I have created 2 views slideshows block with different settings - I want the user to choose how to view the images on any page of a certain content type BUT DONT WANT TO SAVE THE PAGES TWICE - the images must be shown programmatically depending on which view option is chosen.

I saw this tutorial on rendering views via a tpl.php file...

I do not know how to create and where to place this tpl.php file -- Could this be implemented as a module instead?
What do you place in the $args function - are there any useful examples?


texts: Simplenews Scheduler Sending Newsletter Twice a Week

texts:
I'm having trouble configuring how to send a simplenews newsletter to subscribed users twice a week.  I'm using Simplenews scheduler but just don't know how to configure it.  I want to send a newsletter of all my updated content to my users on Sunday and Thursday.

I've got everything else working, just don't know how to configure it to send on Sunday and Thursday.  In Simplenews Scheduler, we can schedule it to start sending on a specific day like Sunday and set the Sending interval to 'Day', then, set Interval Frequency to 4.  But I am certain that after the first two times, the days will shift and the third time it will send on Monday and fourth time on Friday and just keep shifting a day each time.

So, hope you guys have some ideas on how to configure it correctly.


texts: render field collection with already defined custom formatter

texts:
I defined a formatter for a field with hook_field_formatter_info()/view().  This field is a field collection and renders fine when I choose my custom formatter through the ui.

I can get my (already defined) field collection with:

$field_collection = entity_load('field_collection_item', array($field_nid))[$field_nid];

This returns a FieldCollectionItemEntity. (info) But how can I render this field colleciton programatically.

render($field_collection);

Does not seem to work and I don't see any methods to render this field collection through code even though the ui config has no problem rendering it as I've defined it.

Thanks!


texts: how to split mailsytem based on condition

texts: I have a site for sending newsletters and I want to send through two mail system. I was using mandrill mail and PepiPost mail service. If I want to send a newsletter to 100 users, I need to use mandrill mail system for 50 users and pepiPost mail system for 50 users. How can I achieve it?


texts: How to setup birthdate field with optional values

texts:
I want to have a "birthdate" field for my users. It should be optional to enter a year or a date.
If a year is selected I want to display the age. If a date is entered I want to show the birthdate.

If I use the date field and make it optional I can have empty default values. However, as soon as I enter a year it requires the date and month too and vise versa.

Any solutions?


texts: "drush sapi-i" command which calls drush_backend_batch_process() fails with "Output is empty"

texts:
I am trying to integrate ElasticSearch with Drupal and till now everything seems to be working except that the command drush sapi-i crashes with the output:

> 'C:/xampp/htdocs/my-project/docroot/vendor/bin/drush' is not recognized as an internal or external command,
> operable program or batch file.

In ProcessBase.php line 172:

  Output is empty.

search-api:index [--limit [LIMIT]] [--batch-size [BATCH-SIZE]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--druplicon] [--notify [NOTIFY]] [--xh-link XH-LINK] [--] <command> [<indexId>]

After debugging with drush sapi-i -d it seems the call to drush_backend_batch_process() causes the issue for some reason.


texts: Does "hook_ENTITY_TYPE_load" have performance advantages over "hook_entity_load"?

texts:
I googled Drupal 8 hook_ENTITY_TYPE_load faster than hook_entity_load, but got no information on the question.

I was told that putting an entity type in the hook name is faster than putting an if statement for the entity type inside hook_entity_load(). This makes sense to me, but I want to make sure.

I also have a subscription to drupalize.me and couldn't find anything that supports the possibility of hook_ENTITY_TYPE_load() being faster than hook_entity_load(). In fact, it tells me to use hook_entity_storage_load() for that purpose.


texts: dl.example.com/file1.zip instead of example.com/sites/default/files/file1.zip

texts:
How can I convert address of uploaded files from example.com/sites/default/files/file1.zip to dl.example.com/file1.zip?

Is there a module for this purpose? If not what's the solution?


texts: I want to save files directly in Drupal database, is there any solution?

texts:
Possible Duplicate:
  FileField Database

I use Drupal7 with SQL Server Driver for database and I need to save files to db directly. (not directory), convert images to binary code and save them to database maybe a solution? hoom?