Taxonomy block in views which show the description of the children taxonomy, selected by two exposed filters I would like to build a simple block, where my visitors can check our shipping locations.
There are 3 outcome of this form:

Visitor can not find his/her county or city -> we dont deliver there
Visitor finds his/her city and the city field has no description -> we delivery there
Visitor finds his/her city and the city field has description -> we delivery with the desciption's conditions.

I have the following taxonomy tree in Location vocabulary:

County #1

City #1
City #2
...
City #300

County #2
...
County #15

What i did:

I created a new view which shows taxonomy in a block, no pager, only 1 item.
Fields: Taxonomy term: Description
If description has value show that, if empty show "we delivery there"

And this is where I got lost. I would like to have 2 exposed filters, where the visitor can select his/her county and its children cities.

Any help, any suggestions are appriciated, thanks!

One way to do this is possible with contextual filters.

Add a contextual filter based on term name
Add a relationship to parent term.
Add another contextual filter on term name, but this time use the parent term from the relationship.
Tweak the settings (override number of items to show, probably remove the count from the item list, and switch to jump menu instead of regular list if you want a dropdown display.)


Content type which creates sub contents I'm new to Drupal and my first project is turning out quite complex, at least it is when I'm trying to do it with Drupal.

I would like a "project" content type, which on creation will be more than just a page. It should be a page with it's own taxonomy term. On this page there should be a view to show recent media posted to that taxonomy term, along with downloads, articles and a couple of other content types. Essentially the new project page pulls all the other content together.

As I am hoping to hand this site over to less technical people (I barely understand Drupal yet nevermind trying to teach all of this to a non-technical person!) and would like this page to just be set up automatically.

I think the process is this: On creation the page should add it's title as a taxonomy term under the current vocab, then set up a view for each content type to pull the newest content posted under it's term.

Does this make sense? If not I'll update it with more information but if anyone has any pointers/tips or actually knows how to do this then I would appreciate the help!

I'd like to regard content types as a template to create entity objects (much like classes in object oriented programming) rather then as a means to create pages.

I do not see a reason for each project to have its own taxonomy term. If there is a 1:1 mapping between terms and projects, you are effectively creating redundancy. This might be done at a later stage to facilitate using specific modules that rely on the taxonomy module.

Nodes of the content type "media" can be linked to nodes of the "Project" content type by adding a "node reference" field to the "Media" content type. In Drupal 6, the "Node reference" module is part of the Content Construction Kit; in Drupal 7, it has been moved into the References module.

You can use the Prepopulate module to create URLs that show the "Media" creation form with the "node reference" field for "Project" already populated. This URL can be linked to using hook_link() (in Drupal 6) or hook_node_view() (in Drupal 7) to create media from the project page.

The list of associated media can be shown on the project page using the Viewfield module. Alternatively, the project page can be overridden using the Panels module. A second alternative is to add the output of the view to the project node using hook_nodeapi(&$node, $op='view') (in Drupal 6) or hook_node_view() (in Drupal 7).


Can I delete old hook_update_N functions? Suppose you have a custom module, and you have hook_update_N() implementations in your .install file.

If you have old update functions, and all updates have run in all sites that the module is installed, is it safe to delete those functions?
Please note this is about custom modules that you have access to all sites and updates have been run.

Thank you in advance and I wish everyone a merry Christmas!

Actually, there is a situation where you could need to keep the older update hooks: when you restored the database from an old backup and you need to update the database to the latest version of the installed modules.
If that is never your case, then—as long as you are sure all the sites have been updated to the same version of the module—you can remove the old update hooks. Keep in mind that, if you delete an update hook you needed for a site, the alternative is uninstalling the module, and then install the latest version, but this will cause data loss.

Updates hooks are only invoked when updating an installed module, and they are not invoked contemporarly to hook_schema() and hook_install(). When a module is installed, hook_update_N() is not invoked; hook_schema() and hook_install() are only invoked when a module is installed. That is the reason why old hook_update_X() could be removed, once a module is updated to version X or older.

Usually, the update hooks are removed when passing from a Drupal version of the module a more recent one (e.g. from the Drupal 6 module to the Drupal 7 module). Since the installation file is loaded just on updating and installing (and other limited situations), removing the update hooks doesn't give any significant gain.


How to customize the SMTP message When a message is send to the user a message like this is shown to him :

message screenshot

  SMTP -> FROM SERVER: ...........
  SMTP -> FROM SERVER: .......
  ............................................................................
  SMTP -> FROM SERVER: .......
  SMTP -> FROM SERVER: ......
  SMTP -> FROM SERVER: .....................
  SMTP -> FROM SERVER: ................................
  SMTP -> FROM SERVER: .....................................
  Further instructions have been sent to your e-mail address.

I only want the last one: "Further instructions have been sent ..." to show. Is it also possible to personalize it ?

Those messages are shown as the result of enabling logging in the SMTP module. It's only set once from the smtp_debugging variable. If it's still logging after disabling it, you to debug the issue as there's no one cause (e.g. caching, forcing the setting in settings.php/settings.local.php, code base hack, etc.) and is out of scope of Q&A.

As for altering the "Further instructions have..." message, there are many ways to do this (e.g. form alter, translation files), but the simplest is probably utilizing the String Overrides module which will let you override any message wrapped in a t() function.


how to configure drupal settings to be available to visualize the available variables? how must drupal local settings be configured to display available variables using IDEs or other tools ?
I guess this is xdebug and phpstorm but i don't know how to configure it if i don't have full admin access to the server.

You can use kint which will print you all the variables
https://www.webwash.net/how-to-print-variables-using-kint-in-drupal-8/
or dpm (in devel module)
https://www.drupal.org/docs/contributed-modules/devel/dpm-and-other-devel-functions


Email send action fails: Cron has been running for more than an hour and is most likely stuck I am maintaining a Drupal 6 installation. The task was to send an email to all registered users. I was using a rule set containing one rule with a default action: "send email to all users of a certain role". The rule set has been scheduled, was executed and deleted from the schedule (automatically like expected), but the task seemed to restart forever in the background: all (or probably a lot) users got the email every hour (6 times until I stoped cron). I use poormans-cron.

Please help with to answer this questions:

I suppose the mails could not be sent (~300 users) in the 60 minutes before the next cron (1h) decided that the job was still not complete and restarted it. Correct?
300 mails in 1 hour should not be a problem, but I saw somewhere, but cannot remind where, that one can set a wait time between sending mails. Is that correct? Please tell if you know where.
Can you think of something else than 1. for the reason? (I used out of the box drupal 6 functions).

The log shows:

error   cron    18/02/2012 - 12:04  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 11:08  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 11:04  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 10:07  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 10:03  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 09:07  Cron run exceeded the time limit and was aborted.
error   cron    18/02/2012 - 09:03  Cron has been running for more than an hour and is most likely stuck.
error   cron    18/02/2012 - 09:02  Cron has been running for more than an hour and is most likely stuck.
error   cron    18/02/2012 - 07:50  Cron has been running for more than an hour and is most likely stuck.
warning cron    18/02/2012 - 06:46  Cron run exceeded the time limit and was aborted.

Appendix 1, 19.2.2012
I use PHPMailer module to send the emails.

I think that your PHP configuration is not letting cron finish. Turn off poormanscron, then delete your cron entries in your MySQL database:

DELETE FROM `variable` WHERE name = 'cron_semaphore';
DELETE FROM `variable` WHERE name = 'cron_last';

Then go to admin/reports/status and click on your PHP version to see the output of phpinfo(). What is the max execution time? What is the memory limit? You'll want to change those values to higher numbers, then verify that they are indeed different on this page, then run cron manually at admin/reports/status.

To change these 2 values in PHP, create (or edit) php.ini in the webroot of your site and add (or modify):

max_execution_time = 300
memory_limit = 256M

Obviously feel free to try whatever numbers you'd like here. Ideally you don't want to leave the memory limit very high if you don't need to.


Identifying the level of menu items in the item array? I have a D7 menu of nearly 300 terms in a 3-level hierarchy.  Rather than generate them one at a time in the UI, I would like to generate them using code.  I am using the book 'Pro Drupal Development' and the Drupal API documentation for menus and the menus.module to attempt this, but am confused about how to establish the structure of the three tiers.

Creating a menu item appears to be fairly simple, implementing hook menu and creating item arrays  with values assigned to 'title', 'page callback', 'access callback', and 'type'.  My problem is that I must define the hierarchy and I am not clear on how that is done.  How do I identify the parent in the array structure?

EDIT - additional information

The menu items, at all levels must have a callback to a view definition following the pattern View_Name/tid/display_type.  The first level of the URL will be a unique label for the View being called. The next level is a term id identifying the specific term from a vocabulary that defines the relationships of the menu options.  The third level determines which view page in the definition provides the view output for display. My question is addressing how to duplicate the taxonomy hierarchy in a code generated menu? How do I tell the Drupal the relationships between the links to duplicate the three tier menu system when the links are created? I can provide my customized callbacks but haven't found the correct array key-value settings to generate the menu correctly.

I have experimented using the Taxonomy_Menu module to generate the menu directly, but I cannot find a way to generate different third level URL values within the module.  The module generates a menu of taxonomy links and Drupal does not expose the links for editing.

I'm not sure to understand your problem, but as you define everything by code, it should be straightforward.

You can create any menu entry you want, on any existing or newly created entry.

As for the hierarchy, you just have to define your paths like any URL path. As per the doc :
If you have

function mymodule_menu() {
    $items['abc'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
}

You can then define a child entry like this :

function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_def_view',
    );
    return $items;
}

This will give an entry at the root level 'abc' and a child entry 'abc/def'.

HTH.


Overriding File Entity fields when attached to a Node We have a challenging user requirement that I've been puzzling over and wanted to submit this to the community:

