Adding jQuery UI selectmenu() to Drupal form I'm trying to add a styling to the select form elements in my Drupal form using jQuery UI. I'm using Drupal 7 so the usual way to add jQuery UI would be something like this:

 drupal_add_library('system', 'ui.accordion');
 drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion();});', 'inline');

However, when I try to add an effect that isn't bundled with Drupal 7 core, like this one, that approach doesn't work. Has anyone come across this problem before, and if so, is there a "standard" Drupal way of solving this?

I think the 'Drupal' way would be to implement hook_library() to add the new element to the system:

function MYMODULE_library() {
  $libraries['ui.selectmenu'] = array(
    'title' => 'jQuery UI: Selectmenu',
    'website' => 'http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/',
    'version' => '1.8.7',
    'js' => array(
      drupal_get_path('module', 'MYMODULE') . '/jquery.ui.selectmenu.min.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget')
    ),
  );

  return $libraries;
}

And then add it to your pages using drupal_add_library():

drupal_add_library('MYMODULE', 'ui.selectmenu');

Doing it this way ensures that all the necessary core UI files are included in the page automatically, and allows you to add the widget with a single line of code any time you want to.


Which pages affect text area CSS? I have a text area with CKEditor. The default font in this text area and my theme is 20 pixels and I cannot change its size with CSS, but if I change theme and use Garland, the font change to the normal size.

If I copy Garland styles and page.tpl.php in my theme, the text area is still using a 20 pixels font. Why?

CKEditor set its own CSS classes for text areas, but that would not explain why copying the CSS files from a theme to another doesn't change the visualized styles.

The problem here is that simply changing the files used by a theme doesn't change the used styles; you need to let Drupal know the theme has been changed, and this can be done in two ways:

you select a different theme as default one, disable the theme you modified, re-enable it, and select it again as default theme
you force Drupal to refresh the cache it is using, or you empty the cache tables

In the first case, you submit the theme selection form after each operations.


How do I assign variables from FormatterBase-Interface to hook_page_attachments()? I have created new field-types in drupal.

Therefore I have an Instance of FormatterBase, which gets the values from the database and tries to render the values.

but i want to pass the variables #wkt and #zoom also to the _page_attachments-hook of the .module file, because I need the variables in the drupalsettings variable. (js neededs this variables)

class GeoObjectWKTFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = array();
    foreach ($items as $delta => $item) {
      $elements[$delta] = array(
        '#theme' => 'myosm_block',
        '#wkt' => SafeMarkup::checkPlain($item->value),
        '#zoom' => SafeMarkup::checkPlain($item->zoom_level),
      );
    }
    return $elements;
  }
}

My hook:

/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
    $attachments['#attached']['drupalSettings']['mymodule']['zoom'] = //here I want to assign the value;
    $attachments['#attached']['drupalSettings']['mymodule']['wkt'] = //here I want to assign the value;
}

No, you don't want to do this.

You can set #attached everywhere. hook_page_attachments() is just the global hook that allows to add attached things to all pages.

But you don't need this if you want to use #attached for own structures, just add them to your render array that you return.


Cannot trigger CKEditor WYSIWYG in form API I’m using Drupal 7.18 with CKEditor 4.3 (full package), and trying to get a WYSIWYG field via the form API. My code:

function article_edit_form($form, &$form_state, $article)
{
    // ...

    return array(
        // ...
        'content'  => array(
            '#type'    => 'text_format',
            '#title'   => t('Content'),
            '#format'  => 'full_html',
            '#wysiwyg' => true,
            '#input_format' => '1',
            '#value'   => array(
                'value'  => is_null($article) ? '' : $article->content,
                'format' => 'full_html'
            )
        ),
        // ...
    );
}

But this only displays a regular textarea with a section to choose the “text format”. The CKEditor is installed, enabled and I’m logged as admin.

There are a couple of things that you could try changing:

#input_format and #wysiwyg are not in the list of available properties for a text_format element, so even if they're not causing the error, you should probably remove them.
You shouldn't set the #value of an element like that (unless it's a value type itself). Instead you should use #default_value. In the case of a text_format the #default_value is expecting the text for the text area (since you've already set the format with #format).

I would expect this to work (certainly does for me if memory serves), but if not, check the console for JS errors

return array(
    // ...
    'content'  => array(
        '#type'    => 'text_format',
        '#title'   => t('Content'),
        '#format'  => 'full_html',
        '#default_value' => is_null($article) ? '' : $article->content
    ),
    // ...
);


Install profile installation fails with "Base table or [error] view not found: 1146 Table 'xxx.system' doesn't exist'" on aegir I tried to install a custom installation profile on aegir today, the installation failed with this message:

Exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or
view not found: 1146 Table 'xxx.system' doesn't exist'

A local installation in a vagrant via drush worked without Problems.

The reason for this obscure error message was that I had defined a dependency in the installation profile, but the module was missing. After removing the not-existing module from the profile.info-file the installation went smooth.


Render Menu using embed token Is it possible to render a menu in a block or a node's body using [embed] or any similar token?

What I want to achieve is to render the main menu in a custom block. I don't want any solution that involves PHP or changes in source code. Token seems like a good option but I'm unable to find a token to render the main menu.

Thanks for the help in advance!

There is no way to achieve that without coding, you have to create your own module, which will create this token (implementing hook_token_info and hook_tokens) - see example here - http://www.taggartjensen.com/code-snip/drupal-7-create-custom-token-module.

EDIT: I created a simple module out of this - Token Menu Render.


How can I programmatically remove the file from a managed_file form element? I have a form where users upload images.  When an image is submitted it is validated against various criteria.  If the validation fails the user is returned to the form but the failed file is still showing in the file upload element with the remove button.

I have been trying to find a way (with no success so far) to automatically remove the file if it fails validation so the user does not have to do it.

It doesn't bother me but the client has requested it so I need to do it somehow.

Any ideas?

hook_field_widget_form_alter(&$element, &$form_state, $context)

this may help you to validate your file and if validation criteria fails return empty form element.


Flag Module: "Never Flagged" Status Flag Module is a very effective module for tagging entities which -  apparently - only handles two status: "flagged" and "unflagged", while  I need now to know if an entity was even been flagged before. So, 3 status:

"never flagged"
"flagged"
"unflagged"

Which solution have we today in order to see if an entity has ever been flagged?

IMO there is a solution without custom coding ... Below is a synopsis (to avoid writing a manual ...) of how to get this to work ...

Step 1:

Create an additional flag, let's label it like "Ever flagged with FlagX" (whereas 'FlagX' reflects the flag for which you want to know if the entity was ever flagged).

Step 2:

Use the Rules module to create a rule like so:

Rules Event: After entity (=node or user) is flagged with FlagX
Rules Action: Flag an entity (= node or user), with parameter the flag "Ever flagged with FlagX"

Here is a sample of such rule (in Rules export format, adapt the machine name of both flags to fit your needs prior to importing it in your own site), for a flag used for flagging an entity of type "user":

{ "rules_set_the_ever_flagged_with_flagx_flag" : {
    "LABEL" : "Set the ever flagged with FlagX flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_flagx" : [] },
    "DO" : [
      { "flag_flaguser" : {
          "flag" : "ever_flagged_with_flagx ",
          "user" : [ "flagged-user" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3:

"To know if an entity was ever been flagged before" (as in your question), all you need to do now is to check for the entities that have been flagged with the "Ever flagged with FlagX" flag. Obviously, it should be straight forward to use the Views module to create an appropriate list of those entities (like users) for which the "Ever flagged with FlagX" flag is not yet set ... which would then be the actual answer to your question, i.e. the entities (like users) which were "Never flagged with FlagX".


drupal_get_path function for third party PHP includes files I am trying to add some PHP includes files into Drupal 7 site. The files are on this page - https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/connecting_to_the_api_using_php.htm under the "Required PHP Includes" heading. It looks like I need these files: soap-wsse.php, exacttarget_soap_client.php, xmlseclibs.php in my Drupal install.

I will need to use the require('exacttarget_soap_client.php') function in a Drupal custom module.

My question is where to place these files in the file structure of Drupal and what would be the $type using drupal_get_path() function? Should I be using the Libraries API instead?

drupal_get_path() returns the path of a module, a theme, a theme engine, or a profile. It's not for loading a generic PHP file, for which you need module_load_include() which (despite the name) can be used for a PHP file that can be loaded with require_once.

Supposing you add the soap-wsse.php file in the includes directory of the test_module module, you cal load that file using the following code.

module_load_include('php', 'test_module', 'includes/soap-wsse');


Getting drush to install missing dependencies automatically into libraries How to get drush to automatically install libraries or ignore dependencies?

Trying to automate enabling modules in batch with Drush

c:\2016\sites\all\modules>drush en views_slideshow_cycle -y
Module views_slideshow_cycle doesn't meet the requirements to be         [error]

enabled.
You need to install the jQuery cycle plugin. Create a directory in       [error]

sites/all/libraries called jquery.cycle, and then copy
jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find
the plugin at http://malsup.com/jquery/cycle. (Currently using jQuery
Cycle Library Library required for Views Slideshow Cycle)

c:\2016\sites\all\modules>

It's the module that handles "libraries" dependencies - not Drush. AFAIK you can't force Drush to ignore hook_requirements implemented by the module in (the install file). Some modules, for example Colorbox, provides a Drush command to download the missing libraries dependencies, but it's not automated.


Is it possible to install Drush 9 without using Composer? Is it somehow possible to install Drush 9 without using Composer?

No.
As it says in the docs:

Drush 9 only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

If you don't know how to use composer, you need to learn now, because you'll have serious problems using Drupal without it.


Views Field View - No results behavior I have a view with 2 fields - one is another view, one is a node field. I do not want to display the parent view header when the inner view result set is empty and the node field does not have a value. "Display even if view has no result" is unchecked on the header settings but does not work because the parent view always has a result regardless of the presence of a value.

I am trying to add a PHP filter that checks for both criteria. I am running into the old issue that the $row object only contains node ids, but the $data object does not seem to work here, either. It only contains two properties, the view and the entity type of the attribute (called field_data_field_electronics_description_node_entity_type in this case).

So, this does not work for my filter code because the entity type is always set, even when the value is empty:

if ($row->view != NULL ||
   $data->field_data_field_electronics_description_node_entity_type != "" )
{
   return FALSE;
}
else return TRUE;

This does not work because field_electronics_description always contains the node id, regardless of the presence of a value:

if ($row->view != NULL || $row->field_electronics_description != "" ) {

I don't see anything else in the $data object in devel that I could use. How can I suppress the parent view display?

The answer was - the node fields are not available and you have to reload the node, like so:

$nodef = node_load($data->nid);
$el = $nodef->field_electronics_description[und][0][value];

if ($row->view != NULL ||  $el != NULL) {
   return FALSE;
}
else return TRUE;


What is the recommended way for using PHPUnit? Installing Drupal 9 with the drupal/recommended-project Composer package ships without PHPUnit. Why? (In Drupal 8 it is included. The documentation only tells about Drupal 8.)
Which version of PHPUnit should I use? In this post kiamlaluno answered that Drupal 9 supports PHPUnit 8 at the moment; therefore, I think that version 8.5 is OK, isn't it?
I installed PHPUnit 8.5.8 with composer, but when I try to use it, I get this error.

Class "Symfony\Bridge\PhpUnit\SymfonyTestsListener" does not exist.

This post suggest installing symfony/phpunit-bridge, Composer choose version 5.1, but it didn't work, and I got the same error message. Is this a wrong version for Drupal 9 and PHPUnit 8.5.8?
It solved the issue commenting out the listener class in phpunit.xml. But I'm not shure if this is the right way.

Is there anywhere a documentation/tutorial for the actual official release of drupal to get PHPUnit running the recommended way?

drupal/recommended-project doesn't install PHPUnit, which is instead installed with the drupal/core-dev meta-package. For example, if I wanted to install Drupal 9.0.3, including PHPUnit, I would use the following commands.
composer create-project drupal/recommended-project:^9.0 my-project
cd my-project
composer require 'drupal/core-dev:^9.0'

As said in Starting a Site Using Drupal Composer Project Templates / Adding drupal/core-dev, drupal/core-dev still doesn't depend on drupal/core. Specifying a version of drupal/core-dev is necessary to get a version that matches the Drupal core version you are using.
Also, if you want to install Drush, you need to first install drupal/core-dev and then drush/drush.
As for the PHPUnit version, drupal/core-dev 9.0.3 requires the following packages.

phpspec/prophecy: ^1.7
phpunit/phpunit: ^8.4.1
symfony/phpunit-bridge: ^4.4

Using more recent version for phpunit/phpunit and symfony/phpunit-bridge hasn't been tested, yet.
For Drupal 8.8.0, drupal/core-dev 8.8.0 requires a version of phpunit/phpunit
that matches ^6.5 || ^7, a version of phpspec/prophecy that matches ^1.7, and a version of symfony/phpunit-bridge that matches ^3.4.3.
Even with Drupal 8.8.0, installing PHPUnit after installing Drupal core with drupal/recommended-project requires the same steps I described for Drupal 9.


Scheduler Module crontab job does not publish content When running the Scheduler lightweight cron through crontab, I am getting a message that the lightweight cron has activated and completed in my D8 log, but content is not publishing. When running the lightweight cron through backoffice, items publish correctly. I've checked the cron log to see if the cron is encountering errors, and am seeing no issues. Is there something I am missing in my crontab command that is causing the cron to run but not update publish status on any of the scheduled nodes?

If you use Content Access module, see that issue :
https://www.drupal.org/node/2865787

Enzo


Add [] to the end of the data field.

eg.

    foreach($vals->field_event_date as $fed){
        //notice the []!
        $node->field_date_of_event['und'][]= array(
            'data1' => $fed->data1,
            'data2' => $fed->data2
        )
    }


How to display the variation of a custom display in Twig In my type of product variation, I have 4 different display :

Default
Panier (Cart)
Teaser
Teaser relation

I have created a template for product type and want to display the "Photo" field of the "Teaser" display of the product variation type.

Here is what I put in my template:

{{ product.variation_field_produit_image }}

The problem is that it displays the "Photo" field of the "Default" display.

How to get the "Photo" field of the "Teaser" display?

You can create another template for that specific view mode.

The naming of that template should be commerce-product-variation--product-type--view-mode.html.twig.

So you can create a template called commerce-product-variation--PRODUCTTYPE--teaser.html.twig, and then print the image field from there.


Managing large taxonomy I've got a vocabulary with 700 terms and Views term hierarchy weight field enabled (version 7.x-1.6). When adding or movind a term, it starts to recalculate depths for every term, and the "Computing the weight and depth of each term" screen takes more than 3 minutes in a site that is not in production. Vocabulary is not more than 3 levels deep. Drupal version is 7.44.

I disabled the VTHWF module for comparison, and the processing time for adding /moving terms was cut to a tenth, so I thought "great: disable it, move and create, and then re-enable it!"... BUT the missed terms' depths were not recalculated as the module was reenabled.

Any help possible?
thanks

Firstly it depends on your local environment. 700 Taxonomy terms are not a lot but calculation might be affected if your local environment is not powerfull enough. To mitigate your performance drawbacks take two steps.

Make sure you are using php 7 because it actually has a significant performance increase.
Increase your php memory limit to 128MB. Find the memory_limit variable in php.ini file and add 128MB next to it.

Now in the case of your calculation of depth after re-enabling the module issue I guess the correct path to take is the issue queue of the module itself. Issue Queue


How to display menu in view Block in drupal 7 I am creating a website in which i am trying to display the submenu into view block . how can i do this.

menu is Like

A -B-c

D -E-F

I have to display in block view

like This is view block

B C | E F

this have to display in views block  using view.

If you use Views 3 then install Views Menu Area module, you can show any menu in the views block.

Enable the module
Edit your preferred view
Click "Add" link in header/footer section
Check "Global: Menu area" and click "Add and configure footer" button
Enter label and select the menu you wish to list links from
Click "Apply" button and save the view

also take a look at Menu Views module.


Error on module admin configuration page I cannot find any documentation or similar problem with mine.

Whenever I am trying to go to the configuration page of some installed module like "Pagetitle" module and Add menu links module.

The page is at unformatted layout, doesnt seem to load the css or javascript, and some links in the configuration page are not showing

Here is the screen shot of the configuration page of page title module (I am logged in as administrator).

I dont know whats causing this, I have disabled modules Im not using and updated the core files as well as all installed modules I can not configure the module.

Please any idea to solve this?

This is because the page rendering stopped when an error occurred. By default, Drupal does not display such kind of errors.

Enable your error reporting by temporarily editing your index.php file (normally located in your root directory) directly after the first opening PHP tag to add the following:

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

After you edited the file, run your site and see what error came out.

WSOD is not directly related to this question, but it may be useful for you to tackle down your problem. It will help you to find out invisible errors.


Views sorting by number of values in field I have a content type with an text field with unlimited number of values.

I have a view for that content type and I want to sort it by number of values in that field.

How can I do that in Views?

Enable Aggregation in View settings.
Add Your Multiple Field in Sort Criteria
Select Count as Aggregation Settings
Select Sort Criteria - Asc , Desc

PS: Do not add same field to field list , it will lead to multiple results in the view


Search block not showing if not logged in When I am logged in I can see the the search form block, however when logged out I can not see it, I'm guessing its some sort of user config, but I can't seem to find anything

You have to go to the Administer › User management section, under the search module area, you need to give the necessary permission to the user that needs to see the search form. If you want everyone to view this Search Module check the box corresponding to anonymous and authenticated users.

From https://stackoverflow.com/a/17027332/1795426


Forum lay out problem I'm having some problems with my forum, I messed up my lay out and can't seem to get it back. Reinstalling the Advanced Forum module doesn't help.

Does anyone know how to get my text to the right, in other words next to the red line I drew? Also it doesn't register my 'enter' clicks, so a reply is just plain text without structure.

Thanks

In Chrome right click on the text and choose 'inspect element'. Find the css selector for that element. Then go into the stylesheet for your theme, and add a rule there to add margin-left to the text.

It sounds like it might be a javascript problem if you can't click a certain link. Check javascript errors in the console.


How to set value after the page redirecting? My scenario is set Taxonomy value after the page redirected.

if(($weight === "Above 90") && ($height === 'Above 7.0"')) {
    $form_state['redirect'] = $base_path . '/example/other/redirect-1';
    $term = taxonomy_term_load('371');
    // echo '<pre>'; print_r($term->description); die;
    print render($term->description);
 }

Here, Once the condition is satisfied, its redirecting to the (/example/other/redirect-1)page.  But, the Taxonomy value is not displaying in this page.

I am not sure, whether I am doing in a right way, or Please guide me to solve this issue ?

You need to pass the term_id along with the $form_state['redirect']
like   $form_state['redirect'] = $base_path . '/example/other/redirect-1/?tid='.$term_id;
and
get the term_id in /example/other/redirect-1/ page  write something  like below

 $term_id = $_GET['tid'];
 $term = taxonomy_term_load($term_id);
 print render($term->description);

I am giving you an idea some modification may need on code. You need to check.


Required Fields with unlimited field collection items I have a D7 instance with a field collection called field_professions and associated to a content type with "unlimited" amounts of fields. Within this field collection I have two fields that are required (field_professional_user and field_professions). I also have an unrequired field called field_serving_since. For the sake of testing I made the entire field collection required.

Now, when I have an item entered, I can enter a 2nd, 3rd etc. item, but whether I fill out all 3 fields, 1 of the required fields, or the unrequired and none of the required fields, it never validates that the fields are required. I can obviously see the red asterisk, but there is no validation.

I faced This bug in field collection module ( really I didn't find out why they do this :(  ). There is no way to achieve this ( have unlimited and required fields in field collection ).
You just achieve it trickly . (set it unlimited and none-required) . use jquery for validate( checking filled )  fields.

This problem almost accures when you don't want set default value for field .(if you set default by any edit add a waist item  ).


Custom form validation I've created a custom module for populating a database and now I need to apply form validation to this form.

I want a few different validation things to happen.

I want to limit specific entries on the client side IE: only allowing 6 characters being entered etc.
On submit I want to run through validation rules to make sure what was entered is correct. IE: only positive #s etc.

Are there any drupal 7 FAPI fields to validate specifics like this?

I found something like '#element_validate' => array('element_validate_integer_positive'),

Is there a list anywhere of element validations like this? I'm unable to find documentation anywhere :(

I assume you are using Drupal's Form API.

  I want to limit specific entries on the client side IE: only allowing 6 characters being entered etc.

In your element definition, you need to add the HTML attribute maxlength. For example:

$form['your_field_name']['#attributes'] = array('maxlength' => array('6'));

Regarding:

  On submit I want to run through validation rules to make sure what was entered is correct. IE: only positive #s etc.

You can create your own validation function for the form or the element. For example, in your form definition, in the element you want to validate, you need to enter:

$form['your_field_name']['#element_validate'] = array('your_field_name_validate');

In this case, your_field_name_validate is the name of the function that will be invoked when the form is submitted. The function needs to be in the same module as the form definition, or in an include file. See an example here. Pasting:

function my_field_name_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}


How can I restrict a Flat Rate to a single product SKU? Shipping 2.0.
Flat Rate is $4.95.
I only want to offer this one Flat Rate I created to product SKU= 146

The place I am confused is in editing Conditions. What do I set the "Data Selector" to? Everything else makes sense to me but the Data Selector.

It really depends on the context of the event. If that event is receiving an order by default, then your conditions either need to be based on the order (such as "Order contains a particular product") or you'd need to loop over commerce-order:commerce-line-items and evaluate line item based conditions via custom Rules components.

I'd give that condition I mention above a shot before trying anything more complicated, though.


How to print only certain block of content in a view I have a view that displays shipping details that you print and put on a box before shipping. But using Print module when you click the link it gives entire page to print with all the headers, footers and menus. I need only that block of text rendered by a view.

Also I couldn't make the Print module link appear in a view even though it claims it works, so I had to use View Footer Area and add some PHP to make link work.

<?php $current_url = getenv('REQUEST_URI'); ?>

<a href='/print<?php print $current_url; ?>'>Print

But like I said it prints entire page and I need only view content.

I would look at this as most a front-end styling problem. Basically, you need to add print-only style rules that hide all the page elements you don't need. You can do this via an inline media query:

<style>
@media print {
  /* @TODO: Add other selectors that remove page elements
  header, footer, .my-custom-class, #my-custom-id {
    display: none;
  }
}
</style>

Or a better, more portable, method is to just attach a custom print CSS stylesheet to whatever view that needs to be altered for printing:

drupal_add_css(drupal_get_path('theme', 'MYTHEME').'/css/print-page.css', array('media' => 'print'));


How do I add a date field that can be filtered by a relative value? If I create a view, I can add a filter that filters on a relative value on some built-in date field, such as Post date.  For instance, the screenshot below shows a filter I've created that will show articles posted in the last four days.

Unfortunately, there is no date field type in core.  To get a date field type, you can install the Date module.  This allows you to create nice widgets for inputting dates.  However, I've found no way to filter the date fields created by the date module by a relative value (like the filter shown above for Post date).  There are Is equal to and Is not equal to operators, but no greater than operator, in the "Configure filter criterion" screen.

I believe that this should be possible, as is also evident from Nigel Waters's upvoted answer to this question: view to show content with future date. However, the exact steps one must take to reproduce the result shown in the upvoted answer eludes me.

I've found the solution. (Doh!)

It turns out that there is a module named Date Views that comes as part of the Date package.  If you enable this, the filter criterion screen changes, and you can use relative operators.


Is it possible to automatically delete image files that have been uploaded when a node is not saved? I'm using Drupal 7.  On my site, users can add pictures via a content type, Pictures, that makes use of the core image field.

If a user uploads an image file and saves the node, then if the node is deleted the image file will be deleted as well.

However, if a user uploads an image file and then leaves the page, the image file remains stored in the filesystem and is not deleted.  This means that if users are careless, it is possible for them to add lots of pictures that will never be seen and never be deleted, wasting lots of disk space.

Is there any way to automatically delete these "orphan" files?

That would be difficult to accomplish automatically, since as you pointed out, these nodes / profiles are not saved and therefore the data isn't loaded into Drupal 7's file management table. Drupal 7 will automatically delete all files it is tracking in the file management table when the node is deleted.

Another way to approach this then is to try and detect any files in your target folder (ex. 'files/') that do not have a corresponding data entry in the database and then delete those. Here is a script from Caribbean New Media that does just this task (and even cleans up image styles):

  The script will scan through your chosen directory (and
  subdirectories), for every file found, it will endeavour to
  cross-reference that file within your chosen table.
       If the file doesn't exist in the tables, it will delete the original file and all it's generated image style files you have
  defined.

Definitely should be carefully configured and tested in a safe development environment before moving to your production site, but once running correctly, you can set this up in a cron job to at least have it run every few days / week to clean up orphaned uploads.


How do I integrate Google Adsense? How do I integrate Google Adsense? I have installed the Google Adsense module but when I insert the publisher ID, it says I have to insert an ID similar to pub-9999999999999, but Google gave me an ID similar to ca-pub-9999999999999.

Is there a way to resolve this?

In the issue queue of the Google AdSense integration module your problem is reported: Support current CSE code

You could try to create a patch using the suggested information, test it and report back in the issue queue.


Is there a module to track future revisions of published content in Drupal 6? I need to track a future revision of a published node that can be reviewed, edited, and eventually published over the currently published revision of the node.

The idea is that you have a page that is published and public but you are able to start making edits on a copy of the published page that are not visible to the public. When you are ready you can then publish this revision over the published, public one.

This feature is provided by the (excellent looking) Workbench module. However, Workbench is only for Drupal 7. Is there a Drupal 6 module that provides this future revision support?

In D6, you can do this with Revisioning and Rules.  You may also need to throw views, etc. into the mix.

Revisioning provides the ability to add pending revisions to content types.  You can set it so that you are tracking only one pending revision per node or you can even track revisions of pending revisions.  Revisioning provides actions and events to rules so you can make your own workflow.  It's not as easy to set up as the Workbench module, but I've implemented a similar workflow with these two modules.

There's also the Workflow module but I don't have any experience using it.


Custom search_api query for categories block A site I am building has products that are indexed with search_api + facetapi + search_api_solr.

One of the indexed fields is a (hierarchical) taxonomy term reference. In case this is relevant, I am indexing the "parents all" version of this field.

On the frontpage I want to show some kind of "doormat navigation" showing the most important categories. Something similar for the footer. And for the sidebar maybe.

What I found so far is this article, Display facets on non-search pages

I am not really happy with the options there, and would much rather do a solution with custom code, where I have full control on everything.

The missing part is how to do the search_api query?
I need a search_api or SOLR query that returns a list of category ids, each with the number of indexed products for this category.

How would I build such a query?

The following code does what we need.

  /**
   * @return int[]
   */
  function getCountsByTid($indexName, $facetFieldName) {

    $options = [];
    $options['search_api_facets'][$facetFieldName] = [
      'field' => $facetFieldName,
      // No limit.
      'limit' => -1,
      'operator' => 'and',
      'min_count' => '1',
      'missing' => '0',
    ];

    $q = search_api_query($indexName, $options);
    $q->range(0, 0);
    $q->fields([]);

    // Skip hook_search_api_query_alter().
    $result = $q->getIndex()->server()->search($q);

    if (!isset($result['search_api_facets'][$facetFieldName])) {
      return [];
    }

    $countsByTid = [];
    foreach ($result['search_api_facets'][$facetFieldName] as $item) {
      // The tid comes in a weird format.
      $tid = (int)substr($item['filter'], 1, -1);
      $count = $item['count'];
      $countsByTid[$tid] = $count;
    }

    return $countsByTid;
  }

Normally, the $options['search_api_facets'] would be set in search_api_facetapi_search_api_query_alter(). However, this adds ALL facets, instead of just a specific facet. Also it limits the number of facet counts to 50. See #12132878: search_api_facetapi pollutes and slows all queries

Instead we set this option manually, and then skip the $q->execute() that would trigger hook_search_api_query_alter().

SearchApiService classes always add quotes around the search values, which seems quite pointless to me.

We could get the raw tids from $result['search_api_solr_response']->facet_counts->facet_fields->$propkey, with $propkey = 'im_' . str_replace(':', '$', $facetFieldName), but this only applies to search_api_solr.


PHP Extension gd disabled I know this question is floating out there in the forums, but so far all of the answers I've come across over the weekend have been unable to resolve this issue.

I'm working on an Amazon LAMP server (Non-Ubuntu) and have been trying to enable the GD extension so that I may install Drupal 7 on my new AWS site.

The page installation process is producing the following error:

[X] PHP extensions Disabled: Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information): gd

Here's what I know from my PHPInfo page: http://ec2-54-173-231-195.compute-1.amazonaws.com/info.php

I've gone ahead and run my scripts to install the gd script which I'm produced with the following result:

Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main/latest|2.1 kB 00:00
amzn-updates/latest | 2.3 kB 00:00
No package php5-gd available
Error: Nothing to do

I have also restarted my httpd and mysqld in efforts to restart the system and have my machine honor any restart needed to launch my extension recognition.

Any thoughts are appreciated.

Thanks!

The issue was actually due to I was running php 5.5.*. The following code resolved my issue for any who come across it themselves.

To discover if you too are running over that version type the following:

php -v

Once you've determined your running PHP 5.5.* type the following:

sudo yum install php55-gd

sudo service httpd restart
sudo service mysqld restart

That should resolve your issue.


Ubercart file downloads - group user's file downloads by product Setting up a site using Drupal 6 and Ubercart (UC) to sell video downloads. I've configured UC as required to sell the file downloads and that all works. However, when a user visits their profile and views their file downloads, I need that page to display files on a per product grouping.

For example, a customer purchases product A, which includes three files. They then purchase product B, which includes two files. I need the user file downloads page to display the five files in two groups, Product A files and Product B files.

I solved this issue with a combination of:

Advanced profile
Views
Node access

I used the Node Access module to create products that were nodes. Only users that had purchased a particular node could see it.

I used Views to create a view that displayed all nodes of the relevant type, including the files attached to them, in a table. The view will only display items that the user viewing it has permissions to see (i.e. those that they have purchased).

I used Advanced Profile to create a new profile page that displayed the view outlined above.


How echo a date field in php I am trying to call a custom date field to use in a text pane from a node to use as YYYY-mm-dd in:

yyyy-mm-dd

I have tried to use:

<?php echo date('Y-m-d', strtotime($node->field_custom_date['und'][0]['value']));?>

but this is not working.  I have tied to just print the php but get a result of 1970-01-01 instead of the date in the field.

What am I missing?

Check format_date() function. We can also pass timezone from date field (if any). For example on how to use this function check Formatting the way the date/time is displayed.

$custom_date = strtotime($node->field_custom_date['und'][0]['value']);
echo format_date($custom_date, 'custom', 'D j M Y');


User Not be Sent to Front Page after Submitting Contact Form After submitting contact form (on contact page), the user automatically is sent (redirected) to front page. How can I avoid it? (user remain on contact page)

Thanks

You can use form_state['redirect'] in your form alter,

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == ''contact_us_form) {
      $form_state['redirect'] = array('contact/us');
  }
}


Exposing Related Content filter I have a content type for publications that has a Related Content field for authors (which is another content type). I would like to create a view with exposed filters, where site visitors could browse or search publications by authors.

I created a page view that displays all publications and tried adding a filter [Content: Related content (exposed)]. It works, however I need to enter author's ID rather than name. Is there any way to make the search by related content title rather than ID?

Thank you in advance!

The way to achieve that was adding a relationship for the referenced entity (authors in my case). As a result, all the fields from the referenced entity become available in the current content type.

After adding a relationship, I created and exposed filter for author's name and in the "Relationship" drop-down in the filter settings selected the newly created relationship.


Altering fields before rendering: hook or template? I have made some recent posts about Drupal 8 and its paradigm for altering fields. Having spent many hours reading up on APIs and some trial and error, I have come to the conclusion that I am really not sure how to proceed with certain basic tasks, such as altering a field.

So the point of this post is to see how one should go about a task such as altering a field.

First, let me describe exactly what I am trying to do. I would like to edit a field before it is rendered. It is an image field. So all I need to do is alter the target_id of the field that points to the image. I want this to happen in every view, display, etc.

Some thoughts:

Overriding via templates: I don't think this makes sense. Seems a template gets a render array, and that one would want to alter the array before the theme does its thing. Also, I want to be able to switch out themes, so this approach is non-ideal
Rewriting field in Views: since I want the fields to be altered regardless of whether it is Views, Display Suite, etc, this would not make sense
Module hooks: I think this is what I need to do, but the info online on Drupal 8 is fairly sparse. For instance, I found out by trial and error that mymodule_preprocess_field will not get called if the field is being shown by Views. The Views hooks won't make sense because as I mentioned I need to alter a field regardless of Views.

So this takes me to 3. You can see Drupal 8 hooks here. At first I was trying to use hook_preprocess_HOOK, and in my case mymodule_preprocess_field. But as mentioned above that was not getting called in Views displays. Then I thought about mymodule_preprocess, but deciphering its $variables array is proving daunting, and the more I read about Drupal 8, the more I am convinced that this probably is not really in the spirit of Drupal 8.

The field specific hooks don't seem to be a match, for instance, hook_field_info_alter seems like it is for altering meta data.

So finally, I came to the conclusion that with Drupal 8 being so Entities focused, I probably need to look at an entity hook. For instance one of the following:

hook_entity_prepare_view
hook_ENTITY_TYPE_view
hook_ENTITY_TYPE_view_alter
hook_entity_view

But coming to this conclusion, a) I am not sure it is the right conclusion, and b) if it is the right conclusion, how to choose one of the above and how to actually implement it? (Note, using dsm(), debug() in Drupal 8 often results in results that are not very decipherable since so many array elements are protected.)

Anyway, I am curious how others would go about this!

EDIT: The above entity hooks are not called for taxonomy page... So I guess that takes me back to hook_preprocess which seems to be the only way to alter the field in all cases. But still trying to decode the $variables array and figure out the right methods/functions to make changes.

Thanks

You can configure views in many ways and the hooks, that are called, will change accordingly.

You can easily debug this, if you put a "catch all" hook into your module and print out the hooks that are called:

function mymodule_preprocess(&$variables, $hook) {
   echo "$hook
\n";
}

Then your page will be full of hooks, that are called at different places and you can try to narrow it down to the hook you need.

The next step would be to install devel and enable kint and debug the variables of the hooks, that you are interested in:

function mymodule_preprocess(&$variables, $hook) {
   if ( $hook == 'views_view_grid' ) {
      kint($variables);
   }
}


How to overwrite a view template from within a module? Till now I only used the theme folder to overwrite specific view templates. In order to be able to separate code from theming and bundle functionality I would like to put this view template into a custom module using features.

I guess there won't be a direct way to do this in features itself but that wont be the main problem here.

You can define the views template path directly within your module (following assumes views 2.x):

/**
 * Implementation of hook_views_api().
 */
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'api' => 2.0,
    'path' => $path,
    'template path' => $path . '/templates',
  );
}