We're using the Media 2 + File Entity modules for managing our site's image library.  The Image bundles are fielded with meta data fields e.g. Title, Caption, Source, etc.

So here's the thing-- we need to have a way to override these on a case by case basis but if at all possible without duplicating the File.  For example, with stock photography images, we only want to have one image of the lady with a pregnant belly, but it will be used in different ways throughout the site, and we need to be able to give it a different caption in two different places.

We really don't want to have the same image in the library twice with two separate captions.  This would drive our editors crazy.

Thanks for any ideas!

There's no easy way to do this for files or images, which are essentially reference fields. There's no native way to do this for any type of reference field in Drupal. For example, you can create a reference field to a node, but override what the node's title is in a certain article when you reference it.

Typically what people recommend is using a Field Collection or a Multifield that consists of an image field + whatever field you want to have as the 'use this value only when this image is used here' stuff.

For captions, I know we added a caption filter specifically in Drupal 8 core, but I cannot find if it got back-ported for Drupal 7. That would be handy to have and use now.


How can I use Javascript (Google Analytics) in my "Rewrite Results" in Views? I'm trying to track downloads as events in Google Analytics for file fields.  The links are displayed in Views using "Rewrite results."

I tried the following:

Windows

But the onclick part gets stripped out by Views.  I know the Full HTML filter does this by default, but how do I get around it?

Views will indeed strip out onclick attributes.
You can work with data attributes and use an external JS file to add the onclicks.
Example for Views rewrite:

[myfield]

External Javascript (jQuery example):

jQuery(document).ready(function(){
 if(jQuery("a[data-event-type]"){
   jQuery("a[data-event-type]").click(function(){
    _gaq.push(['_trackEvent',jQuery(this).attr('data-event-type'),...........);
   });
 }
});


Setting a Drupal.settings JS variable from a form field i'm working on my first custom module and really fumbling along :). thanks in advance for your advice!

goal
i've added a checkbox to the comment form. if the user leaves it checked, then following comment insertion, i want to run some javascript on the following page.

possible approach?
i've added the checkbox using hook_form_alter:

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

//show the checkbox
  $form['wt_comments_share'] = array(
    '#type' => 'checkbox',
    '#title' => t('Post this comment on your Facebook wall too. Spread the word!'),
    '#default_value' => 1
  );
}

this works fine. however, i'm struggling to pass the variable from php to js. i read up on adding variables to Drupal.settings using drupal_add_js(), but i don't have a solid understanding of basic concepts. this post seems to add values to Drupal.settings using #attached, but i couldn't figure out how to add the value of a normal form field.

i tried to run drupal_add_js() within hook_comment_presave or hook_comment_insert, to no avail:

function wt_comments_comment_insert($comment) {
  dpm( get_defined_vars() );

  //nothing
  drupal_add_js( array ("wt_comments" => $comment), 'setting');

  // nothing
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
}

So i added the variable to the global $_SESSION object:

function wt_comments_comment_presave($comment) {
  $_SESSION['wt_comments'] = $comment->wt_comments_share;
}

then, within a hook that does run drupal_add_js, i add the new session variable to drupal settings as described here:

function wt_comments_page_alter(&$page) {

  drupal_add_js("jQuery(document).ready(function () {

      if ( Drupal.settings.wt_comments.wt_comments == 1 ) {

        // dance around! jQuery('body').css('background-color','green');

      }

    });",
    'inline'
  );

  //reset session variable
  $_SESSION['wt_comments'] = '0';

}

note: i wonder if hook_page_alter is the best choice here...

is this the right approach? thanks again folks!
-ryan

Adding the value of the new field wt_comments_share to $_SESSION['wt_comments'] is considered a good idea.

Because you're using session to pass values, you don't need to pass it to Drupal.settings unless if you want to add new JS file.

To add javascript code to node view you need to use hook_init or template_preprocess_node

function wt_comments_init() {
  // check if page is node and wt_comments is set
  if($node = menu_get_object() && isset($_SESSION['wt_comments'])) {
    // check users allowed to comment on this node
    if($node->comment) {
      // add javascript code
      drupal_add_js("jQuery(document).ready(function () {
            if ( Drupal.settings.wt_comments.wt_comments == 1 ) {
              // dance around! jQuery('body').css('background-color','green');
            }
          });",
       'inline'
      );

      // unset session wt_comments
      unset($_SESSION['wt_comments']);
    }
  }
}


How do I override the date filter to filter by years instead of exact date? I want to add another option to Date filter to filter with only years not the exacte date.
So i want to add another radio option here:

Like:

The above options added by Date Filter.
I have tried two ways:

Add new filter like date filter:
modules/custom/my_module/src/Plugin/views/filter/DateYear.php

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("date_year")
 */
class DateYear extends NumericFilter {
  // Same Code Date class with a little changes.
}

I tried to extend Date class and alter date filter plugin.

I create Class DateYear extending Date filter class:

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\Date;
/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("date_year")
 */
class DateYear extends Date {
  // Override valueForm method..
}

Then i implement hook_views_plugins_filter_alter to override class.

   /**
 * Implements hook_views_plugins_filter_alter().
 */
function cam_views_views_plugins_filter_alter(array &$plugins) {
  if ($plugins['date']) {
    $plugins['date']['class'] = 'Drupal\my_module\Plugin\views\filter\DateYear';
  }
}

But none of the above works ?

I contribute a module for this check it out here:

  This module add views filter by year exact, instead of full date like mm-dd-yyyy you can use date year like yyyy.

https://www.drupal.org/project/views_year_filter


Remove one item in cart removes all - Ubercart/Webform I'm using:

Drupal: 7-4.1
Webform: 7.x-4.12
Ubercart/webform intg: 7.x-3.0
Ubercart: 7.x-3.8

I am using this wonderful Webform module to add products to cart, all works ok, however, when added more that one item to the cart using multiple webform submissions then When I try to remove one item from the cart it says:

  If you remove this product from your cart, all products associated
  with your form submission will also be removed. Are you sure you want
  to delete this product?

So my question is; is there a way to remove one single item from the cart without removing all?

Yes, but not with the module itself. You can build a custom module to modify UC Webform Integration to suit your needs. This would involve 3 parts:

Implement a HOOK_form_uc_cart_view_form_alter() function such that cart Delete link for each submission and they have 2 arguments: cart/delete-form/$NID/$SID. You may need to adjust your custom module weight so that it executes after, uc_webform_form_uc_cart_view_form_alter().
Implement a HOOK_menu() function that defines the new cart/delete-form/%/% path. uc_webform_menu() should give you an idea how it's done.
Implement your own form/submission handler for the cart/delete-form/%/%. The function uc_webform_submission_delete_products_form() & uc_webform_submission_delete_products_form_submit() should give you an idea how it's done. The key thing here is you'll be adding something like $wf_sid = arg(3); and replacing isset($cart_item->data['webform_sid']) with $cart_item->data['webform_sid'] == $wf_sid so that only the selected submission is deleted instead of all submissions on that form.


Run KernelEvents::REQUEST event before hook_node_access? I'm doing some central static variable setup for the request and was hoping to use KernelEvents::REQUEST to run first and set the variables.

However, I've found that while the documentation states:

  The REQUEST event occurs at the very beginning of request dispatching.

hook_node_access actually runs before the KernelEvents::REQUEST event handler:

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 1];
    return $events;
  }

then in the event listener:

  public function onKernelRequest(GetResponseEvent $event) {
    drupal_set_message(__FUNCTION__ . ': ' . microtime());
  }

and in hook_node_access

then in the event listener:

  public function mymodule_node_accesss(NodeInterface $node, $op, AccountInterface $account) {
    drupal_set_message(__FUNCTION__ . ': ' . microtime());
  }

Output:

mymodule_node_access: 0.76379200 1518995630
onKernelRequest: 0.77758400 1518995630

As we can see from microtime order, hook_node_access runs first. Anyway to make it run after the KernelEvents::REQUEST event handler? thanks.

OK, after a bit more digging, I found the solution.

The "weight" param for ['onKernelRequest', 1] is sort DESC, so the higher weight number will run first.

Adjusting the event listener with weight 1000 as follows means it runs before the hook_node_access invoking listener

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 1000];
    return $events;
  }


Plugin Not Found Exception I am implementing REST in Drupal 8. I have created a custom plugin for REST resource, enabled the plugin and configured permissions for that REST endpoint.

After few days, I removed the code for plugin without disabling the REST endpoint. I am encountering a plugin not found function for that REST endpoint.

Following this Drupal\Component\Plugin\Exception\PluginNotFoundException: The "glossify_taxonomy" plugin does not exist., I made changes in the config and cache config table. Still I am encountering Plugin not found exception when I click on Permissions and Extend in Menu.

How can I remove this exception?

Could you try these steps

drush cex -y actual configs.
Find in your config folder yml file rest.resource.{YOUR_RESOURCE_NAME} and delete it.
drush cim -y this change, it will be correctly removed from DB.
drush cr for sure, and error will miss.

Some related discussion going here
https://www.drupal.org/project/restui/issues/2889860


How do I add a custom sorting variable to a view? I have a view that displays a list of items. Each item has a date field called "Featured Until". This can be set to a future date. If the data is in the future, I want this item to be seen as "featured" and appear at the top of the view.

I can't just sort by "featured until date", because that would still be an issue when the featured date is passed.

Is there any easy way to do this on a view?
Should I perhaps consider just adding a new boolean field called "Featured" and then use cron to update this value when the featured date is passed?