Check out the API documentation built into views for adding templates into your module: http:///help/views/api-default-views (<-- requires advanced help module)


Get field types of a content type I am using Drupal 8.4.
I am trying to dynamically create/update field data for a content type.

Is there a way to get the type of a field (e.g. text, image, file upload) for a content type?

You can obtain the field type using Entity field manager.

$definitions = \Drupal::service('entity_field.manager')
  ->getFieldStorageDefinitions('node');

$field_type = $definitions['field_image']->getType();


What bundle and entity_type do I use in field_create_instance to add a field to a taxonomy vocab? I have a vocab with the machine_name = the_bundle. This is my call to field_create_instance:

field_create_instance(array(
  'field_name' => 'category',
  'label' => 'Some label',
  'required' => true,
  'widget' => array('type' => 'autocomplete_deluxe_taxonomy'), // I've also tried options_buttons
  'entity_type' => 'taxonomy_vocabulary',
  'bundle' => 'the_bundle'
));

However when I use the drupal UI to manage the fields on the vocabulary, the instance does not exist. I have verified that the field I'm attempting to create an instance of does in fact exist. I'm also not getting any errors when I enable the module.

What am I doing wrong?

The taxonomy module doesn't define any bundle types for taxonomy_vocabulary (see taxonomy_entity_info()) so Drupal's entity/field system assigns it a default one with the same name as the entity type (taxonomy_vocabulary).

field_create_instance(array(
  'field_name' => 'category',
  'label' => 'Some label',
  'required' => true,
  'widget' => array('type' => 'autocomplete_deluxe_taxonomy'), // I've also tried options_buttons
  'entity_type' => 'taxonomy_vocabulary',
  'bundle' => 'taxonomy_vocabulary'
));

I have to ask though, are you absolutely sure you want to add a field to the vocabulary rather than the term entity? I haven't come across many use cases where adding fields to the vocabulary itself is necessary. Drupal doesn't even have a UI to manage the fields (but I guess that could be why you're going this in code!)


Setting up the ideal multiple repository Drupal Site version control with a DVCS I have an upcoming project that will use Drupal, and I've been toying around with repository setup ideas in my head for a bit now and while I've come up with a wishlist, I don't know how to actually set up a source control repository this way. While I'm using Drupal for this, hopefully this setup could be extensible to other CMS systems.

Ideally, I'd be using Mercurial/Kiln since that's what my shop uses, but I'd rather have an ideal workflow than use that particular too.

Here are the features I think are important

Drupal core should be a working copy from their repository, so that I can update it easily
Site specific configuration will be exported from the Drupal DB to files using Features/Strongarm, so the repository should have a sub repository that controls all of the configuration that is not part of Drupal Core
Part of this project might involve writing custom modules. These should also have a separate repository or sub-repository so that they can be managed without interfering with site-specific configuration
I'd like to avoid storing code from Drupal Core in my own VCS, since it's already managed by the initial checkout used for item 1.

Is there some combination of ignore settings, submodules/subrepositories, or other configurations that can yield a setup like this? If not, what are my best alternatives? Or perhaps am I approaching the problem wrong, and there is some well-known workflow that solves these kinds of problems?

A general workflow when it comes to Drupal is to clone the core repository and use it as the base for your local repository. Then, you'd create a separate branch specifically for your custom site, so as not to disturb the core branches.

Next, you'd add each module you'd want to use as a submodule off of this branch: this allows you to track specific versions of modules while still having the flexibility to easily upgrade them in the future.

Then, you'd set up an exclusion plan for user-generated content and your settings file. Generally, this would include:

sites/SITENAME/files
sites/SITENAME/settings.php

Finally, when you want to upgrade third-party content:

With core, you'd pull the latest changes and rebase your custom branch
With contrib, you'd navigate to the specific module's directory, pull the latest changes, and commit the new submodule hash to your custom branch.

The problem is, this works really, really well... if you use git. As Drupal has standardized on git, it's just a matter of linking to the correct drupal.org repositories and pulling when necessary.

If you're using a different VCS, submodules aren't really going to help unless you want to spend the time to convert each and every drupal.org repo for the modules you're using to whatever VCS you want to use. That's a lot of work, especially for a one-off project.

Alternatively, you could follow the above workflow, but instead of setting up a repo for each and every contrib module, you could set up one private repository called contrib, and manually add updates to contrib there. This way, you can keep contrib code separate, but you spare yourself having to maintain potentially dozens of custom repositories that do nothing other than duplicate drupal.org repositories.


Can I put batch api callbacks in an include file? I have a .module file that is getting quite lengthy, and I added some batch functionality to it. I put the form and batch callbacks in a separate .inc file, and added the appropriate file directive to the menu array.

I was able to get the form submission to work, but the batch api threw the error Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_my_batch_callback' not found or invalid function name in _batch_process(). I got this error until I moved the batch callbacks into the .module file.

Is it possible to put the batch callbacks into a separate include file? Or have I just done something wrong?

Actually, there is a file directive in the batch array. I found it was necessary to include drupal_get_path to fully reference the file's path.

'file' => drupal_get_path('module', 'MY_MODULE') . '/includes/my-batch.inc'


How do I print only 2 menu links? I want to print the menu items as follows.

Menu1   Menu 2    Menu3     More
                            Menu4
                            Menu5

I am getting them as in the following screenshot.

The More menu should contain only Menu 4 link. I created these menu links from the administrative pages.

I printed the menus using the following code.

$menutopleft = menu_navigation_links('menu-top-left-menu');
print_r(theme('links__menu-top-left-menu', array('links' => $menutopleft)));

Try this from admin panel. Create hierarchical menu for this. See the screenshots


Added a new field to user profile, how do I set a value for existing users? I have added a new field to the user profile on my site (i.e. in /admin/config/people/accounts/fields), a boolean value that can be either 0 or 1. Existing users have no value. How can I easily set a value for all existing users?

Use Views Bulk Operations Module to update field values

  This module augments Views by allowing bulk operations to be executed
  on the displayed rows. It does so by showing a checkbox in front of
  each node, and adding a select box containing operations that can be
  applied.

Create a view of type users
Add Bulk operations: User field and choose Modify entity values checkbox to select your boolean field


How to create a translation and get author and post date copied from the original node When creating translations of news I want them to have the same author and post date as the original node, so that I (or the translator) don't have to copy paste. Anyone know a module or snippet for this?

The Synchronize translations module, part of the Internationalization (i18n) package, allows you to synchronize fields and other node elements.

After enabling it, have a look at admin/structure/types/manage/your-content-type  options, in "synchronize translations", and check the boxes author and post date


Drush alias files aren't being found I'm working locally on my OSX and I have my drush alias files at ~/.drush/[hostname].aliases.drushrpc.php but no matter what project I'm in, only one of the alias files are being read, as confirmed through drush status. Also of note is that my main drushrpc.php file was never in that directory and I don't think it is anywhere.

I've tried clearing drush cache, and also adding a drushrpc.php and adding this php which I'm not entirely sure what it means:

<?php
// ~/.drush/drushrc.php
exec('git rev-parse --show-toplevel 2> /dev/null', $repo);
if (!empty($repo)) {
  $repo = array_shift($repo);
  $options['config'] = $repo . '/.drush/drushrc.php';
  $options['include'] = $repo . '/.drush/commands';
  $options['alias-path'] = $repo . '/.drush';
}

I found that configuration here: http://www.astonishdesign.com/blog/drush-aliases-what-why-and-how

Anyone know how I should proceed?

I have my drush alias files at
  ~/.drush/[hostname].aliases.drushrpc.php
  […]
  But my other [hostname].aliases.drushrpc.php files cannot be found in
  drush status

The filename should be  ~/.drush/[hostname].aliases.drushrc.php. not [hostname].aliases.drushrpc.php: Your filename contains an extra p. See example.aliases.drushrc.php.


Set from e-mail address for new user registration only? In Drupal 7, it's quite easy to change the body of the emails here:

/admin/config/people/accounts

However, it has no place to set the "from" email address. I'm getting lots of spam signups and want the from email address to be "noreply@mysite.com", so as to make any responses get disgarded.

Any idea how to do this? Or even what email address is set for these emails?

You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. Your code would look something like...

function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <noreply@mysite.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.


Generate consecutive number as title using auto_nodetitle? I need that new submissions for an specific content type have a consecutive number as title. Found auto_nodetitle, but I don't know how to make it a consecutive number, they don't give clear instruccions as how to program it. I'm fairly new to Drupal.

If you haven't installed Token module, do so.

From there, you can insert the token [node:nid] into the auto title field. If you don't want to use the nid, you can install the Serial field module, add a field to the content type, and insert that into the title via [node:field_machine_name]. For most purposes, nid should suffice.

You can browse & insert token values via the supplied token browser ui.


Advanced Migration - update nodes I'm a little bit new in Drupal but experienced in PHP.
I would like to migrate data from CSV and assign to existing nodes in DB.

My question is about the possibility to match processing rows with existing data from the database.
I mean, I have CSV file with data and with foreign key called: SERVICE_ACTION and now I would like to assign that data to existing NODE which hasn’t SERVICE_ACTION key but has different KEY which is assigned to another specific entity with Service Action key. How can I get ID of that entity in migration script to assign?

Perhaps, I need target_id to assign newly created paragraph to the specific node. I’m not sure what I’m working bad.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - xxx_migration
      - paragraphs
id: xxx_release_notes
migration_tags:
  - custom-migrate
  - soap-apis
migration_group: xxx_soap_api
label: 'xxx release notes'
source:
  plugin: csv
  data_fetcher_plugin: file
  path: modules/custom/xxx_migration/artifacts/releases_notes.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: 'Unique Id'
    -
      title: Title
    -
      body: 'Post body'
    -
      service_action_code: 'Service Action Code'
process:
  type:
    plugin: default_value
    default_value: people
  field_service_action_code:
    plugin: migration_lookup
    migration: xxx_release_notes
    source: service_action_code
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: release_note
migration_dependencies:
  required: {  }
optional: {  }

here is my CSV file:

id,title,body,service_action_code
1,TITLE,example body,PassengerDetailsRQ
2,TITLE2,example body2,ePaymentRQ

I don't know the exact answer. But maybe this information can get you on the right track.
First the migration process has the ability to update earlier migrated entities, it does this with the help of high-water-marks and timestamps (see Drupal's documentation). Maybe you can do a trick to use this feature. Furthermore there is a lot of good documentation about the migration-process, I recommend this site, an extensive tutorial about the process in 31(!) steps/days, https://understanddrupal.com/31-days-of-migrations or https://www.phase2technology.com/blog/migration-making-it-all-work. Behind it some of the "Drupalstars" from the migration and comprehensibly written. Hope you find your answer there.


Practical solution to get an overview of input formats in use I'd like to clean up unused text formats on some D7 sites. So I need to know which formats are not used. I tried using VBO for this, but there is no field Content: Text format I can add there.

What's a good way to get an overview of formats in use? I'd be ok with using drush for this and I can settle with just knowing the nodes and blocks that use a specific format (ignoring other places like views headers).

I'm not looking for a generic answer like "it's stored in these and these database tables". I'm looking for a practical solution that I can use on many Drupal sites.

This is stored on a per-field basis.

Take a look at your database,  any field_data_*  table.  In those tables, the field_X_format column will contain the input format.


how to use public:// in page content As content author creates a page, she wants to have something like . Is it possible? the goal is to avoid hard-coded drupal installation path; that is she doesn't want to have  on test site and  on production site.

you can use one of this function

file_create_url($uri);

or

image_style_url($style_name, $path)


Add images to blog with ImageField? Using drupal 5.x.  I have a content type I created called "Blog Entry"  it has no fields other than the standard title and body.  Now I want to be able to place images at arbitrary points in the body of the blog entry and have them appear.  I already have ImageField and ImageCache installed for use with another content type.  Is there a way I can use those two modules to achieve my goal or do I need to install something like the Image module?

I found this article which describes one method of doing this.  Looks promising not sure if it's the best way.   For one I'm not immediately sure how to handle multiple images.  How To: Inline Images with ImageField and ImageCache using HTML

UPDATE

Yes I can confirm this works.  You can use a single ImageField and check the "Multiple values" checkbox when creating the image field to support multiple images.  I named my field "blog_images".  Then on the "Display Fields" tab I set the label, teaser, and Full values to all be "<hidden>"


How to make a change that affect several site at once? We have two Drupal 7 and two Drupal 8 website for an airline company. We want the staff at the airport to upload a flight schedule in such a way that it will get displayed in all the four sites at once. How can I achieve this?

You should be able to do this by uploading the schedule to one site and then exposing an RSS feed for the other sites to pull it down.


How to get submitted values on $formstate['values'] instead of $formstate['input']? I was generating a simple form with below fields, but i am wandering why my field values are not storing in the $formstate['values'], but its in the $formstate['input'].. please have look into below code and correct me if i am doing something wrong.

function create_entry_form($form, &$form_state){
    $form['entry']['password'] = array(
      '#type' => 'password',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 15,
    );

    $form['entry']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('OK'),
      '#weight' => 100,
    );
    $form['entry']['emailid'] = array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' => '',
      '#maxlength' => 25,
    );

    $form['entry']['reqbtn'] = array(
      '#type' => 'button',
      '#value' => t('Request'),
      '#weight' => 106,
      '#executes_submit_callback' => TRUE,
      '#submit' => array('request_site_password'),
      '#limit_validation_errors' => array(),
    );

  return $form;
}
function request_site_password($form, &$form_state) {
    echo '<pre>';print_r($form_state);exit;
  }