(I don't prefer the second option because I would need to add a cron task for  updating.)

Have you created a custom theme, or are you using a contrib theme?  If you have created a custom subtheme, then you can override the template for this particular view at the appropriate level (e.g. something like views-view-fields.xxx.yyy.twig) and then you can implement custom logic that tests if that particular field is greater than today's date, and then inject a CSS class, or change the markup, etc.

If are not subtheming or just don't want to go down that road, you can do as you suggested and have a "Featured field".  There is a module called Computed Fields (which helps you create derived fields, essentially) which may facilitate you doing this: https://www.drupal.org/project/computed_field.  I've not tried it myself for your particular use case, but it may be worth exploring.


Can Rules be used to disable the logo variable on some pages? I have a change in Drupal 6 that I would like to make quickly without doing another SVN roll (until I get a more permanent solution in place) and I would like to create a triggered rule that will null the $logo variable that is being sent to the theme before it gets there.

I know how to tell it to identify the page in question and control it based on role. However, I am having trouble figuring out what PHP code to use in the custom PHP code section. Partly because I just don't know what variables are available nor at what point in the code flow I am sitting in (which is important for this).

Does anyone have any ideas or suggestions?

I don't think that I'm on the wrong way (correct me if) but I think you should do a hook_preprocess_page(&$vars) in your theme's template.php and unset the $var['logo'] when you meet your condition.

I wouldn't do that with Rules, I don't even know if it's possible.


Where is tmp file directory? Strangely I cannot find this directory anywhere inside sites or files. There is only one in /var would that be it? I need to edit the .htaccess as it states in my reports. Also what ownership and permissions should this display?

Ok I found it in directory above /var and deleted it then created it again and set it as 755 permissions with apache ownership and placed security script in .htaccess as given in reports link.

Update: the .htaccess in files and tmp folders to create more security shut me out! I had to remove them. OKAY finally worked this out and why looking for tmp folder in first place! A status report glitch error for files and tmp folder saying needed to add security .htaccess file is BOGUS! it is a bug of some sort in 7.24 for my system Centos linux so my removing them was exactly what I needed to do after adding erroneous security updates.

Look in your Drupal admin area at /admin/config/media/file-system

This will tell you where Drupal thinks it's tmp folder is currently set to.

Depending on your host provider you may or may not be able to write to that location.

The php-info report found on your Status Report page admin/reports/status can tell you where PHP's temp directory is defined to be on your system:

upload_tmp_dir     no value

Using htaccess, or ini_set in settings.php you can tweak where the upload temp directory is for your Drupal installation if need be.


How do I get product variations in a preprocess function? I'm trying to do something like this.
function clientname_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  // Get the product variations and store them in $variations.
  if (!empty($variations)) {
    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
    $variation = reset($variations);
    /** @var \Drupal\commerce_product\ProductVariationFieldRendererInterface $variation_renderer */
    $variation_renderer = \Drupal::service('commerce_product.variation_field_renderer');
    // Override the variation list price with the price of the variation.
    $product['variation_list_price'] = $variation_renderer->renderField('list_price', $variation);
  }
}

I am not sure how to get the product variations in hook_preprocess_commerce_product().
What code should I use to get the product variations and store them in $variations?

$product = $variables['elements']['#commerce_product'];

  $variations = $product->getVariations();

  foreach ($variations as $variation){
      $list_price = $variation->getListPrice();
    // Do something with the variation list price here...
  }


How to use drush site-lists alias? I several folders containing symlinks to my drupal sites.  I'd like to use this folder structure to create an alias so I can run commands on each group of sites.

I'm trying to do what "drush @sites status" will do, but on a smaller subset.

I wrote the following based on the docs

// List the instances from the OU instances folder
$full_path = "/opt/drupal/sites/instances";
if ($handle = opendir("$full_path")) {
    while (false !== ($file = readdir($handle))) {
        if(is_dir($full_path."/".$file)) {
          if ($file != '.' && $file != '..')
            $instances[] = $file;
        }
    }
}

// Turn them into aliases so we just have to type @instance
foreach ($instances as $instance) {

    $site_list = [];

    // Look at each instance
    $site_paths = $full_path . "/" . $instance;

    if ($file_handle = opendir("$site_paths")) {
      // List out the folders in this instance
      while (false !== ($site_folder = readdir($file_handle))) {

        if(is_dir($site_paths."/".$site_folder)) {
          // If the folder represents a drupal site
          if ($site_folder != '.' && $site_folder != '..')
            // Add it to this instances list
            $site_list[] = '@' . $site_folder;
        }
      }
    }

   $aliases[$instance] = array(
            'site-list' => $site_list,
        );
}
print_r($aliases);

The cheeky print_r on the end shows my array as

 [partnership] => Array
        (
            [site-list] => Array
                (
                    [0] => @www.1.co.uk
                    [1] => @www.2.org
                    [2] => @www.3.org.uk
                    [3] => @www.4.org
                    [4] => @www.5.eu
                    [5] => @www.6.net
                    [6] => @www.7.com
                    [7] => @www.8-ri-2020.eu
                    [8] => @www.9.edu
                    [9] => @www.10.ac.uk
                    [10] => @www.11.org
                    [11] => @www.12.ac.uk
                    [12] => @www.13.co.uk
                    [13] => @www.14.org.uk
                    [14] => @www.15.ac.uk
                )

        )

I've changed the names to protect the innocent, but they are valid aliases.

When I run "drush @partnership status" I get

drush @partnership status
You are about to execute 'status' non-interactively (--yes forced) on all of the following targets:
Continue?  (y/n): y
Invalid argument supplied for foreach() backend.inc:661

How do I get drush to actually run through this alias list telling me the status of each site?

I found that one of my colleges had written an invalid file in the drush folder.  I was writing mine in my ~/.drush folder.

The result was it would run his code, then my code, leaving a big mess that drush could only partially understand

I fixed the incorrect file and the code I posted in the question started working.  I can now run drush commands against a site-list.


Print stylesheets & overriding a base theme style sheet Since adding a print style sheet and marking the screen stylesheets accordingly:

stylesheets[screen][] = css/example.css

rather than

stylesheets[all][] = css/example.css

The Genesis base themes are overriding the similarly named site styles in my sub theme. Specifically /sites/all/themes/genesis/genesis/css/layout.css is overriding my sub-theme layout.css file.

I've tried adding 'fake' calls to empty stylesheets (as per 'Overriding style sheets from modules and base themes'), with no success:

;----------// Modular Stylesheets

; Stop base overrides with fake file
; http://drupal.org/node/225125#comment-3028740
; http://drupal.org/node/263967
stylesheets[all][] = css/base.css
stylesheets[all][] = css/layout.css
stylesheets[all][] = css/blocks.css
stylesheets[all][] = css/comments.css
stylesheets[all][] = css/nodes.css
stylesheets[all][] = css/page.css
stylesheets[all][] = css/style.css

; block, comment, node, page and style CSS.
stylesheets[screen][] = css/blocks.css
stylesheets[screen][] = css/comments.css
stylesheets[screen][] = css/nodes.css
stylesheets[screen][] = css/page.css
stylesheets[screen][] = css/style.css
stylesheets[screen][] = css/layout.css
stylesheets[screen][] = css/forms.css
stylesheets[screen][] = css/rows.css

; Print css
stylesheets[print][] = css/print.css

I think the issue is that the later [screen] type is included as an extra stylesheet, rather than overriding the first [all]. But I can't see a way round it ....

You shouldn't be doing

stylesheets[][] = ...

Instead you should be doing

stylesheets[type][] = ...

type is the type of media to include the stylesheet for, like all, screen etc.


How do I embed a view as a form field and pass the information on I have a view that lists a number of nodes with images, I would like to take a grid view version of this and utilize it as a form. When the user clicks on an image, it will act like a selection box. Then, when the form is submitted that information will be passed on. What is the best way to do this?

I ended up doing this with hook_form_alter() and views_embed_view you can also add html to a form this way.

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

if ($form_id == 'your_form_id') {

       $form['what do you want'] = array(
         '#type' => 'textfield',
         '#title' => t('Question'),
         '#description' => t('Here is a question ?'),
         '#default_value' => $form['#node']->something ? $form['#node']->something : 'itis',
         '#required' => FALSE,
         '#suffix' => '
html test here
',
         '#weight' => 0,
       );

       $form['contact_information'] = array(
         '#value' => "
some html
",
       );

       $form['choose_an_image'] = array(
         '#value' => views_embed_view('my_image_view', $display_id = 'default'),
         '#weight' => 0,
       );

      return $form;
   }

}


$user -> uid always return 1 I found on google that hook_menu() is cached, and I have to use a callback function, but I couldn't fix it. $user->uid is always 1. I don't know how to solve this problem.
I'm a beginner. Tnx.

function test_menu() {
  $items = array();
  global $user;

  $nodde = db_query("SELECT title, nid, vid FROM {node} WHERE uid '$user->uid'")->fetchObject();

  $items['test'] = array(
    'title'            => t($nodde->title),
    'page callback'    => 'test_output',
    'access arguments' => array('access content'),
  );

  return $items;
}

As you suspect the results from hook_menu() invocations are cached. As you're only clearing the caches while logged in as user 1, that's why the logged in user is always user 1 for your router item.

To get around it you'll need to use a title callback, which is evaluated separately to the cached data:

function MYMODULE_menu() {
  $items['test'] = array(
    'title callback' => 'MYMODULE_title_callback',
    'page callback' => 'test_output',
    'access arguments' => array('access content')
  );

  return $items;
}

function MYMODULE_title_callback() {
  global $user;

  $args = array(':uid' => $user->uid);
  $node = db_query("SELECT title, nid, vid FROM {node} WHERE uid = :uid", $args)->fetchObject();

  return t($node->title);
}

Also make sure you're not putting variables directly into the query string as this will leave you open to SQL injection attacks. You should use parameter replacement instead (as in the above example).