If you want to get $formstate['values'] or $form_state['input'] values .You have to write like below.

    function create_entry_form($form, &$form_state){
        $form['entry']['password'] = array(
          '#type' => 'password',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 15,
        );

        $form['entry']['submit'] = array(
          '#type' => 'submit',
          '#value' => t('OK'),
          '#weight' => 100,
        );
        $form['entry']['emailid'] = array(
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 25,
        );

        $form['entry']['reqbtn'] = array(
          '#type' => 'submit',
          '#value' => t('Request'),
          '#weight' => 106,
          '#submit' => array('request_site_password'),
          );

      return $form;
    }
   function request_site_password(&$form, &$form_state) {
    drupal_set_message('<pre>' . print_r($form_state['input'], TRUE) . '</pre>');
  }

You missed '&$form' in this function request_site_password(&$form, &$form_state)


CCK counterpart for user's profiles? Im looking for a module that allow to add fields to users profiles, with the same functionality and flexibility of CCK for nodes; I've actually activated the profile module, but the fields type doesnt fit my needs.

For example, i need to have a node reference field on my users (for nodes that they belongs to - follow), but in general, profile's fields doesnt allow multiple values at all..

I've tryed content profile module, i guess will be my last choice, i dont like to have the user profile and the profile node as two separate entities.. and look a bit overlìkill for me.

Any idea?

For Drupal 6, these are the only two options I know of, either use content_profile and use aditional nodes or stick with what profile.module can do.

In Drupal 7 however, users are fieldable, which means that you can attach any field that you can attach to nodes too. Additionally, there is the http://drupal.org/project/profile2 project, which provides something similar to content_profile. However, profiles are in that case not nodes but a custom entity.


How to display $date in node.tpl.php using a preprocess function in template.php I want to check if the node is not a static page, and display $date in "node.tpl.php" within this
:

I currently have this in my node.tpl.php file:

<?php print $date; ?>

I currently have this in my template.php file:

function thebridge_preprocess_node(&$vars) {
  if($vars['type'] != 'static_page') {
  }
}

function thebridge_preprocess_node(&$vars) {
  if($vars['type'] != 'static_page') {
    $vars['date'] = date('Y-m-d');
  }
}

You might want to change the parameters of date(). More information in the Drupal documentation.


I cannot get fields to render in a view fields template I created a view "Blog Listing Cards" [machine name: blog-listing-cards]
I created a views view fields template [views-view-fields--blog-listing-cards.html.twig]
The template is properly 'picked up' and the static content displayed.

However, any time I try to print a field in the template, whether a Drupal default or custom field, it doesn't render in the browser.

The syntax seems correct when compared to documentation, other templates, and others with the same issue.

Examples of code not rendering

{{ fields.created.content }}

{{ fields.title.content }}

What am I missing?! Sorry, I'm a Drupal 7 guy re-learning in Drupal 8.    Thanks in advance  :-)

The problem is because those fields are hidden in the view and {{field.<field-name>.content}} will be empty.


Is there a way to disallow the node/* path for anonymous users? The reason of my question is that I have built a one-page website, but if people who knows a bit of drupal patterns wants to try to request the site by editing the url with a path like domain.tld/node/12 (for ex.), they will be redirected to the clean url and it will work, but this behavior is not intended and the theming customized in a way which is not made for direct requests on nodes.
Apart from the one-page, all the other content is in views and blocks, with a few colorbox links to open one content type in detail.
What I want to do is find a way to disallow node/* requests in path, just to "keep some control" of the way anonymous users visit the site (and potentially test it).

I have tested internal nodes which gives a partial answer, but it disallows all node's requests in colorbox.

I tried path rules but same issue as internal nodes.

Any idea to help me?

You can give permission to particular node using hook_permission().

function your_module_name_permission() {
  return array(
    'access your modulename module' => array(
      'title' => t('Access your modulename module'),
      'description' => t('Allows access to your modulename module'),
      'restrict access' => TRUE
    ),
  );
}

and then go to permission section under people menu. and uncheck above created permission for anonymous user.


How can I get a list of the patches I submitted for issues on drupal.org? How can I get a list of the patches I submitted for issues on drupal.org?

I can see the list of my posts, but I need only those with a patch.

If you contributed patches, they will be credited to you. In that case, on your profile, you will see the ones credited to you in the past 3 months. In my case, I see the following.

Keep in mind that sometimes you participate in an issue without contributing patches, and you get credited for participating.

Unfortunately, there isn't a page with all the credited issues for all the projects, but if you have a list of the projects to which you contributed patches, you can get the list of the credited issues for that project by looking at https://www.drupal.org/u/<username>/issue-credits/<project-id>, where <username> is the username on drupal.org (in my case, kiamlaluno) and <project-id> is the ID for the project (for example, 3060 for Drupal core). So, if I would want to look to all the patched I submitted for Drupal core, I would look at https://www.drupal.org/u/kiamlaluno/issue-credits/3060.

It seems that the list of credited patches has been created on 2015, so you would not get any credited patch before that year.


Display block on certain page I want to display a block on the user/* page. I checked "only the listed pages" and entered "user/" but the block also appears on "user//relationships" for example.

How can I keep the block on just the first path?

If you want more control on this, you can choose the option "Pages on which this PHP code returns TRUE (experts only)" and you can write the following similar code snippet the the box.

<?php
if( arg(0) == 'user' /* && you may add more conditions here by checking arg(1), arg(2) */) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

The alternative way is to check the path with regular expression:

<?php
if( preg_match('/^user\/[[:digit:]]$/', current_path()) ) {
    return TRUE; // will display the block
}
return FALSE; // will not display the block
?>