Display drupal 7 site in iframe? I have a Drupal 7 site and a Facebook page. I have created a tab on the Facebook page which should allow me to display a page from my Drupal site within the tab. On Microsoft Edge I get a warning saying that the site doesn't allow iframes, on all other browsers I have tried nothing displays at all.

I have enabled Security Kit, disabled X-XSS-Protection, allowed cross-site request  from https://facebook.com and disabled X-Frame-Options.

I enabled the iFrame entity module and allowed nodes to be iFramed.

And I have put $conf['x_frame_options'] = ''; in my settings.php.

I still am unable to display a node from my site on an iframe.

How do I get around this?

Thanks

I put this towards the end of settings.php (Drupal 7). It worked for me:

$conf['x_frame_options'] = 'ALLOW-FROM .facebook.com';

(I also use SSL/https (Let's Encrypt) on this site.)

x_frame_options don't allow for multiple values, i think. So 'allow-from domain.com' might disallow SAMEORIGIN. From this post it looks like the module Security Kit allow for setting Allow-From dynamically based on the current page request. I haven't tested it myself.


Hide profile picture This is the profile page http://www.lusciousanime.com/users/ruriko
You notice there 2 duplicate profile pictures. I am using panels to layout the profile page. On the left column it uses Author Pane and the right column it uses User Profile token. I am also using Profile2 module. I want to remove the picture in the right column. How can I do this?

If you're comfortable with the views module, I would recommend adding a view that displays the user profile the way you want it and using that as the right part of the panel.  In the view, just add the fields you want displayed-- if you don't want the user profile picture, simply don't add it.


Add a user/author field formatter i have a site where I use display suite for custom page display. And all works. Now I need to add a custom field formatter for the "Author" field, but I don't find how to link "author" to a new field formatter.

I know that I need to use hook_field_formatter_info() but I don't understand which is the right value for "field types". I have tried with "user", "user_reference", "text","author" but nothing.

I have tried to see how Display Suite define its fields formatter, but for this field the module use "2" for this value:

$fields['node']['author'] = array(
    'title' => t('Author'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'ds_render_author_field',
    'properties' => array(
      'formatters' => array(
        'author' => t('Author'),
        'author_linked' => t('Author linked to profile')
      ),
    ),
  );

where

define('DS_FIELD_TYPE_FUNCTION', 2);

So how can I add one new field formatter for the author field ?

Thanks.

I have found the solution: I have to create a new display suite formatter because that page use ds for the display.

I have read this

  http://www.previousnext.com.au/blog/creating-custom-display-suite-fields-or-how-i-learned-stop-worrying-and-use-hookdsfieldsinfo

and I have created my formatter. All works. Thanks for all to all.


What is the command to execute after manually editing the composer.json file? I want to build a site broadly based on an exiting site and was thinking that the best way to do this would be to copy and paste required modules from the existing site composer.json and paste them into the new composer.json. What would be the correct command to download the modules via Composer once the file has been amended?

I think composer update is the command, but I don't know if it also updates dependencies that should not be updated.

You are better off calling composer require some/library. This will update the files accordingly and install the library as well.
That said, you can run composer install after manually editing composer.json.


Requesting a new password I need to request a new password via services.

I used the URL:  <endpoint>/user/password?args['name']=test2

but it returns Access denied for user anonymous

It's supposed to be used by non authenticated users so why does it return this error?.
What am I doing wrong here? What is the URL should I use?

This feature was added with the resolution of this issue:

https://www.drupal.org/node/1303400

To use this resource, make a POST to:

?q=rest/user/request_new_password.json

...and send along a name

name=john

...or e-mail address:

name=john@example.com


Site logo display is low quality My site logo looks pixelated even though the image has been sized exactly. When I open the image url in a separate window, the quality is as per expected, however, the display on the site is low quality. Is there any settings I should be tweaking in Drupal?

After a lot of trial and error, I realised that as long as the image goes through processing by Drupal, it's resolution somehow deteriorates during the process. As the issue with the site logo was a client complaint, I chose to bypass Drupal processing altogether by replacing site logo with site title, then applying text-indent: -9999px and background: url("../logo-image.png") to render the logo instead.


Moving an existing site to Mongo DB How hard is it to move a live site to mongoDB when its traffic hits high? Is it easy to built a Drupal site on it? How is the learning curve for a developer who is quite comfortable with Drupal7 and php.

I assume you're going to use the mongoDB module. This doesn't move the ENTIRE database over, just parts of it, like cache, blocks, watchdog, etc.

This works well because mongo, or any "document" oriented database is not great at relations. So you can move the data that is not very relational into mongoDB easily.

Mongo itself is cake. Easy to install, easy to understand. It's simply "JSON" data. If you don't know JSON, read up on it now. Already, many parts of Drupal's data are stored as JSON inside text fields in a regular SQL database such as MySQL.

I'd re-iterate that you probably don't want to move EVERYTHING over, like the nodes, taxonomy, etc. Those things are highly relational. Also, the mongoDB module doesn't support those for that reason.

Installation of the module is pretty straight forward and happens in settings.php. See the mongo module readme file for more info.


What does rebuilding content access permissions do? Since installing the node access module I see the following message randomly.

  Content access permissions need to be rebuilt.

Will rebuilding them remove all the node access permissions already set? What does "rebuilding" do? Why do I get this message?

There's a quote in the comments on this post that puts it nicely:

  Drupal maintains a table of who can access what; this needs to be rebuilt when a new module affecting user access is enabled.

Think of it as a cache-clear for node access data, except that it's quite complicated so needs to be run as a batch job rather than all at once (e.g. on a cron run).

Since node access is a sensitive issue it's also not wise to rely on scheduled jobs to make the necessary changes, hence why this is all done in one go.


How To Remove Content Types? I installed a custom module that created few content type that I'm no longer need it. I disable and uninstall that module but I still have the content type. And it bother me every time I see it. So I try to delete it however, I cant because for some reason doesnt have the delete button. So now I have 5 content type that I don't need. Can anyone have a solution on how to remove these content types ?

In this picture you will see that doesnt allow me to delete the content type.

If nothing else helps, delete them in the database directly (its probably advisable to make a backup):

DELETE FROM `your_database`.`node_type` WHERE `node_type`.`type` = \'blog_post\'"


Display custom text if there is no comments I want to display custom text on a node if there is no comments yet.
I think i should check for comments count in preprocess_node, and somehow add the text below Comments title.

function MYTHEME_preprocess_node(&$variables, $hook) {
  if($variables['comment_count'] === '0') {
     //somehow i need to display text - There is not comments yet
  }
}

How can achieve this? here is an example of how it should looks like:

EDIT:
Also i have found better solution, may be useful for someone.
(using Zen theme - aka STARTERKIT modified)
I have added comments-wrapper.tpl.php

And in a template.php added preprocess function of this wrapper

function MYTHEME_preprocess_comments_wrapper(&$variables) {
    $variables['MYTHEME_comment_title'] = t('Comments');
      $commented_node = $variables['node'];

      if(!empty($commented_node) && is_object($commented_node)){
        $comment_count = 0;
        if(isset($commented_node->comment_count)){
          $comment_count = $commented_node->comment_count;
        }
        $variables['MYTHEME_comment_title'] = format_plural($comment_count, '1 comment', '@count comments');
         if($comment_count == 0) {
            $variables['MYTHEME_comment_title'] = t('Comments');
            $variables['empty_comments'] = t('There is no comments yet');
     }
}

And in a comments-wrapper.tpl.php i have printed out $empty_comments variable

  <?php print $empty_comments; ?>

In your node.tpl.php you could check the $comment_count variable to see if there are comments. If so, render the comments, if not display your alternet text.

Example:

<?php if ($comment_count > 0 ): ?>
  <?php print render($content['comments']); ?>
<?php else: ?>
        <strong> 0 comments yet</strong>
        <?php echo l('Be the first','commentpath'); ?>
<?php endif; ?>


Only the first result shows in my view I have a view with 2 fields, node_title and node_related_content. For the field node_related_content I use the formatter = rendered node and view mode = Preview. These rendered nodes are fetched from a multiple value field in a content type "product group" that I use for listing related products.

In the view I use a contextual filter that gives me all the node IDs that belong to this view.

Now, the view works fine for one result (one group of rendered nodes). But if I enter more than one node ID in the preview field it onlyt gives me the first group... I need to have all the products groups, not just the first one.

What do I do wrong here?

This is the resulting SQL query:

  SELECT node.title AS node_title, node.nid AS nid,
  field_data_field_koppla_givare.delta AS
  field_data_field_koppla_givare_delta,
  field_data_field_koppla_givare.language AS
  field_data_field_koppla_givare_language,
  field_data_field_koppla_givare.bundle AS
  field_data_field_koppla_givare_bundle,
  field_data_field_koppla_givare.field_koppla_givare_nid AS
  field_data_field_koppla_givare_field_koppla_givare_nid, 'node' AS
  field_data_field_koppla_givare_node_entity_type FROM  {node} node LEFT
  JOIN {field_data_field_koppla_givare} field_data_field_koppla_givare
  ON node.nid = field_data_field_koppla_givare.entity_id AND
  field_data_field_koppla_givare.entity_type = 'node' WHERE (( (node.nid
  = '26262,21888' ) )AND(( (node.status = '1') )))

So the above query only shows the rendered nodes found in the product group 26262. The product group 21888 is ignored.

UPDATE: after experimenting with the SQL query in phpmyadmin I have found out that the last row in the query should look like this:

  WHERE (( (node.nid IN('26262', '21888', '21877') ) )AND(( (node.status = '1') )))

Now, how can I alter my view to reflect that change?

The solution was very simple, and I found it here: Views related nodes with contextual filters multiple-value handling problem

I just had to tick the "Allow multiple values" box under the More section in the contextual filter. A bit embarassing in the end... but that box was very well hidden indeed.


How to set canonical urls to migrated data I have a new site, to which all the articles from my four old sites are migrated. Now in a search engine,if anyone searches and clicks on any article's link it should redirect to the same article in the new site.

How can a get this in Drupal?

Please tell me about canonical url of nodewords module?

The canonical URL informs websites that the current URL is the authoritative location for the content contained on this page. This is useful if you're sharing content across multiple domains, have content available via feeds on other sites, etc.

With Nodewords (6.x-1.14-beta1 and above) it will automatically assign the canonical URL tag for the current pages using the page alias, so search engines will index e.g. /products/flying-monkey rather than /node/42. Also, with the 1.14-beta1 release I've made a concerted effort to make it "just work" out of the box, so you should get reasonably useful meta tags just by enabling the modules.

Also, if your content is available via multiple domains you can hardcode which domain the content is available from, that way even if the content loads on all of the old URLs the search engines will present the canonical one as the preferred page.

Disclaimer: I am the maintainer of the Nodewords module.


Seeing PHP info twice in status report On the status report page of a drupal site we run with 7.78, the PHP version number gets reported twice.
We have only setup 1 PHP instance in IIS with version 7.3.24.
How do I correct this to pull from the right PHP instance.

This is perfectly normal.
Every module you have enabled declares its own set of requirements. In your case, it seems that one module requires a version of PHP greater than the Drupal 7 default minimum PHP version of 5.2.4. Because of this, you will see two entries in the status report:
The first entry shows you what version of PHP you are using. This is always present.
The second entry shows you a status message from one of your enabled modules. This also shows you the version of PHP you are using, but in a slightly different format. This is only present if you have a module that checks the PHP version in hook_requirements().
If you want to find out which module you are using requires a non-standard PHP version, search your modules directory for hook_requirements. This is usually found in the <modulename>.install file for the module.
You will commonly see multiple entries for a variety of things. In my experience, the most common (in Drupal 7) is for cURL support - many modules require cURL, so you may see two, three, four or even more lines in the status report that tell you cURL is enabled. Again, perfectly normal.


Views title instead of id I have create new view showing all content referenced by given tag using contextual filter (field_tag: Content) Content: ID zawartości. Now I struggle how to overwrite the view page title with id of tag instead of node id provided as argument of contextual title.

In the contextual filters menu I have only following tokens avaliable:

while I am looking for the token allowing me to use "tag title" instead of "tag id" in the view page title.

The general idea is to have a page listing all content which is referenced by a tag given as a url argument.

I have read answers for similar questions here, but can't really find working solution.

At the end I benefited from both @No Sssweat and @Neograph734 answers.

First of all I added (field_tag: Content) Content: Title [nie pokazuj] field. Than I entered Content: Title field marked "modify output value" and get replacement token from there.

At the end I inputed the replacement token in contextual filter menu.

As @Neograph734 mentioned my problem was that the contextual filter did not proper list all available tokens.


Drush policy restriction doesn't restrict sql_sync On my @dev machine, I've installed a drush policy rule that should (?) prevent sql_sync to my remote @prod machine,

cat /etc/drush/policy.drush.inc
    <?php
    function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) {
        if ($destination == '@prod') {
            return drush_set_error(dt('POLICY: sql_sync TO @prod is NOT allowed'))
        }
    }

When I attempt the sql_sync, instead of preventing the action and printing the error, it allows it,

drush -v sql-sync --simulate=0 @dev @prod
    Loaded alias @defaults from file /etc/drush/aliases.drushrc.php                                [notice]
    Loaded alias @prod from file /etc/drush/aliases.drushrc.php                                    [notice]
    Loaded alias @dev from file /etc/drush/aliases.drushrc.php                                     [notice]
    /home/drupal/drush/drush  --backend=2 --verbose --uri=https://dev.mydomain.com                 [notice]
    --root=/home/drupal/dev  sql-conf   --all 2>&1
    ssh -o PasswordAuthentication=no root@prod.mydomain.com 'drush  --backend=2 --verbose          [notice]
    --uri=https://prod.mydomain.com --root=/home/drupal/prod  sql-conf   --all
    2>&1' 2>&1
    Modification time of local dump file /home/drupal/drush-dumps/sql-sync-dev.sql is less than 24 hours [warning]
    old. Use the --no-cache option to force a refresh.

    You will destroy data in prod.mydomain.com/prodDB and replace with data from devDB.

    You might want to make a backup first, using the sql-dump command.

    Do you really want to continue? (y/n): y
    Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --stats --progress /home/drupal/drush-dumps/sql-sync-dev.sql root@prod.mydomain.com:/home/drupal/drush-dumps/sql-sync-prod.sql);
    sending incremental file list

    Number of files: 1
    Number of files transferred: 0
    Total file size: 14634184 bytes
    Total transferred file size: 0 bytes
    Literal data: 0 bytes
    Matched data: 0 bytes
    File list size: 37
    File list generation time: 0.001 seconds
    File list transfer time: 0.000 seconds
    Total bytes sent: 46
    Total bytes received: 12

    sent 46 bytes  received 12 bytes  38.67 bytes/sec
    total size is 14634184  speedup is 252313.52
    Calling system(ssh -o PasswordAuthentication=no root@prod.mydomain.com 'mysql --database=prodDB --host=127.0.0.1 --user=dbadmin --password=secretpassword --silent < /home/drupal/drush-dumps/sql-sync-prod.sql 2>&1');
    Command dispatch complete                                                                      [notice]

What do I need to change/add to get the policy to restrict the sql_sync?

I added this to my sync_enable commandfile, and it definitely worked:

function drush_sync_enable_sql_sync_validate($source = NULL, $destination = NULL) {
  if (strpos($destination, 'live')) {
    return drush_set_error('DRUSH_BAD_DEVOPS_NO_BISCUIT', dt("Don't sync to live."));
  }
}

That looks the same as what you've got, so the next thing I'd recommend that you try is drush cc drush, to clear the Drush commandfile cache.  That will insure that Drush can see your policy file.

UPDATE:

Sorry, the problem was that Drush looks for site-wide commandfiles in '/usr/share/drush/commands', not '/etc/drush'.  Move your policy file there, and then drush cc drush, and it should work.


Disable pre-emptive validation of empty textfield On my form I have some fields and I set form['#required_error'] to generate a message on empty fields.
Works OK on select and option fields, but not on textfields.

It seems there is a (kind of ajax) validation before, which gives a pop-up with "fill in this field".

How can I disable pre-emptive validation of empty text fields, so that I can generate my onw messages

The 'fill in this field' message is browser specific HTML5 error handling.
Which is triggered before the form is submitted.
Only modern browsers show this, and it may currently not be consistent between browsers.

About this behaviour is an interesting discussion here: https://www.drupal.org/node/1797438.

If you have your own logic in place to assist the user with problems in the form you can disable HTML5 validation altogether by setting the novalidate attribute on the <form>. More specific is setting the formnovalidate attribute on a submit button.

In a hook_form_alter you can add the following line:

$form['#attributes'] += ['novalidate' => TRUE];


welcome page before main page (home page) How do I redirect the users who want to visit my site to a PHP page that has a link to index.php?

When someone go to example.com they should see a PHP page (e.g. a welcome page) where they would find a link to access the front page.

If you're happy to go down the module route, the following should get you started.

You're going to want to set a cookie to see if the user has been to the site before.  If the cookie is set, then you know the user has been to your site ebfore and it shouldn't redirect to the splash page.

function MYMODULE_init() {
  if (!isset($_COOKIE['mysite_firstvisit'])) {
    drupal_goto('path/to/splash/page');
    setcookie('mysite_firstvisit', '1');
  }
}


Ajax Submitted forms with ENTER I have this code:

function THEME_form_user_login_alter (&$form, &$form_state){
  $form['actions']['submit']['#ajax'] = array(
        'callback' => 'ajax_process_form',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace'
    );

};

It work when i click on the submit button, but when i press ENTER Ajax doesn't get triggered.. Is there a way around that?

Edit: I tried to enable ajax on all fields and set keystroke to True, but then only one field is sent so i get an error as the form process script is expecting two fields.

I realize this is an old thread but it shows up high in the Google search results.

Just set your submit button's Ajax event to 'click'. I believe its default value is actually 'mousedown' which won't make it trigger when the enter key is pressed within a field of the form.

If you set it to 'click', that event will trigger when the submit button is clicked as well as when the enter button is pressed within a form field.


Permission to edit a node by multiple users Suppose there is one node (Like node/4) which the Admin can edit. My requirement is to give permission to multiple users to edit the same node i.e. node/4. Please help how to accomplish this task.

The best option is to install a node access module that allow the admin to:

Create access control lists (ACLs) to individual nodes; and
Add and remove individual users from an ACL.

The module named Flexi Access lets you do exactly that.

The Flexi Access module will provide a simple and flexible interface to the ACL (Access Control List) module. It will let you set up and mange ACLs naming individual users that are allowed access to a particular node.
The module let you manage access to individual nodes. The administrator may grant individual users the right to: View (read), update (edit/write), and delete the node.

It depends on the ACL module.  (It actually provides an administrative interface to ACL.)
Disclosure: I am one of the maintainers of Flexi Access.


Cannot access empty property on entity.inc line 277 when trying to access entity add page I created a new entity type with hook_entity_info using this code:

/**
 * Implements hook_entity_info().
 */
function custom_payment_entity_info() {
    return array(
        'custom_payment_period' => array(
            'label' => t('Period'),
            'plural label' => t('Periods'),
            'entity class' => 'Entity',
            'controller class' => 'EntityAPIController',
            'base table' => 'custom_payment_periods',
            'revision table' => 'custom_payment_period_revisions',
            'entity keys' => array(
                'id' => 'pid',
                'revision' => 'pvid',
            ),
            'fieldable' => TRUE,
            'static cache' => FALSE,
            'label callback' => 'entity_class_label',
            'uri callback' => 'entity_class_uri',
            'access callback' => 'custom_payment_access',
            'module' => 'custom_payment',
            'views controller class' => 'EntityDefaultViewsController',
            'admin ui' => array(
                'path' => 'admin/config/custom/custom-payment',
                'file' => '/forms/custom_payment.period.form.inc',
                'controller class' => 'EntityDefaultUIController',
                'menu wildcard' => '%period',
            ),
            'bundles' => array(
                'period' => array(
                    'label' => t('Period'),
                    'admin' => array(
                        'path' => 'admin/config/custom/custom-payment',
                        'access arguments' => array('administrator custom payment periods'),
                    )
                )
            )
        )
    );
}

But when i try to create new entity through the admin add page i get this error:

  Fatal error: Cannot access empty property in
  F:\xampp\htdocs\sfn\sites\all\modules\entity\includes\entity.inc on
  line 277

This is the form function:

function custom_payment_period_form($form, &$form_state, $period = NULL) {
    $form['period'] = array(
        '#type' => 'textfield',
        '#title' => t('Period'),
        '#size' => 5,
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
        '#default_value' => isset($period->period) ? $period->period : ''
    );
    $form['type'] = array(
        '#type' => 'select',
        '#title' => t('Period Type'),
        '#options' => array(
            1 => t('Day'),
            2 => t('Month'),
            3 => t('Year')
        ),
        '#required' => TRUE,
        '#default_value' => isset($period->type) ? $period->type : ''
    );
    $form['price'] = array(
        '#type' => 'textfield',
        '#title' => t('Price'),
        '#size' => 5,
        '#field_suffix' => t('SYP'),
        '#required' => TRUE,
        '#element_validate' => array('element_validate_integer_positive'),
        '#default_value' => isset($period->price) ? $period->price : ''
    );
    $form['weight'] = array(
        '#type' => 'weight',
        '#title' => t('Position'),
        '#default_value' => isset($period->weight) ? $period->weight : ''
    );
    field_attach_form('period', $period, $form, $form_state);
    $form['actions'] = array(
        '#type' => 'actions',
        'submit' => array(
            '#type' => 'submit',
            '#value' => t('Save')
        )
    );
    return $form;
}

Can you help me fix this?

It's my first time working with entity type creation i followed the entity API documentation and the video entity example found here github.com/Lullabot/entity-api-demos/tree/master/docroot/sites/… i don't know exactly what is messing here.

Your entity keys don't seem to include bundle, label, or language. - @beth


How do I display a custom field from taxonomy term in user list in rewritten field I'm trying to display a list of taxonomy custom field terms next to a user's name. Though when I use a custom function to get the custom field (abbreviation) and then use it in a rewrite it still displays the original term list.

The taxonomy field is field_awards, the custom field attached to field_awards is field_abbreviation.

This is my custom function to display the abbreviation instead of the full term:

function ppw_views_view_field__field_awards($vars) {
    $row = $vars['row'];

    $abbr = array();
    foreach ($row->field_field_awards as $record) {
        $abbr[] = $record['raw']['taxonomy_term']->field_abbreviation['und'][0]['safe_value'];

    }

    return (count($abbr) > 0) ? ", " . implode(", ", $abbr) : "";
}

In this screenshot my theme shows the output of the function (it is excluded from display), the user's name with the awards field is rewritten into the output.

I've also tried to implement a custom field format in my theme:

function ppw_field_formatter_info() {
  return array(
    'ppw_term_reference_plain_abbreviation' => array(
      'label' => t('Plain text Abbreviation'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

function ppw_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Terms whose tid is 'autocreate' do not exist
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
  // just their name.

  switch ($display['type']) {
    case 'ppw_term_reference_plain_abbreviation':
      foreach ($items as $delta => $item) {
        $name = $item['taxonomy_term']->field_abbreviation['und'][0]['safe_value'];
        $element[$delta] = array(
          '#markup' => check_plain($name),
        );
      }
      break;
  }

  return $element;
}

How do I get the abbreviations next to the name? I've been unable to find what function to implement or what theme file to add to get this to work.

I solved my problem by fixing my field formatter (in its own module).


Aegir hosting_https commercial SSL cert Similar to Aegir no longer seems to be adding SSL info to apache config files for sites

The documentation still mentions a way to use commercial certs: https://docs.aegirproject.org/usage/advanced/ssl/#commercial-certificates

I too have run into the problem aegir_https not working the same way regarding chain certs.

Running aegir3-provision/stable,stable,now 3.182

LE is not an option for our org unfortunately.

Is there a way to use commercial apache certs with aegir_https/hosting_https?

As stated at the top of that documentation page, everything there is legacy and is no longer supported.

The feature request for being able to use commercial certificates with Aegir HTTPS (the officially supported way of running HTTPS now), is Add a 'manual' Certificate implementation.

So your options are either:

Write a patch yourself (and upload it to the issue), or
Pay us, the maintainers, (or someone else) to do it for you.


Is it fine to use hook_entity_view_mode_alter() to intercept an entity view to change the view mode based on an attached field value? Basically I want to let the content creator choose an arbitrary view mode. For example, be able to choose a gallery that is a FlexSlider slideshow, a Masonry jQuery plugin type image gallery, or an image gallery that displays metadata below each image.

On the entity there would be a field called field_view_mode which is an options list. The options are flex slider, masonry, and full images with text. Depending on the option they get the images and other fields formatted differently in different templates.

I'm thinking about defining 5 different arbitrary view modes. One more view mode would be custom_view_mode.

function hook_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when it is teaser.
  if ($context['entity_type'] == 'node' && $view_mode == 'custom_view_mode') {
    $view_mode = 'use entity metadata wrapper to pull field_view_mode value here';
  }
}

I don't want to use the Template Field module because it seems like overkill. I'm not sure if the Display Suite module does this but that seems like overkill too. I just want different view modes to be available. Has anyone done this before?

I know it's been a while since you asked...

As far as I can say, if you want use your own module, and not a contributed one, you have to define the view modes using hook_entity_info_alter, for example:

function mycustommodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['mycustommode'] = array(
  'label' => t('My custom view mode'),
  'custom settings' => FALSE, //Or true if you want to allow a certain role to modify it
  );
}

After that, you can use the hook_entity_view_mode_alter from your custom module (not working if you are trying to use in from your template.php in your theme). Hope that helps to anyone coming here from search as I did.


Form - Prepopulate and hide field with given argument I have two content types: City and Request.
Request is entity referenced to city.

Now i created a custom themed node /berlin.
On this page i have a button that says "send request", which brings you to the node/add/request form.

The form should now somehow pre-populate the field "field-city" with the previously selected city entity/node.

Additionally the field should be hidden.

Could you guys point me in the right direction?

There appears to be a dev version of the Prepopulate module for Drupal 7:

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.
For example, the following URL,
http://www.example.com/node/add/blog?edit[title]=this is the title
will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.

So you would just have to craft that button on your City node page to include the additional variable for your city field.
If for whatever reason this doesn't work exactly to your liking, eg, I am not sure if it allows for hiding of the prepopulated field, it would be fairly trivial to craft the functionality in a form_alter() hook in a custom module.


using DrupalWebTestCase - any trick to prevent it from running from scratch each time? It makes sense to run each test in a completely clean environment. However, before tests can be run, they have to be developed, during this process it is so frustrating to have to wait 3 or 4 minutes each time to see the result of any change/correction in the test.

Is there any trick to somehow resume the test in the environment where is finished or broke last time, without recreating the whole Drupal database? At this point, I am not interested in the tests to be 100% reliable, but rather in getting rid of more or less obvious errors in tests themselves.

For example, in my WebTestCase, I wrote $myfunction instead of $myfunction() and the test failed. The test so far created a content type, so in order to re-run it in the same environment, I would just delete that content type if exists, etc. It would be quicker.

No, there isn't. Simpletest doesn't know if your last test run was successful, or maybe broke something within the test environment, or if you changed it. That alone would be problematic, beside technical reasons. Also, the really slow part isn't your custom setUp() code but setting up a complete Drupal installation every time.

There are some tricks to improve the speed, however.

Use the testing profile by adding a protected $profile = 'testing'; to your test class. Maybe you need to define a few additional dependencies though, because that only installs the absolutely required modules. This improves test speed ~50%.
Have a single public test*() method, which calls a number of functions. Then you only need a single set-up for the whole test class. However, you need to be aware that your test methods aren't run in a separate environment anymore.
"Hacking" core by changing the default engine from InnoDB to MyISAM. That makes create TABLE statements much faster.
Improve your MySQL configuration, here's my configuration as an example: http://techblog.md-systems.ch/blog/improve-mysql-performance
When actively working on a single test method and the class has multiple ones, disable the others by replacing function test... with function dtest... Don't forget to revert that before committing.

A single test method takes ~10 seconds on my laptop. That's not too bad.


Drupal 6: Having a menu where more than one Item is active I'm trying to build a menu where a node can be a child of more than one item. That's not really an issue because Drupal 6 can handle it. However only one parent menu item will be active.

It's some sort of a portfolio where a client-node can be a child of photography and design and when the page of the node is opened the entry for photography and for design should be active.

Does anyone have an idea?

Drupal has built in the assumption that only only one item in a single menu can be active.

You hack the core menu system or create your own, but both would not be recommended.

The best workaround I can think of, is to expend the menu and use css and JavaSript to show/hide the menus and mark them as active. This could be doable but might be quite hard if you have a complex menu structure.


theme_preprocess_node not working inside of a view I'm trying to add a variable to the $classes array on a node, but it's not adding it while the node is in a view.

function MY_MODULE_preprocess_node(&$vars, $hook) {
  // Add the terms to the body classes for my_node_type'.

  if ($node = menu_get_object()) {
    if ($node->type == 'my_node_type') {

  // Return an array of taxonomy term ID's.
  $termids = field_get_items('node', $node, 'my_field_name');

  // Load all the terms to get the name and vocab.
  foreach ($termids as $termid) {
    $terms[] = taxonomy_term_load($termid['tid']);
  }

  // Assign the taxonomy values.
  foreach ($terms as $term) {
    $class = strtolower(drupal_clean_css_identifier($term->name));
    $vocabulary = drupal_clean_css_identifier($term->vocabulary_machine_name);
    $vars['classes_array'][] = $class;
   }
  }
 }
}

I added a

<?php dpm($classes); ?>

on my node.tpl.php I'm able to see the particular field being added to the classes array in my <div class="my_field_name">. But when it's in a view, the class isn't applied which makes me think that the preprocess_node isn't being called properly. Any suggestions for what I should do or anything I'm missing that's preventing the hook_preprocess_node from being called properly? I've tried placing it into my theme's template.php instead of in the custom module I'm using but neither work.

ANSWER NINJA EDIT (can't post one for another 8 hours)

I was able to finally get it to call the classes properly. Appears that these conditions were not being met in the view:

if ($node = menu_get_object()) {
    if ($node->type == 'my_node_type') {

so I removed that line and instead replaced it with

$node = $vars['node'];

Removed the code from my custom module and placed it in my custom theme's template.php o the function now looks like this

function MY_THEME_preprocess_node(&$vars, $hook) {
  // Add the terms to the body classes for MY_NODE_TYPE'.
  $node = $vars['node'];

  // Return an array of taxonomy term ID's.
  $termids = field_get_items('node', $node, 'MY_FIELD_NAME');

  // Load all the terms to get the name and vocab.
  foreach ($termids as $termid) {
    $terms[] = taxonomy_term_load($termid['tid']);
  }

  // Assign the taxonomy values.
  foreach ($terms as $term) {
    $class = strtolower(drupal_clean_css_identifier($term->name));
    $vocabulary = drupal_clean_css_identifier($term->vocabulary_machine_name);
    $vars['classes_array'][] = $class;
 }
}

$node = menu_get_object() works only when the page you are seeing has a URL that is similar to node/12, or node/12/view. When you are watching a view, its URL is probably different.

That code is also not necessary, as template_preprocess_node() already initializes $variables['node'] with the node object.

$variables['node'] = $variables['elements']['#node'];
$node = $variables['node'];

If you want to check if the node is being viewed in its own page, you can use the following code.

if ($variables['page']) {
  // The node is shown in its own page.
}
else {
  // The node is shown together other nodes.
}

$variable['page'] is a variable set by template_preprocess_node().

As side note, this is the code used by views_plugin_row_node_view::render() to render a node.

function render($row) {
  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }
}

node_view() is the function that calls the theme_node() theme function, causing preprocess/process functions to be called.


View filters are not updated I have a View filter that contains a list of taxonomy terms; the problem is that when i add new terms to the vocabulary, the new terms are not automatically added to the filter view so i do not see the nodes related to the new terms. Is there a way to link the filter to the vocabulary by saying "all the terms"?

In the filter for the taxonomy term, try choosing no terms at all instead of choosing all.


Is there a way to set only the "Full HTML" input format for the administrator role? A plain Drupal 8 installation set the following input formats for the administrator role it creates:

Basic HTML
Restricted HTML
Full HTML

The first one is assigned to authenticated users; so, I guess it would be automatically allowed to the administrator role. The second one is assigned to anonymous users too.

Is there a way to assign the Restricted HTML input format only to anonymous users? I tried editing it to remove the administrator role from it, but when I edit that input format again, I see it is still assigned to the administrator role.

To make the question more understandable, I am referring to the settings in admin/config/content/formats/manage/basic_html.

I can unselect Administrator from the Roles list, but that change will not be keep after saving. Differently, I can take off the permission to use the Basic HTML format from the Authenticated user role, select it in admin/config/content/formats/manage/basic_html, and the selection will be kept.

User #1 is a special user that gets all permissions, always. Its access privileges are not controlled by the administrator rule. You can read more about it here: Securing user #1

I haven't tried this, but the following should work: you could create a new admin user with the administrator role, and give it access to Full HTML only. If you want you can then disable user #1 completely. Before you disable user 1 make sure that the administrator role really does have all permissions. I don't know about D8, but in D7  the administrator does not automatically get all permissions when contrib modules are installed.


Drupal 7 OG Group Unsubscribe after given time period for member I am new to drupal 7 and was willing to implement something like time based unsubscription from a OG Group.

I have users added in OG Group. I want to implement time based unsubscription of the users already added in the group say 'Computers'.

User say 'Tony' is added to the group 'Computers' today, now I wish that a user 'Tony' should be unsubscribed from the group 'Computers' after a subscription of 3 months (a specific time period).

A Notification message should be sent to user 'Tony'.

All the process should be based on systems current date and the joining date of user 'Tony' to the group 'Computers'.

Please help me with any solution.

This is definitely a job for rules. It is also quite a complexed subject as you are going to need to utilise components so that you can schedule this to happen every day. I would do it like this:

Set up a views_bulk_operations view that looks up all users that have been members of groups for 90 days.
Create a rule component that loads the list of users, loops through the list, sends a notification and unsubscribes the user from the group.
Schedule the rule to do this every day.


How to get link path in custom block for a view? I created a view (unformatted) associated with a content type with two simple fields for a block.
The view is called "phrases" have generated two .tpl:

a) views-view-unformatted--phrases-block.tpl.php (to style row).

b) views-view-fields--phrases-block.tpl.php (to style the fields).

How to generate the link to the content, because by the variables I do not receive the direction I need.

I have available only the variable "$content", but this is formatted with something like:

     Path

I need to assign a class to the "a tag" , but as I receive all formatting can not.

Example i need:

    Path

As I can generate the correct path to the content?

In your view, in FIELDS add Content: Path

Then in views-view-fields--phrases-block.tpl.php add:

    <a class="my-link-class" href="<?php print $fields["field_path"]->raw; ?>">Path

if the above doesn't work try:

<a class="my-link-class" href="<?php print $fields["field_path"]->content; ?>">Path

If the 1st and 2nd doesn't work, to make the 2nd one work, get rid off all your html markup, because it's probably printing as href="/yourpath"

Click on your Path field and unchecked add default classes.

In field settings, uncheck add field wrappers.


Use 'Contains' in better exposed filters? I have a taxonomy of Office departments that I am using to filter my contacts which are brought into drupal with Ldap to search people by department. Some contacts have more info in their dept field when brought in from Ldap.
For example 'Credit - London' instead of just credit. Is the a way to filter by contains 'Credit'?
There are no options on the expose filter

If you use the field as textfield, then you will have options to filters department like above.


How to email all group members after a new node is added when using the Group module? I have created one group using the Group module. In that group I have 1 node type and 3 members.

I want to send a confirmation email to group members whenever I add new nodes of that node type. How can I do that?

Notes:

My question here is different from the question about "Mailing content to a list/group of email addresses" (mine is specific to the Group module).
I have not (yet) tried using the Rules module for this, since I don't know how to integrate the Group module with the Rules module.

Only using the Groups module
The Group module is an upcoming alternative for the Organic Groups module for D7, for which right now there is only a beta version available.
Remark: the Groups, Communities and Co module (= GCC) is yet another alternative (with an official release for D7).
The Group module appears to be an interesting alternative, though it doesn't come with a lot (if any) documentation so far.
The best docu available, I think, is to read its sources. In doing so, I learned that its Group Invite submodule "Allows group members to invite people into their group", which will trigger appropriate eMails. Of course, that implies that the user who wants to send these invites, is already a group member. But this "function" is not really what you seem to be looking for (as per your additional comment to my answer here).
Instead, you want to "Send an email to group members of particular group when a new node is created". To do so, I'd narrow down your question to 3 sub-questions (= tasks), and try to implement this using the Rules module, as further detailed below ...
Also using the Rules module
Rules Event
That's easy, more or less out-of-the-Rule-box: When a new node is created.
Rules Condition
This is your Challenge 1: Only if "Node type of the created node belongs to some group".
Rules Action
Create a Rules "component" to send an eMail (anybody can do that, right?). Here is a typical sample of such component (in Rules export format, just import it in your own environment via copy-paste):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "New node was added",
          "message" : "New node was added for content type ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.
This is your Challenge 2:  construct the "To" content of such eMail, i.e. all eMail IDs of all members of the group. That is what the value should be for user-to-notify:mail in the Rules component shown above.
Write your custom Rule(s)
To address the above Challenges 1 and 2, you could write your custom module, in which you basically would do 2 things:

Take advantage of the very well documented API provided by the Group module.
Write your own custom Rules, similar to what's explained in the great tutorial Drupal custom Rules how to write your own events conditions, actions and custom object (+ custom tokens).

If you're looking for more Rules related coding samples, you may want to look at the Rules URL Argument module. Here is a quote about it (from its project page, bold markup added here):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10".


Related Content Block for a Views Page, Not a Node Page I've created a views page that displays the most recent node of a certain content type. I have an image field in that content type that I would like to have displayed in the sidebar in a related content block. I have achieved this on the individual node pages using the contextual filter of NID with Content ID from URL. However, the views page is not the node page, so the related content block will not appear. How would I achieve this? Thanks!

You created views block which display current node images - right? What images you want to display on views page?

You can create another views block where display images from some nodes(add some term to nodes to mark them) or images from recent nodes which views shows.


Using Views and adding ALT and TITLE to an image I've been attempting to add my node Title to the image ALT and TITLE fields during their output in a view.

I am using the Media module to mange my images, and I have included the image_url_formatter module to offer up the image URL information in my view.

I attempted the advice in this post How to add alt and title attributes to an image gallery View?
and it almost works however this is occurring:

Within the View, If I alter the Image field to output the Image URL this works and I get my option of URL information in both preview and actual view.
If I then attempt to Rewrite the results, I suffer from two issues.

The [field_image-fid] outputs a numerical number only. i.e 1 or 4 etc...
The [field_image-width] & [field_image-height] output the actual image height and width rather then the selected image style, i.e. Thumbnail.

Anyone suffered from these issues, or know the answer?

Is the title-field before the Global text-field?
Can you provide a screenshot of your field-settings in the View? (the most left column)


Advanced Forum Work with HoneyPot? How do I configure HoneyPot module spam blocker to work on my comment pages for my Advanced Forum?

I enabled the Honeypot in Config section, checked Blog entry node form and Forum topic node form in Node Forums and Comment Forms.

The module configuration page is just the one on /admin/config/content/honeypot, which has the following settings.

If you expect to see a difference on protected forms, there isn't anything visible. The module creates a form element that is hidden to users, but tools that automatically fill the form will fill also that, making clear they aren't human users.
The module also doesn't accept a form submission before time limits seconds are passed from the moment the form is rendered.

If you are testing a form using a user account with the administrator role, that has the Bypass Honeypot protection permission, so you will not see any hidden form element even watching at the HTML markup of the page.


Converting UTF8 Data to SQL_ASCII I want to convert my query results from a database, which is SQL_ASCII database encoded, to UTF-8.

$result = $query->execute;
$converted_data = array();
foreach($result as $record){
    $converted_data[count($converted_data)] = drupal_convert_to_utf8($record->name, 'sql-ascii');
}

I used drupal_convert_to_utf8 but it returns blank all the time. I was confused if sql-ascii should be the second parameter of drupal_convert_to_utf8. The database encoding, where the query results is fetched, is SQL_ASCII in postgres.

UPDATE:

According to the official documentation, It

  Requires the iconv, GNU recode or mbstring PHP extension.

What are they? Am I going to install/include it or what?

Go to /admin/reports/status and take a look at your unicode library. If you don't have multibyte support, install it: http://php.net/manual/en/mbstring.installation.php

I.e. for ubuntu like systems it's sudo apt-get install php7.0-mbstring for PHP7.

EDIT:

You could try 'auto' instead of 'sql_ascii', and btw., you can skip the count() call and can just write $converted_data[] = drupal_...

END EDIT


HTML5 doctype with RDFa I'm using Omega 3, and have a redundant HTML doctype header line.

How do I correct this so I have my HTML5 <!DOCTYPE html> line, and specify RDFa?

Currently, the first two lines of my pages are:

<DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">
<html lang="en" dir="ltr" version="HTML+RDFa 1.1"...>

Omega4 supports

<!DOCTYPE html>
<html lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

where you don't have to manually define RDFa.

Beside Omega4 I normally do (usually I use Zen, but you can do this in other themes too):

<!DOCTYPE html>
<html lang="en" prefix="dc: http://purl.org/dc/elements/1.1/">

and define property="http://purl.org/dc/terms/TERMS wherever I use RDFa

Dublincore Metadata Initiative has detailed information about the terms

Drupal7 core has RDF support via rdf_namespaces. The hook implementation is:

function hook_rdf_namespaces() {
  return array(
    'content' => 'http://purl.org/rss/1.0/modules/content/',
    'dc' => 'http://purl.org/dc/terms/',
    'foaf' => 'http://xmlns.com/foaf/0.1/',
    'og' => 'http://ogp.me/ns#',
    'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
    'sioc' => 'http://rdfs.org/sioc/ns#',
    'sioct' => 'http://rdfs.org/sioc/types#',
    'skos' => 'http://www.w3.org/2004/02/skos/core#',
    'xsd' => 'http://www.w3.org/2001/XMLSchema#',
  );
}

so you can simple do <?php print $rdf_namespaces; ?> in your html.tpl.php file where you start <html>.

If you want latest RDF support there is a module for that one too called RDFX.


How to implement and install Icomoon and Fontello icon packs in Drupal 7? I am trying to get Fontello and Icomoon icon packs installed properly.

I look in the backend and it says import for Fontello and Icomoon.

I have downloaded the packages, but importing creates an error.

I have manually downloaded and extracted them, put them in my libraries and:

Renamed folder: Fontello

And

Renammed folder:  Icomoon

But not found under status report, not even as missing. I have installed the Icon API module and enabled it.

Additionally, Fontawesome installed correctly and is showing ok in status report but it stil shows this error:

The Font Awesome library could not be found.Please make sure that     fontawesome was download & extracted at sites/all/libraries/fontawesome directory.Please check README.txt for more details.

Ok, got it figured out.

Go to Fontello website.
Drag and drop Icons you need in the box on top.
Save file as Zipped, don't do any renaming or extracting.
Go to admin/config/media/icon/import
Give it a title and import the zipped file you just downloaded.

The icons will then show up on the drop down when adding them to articles or wherever.

Addtionally, the help files for Fontello are here:

https://github.com/fontello/fontello/wiki/Help


Composer module doesn't contain a .info file So I am quite new to Drupal and I was hoping someone experienced could tell me what I am doing wrong.

Essentially, I have Drupal 7.5 linked to my website, but I am having problems installing the Composer module using the control panel.

Whenever I attempt to add the module by either URL or a local download, Drupal claims that it doesn't include a .info file. Which, from what I can tell after unpacking it and inspecting its contents, is true.

So, I was wondering if the lack of a .info file is a problem on my end (likely) or just a case of the Composer devs forgetting to include it (unlikely).

Hopefully someone will be able to help out.

The project you linked to is a Drush extension, not a module, and only compatible with Drupal 8.

So it makes sense that you can't install it as a module into a Drupal 7 site ;)


What are the conditions for the "is one of" operator being enabled for filters on a particular field? When I am creating a filter on a field, the "is one of" operator is not available. What are the necessary condition for the "is one of" operator to be available for field.

I have seen an example in which the "is one of" operator is available for taxonomy values. What is it about taxonomy values that make the operator available for them?

'Is one of' operator in views filter aka ORoperator in SQL, it is only available for list fields or fields with allowed values that means any field which has the select list, radio buttons, or checkboxes widget can have and use 'Is one of' operator in views filter.

Theoretically, any reference field or any list field should have 'Is one of' operator available in views filter.


Facet block based on other facet choice I have a site where search is based on Search API (mysql server). I have two fields in my content type (brand and model) and I have created two faced block based on these fields. They work.

Now I want to make visible the model's facet block only when users have chose the brand (from the faced block).

Is this possible without a custom module or PHP code that searches in $_GET the brand chosen from the users?

Better is later than never :)

Try to use "dependencies" from context menu of facet block.


retaining upload file information in form when validation fails on other fields If there are required fields in a form (ie '#required' is set to TRUE), and the user sets a file to be uploaded but not provide all the required fields, validation fails on the required fields and the validation hook does not get called; the specified file does not get uploaded (if that is where the upload code is placed) and the form is refreshed without the previously provided filename wiped out. Is there a way to either upload the file during validation, or reset the filename in the form field, so that the user doesn't have to reselect it again?

thanks

I believe using the File_Managed fieldtype will fix your problem. This Drupal FAPI field type uploads the file to a temp directory BEFORE the form is submitted, and so you can access the file during/after validation. You can see an example of it being applied in the "image_example.pages.inc" in the Examples module. Hope this helps.


Restore role visibility in blocks I upgraded my Drupal 8 site from 8.4.5 to 8.5 and I noticed the role visibility in blocks disappears. I did a clean install and it's in Drupal Core, so the problem is not with my upgrade. I am thinking it's in the database but I have no idea how to track it. Does anyone know how?

I had the same problem. Solved it by editing the content of the block.
(we logged in as admin you see a button in the right upper corner, click it and select Edit). It appeared the the translated content was not published.


Embed a collection of form inside a form With Symfony2 I can embed a collection of form inside an another form (subform inside form).
http://symfony.com/doc/current/cookbook/form/form_collections.html

I would like know if it's possible inside Drupal 8 please, The documentation (Drupal 8 - Form API) don't talk about that.

Thanks.

Drupal forms are very different from Symfony forms.

There is no concept of sub-forms, but there is no limit to the complexity a single form can have as a form is an almost arbitrary render array structure.

A commonly used concept there is #tree. By default, the form input element names are flat.

If want to edit multiple elements in the same form, you can build a structure like this:

<?php
$form['#tree'] => TRUE;
foreach ($things as $id => $thing) {
 $form['things'][$id]['name'] = ['#type' => 'textfield', ...]
}

Without #tree, you would have multiple textfields named 'name', when set to TRUE, you get something like name="things[5][name]".

In Drupal 7 and earlier, it was complicated to render those nested forms in a table, you needed custom theme functions that then built the actual table. In Drupal 8, it just works, in the above example, you would just need to add something like $form['things']['#type'] = 'table' and then each $id will be a table row.

Then you can get all those values in the submit method with $form_state->getValue('things') and process them again in a loop.


taxonomy vocabulary access I want a role to have access to

add and view terms to any vocabulary,
the overview admin/structure/taxonomy/foo_vocabulary for sorting the terms by draging

but deny the access to edit the vocabulary or its fields. its like administer-taxonomy permission without the option to edit a vocabulary. TAC wont help.

I know, this question is pretty old, but I was looking for a solution by myself.

Maybe someone is looking as well: http://drupal.org/project/vppr
This module provides some new permission settings just for viewing terms which is exactly what I was looking for.