This will show your block only at the path user/*.


Unable to login into admin after theme change I am new to Drupal and to understand the basics I created a new theme in Drupal and enabled it as default. It works fine, however, I am not being able to log in into admin. I reinstalled Drupal and the admin login works fine. When the default theme is enabled it works, but it doesn't work when my custom theme is enabled.
My .info file is -
name = My First Custom Theme
description = A custom them to understand how Drupal works
core = 7.x

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

regions[header] = Header
regions[content] = Content
regions[menu] = Menu
regions[left_sidebar] = Left Side Bar
regions[main_content] = Main Content
regions[footer] = Footer

And my tpl.php file is -

    <?php print render($page['header']); ?>

    <?php print render($page['menu']); ?>

            <?php print render($page['left_sidebar']); ?>

            <?php print render($page['main_content']); ?>

    <?php print render($page['footer']); ?>

I tried accessing admin page using following ways but without success -

http://www.mysite.com/user
http://www.mysite.com/?q=user

Any idea where I am going wrong ?

To quote you, it sounds like the answer to your question is you needed to:

  ...include <?php print render($page['content']); ?> in my tpl.php file.
  ...the drupal login form wasn't appearing on my site since no default
  region was specified.


How do I display a view pane with all items of a category? I created an Events content type.
I created a vocabulary that has two category terms, Events and Plays.

I have a view that contains a list of all content of type Events.

Each Events listing displays with the category term as the title/link.

The link should go to a page that has a content pane containing a list of all of the Events with that tag.

So, the view looks something like,

Movie (term)

movieName

movieTime

Play (term)

movieName

movieTime

Movie (term)

movieName

movieTime

Play (term)

movieName

movieTime

Movie (term)

movieName

movieTime

The term field is configured to be a link.

If I click on Movie or Play I want to go to a page that has a content pane containing a list of all of the Events tagged with Play or Movie, depending on which I clicked.

On the view, I set up a Contextual filter:

Content: Has taxonomy term ID

I set up a Relationship:

Content: Taxonomy terms on node

How can I set up this view so that clicking on the category will take me to another page with a view/content pane that displays a list of Events based on that tag?

First you will need to have the views page that displays all the Events for the tag you want, then it should be a matter to rewrite the Link field to output as a link that point to that page you had created.

FOR THE PAGE:

Create the page using views that will filter all Events with category Terror
In the URL make it the exact TERM you will have in the list you need, i.e. www.yourwebsite.com/TERROR
Save

FOR THE LIST:

Create the block/page view you need with the list
You need to add the field TERM again (it should appear twice, one above the other, rearrange if not).
In the first TERM FIELD check the box for Exclude from display
On the second one, go to Rewrite Results > Output this field as a link, check that box
In the text field that appears, enter the replacement pattern for the first TERM FIELD, something like [field_term].

That will render your TERM as a link to the TERM page, that will contain all the events for that term.
If not, place a link so I can help you.


"Undefined index: und" Error fetching array in node form I am facing this error in node form when I going to be print title of the body field.
Error:

  Notice: Undefined index: und in include() (line 4 of C:\wamp\www\drupalapi\themes\bartik\article-node-form.tpl.php).

I need to print the title of the body field, and my code looks like:

print $form['und']['#title'];

And shortly, the array is:

Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-text-with-summary
                [1] => field-name-body
                [2] => field-widget-text-textarea-with-summary
            )

    )

[#weight] => -4
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#theme] => field_multiple_value_form
        [#field_name] => body
        [#cardinality] => 1
        [#title] => Body
        [#required] => 0
        [#description] =>
        [#prefix] =>
[#suffix] =>

        [#max_delta] => 0
        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

        [#language] => und
        [#field_parents] => Array
            (
            )

What i am missing in my code to print the title of the body field. Thanks

To get usable markup of the field in template you need to render it before print.

print drupal_render_children($form['title']);

As explained here Theming Node Forms in Drupal 7

Additionally make sure you also render the hidden parts of the form to keep track of form identity related to system. If you wish to exlude some parts of the form, do something like this.

hide($form['field_body']);
print drupal_render_children($form);

This way drupal "render api?" can be aware of what has allready been rendered, what needs to be hidden and finally push out all required parts to make form functional.


How to add custom language specified text? I'm using multilingual feature in D7.

Let's say...I have a word 'standard' that I like to use in other languages.

Where do I put the word and how do I load it in my templates?

You can set the translations for each specified language in the strings settings part of the internationalization module: /admin/config/regional/i18n_translation

To show it in a template file you simply use the t() function to wrap your text - which translates text for you and automatically adds new text defined in the t() function to the strings page.

See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

If you are hardcoding links with your text you can use l(), so if you have say a text link and want the text to be translated you would use l() and in it define your text using t() - something like this:  http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7 for its usage.


Modify output on a page created with the View module I'm pretty new to Drupal and I'm also pretty sure this is a noob question.

I'm trying to build my theme, and in particular I'm trying to manipulate node output to the page, before using the View I simply implemented myTheme_preprocess_page hook and got the content doing $nodes = $variables['page']['content']['system_main']['nodes'];. From that I made all the needed modification.

Now, I want to order the node using the modification date (or whatever parameter) and the View module seems to do just what I want. The problem is now that in my preprocess_page hook I don't have an array of nodes, but all the markup coming from the node.tpl.php file (with missing field of course, because I haven't had the chance to make modification to the output), e.g. insted of $variables['page']['content']['system_main']['nodes'] I have $variables['page']['content']['system_main']['main']['#markup'].

What am I missing? Shouldn't the preprocess_page function return the nodes fro the database (as it did without using View) instead of the markup? Is there another hook I don't know about that allows me to do my preprocessing stuff?

If you want to access modify date and render data so you can use hook_views_pre_render(&$view) $view->result to access result nodes.

and you want to change query condition the you can use hook_views_query_alter(&$view, &$query)


Where should one add the js file (D7) to be attached to the custom theme's template.php file I have js file which needs to be attached to template.php file.
Can I directly add the js file in template.php file ?
I am using drupal_add_js() but
should I add it inside the functions of template.php
or
should I add it directly into template.php file
I have the code in d6 which has added the drupal_add_js() in template.php file
without including it in any of the functions?

Quick example of use in your theme's template.php

function MYTHEME_preprocess_page(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

Reference : https://api.drupal.org/comment/14344#comment-14344


Custom Password validation on Drupal 7 form I am using the Drupal Form API for a customized Login System. It has the password field which needs to be validated. We have a custom criteria of Uppercase, Lowercase, numeric and special characters to validate the password.

The one way I see is to write the RegEx inside the Validate function. Is there an alternate way in Drupal to do this via an existing function or module?

(I am aware that the Webform Validation Module can do this for the webforms.)

Thanks.

Please check Password Policy module. It will satisfy all your above requirements (Uppercase, Lowercase, numeric and special characters).


How to easily display a 12 by 12 matrix of input field for integers? I am still very new to Drupal. I need to let users create nodes to enter 12 by 12 matrix of numbers on one screen block. I don't really know where to start regarding displaying those fields (i.e. layout).

Is there a module/functionality helping defining the layout of those 144 input field in a square shape in Drupal? Some kind of WYSIWIG layout editor? Or, should I try to position those input fields with Javascript within a block?

Thanks.

Might be worth trying CCK table field or Table Field

Both seem to do a very similar function, I would give them both a try on a local dev environment


Pathauto taxonomy terms in content paths I'm using pathauto and want to set it up so that when a new page is created (which has the taxonomy field) it will add the taxonomy terms into the url. For example, if I have the following vocabulary:

Page Categories

About
Articles

When I create a page called 'My Page', and select 'About' as the taxonomical term, I would like the url to be http://example.com/about/my-page.

I've messed around with the URL Aliases settings page but 'Taxonomy term paths' does not apply to Basic pages.

I've looked everywhere for this and I'm going crazy.

You are looking under the wrong section. You want to look at 'node paths' in the path auto settings. Under that section you need to put '/[term-raw]/[title-raw]' for content of type 'Page'.

Install token module as well


Where can you change the #type of a checkbox? I have content type with a taxonomy attached to it (since it is Drupal 8, it ends up being an Entity Reference field).  The form is configured to render out this field input as checkboxes.

I have run into a situation where I need to change some of the checkboxes into plain text when the form is rendered (node create, note edit etc).  I tried to push a #process function onto the field,

function MYMODULE_form_node_job_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['field_foo']['widget']['#process'][] = 'MYMODULE_foo';
}

function MYMODULE_foo(&$element, FormStateInterface $form_state, &$complete_form) {
  // do stuff
}

but when I inspect the $element with XDebug, the #options haven't been processed yet.

So, where in the form / render pipeline can this be changed?

Beside preprocess you can add code to the rendering of form elements in #pre_render, #theme, #theme_wrappers and #post_render. Part of the rendering pipeline of checkboxes is for example CompositeFormElementTrait::preRenderCompositeFormElement:

  public static function preRenderCompositeFormElement($element) {
    // Set the element's title attribute to show #title as a tooltip, if needed.
    if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
      $element['#attributes']['title'] = $element['#title'];
      if (!empty($element['#required'])) {
        // Append an indication that this field is required.
        $element['#attributes']['title'] .= ' (' . t('Required') . ')';
      }
    }

    if (isset($element['#title']) || isset($element['#description'])) {
      // @see #type 'fieldgroup'
      $element['#attributes']['id'] = $element['#id'] . '--wrapper';
      $element['#theme_wrappers'][] = 'fieldset';
      $element['#attributes']['class'][] = 'fieldgroup';
      $element['#attributes']['class'][] = 'form-composite';
    }
    return $element;


How can I add field to the view? I have created a view, which displays different content types. I have added some fields for dispalying (image, title, description). The issue for me is that not every node has an image. When it doesnt have the Drupal renders only title and description. How can I force adding image field for all nodes, even when it doesnt exist?

In my css I am using an :empty selector to add default background image.

In the view configuration settings for the Image field, there is a "No Results Behavior" section that allows html text input:

You can add some html code like:

<img src="/sites/default/files/no-results.jpg" alt="Description">

to add an anchor image that only displays in the View if there are no Image files attached to the node field.


How to set Drush sql-sync not to clone users between @dev and @staging? As I wrote in my previous question,
I am using the following drush commands to synchronize development and staging environments.

drush rsync @dev @staging
drush sql-sync @dev @staging

How to set up drush sql-sync not to clone users between @dev and @staging environments?
I would like to have separate users (and passwords) on @dev and on @staging sites.

The drush sql-sync has an option --skip-tables-key that allows you drushrc.php to skip tables during the synchronization.

In your drushrc.php you add this line.

$options['skip-tables']['staging'] = array('users', 'users_roles', 'roles', 'permission');

Your drush command line should look like the following.

drush sql-sync --skip-tables-key=staging @dev @staging

You've to be careful, as you've to skip all tables that had informations related to your users, including the tables used from third modules.


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

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

In my opinion if you can create a subdomain dl.example.com then you can also redirect all requests to default/files subfolder using symbolic link in /home/domains/dl.example.com/ linking to /home/domains/example.com/sites/default/files/
depending on your .htaccess or httpd.conf setup.

Please note I don't think this is a Drupal-specific question, I am not an expert on this and you'd better asked on https://serverfault.com/

I think using this method will be faster then creating a custom module to do this for you because the method I explained doesn't even require loading Drupal for the request handling.


Apache Solr: get list of "More Like This" nodes programmatically I'm using apachesolr module and it's "More Like This" block.

This block displays only titles of similar nodes as links to these nodes. I need to display rendered nodes with specific view mode. How can I do this programmatically?

Here is the solution that I came up with.

function mymodule_similar_nodes($node) {
  if (module_exists('apachesolr_search')) {
    $output = '';
    $env_id = 'solr'; // machine name of solr server
    $delta = 'mlt-002'; // "More Like This" block delta
    $block = apachesolr_search_mlt_block_load($delta);
    $solr = apachesolr_get_solr($env_id);
    $context['search_type'] = 'apachesolr_search_mlt';
    $context['block_id'] = $delta;
    $docs = apachesolr_search_mlt_suggestions($block, apachesolr_document_id($node->nid), $solr, $context);
    $view_mode = 'teaser'; // view mode, e.g. 'full', 'teaser'...
    foreach ($docs as $doc) {
      if ($doc->entity_type == 'node') {
        $similar_node = node_load($doc->entity_id);
        $similar_node = node_view($similar_node, $view_mode);
        $output .= drupal_render($similar_node);
      }
    }
    return $output;
  }
}


CSS-tags added using Display suite on products disappears Using Display Suite to format output of entity product from Drupal Commerce. HTML- and CSS-tags added by "Expert" formatting tend to disappear when products are viewed using display-nodes. In this case its a image-field with n-number of images that I'm trying to display in a horizontal row instead of stack them vertical. I'm using fancybox as display widget and want to change the behaivor with "float: left; position: relative;". Drupal 7.

The dialog for entering the extra tags are displayed both in product-type view and node-type view when administer fields. It does not matter if I do the formatting at product-type-level or node-type.

When adding the same formatting with a non commerce node-type it works as I suppose it should.

Are there a better way to accomplish horizontal rows with thumnails and displaying full size-pictures using fanzybox when presenting commerce products?

I have been using lightbox2, but it seems to be a bug when combining it with Drupal Commerce.

I am not trying to do any grid nor gallery, but have had success with Colorbox.
http://drupal.org/node/1230232 for info on enabling it.


Conditional Views exposed filters So, I have a view that has multiple exposed filters.  If someone selects one of the filter options, I need the rest of the exposed filters options to change dependent on what was selected in the first.
For example three of the filters are: instruction, video duration, learning level.

If a specific instructor is selected, the video duration and learning levels should change to shown only the videos of that instructor. (These are not based on taxonomy.)

I am using Drupal 6 and Views 6.x-2.

Here is one module that I found that will do this work for me. Views hacks, selective views Filters: Views Selective Exposed Filters.


Adding multiple checkbox in drupal using cck I am trying to add multiple checkbox. My requirement is how can you travel the place with

Plane
Train
Bus
Ship

One can select all the four above options. For that I added a new field Travel Details , field type Boolean , Widget Check boxes/radio buttons . From Drupal CCK

I made Number of values equal to 4 . But I am getting only two fields, also without their names ! How can I able to make this content type to behave like normal HTML checkboxes with their names ?

A Boolean field/value can only store True or False. What you need is a List (text) field with Check boxes/radio buttons widget.

Then put

Plane
Train
Bus
Ship

in the Allowed Values list.

You can set Number of Values to 4 but I'd set it to Unlimited just in case you add more allowed values and forget to update the number of values.


how to create the pagination for customized portfolio template I will create the portfolio gallery page using custom content types with thumbnail and bigimage  image fields. then i am using the following code for rendering content types

<?php
$content_type = 'websiteportfolio';
$query = new EntityFieldQuery();

$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', $content_type)
->propertyCondition('status', 1)
->pager(9)
->execute();
$nodes = entity_load('node', array_keys($entities['node']));?>

<?php
  $i = 1;
  foreach($nodes as $val=>$key1)

  {

 ?>

<a href=<?='sites/default/files/'. $key1->field_bigimage['und']['0']['filename']; ?> rel="lightbox[portfolio]"  title="<?= 'Portfolio'.$i ?>"><img src=<?='sites/default/files/websiteportfolio/'. $key1->field_images['und']['0']['filename']; ?> alt="<?= 'Portfolio'.$i ?>" />

 <?php
$i++;
}

 ?>

finally i got the 9  thumbnail images in my page and also light box functionality working well.My issue Only show first 9 images I need pagination for showing the remaining images how  can fix this issue..

First things first, that code shouldn't be in the template file; it should be in a preprocess function. The reasons for this have been documented at great length both on this site and the internet in general so I won't go into them here.

You might also find the l() function interesting, as well as theme_image()...API replacements for the custom HTML you're building up.

Other than that, the only thing you're missing is the code to actually render the pager; that would entail adding this to your preprocess function, after the query has been run:

$vars['pager'] = theme('pager');

And in the template file simply outputting it wherever you'd like it:

<?php echo $pager; ?>


Can't show gist code in Drupal blog I'm completely new to Drupal. I've installed Gist Input Filter. In blog, when I write [gist:6351376], as said in the project page, it just shows as it is. Please help.

Go to Home > Administration > Configuration > Content authoring > Text formats. Click Configure next to text format you are using for blog posts, probably Filtered HTML. On the Enabled filters list, check Gist. On the Filter processing order, drag it to the end, or at least to be after Convert URLs into links and Limit allowed HTML tags filters.


$node->form_id doesn't exist? function mymodule_node_insert($node){
    if($node->form_id == 'whatever_node_form'){
        // do stuff
    }
}

Returns an error:
Notice: Undefined property: stdClass::$form_id in mymodule_node_insert() (line 16 of /home/admin/public_html/website.com/sites/all/modules/mystuff/mystull.module).

I can clearly see the array dump of $node that it is indeed an object and it contains form_id. What am I doing wrong?

This code is actually correct. When checking for an object, it's always a good idea to use isset() to make sure the variable exists!

This code was adjusted to the following:

function mymodule_node_insert($node){
  if (isset($node->form_id) && ($node->form_id == 'whatever_node_form')) {
    // do stuff
  }
}


Upgraded Contrib modules & Drupal to 7.14 now SSL doesn't turn green I'm using the latest D7 & securepages. When I took over this website from the previous developer, they had the problem that when they would update "anything" (according to them) it would break the SSL. I didn't believe them, so I cloned the site to a sub domain and updated everything. It still worked. My pages in the shopping cart turned into HTTPS, so everything was good. The only problem is that now the browser address bar doesn't turn green (still HTTPS, though) even though we are paying for an extended validation cert. So now the boss is asking why it doesn't turn green.

I checked the certificate and got the following:

Website: www.[site].com <- this is correct
Owner: This website does not supply ownership information.
Verified by: Not specified

This wouldn't happen prior to the update. What is causing this and how can I fix it?

I was able to get a full SSL connection again. It was one of my images that I manually edited in one of my template files. So now that I have a full SSL connection again, I guess the question has changed slightly to: Why isn't it green? The only thing I notice when checking the cert is that it shows: This website does not supply ownership information.

For anyone else encountering this issue with secure pages: In your settings file, make sure that if you have redirections to www.example.com or example.com, and that you have your $cookie_domain set properly.

I am not sure if it would cause your problem, but Secure Pages requires patches to core.  The two you need are listed on the main project page.  I use 961508-23-32-D7 instead of 961508-21.  I am not 100% sure which version of 471970 I am using (that is just for unit tests, anyway).  Both apply to 7.14, but with some fuzz.


Enable fields in manage display programmatically D7 I have just started to use Drupal and I'm trying to add programmatically field in the .install file.

 $field = array(
   'field_name' => 'title',
   'cardinality' => 1,
   'type' => 'text',
   'settings'    => array(
     'max_length' => 1024,
   ),
 );

 field_create_field($field);

 $instance = array(
   'field_name'  => 'title',
   'label' => $t('Title'),
   'type' => 'text',
   'widget' => array(
     'type'    => 'text_textfield',
     'weight' => 1.0,
    ),
   'display' => array(
     'default' => array(
       'label' => $t('label'),
       'type' => 'text',
      ),
    ),
 );

$instance['entity_type'] = 'node';
$instance['bundle'] = 'mytype';
field_create_instance($instance);

The field is added correctly but it is disabled in the Manage Display. How can I change the region column from 'disabled' to 'content'? I tried to add 'region' => 'content' in the instance array but it is not working and I cannot find a good example or documentation about the problem.

Thanks.

I couldn't find any concrete documentation either. However, I'm going out on a limb here and not 100% certain but, I think you just need to specify a correct formatter and the settings since it works that way in the UI.

$instance = array(
   'field_name'  => 'title',
   'label' => $t('Title'),
   'type' => 'text',
   'widget' => array(
     'type'    => 'text_textfield',
     'weight' => 1.0,
    ),
   'display' => array(
     'default' => array(
       'label' => $t('label'),
       'type' => 'text', // <-- invalid formatter
      ),
    ),
 );

text is not a valid formatter type. It should either be text_default or text_plain or text_trimmed or text_summary_or_trimmed or hidden (which hides the field from display).


Why is the button to install a new module missing in the admin interface? I am new to Drupal and am attempting to install pathauto. But when I click on "extend," I don't have a "install new module" button.

Any suggestions?

You need to enable the core Update Manager module:

  Checks for available updates, and can securely install or update modules and themes via a web interface.

Emphasis mine.

Also make sure the user you're logging in as has the Administer software updates permission granted. If it's user 1, you already have access.


How to query entities/nodes that does not have the field "field_parent" with EntityFieldQuery? I'm using the Entity reference module and want to select all nodes that has no parent defined. I'm trying with:

$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_parent', 'target_id', null, 'IS NULL')
    ->execute();

.. but that does not give anything as the field "field_parent" is missing and not set to NULL. If I use IS NOT NULL I get all nodes that has a parent.

How can I select all nodes that has no parent (or is missing the field "field_parent")?

Thanks to Clive I managed to solve this in the following way:

$query = new EntityFieldQuery();
$children = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'page')
    ->propertyCondition('status', 1)
    ->addTag('filter_no_parent')
    ->execute();

/**
* Implements hook_query_TAG_alter()
*/
function mymodule_query_filter_no_parent_alter(QueryAlterableInterface $query) {
    $query->leftJoin('field_data_field_parent', 'p', 'node.nid = p.entity_id');
    $query->isNull('p.field_parent_target_id');
}

You can't (natively) I'm afraid. An EntityFieldQuery doesn't have support for IS NULL or IS NOT NULL.

There are workarounds, however, essentially by adding a tag to the query and implementing a query alter hook, in which you add the required LEFT JOIN and IS NULL statement.

See EntityFieldQuery does not support isNull or isNotNull for a code example. I've used that code before with good results.


Export Webform submission data into external database I need webform submission data to be inserted into an external sql database.  How would I go about doing this? Would this be a custom module, or be processed in template.php?  I am having trouble understanding how I can capture that data and have it sent over to an external database.

Usually the first step to solving a problem like this in Drupal is finding the right hook.

A quick google search for "webform hooks", and then we pick the hook where we'd have access to the completed webform's data: http://api.lullabot.com/hook_webform_submission_insert/7

The example on that page happens to be exactly what you want to do!