Embedded View Form Ajax not working I have a an embedded view display (type = embed) with an exposed form and pager. Ajax is enabled for the display. The pager reloads the display via ajax, however the form does not. I'm all but certain the form used to trigger an ajax reload, but no longer does, and I'm not sure why.

I have used the viewsreference module, viewfield module, and straight views_embed_view() to embed the display and none produce a display where the form reloads via ajax. I have other sites using all three of these methods and those sites all have properly functioning views with ajax forms.

I have used the "Duplicate this display as Block" option in the views ui, placed the block on a page, and that form does reload via ajax properly.

I have tried different themes, including core themes, and the form still doesn't reload the display via ajax.

As far as I can tell, there's no markup difference between displays where views exposed forms are processed via ajax and those that aren't. (Comparing with another site. It seems that all embed display forms on this site won't filter the view via ajax.)

I don't have any custom code interacting with the views or their forms.

Does anyone have any idea what may cause Drupal views exposed forms to not process via ajax? Or can anyone recommend a way to further debug this?

Thanks @4k4. Your comment started me poking around in ajax_view.js which ultimately led me to the cause. My issue was that my display ids had multiple underscores in a row, e.g. listing__large. If I update the display id to large_listing everything works fine. I guess multiple underscores in a row aren't supported in the display ids, and I'm guessing also with view ids.


Rendering view output into a separate region For the sake of theming, I need to render the output of a view into a separate region. I could create a view block, but this way I lose the ability to pass contextual arguments to it. Any suggestions?

There are a lot of hook for views, you can use hook_views_pre_execute or another one it depends of what you need to do.

See here the list


Undefined property: FieldCollectionItemEntity:: Notice: Undefined property: FieldCollectionItemEntity::$field_wa_thick
  in _get_details() (line 385 of ...../er.module).

  Warning: array_key_exists() expects parameter 2 to be array, null
  given in _get_details()

The error is on the following line:

$wt = ((array_key_exists('und',$li[$li_id]->field_wa_thick))?$li[$li_id]->field_wa_thick['und'][0]['value'] : NULL );

What may be the reason for the following error above??

By allowing only if the value is set the error disappeared.

if (isset($li[$li_id]->field_wa_thick['und']) {
  $wt = $li[$li_id]->field_wa_thick['und'][0]['value'];
}

Also applying the isset if the value is used elsewhere.


Field inside of a Field I need to put a field (field_names) inside of the body of the node.

I read that you could do something like:

<?php print render($content['field_names']); ?>

The above code does not work for me, and just does nothing. Do I need to declare some variable beforehand, or do something else to make the field display? (yes I do have PHP enabled)

What I suggest you do is use Token filter instead of depending on PHP in fields. Tokens look like [node:field_names], and can help you achieve putting one field value inside another.

The php module depends on bad judgement for a reason, so I will skip trying to help you hurt yourself.


Best solution for public shop I want to create a site where users can sell their products.

How best to do this kind of system?

Is it a good idea to use Ubercart or it may be better to use something else?

You have got two options. Ubercart or Drupal commerce With Ubercart you have to do some bits of configuration to get your store ready.

With commerce, you have a basic store setup for you if you use the Commerce kickstart distribution.

  Commerce Kickstart is the quickest way to get up and running with
  Drupal Commerce. It includes the latest versions of Drupal core,
  Drupal Commerce, and the other modules it depends on. It also gives
  you a set of options to create a fully-featured demo store out of the
  box complete with an attractive theme, catalog and search
  configuration, and a custom back office interface.

  Who should use Commerce Kickstart? Anyone who wants to skip weeks of
  configuration to build a commerce site on the Drupal Commerce
  framework.


Modifying CSS class of Menu Block links? The Menu Block offers several hooks to override the markup it generates:

#theme:
  menu_link__menu_block__1
  menu_link__menu_block__main_menu
  menu_link__menu_block
  menu_link__main_menu
  menu_link

However, the variables don't seem to be passed by ref, and if I don't return any string, the links render out null. So, what should I do if I want to just append a custom class to the links and then render them just the default way?

I tried something like in template.php:

function MYTHEME_menu_link__menu_block($variables){
  $variables['element']['#attributes']['class'][] = 'my-class';
  return theme('menu_link__menu_block', $variables['element']['#original_link']);
}

but it causes fatal error.

Any help please?

You would need to copy the whole function. There is a good example on the theme_menu_link() page.

You could also check out the Menu attributes module which allows you to add classes to individual menu items.


How to stop the script drush if previous command failed? Any idea how can I tell the script/drush to stop when the previous command failed?

Ex:

#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0

drush vset preprocess_css 0
drush vset preprocess_js 0
drush cc all

# Disable Mobile theme
echo "Disabling Mobile theme..."
drush dis --yes mobiletheme

# Disable Zen theme
echo "Disabling Zen..."
drush dis --yes zen

# Running the site to offline mode
echo "Running site in offline mode..."
drush vset --yes site_offline 1

# Deleting node revisions
echo "Deleting node revisions..."
drush delete-revisions -y

echo "Clearing all the caches..."
drush cc all

# Rename duplicate files
echo "Renaming duplicate files..."
drush rename-duplicate-files

drush pm-uninstall publication_date -y
drush pm-uninstall date -y
drush pm-uninstall custom_pagers -y
drush pm-uninstall custom_breadcrumbs -y

I want something like this:

#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0
if [ ! success ]; then
  echo "The command failed to execute."
  exit
fi

Checkout the run_cmd function in this file: base_functions, which wraps any command and terminates the script if it fails.

You should also be able to do something like:

drush cc all || exit;

where exit will only run if the previous command fails, and you could replace exit with a call to a function that outputs a more meaningful error message. You may also add a number between 1 and 255 after exit to have your script emit an exit status that can be used further using $? in any other script calling this one.


Group sub sub theme CSS separately I have a base, sub theme, and sub sub theme. I don't want the sub sub themes CSS to be grouped to CSS_THEME due to support for legacy IE browsers and the issues associated with large CSS files.

$value['group'] = 100 = CSS_THEME = (Theme-Layer CSS)
$value['group'] = 0 = CSS_DEFAULT = (Module-Layer CSS)
$value['group'] = -100 = CSS_SYSTEM = (System-Layer CSS)

Possible to add to this with a different weighting?

$value['group'] = 200 = CSS_SUB_THEME = (Sub Theme-Layer CSS)

Adding CSS to separate group.

  // Add sub sub theme css to separate group.
  drupal_add_css(PATH_TO_THEME/sub_sub_theme.css',
    array(
      'group' => CSS_SUB_THEME,
    )
  );

NOTE: not looking for related answers to legacy IE browser limitations as solutions such as css_splitter are already in place, simply can the above be done or is there a good reason you can't.

May not be the answer you're looking for but have you considered Advanced CSS/JS Aggregation as one of the features is "Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation)"


Trusted Host Settings Not enabled In the settings.php file if the site, I added the following line.

$settings['trusted_host_patterns'] = array(
  '^www\.example\.com$',
);

I'm using Drupal 8.2.6.

Do I need to add the proxy address too, or my IP? It is a single domain.

Every entry in the array contains a RegEx. So you must escape the dot too.

$settings['trusted_host_patterns'] = array( '^www\.example\.com$' );

This will match the exact the host "www.example.com".


What is the best-practice for managing Aegir sites in Git? I know there is a million ways this could be done, I'm more looking for the "best-practice" of how this "should" be done.

I have an Aegir setup with 4 different Drupal platforms.
Within each platform there are several Sites.
There is also modules/themes in the "all" directory that are shard between the sites.

How would one one manage these platforms/sites in Git?

Should we create 1 repo for the entire "platforms" folder?
A repo for each platform folder?
A repo for each platform folder and a repo for each site?
A repo for each site and a repo for each "all" site?

What would be the best practice for this?

thanks!

Here's the recommended way for Barracuda/Aegir by Omega8:

  The recommended (and also more advanced) way to manage your Sites code
  is to use Makefiles (and then Drush Make) to build your Platforms,
  apply patches to contrib or custom modules etc, then using Profiler
  module to create your custom Installation Profile and manage in your
  Git repo just your Makefiles, your Installation Profiles and only your
  custom modules and patches – in a separate repo per module and per
  theme.

Source: http://omega8.cc/managing-your-code-in-the-aegir-style-110.


Auto remove white background and add alpha channel to images? I use Drupal 7.41 and created a "customers" view. This view get's nodes from the content-type (also called) "customers".

When I add images, some of them contain white background that conflicts with the sites gray-brick background; Is there a way to automatically make all uploaded images' white background removed and added an alpha channel so there won't be such a conflict?

Note: I can do that process manually with GIMP\Photoshop but looking for a module that does that automatically.

Thanks.

I think you will need something like https://www.drupal.org/project/imagecache_actions if this is in fact not a CSS border added to the image. I would definitely check that first but the above module does do some alpha blending and you can also run your own PHP/GD code during an image cache action so if they don't include it you can find code that does and run that code to perform the change.

You could also put a border around the image with CSS that would separate the image from the site background to solve something like that.


How can I hide fields by user role when viewing a node? I have managed to hide certain fields for certain roles programmatically in Drupal 8 using function module_name_form_node_form_alter(array &$form, FormStateInterface &$form_state, $form_id).

The matter is that what I managed to hide such fields in the "Edit" tab, but I would also like to do the same in the "View" tab. What I intend to do is to hide certain fields depending on their machine name and the role of the user logged.

Do any of you know which hook should I use for that?

OK, this code seems to be the solution:

/**
 * Implements hook_entity_field_access().
 */
function MYMODULE_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Field\FieldItemListInterface $items = NULL) {
  if ($field_definition->getName() == 'NAME_OF_THE_FIELD' && $operation == 'view') {
    return \Drupal\Core\Access\AccessResult::forbidden();
  }
  else {
    return \Drupal\Core\Access\AccessResult::neutral();
  }
}


After registration, store email address and redirect to to another page I have this code working:

function custom_form_alter(&$form, &$form_state,$form_id) {
switch ($form_id) {
case 'user_register_form':
      $form['#submit'][] = 'custom_user_register_submit';
  break;
}
}

function custom_user_register_submit($form, &$form_state) {
$form_state['redirect'] = 'content/welcome';
}

This is working great no problems.

The node I'm redirecting to has a typical welcome message.  Part of the message has:  Your verification has been sent to (user's email address).

How do I get the registration email address for the welcome message?

I've created a custom template for the content/welcome node.  Just not sure what to do from here.

In your submit handler, you could use drupal_set_message to set the message like this:

function custom_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'content/welcome';
  drupal_set_message('Your mail is @mail', array('@mail' => $form_state['user']->mail));
}

You could also save it in the $_SESSION if you don't want to use drupal_set_message and get it from there.


How change views exposed filter drop down format? I'm working on a D7 site where I am trying to implement a simple view of a custom content type. I want to have a drop-down select list of taxonomy terms to be able to filter the content by. At the moment, I just seem to have a box with the taxonomy terms in it. They filter the content appropriately when selected, but the UI seems bad to me and I'm not sure how to change it. It has the same UI implementation whether or use Better Exposed Filters or not.

What I'd like to implement is just a scrollable drop down select list but I'm not sure how to go about this.

It appears currently that you have the select box as multi-select. Do you want the user to choose 1+ values or only 1 value? If you want it as a dropdown in the more classic sense, then limit that to one value. BEF would allow you to modify some of the aspects of the select box, as well as allow you choose to use checkboxes instead of a dropdown.


How do I translate hard coded words in twig file Is there a way to translate hard coded words in twig when selecting a language from the language dropdown? I have used the |t ({{ myword|t }}) function but it doesn't seem to be work when selecting another language.

Is there a way to do this?

{{ myword }} is a variable, not a string. You need to use {{ 'myword'|t }} (with quotes)


Get Current Applied Image Style Name How do you get the currently chosen image style name from the field format display option?

I can load an image with a given style with the code below, however, the style name (e.g. thumbnail) is hard-coded.

$imageStyle = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load('thumbnail');

I am hoping to get the selected style name dynamically.

MYMODULE.module:

HOOK_preprocess_menu() {

  $imagePath = getUser()['currentUser']->$imageFieldName
    ->entity->uri->value;

  $imageStyleFormatterValue = ???;

  $imageStyle = \Drupal::entityTypeManager()
    ->getStorage('image_style')
    ->load($imageStyleFormatterValue);

  $imageStyleURL = $imageStyle
    ->buildUrl($imagePath);

  $markup = new TranslatableMarkup(
    '', [
      '@imageStyleURL' => $imageStyleURL,
    ]
  );

}

For my case, $imageStyleURL will be printed as background-image: url();, so I need to build the path in preprocess.

I've tried going through FieldConfig, ->entity, and FieldStorage, but cannot find the image style value stored anywhere.

Field format display options are components of view modes, stored in the config entity EntityViewDisplay.

For example, load the default view mode for the user and extract the configured image style of the user_picture field:

use Drupal\Core\Entity\Entity\EntityViewDisplay;

  $component = EntityViewDisplay::load('user.user.default')->getComponent('user_picture');
  $image_style = $component['settings']['image_style'];


REST Export Views and images alternative text I have a simple REST export View. The View format is set to "Show: Entity".

The content type I am exporting contains a standard image field. My image field settings is set to "Enable Alt field" and "Alt field is required".

Therefore all my nodes that have an image, have an image alternate text (Alt).

In the JSON that my view outputs, there is nowhere that I can find the value of the image alternate text.

For each image, I get the filesize, the filename, the filemime, the uri, etc. etc. but no alt text.

Any idea why? And how could I retrieve it? (other than by replacing the image alt text by a separate field...)

Views Format: Fields

I don't think there is a special separate field in Views UI for the Alt field. Alt text is part of the Image field data, stored with the content entity (not the file).

So what you do is add another Image field to your Views, but configure it this way:

Rewrite results
Override the output of this field with custom text
Check Replacement patterns below to find your Alt token
Enter the replacement pattern into the above Text field {{ field_image__alt }}

Now you have the image Alt text showing as the field output instead of the actual image.

Edit: The above can only help if you're using Fields under your Format settings in Views.

Views Format: Content/Entity

When showing full entities in Views you need to use Content Type/Entity View modes (not to be confused with anything Views related). On your CT add a new View mode on the Manage display page, or adjust the existing one you're using in your Views Format settings.

Custom Image field formatter

This is where you should be able to adjust your Image field Formatter, but unfortunately the Image field doesn't seem to come with the "Alt" text formatter.

Other than creating the custom Formatter yourself you can check out this Issues and module:

Add 'alt' and 'title' tokenized text options for image formatters, and a 'title' option for the generic file formatter
Custom Formatters


Changing the registration form I would like to revise the default new user registration form in Drupal 7.
Rather than to requst "username", I want to request "full name" with helper instructions to enter the text "username is your full name as you would normally use it."

There may be some other minor formatting changes I would like to make as well.

I cannot find an admin menu item to access anything relating to this question. And I am unable to locate a file within any director that has any text that would indicate it is the source for the new user registration form.

I realize this is a bit unconventional, however it is useful for our needs. I am aware of a module that allows the input of First Name / Last Name, but in processing it changes the input to first initial/lastname, ie Tom Thumb = username of "tthumb". The module "Realname Registration" would be just what I am looking for if it would only translate the username the same as the input.

That wouldn't necessarily solve the other formatting edits, but I would be very happy just to be able to manually edit the registration form help text under the username field, instructing the new user to register using thier real name.

Thanks for any help that you can provide.

J.M.

The easiest way is to create a custom module and use hook_form_alter():

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'user_register_form') {
    $form['account']['name']['#title'] = t('Full name');
    // perform other changes here
    // var_dump() or krumo() the contents of $form to see what you can change
  }
}

If you prefer you can also a variation of hook_form_alter to target the form specifically instead of having to do an if

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['name']['#title'] = t('Full name');
  // perform other changes here
}


Why I am not able to add custom validate Handler function for UserPasswordResetForm on form_alter? I am trying to override default reset password functionality by using hook_form_FORM_ID_alter as below:
The below code is written in custom module called usr_registration.module file

    /**
     * Implements hook_form_FORM_ID_alter().
     */
    function usr_registration_form_user_pass_reset_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id, AccountInterface $user = NULL, $expiration_date = NULL, $timestamp = NULL, $hash = NULL) {

            $form['account']['pass'] = [
            '#type' => 'password_confirm',
            '#size' => 25,
            '#description' => t('Provide a password for the new account in both fields.'),
            '#required' => TRUE,];

             $form['#validate'][] = 'usr_registration_validate';
             $form['actions']['submit']['#submit'][] = 'usr_registration_form_user_pass_reset_custom_submit';
    }

    // this function itself is not getting called
    function usr_registration_validate(&$form, FormStateInterface $form_state) {

      //unable to see below debug message and form is getting submitted
       echo "I am here"; exit;

       if($never_login) {
                        //some custom logic
       } else {
                       //some custom logic
       }

     }

The important thing I noticed in UserPasswordResetForm class(user core module's form) is that there is no default validate method defined.
I am unable to find out that why I cant alter the UserPasswordResetForm and custom validate handler over here.

note: My question is similar to this but not exactly same so please dont mark it as redundant.

$form['#validate'] will not work as that form
"This form works by submitting the hash and timestamp to the user.reset"
aka redirects you to the user.reset from

what you can do is something like temp replace this form with a custom one though. however i don't really see the point

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_pass_reset') {
    $action = $form['#action'];
    // Set the original action.
    $form_state->set('original_action', $action);
    // temp replace from with custom one.
    $form = \Drupal::formBuilder()->buildForm('\Drupal\yourmodule\Form\AlterTheLoginResetFrom', $form_state);
    return $form;
  }
}

then do

class AlterTheLoginResetFrom extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'alter_the_login_reset_from';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get the stuff you need from ...
    dump($form_state->get('original_action'));
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      // @TODO: Validate fields.
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // redirect to original as uses get
  }
}

or alter the user.reset directly
see Drupal\user\Form\UserPasswordResetForm; line 60 & 71
and see how core does it (resetPassLogin)
\Drupal\user\Controller\UserController::resetPassLogin

if all else fails perhaps just validate the passwords in js.


How to use admin table theme with multistep form? I have 1000 records of users with name and checkbox. I want to show the list of users in table theme. I have use

theme('table', array('header' => $header, 'rows' => $rows));

But how to use it with multistep form. Please find the below code.

function getForm() {
$form = array();
$step1 = array();

drupal_add_js("
function checkUncheckAll(theElement){
  var theForm = theElement.form, z = 0;
  for(z=0; z<theForm.length;z++){
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = theElement.checked;
    }
  }
}", 'inline');

$step1['user'] = array(
   '#type' => 'container',
   '#tree' => TRUE,
   '#prefix' => '
',
   '#suffix' => '
',
);
$results = db_query("SELECT* FROM {user_token} ut LEFT JOIN {users} u ON u.uid= ut.uid where u.status=1 and u.uid!=0 group by ut.uid ")->fetchAll();

foreach($results as $k=>$result)
{
  $user[$result->uid] = $result->name;
    $defaults = array_keys($user);
}

 $step1['checkall'] = array(
 '#type' => 'checkbox',
 '#title' => t('Select / Unselect all'),
 '#attributes' => array('onclick' => 'checkUncheckAll(this);'),
 '#weight' => -1,
 );

 $step1['user'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Send message to listed users'),
 '#options' => $user,
 //'#default_value' => $defaults,
 '#attributes' => array('class' => array('check_notify_user'))
 );

 $step1['submit']=array(
     '#type'=>'submit',
     '#value'=>t('Next')
 );

$form[] = $step1;

$step2['message'] = array(
  '#type' => 'textarea',
  '#title' => 'Message',
  '#description' => t('No more than 250 words please!'),
  '#wysiwyg' => false,
  '#attributes' => array('maxlength' => 250),
);

$step2['prev'] = array(
  '#type' => 'submit',
  '#value' => t('Previous'),
  '#name' => 'prev',
  '#submit' => array('custom_previous_submit'),
);

$step2['submit']=array(
    '#type'=>'submit',
    '#value'=>t('Submit')
  );

$form[] = $step2;

return $form;

}

I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:

$form['table'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#empty' => 'Empty List - No Entries',
  '#header' => $header,
);

or

$form['table'] = array ('#value' => theme('table', $headers, $rows));

You can use this in multistep form also.

If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:

$form['table'] = array ('#theme' => 'output_table');

$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);

Within 'theme_output_table', generate your $headers and $rows to feed to 'theme_table' by calling 'drupal_render' on the relevant form elements that are children of $form['table'].


how to customize autocomplete TO field in privatemsg module - drupal 6 Using the privatemessage module, users can send messages to each other as in facebook. The page displays a form with a TO field, subject and message. The TO field is an autocomplete field by default. Upon searching for a user name, it shows a drop down with only the names. How can i customize it to show the user's profile picture also in the drop down??? I dont know where to go and make the code changes.

Open privatemsg.module

in hook_menu search for $items['messages/user-name-autocomplete']
this particular menu item  defines that auto complete path.

Search for privatemsg_user_name_autocomplete function where the output defines.

Edit this function. Thats all.
Also Create a patch if youre familiar with patching, so that others c


Organic groups: permissions groupadmin not respected I am having troubles getting organic groups permissions working.

In my grouptype I want to give the groupadmin the permission to edit the group.

  On an OG level:

  admin/config/group/permissions/node/mygrouptype

I have set the permissions to 'Edit group' for administratormember

  On a Global level:

  admin/people/permissions

I have set the permission to Edit 'Mygrouptype'

However still my groupadmins are not able to edit their group. Setting this permission on a groupmember level does give the groupadmin the permission.

What am I missing?

Three steps solved my problem:

1.On admin/config/group/settings i selected a default administrator member

2.and disabled the : 'Strict node access permissions' setting.

On admin/config/group/permissions/node/mycontenttype i disabled the administer group permission.


layout content in columns I'm trying to figure out someway to allow end-users to format page content into columns. Right now if they edit a page they get a title field and a body field which is fine a lot of the time but what if they want to do something like this...

-------------------------------------------------------------------------
| TITLE                                                                 |
|                                                                       |
| Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam      |
| pharetra lorem mollis dui egestas convallis. Nam vitae sapien urna.   |
| Nam quis tellus ligula, non gravida metus.                            |
|                                                                       |
|              HEADER                             HEADER                |
|                                                                       |
|      ----------------------             ----------------------        |
|      |                    |             |                    |        |
|      |                    |             |                    |        |
|      |       image        |             |       image        |        |
|      |                    |             |                    |        |
|      |                    |             |                    |        |
|      ----------------------             ----------------------        |
|                                                                       |
|    Lorem ipsum dolor sit amet,       Aliquam pharetra lorem mollis    |
|    consectetur adipiscing elit.      dui egestas convallis.           |
|                                                                       |
|                                                                       |
| Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam      |
| pharetra lorem mollis dui egestas convallis. Nam vitae sapien urna.   |
| Nam quis tellus ligula, non gravida metus.                            |
|                                                                       |
-------------------------------------------------------------------------

A title followed by a full width paragraph
then two 50% width columns with headers, images, and text
and a full width footer paragraph

This is just an example of what they might want to do. I'm using the WYSIWYG module's ckeditor to edit the page contents. The only way I can think of doing this is either allowing them to inline css in style attributes or using something like panels.

using inline styles and predefined classes might work but it would require the end user to know css. Panels looked good as I could create the layout the way I liked and add custom content (or otherwise customize the page) but I couldn't figure out how to translate the panels page into another language like I can with nodes.

This must be a common situation but I haven't found the solution yet. Anyone have any suggestions?

In a recent project I needed content editors to insert a special div wherever they needed that would float right and have custom styling.

The best solution I came up with was a custom ckeditor plugin. Basically editors just click on the appropriate icon and the necessary html is inserted into the editor. All they have to do is add the content.

Example:

Create a folder inside ckeditors plugin dir and name it
"doublecolumn".
Create a plugin.js file inside that dir.
Add an icon to use for the button inside that dir i.e. "myimage.png.

Then, add the following code in plugin.js:

(function ($) {
CKEDITOR.plugins.add( 'doublecolumn',
{
    init: function( editor )
    {
        editor.addCommand( 'insertDoubleColumn',
            {
                exec : function( editor )
                {
                    editor.insertHtml('

');
                }
            });
        editor.ui.addButton( 'doublecolumn',
        {
            label: 'Double Columns',
            command: 'insertDoubleColumn',
            icon: this.path + 'myimage.png'
        } );
    }
} );
})(jQuery);

I haven't actually tested this but it's similar to what I had used and it should work.

You could also expand the html for each column to something like:

Add Title

add image

add text

In your case it might be better to put the two columns inside a wrapper div - just to be safe.

Don't forget to enable the plugin and add it to your toolbar from admin/config/content/ckeditor.

Hope this helps.


Customize "Access Denied" (403) page for specific content type I'm currently setting up a simple LMS in Drupal 8 and would like to customize the Access Denied page as follows:

Anonymous users should be redirected to the Login page, when they hit a 403 error.
Logged in users trying to access a specific content type (a Course),
which they are not allowed to access, should be redirected to a
custom message (telling them to buy the course or something like
that). It would be even better, if they could be shown the teaser of
that node, but that's not a necessity.
In all other cases, I would like to show a general Access Denied page.

Fwiw, there were similiar questions for D6 here and here that also didn't receive any good replies.

Does anybody happen to know a good solution (for D8)?
Any help would be much appreciated.

You could do that using the rules module.

Create a rule using the Rules module, with as Event something like After visiting node no_access. So that the entire rule configuration would look something like this:

Events: After visiting node no_access

Conditions:
        User has role - Parameter: User: [site:current-user], Roles: anonymous user
        NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login

Actions: Page redirect - Parameter: URL: user/login

And then for the logged in user, you can create another rule that checks if the user is logged in, and then redirects to a custom page if the user visits a no_access page.

For the general access denied page, you can set a url in Admin > Configuration > System > Site information, under error pages.

Hope it helps


form button redirecting to .inc module file I'm building a custom module and I would like to add some buttons that redirect the user to other .inc files on click.

My idea was something like this, in my mymod.user.inc file :

if ($form_state['storage']['step'] === 1) {

 $form['button']['addnew_form'] = array(
    '#type' => 'submit',
    '#value' => 'new form',
    '#submit' => array('mymod_form_user_newform_form'),
            );

$form['button']['addnew_form2'] = array(
    '#type' => 'submit',
    '#value' => 'new form 2',
    '#submit' => array('mymod_form_user_newformtwo_form'),
            );

 return $form;

}

I added a hook_menu in my myform.module file :

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

$items['myform/forms/newform'] = array(
    'title' => 'New form 1',
    'description' => 'New form 1',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymod_form_user_newform_form'),
    'file' => 'myform.newform.inc',
    'access callback' => TRUE
);

When I click on my button, it doesn't redirect to the new form page.
Am I totaly wrong using this method ?

You redirect to a URL, you can't redirect to a PHP include file it's not possible.

The function you give as the #submit key is run on form submission, it's not used to build up the next page request or anything like that.

Your code should look more like this:

$form['button']['addnew_form'] = array(
  '#type' => 'submit',
  '#value' => 'new form',
  '#submit' => array('MYMODULE_form_submit'),
);

Then you'll need a submit handler to match that:

function MYMODULE_form_submit($form, &$form_state) {
  // Redirect to the appropriate URL.
  $form_state['redirect'] = 'myform/forms/newform';
}

You can add a second submit handler for your second button, with a different function name, and that redirects to a new menu item that you need to define which contains the second form.


Make a block from a "part" of a drop down menu I have a D7 site with a drop down menu at the top, the second item across the top is "About Us".  Presently it looks like this, see attached pic.

I want the "contents" of this part of the menu to be a "BLOCK" that I can display on several pages.  How can I do that?

In Drupal menus, the arrangement looks like this, see attached pic:

The menu item "about us" has a URL of "about-us".  I'd like the content of this to show up in a sidebar that I could drop in perhaps as a block or other method.  How can I make a block out of just a "section" of a menu, and yet have this as dynamic content?  I want the users to be able to edit the list of menu links included in "about-us" but not have to manually put the contents of the new links into the sidebar.  I'm thinking of maybe a "view" but I've never made a view of a menu before.

Thanks for the help.

Dave N

I would advise using menu block (https://drupal.org/project/menu_block), which allows blocks to be created from menus. The most important part would probably be starting level and max depth, which allows you to specify the options you'd like to use.

If you'd like an example usage similar to what you're attempting to achieve, just let me know and I'll take some screenshots.


Validation error on back button in Multistep Form Validation errors with a back button on Multistep form.

I used form alter for this but this is also not working below are my code.

function mymodule_form_alter(&$form, &$form_state, $form_id)
{ if($form_id=='dataset_node_form')
{
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

Enable devel module. Then put a dpm to make sure that your code is being called.

function mymodule_form_alter(&$form, &$form_state, $form_id){   if($form_id=='dataset_node_form')
{
 dpm($form, 'From my custom module');
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

If your message shows up then some other module is overriding your form_alter. You can implement hook_module_implements_alter in your custom module to make sure that the form_alter of your module is called last.


Drupal-7 Where can I change the text from Simplenews unsubscription confirm page? I want to edit the message of the simplenews confirmation message when you unsubscribe from a newsletter.
It is the simplenews_confirm_removal_form but I can't track the code, to edit the message and the buttons' text.
Do you know where I can find it?

Sounds as if you need the String Overrides module. From the project page:

  Provides a quick and easy way to replace any text on the site.

This includes messages as well. Here's what you would need to do:

Extract to your sites/all/modules directory.
Enable the module in admin/build/modules.
Configure the access permission in admin/user/permissions.
Visit admin/config/regional/stringoverrides and fill in the strings you'd like to replace. This is the string coming from Simplenews: %user was unsubscribed from the %newsletter mailing list.. Just change it to whatever you would like. You have the %user and %newsletter replacements available.


Emails are not triggering when MIME mail is selected I want to send HTML emails on webfrom submission. Gone through many tutorials as well as Questions on stack but didn't found a proper solution.
I am using three modules to send these HTML mails.

MIME mail,Mail system,SMTP Authentication Support

I had configured all the settings in MAIL system module.
when all the the class are set to MIMEmailsystem_SMTPmailsystem.

Mails are being sent but am not getting "Send e-mail as HTML" option my webform email configuration"

When i am setting "Webform module class" to MIMEmailsystem, "Send e-mail as HTML" is visible but mail are not getting dispatched.

You can change the email template format From Custom Template to Default Template or you can create your own template using place it in templates folder (/sites/all/themes/your-theme-folder/templates) and name it webform-mail-webform-node-id.tpl.php


Drupal 8 Bootstrap Theme Background "transparent" (e.g. offcanvas-lining visible) I have installed the Drupal 8 Bootstrap Theme (version 8.x-3.0-rc2) on a newly setup site. When I logout and view the page everything looks as I would expect it. But while I am logged in when I click on "Back to Site" in the top left corner then I only see a background ofbackground-color: #333 which is being set by a class named .offcanvas-lining. This makes working with the theme almost impossible because the text and headers have the same color and so the text is invisible.

I could probably override that somehow but I would like to understand if this is an issue with the Drupal 8 theme or if I have made a mistake when I setup the theme.

What is this offcanvas-lining element doing and why am I seeing its background rather then the usual white bootstrap background which is the default.

Looks like this was being caused by the "Settings Tray" module which was added in Drupal 8 and which I had activated. Deactivating the module has fixed the issue for me.

It seems other people also have this issue with other themes: https://www.drupal.org/node/2819091


Get path like path/* I'm writing a module and there is a text area where the users have to add paths; then, I explode these paths, and run some commands.

I would like to let users add something like "path/*" (as in context conditions).
Is it possible?

First get a list of all paths, and then check each path.  Here is a quick example, and see drupal_match_path():

<?php
  // $paths would be the value of the textarea,
  //    with path expressions separated by newlines
  $paths = "mypath/*\nmy-page-name\ntopics/cheese*";
  $aliases = db_query("SELECT alias FROM {url_alias}")->fetchCol();

  $matches = array();

  foreach ($aliases as $alias) {
    if (drupal_match_path($alias, $paths)) {
      $matches[] = $alias;
    }
  }

?>


How to pass a form field value from THEME_system_theme_settings_alter() to THEME_form_system_theme_settings_submit() MYTHEME/theme-settings.php: THEME_form_system_theme_settings_alter() builds an input form for /admin/appearance/THEME and the input (values) of the user will not be known by Drupal nor by theme_get_settings() before saving the user given input.

I'm kind of curious how to pass this value to THEME_form_system_theme_settings_submit() in theme-settings.php?

In other words: I need the value from the user input of the theme settings form BEFORE we leave theme-settings.php - Is that possible? Or do I need another way around this?

Test: Let's say the value gets stored in a 'textfield', build by the THEME_form_system_theme_settings_alter() function:

// theme-settings.php
function THEME_form_system_theme_settings_alter(&$form, &$form_state) {
// Test form
$form['whatever_fieldset_group']['user_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Test to get value'),
    '#default_value' => theme_get_setting('user_input'),
    '#description' => t('
         Type some text in textfield
         to get shown in submit message'),
);
}

To test if I can pass that value to THEME_form_system_theme_settings_submit() we try to show the value of this field in a submit message:

// theme-settings.php
function THEME_form_system_theme_settings_submit($form, &$form_state) {

    // the following will not work inside theme-settings.php
    // because value is not known yet by theme_get_setting()
    $data = theme_get_setting('user_input');

    drupal_set_message(
          'For testing purposes we submit that you have
           filled the textfield with the following
           mindless value: '.$data
          );
}

This will not work. Of course. And variable_get() and variabel_set() seems to be no option ether, because we can not fill any variable without knowing the value in theme-settings.php.

The reason for asking this is, I want to write css from user input in a css file while saving theme settings. Maybe there is a way to fire a function after theme-settings got saved? Not sure. Maybe I need more examples of custom themes and how they solved it there without an additional module ...

The answer to the question is quite simple, but not easy to find in the d.o. docs. Thanks to Clive and Jack-PL who gave me the right direction. To reuse the example from the start question we need to summarize:

A form field input value needs to get splitt off (intercepted) from its usual way getting stored for a short moment. Why? For us to do our own processing while submission before theme-settings.php Party is over. Our form field:

// theme-settings.php
function THEME_form_system_theme_settings_alter(&$form, &$form_state) {
// Test form
$form['whatever_fieldset_group']['user_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Test to get value'),
    '#default_value' => theme_get_setting('user_input'),
    '#description' => t('
         Type some text in textfield
         to get shown in submit message'),
);
}

Now the value will get stored when the user hits submit button. But what if we need to get in between before?

Injecting ...

drupal_set_message('<pre>' . print_r($form_state['input'],1));

... in function THEME_form_system_theme_settings_submit for a moment has revealed, that we were looking for $form_state['input']['user_input'], were our fruits are hanging. Searching the value with drupal_set_message('<pre>' . print_r($form_state['input'],1)); gives us orientation to be able to intercept the right value for our own value processing, demonstrated here in a simple representational form with another little drupal_set_message() scenario:

// theme-settings.php
function THEME_form_system_theme_settings_submit($form, &$form_state) {

    // the following will not work inside theme-settings.php
    // because value is not known yet by theme_get_setting()
    // $data = theme_get_setting('user_input');

    // But this works!
    $data = $form_state['input']['user_input'];

    drupal_set_message(
          'For testing purposes we submit that you have
           filled the textfield with the following
           mindless value: '. $data
          );
}

In my case, I was able to save user input into a file now with file_unmanaged_save_data($form_state['input']['user_input'],$filepath); while the user hits submit.

Thanks to Clive and Jack-PL for the fast reply. It helped me a lot!


Install Drupal into a different directory than drupal-vm is installed I installed Drupal Virtual Machine (Drupal VM) from drupalvm.com using vagrant. This worked fine - but I want to install the drupal files into a different directory.

How can I modify the Vagrantfile in order to install drupal and the drupal vm into different directorys (drupal not as a sub diretory of drupal vm). Thank you.

You can override the default configured webroot directories by altering the local_path property in the vagrant_synced_folders array with a custom config.yml file (copy over default.config.yml if you don't have one).

Per default.config.yml:

# A list of synced folders, with the keys 'local_path', 'destination', and
# a 'type' of [nfs|rsync|smb] (leave empty for slow native shares). See
# http://docs.drupalvm.com/en/latest/extras/syncing-folders/ for more info.
vagrant_synced_folders:
  # The first synced folder will be used for the default Drupal installation, if
  # any of the build_* settings are 'true'. By default the folder is set to
  # the drupal-vm folder.
  - local_path: .
    destination: /var/www/drupalvm
    type: nfs
    create: true


menu_tree_all_data returning empty arrays for custom menus I have tried to get the menu tree for two different custom menus using menu_tree_all_data, but they have returned empty arrays, while using it to get 'navigation' menu works.

Does anyone have any idea about what might be going on?

If you are looking to print a menu tree, then it's answered here. I have tried this and solution worked !

<?php

$tree = menu_tree_page_data('menu-name'); // Replace menu-name with menu name you want to print
$first_level = db_query("SELECT mlid FROM {menu_links} where menu_name = 'menu-name' and plid = 0 ORDER BY weight ASC");
while ($item = db_fetch_object($first_level)) {
  $mlid = $item->mlid;
  // Extract subtree
  $subtree = admin_console_menu_get_subtree($tree, $mlid);
  // Render as HTML menu list
  $content .= menu_tree_output($subtree);
}
return $content;
?>

/**
* Extract a specific subtree from a menu tree based on a menu link id (mlid)
*
* @param array $tree
* A menu tree data structure as returned by menu_tree_all_data() or menu_tree_page_data()
* @param int $mlid
* The menu link id of the menu entry for which to return the subtree
* @return array
* The found subtree, or NULL if no entry matched the mlid
*/

function admin_console_menu_get_subtree($tree, $mlid) {
  // Check all top level entries
  foreach ($tree as $key => $element) {
    // Is this the entry we are looking for?
    if ($mlid == $element['link']['mlid']) {
      // Yes, return while keeping the key
      return array($key => $element);
    }
    else {
    // No, recurse to children, if any
      if ($element['below']) {
        $submatch = admin_console_menu_get_subtree($element['below'], $mlid);
        // Found wanted entry within the children?
        if ($submatch) {
          // Yes, return it and stop looking any further
          return $submatch;
        }
      }
   }
}
// No match at all
return NULL;
}


Is there a way show user that the content has been automatically translated? I am using the Translation Management Tool module to translate my nodes automatically. What I want is for users to see whether the node they are seeing (in their language) is the translated, or the original one. I managed to make the translation (when node is saved, it is translated) and with rules I can change value of e.g. some integer field, but it changes on both nodes: original and the translated one.

How can I change it only in translated one?

Instead of setting an integer field, create a text field called original language or source language. Use Rules to store the language code of the source language when the node is created. That way the value of the field is correct regardless of which language the user is viewing the node.

You can then compare the source language of the node with the user's current language and display a message if they do not match.


Can I tell CKeditor to NOT TOUCH my HTML code? I am using the CKeditor module only as an administrator, so I don't need any security protection.

When I add Google Adsense code into a block, CKeditor stripes away the <ins> tag. I am aware of this solution though I rather want CKeditor to not stripe away anything. In other words: I don't want to whitelist any tags, I just want to be sure that nothing gets deleted. Is there a solution for this?

Another way might be: Can I configure the Switch to plain text editor toggle to START with a plain text editor as default, allowing me to Switch to rich text editor?

UPDATE: Some additional info: I'm using the latest version of CKeditor, loaded from: //cdn.ckeditor.com/4.4.3/full-all

The profile in use is "Full HTML". In its settings at ADVANCED CONTENT FILTER "disabled" is checked. In ADVANCED OPTIONS, Custom JavaScript configuration, I have set:

config.fillEmptyBlocks = false;
config.autoParagraph = false;
config.allowedContent = true;

To reproduce the problem, just toggle to plain text, paste the following HTML, toggle to rich text and to plain text again. Only "foo bar" will remain.

foo <ins class="adsbygoogle" style="display:inline-block" ></ins> bar

Even 'Full HTML' does some html tampering - you could try creating a new text format for Admins only without any restriction at all - this is what I usually do for adsense and it has always worked great without the need for another module.


How to check whether a username is in use? I'm currently trying to implement a function to check if a user already exists. I've read that this could be done by Rules whit the condition "Entity exists by property" but I can't find it anywhere. I've tried it with Rules 7.x-2.2 & Rules 7.x-2.3

Is this option still available or not? Or is it located in a other module?

it's related to this question: How can I check whether a username is in use?

Drupal 7 has a function to return a user object by username:

$user = user_load_by_name($name);
if(!$user){
    // User doesn't exist
}
else {
    // User exists
}

function user_load_by_name

And a function to return a user object by email:

function user_load_by_mail


Ajax validation only works when I am logged in as an administrator I have created a custom contact form and I have set up an ajax inline validation. My form works very well. But Ajax validation only works when I am connected. When I am not logged in as an administrator, ajax validation does not work.

Also I created a block to display the form in my footer. This form does not appear when I am logged in as an administrator. When I am connected I have access to the form only through the path I defined in module.routing.yml. And when it appears (so when I'm not logged in and I'm just a visitor), Ajax doesn't work on this block form either.

Does anyone have any idea what could cause this?
Please help me.

These kind of errors often happen when you have not attached the proper library to your form. So one thing to check is if you have $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; in your form's buildForm().


How to access the value of a referenced node's field to use it as a Rules action? I have a content type A that has a node reference to type B.  Type B has an email address field that I would like to use in a Rules Action.  How do I get the value of a referenced node's fields?

Note: After much searching, I tried the steps Link suggested in Rules: Do action on the field of referenced node, but after adding the Entity has Field condition on my node reference field, there are not any replacement patterns like node:node_reference:field_email, just the normal node:field_email.

Try adding a Rules Action (as the very first action) like "Fetch entity by id", which in your case is probably something like node:node_reference:nid.

This should make the data available from the node that is referenced via your node reference field.


How to make a non-Drupal page and where to place it? I need to create a page (it's receipt) which is not drupal-page. How it should work:

User clicks the link in "User Menu" or in "User Profile"
This link is made from link to custom page itself and user's $POST parameters (name and address fields, for example).
This page consists of HTML tags, CCS styles and PHP $POST-parameters and finally creates a PDF (to print).

I know how to make modules and use Hooks (I made custom registration), and I can use Drupal database (normal and fields entries). But how I should realize this task? And where I should place my custom page's file?

You need to create a custom module and implement hook_menu() for you custom page.
Here you get details about hook_menu "https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7".

To get this link on user menu tab use type as
 'type' => MENU_DEFAULT_LOCAL_TASK
And write your page code by calling a function
'page callback' => 'user_details',

create user_details function and write code for custom page.


CCK Migrate filefield to file error I tried using CCK Migrate and this happens and field fails to get migrated, can someone let me know how to read this kind of error:

Requesting rollback of field "field_evt_mat_download" due to failure to convert record:

array ( 'entity_id' => '4715', 'revision_id' => '4742', 'field_evt_mat_download_fid' => '9109', 'field_evt_mat_download_data' => 'a:1:{s:11:"description";s:32:"Presentation (Open as Read Only)";}', 'delta' => '8', 'entity_type' => 'node', 'language' => 'und', 'bundle' => 'event', 'field_evt_mat_download_description' => 'Presentation (Open as Read Only)', 'field_evt_mat_download_display' => '1', )

Cause:

exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://local marketing/event/member-appreciation-october/2012/' for key 'uri'' in D:\xampp\htdocs\aadev\dev7\includes\database\database.inc:2171 Stack trace: #0 D:\xampp\htdocs\aadev\dev7\includes\database\database.inc(2171): PDOStatement->execute(Array) #1

Well I figured out that the field_evt_mat_download is actually in field_data_field_evt_mat_download so I solved the problem myself.


Static variable scope in drupal I have a hook_user_load function where I am loading some extra user info into the $users array.  I am having trouble storing the info in a static array and would appreciate it if someone could let me know what is wrong in the following function:

function mymodule_user_load ($users) {

    static $my_users = array();

    foreach ($users as $uid => $account) {
        // Only handle authenticated users.
        if ($uid > 0) {

            // Have we loaded this user before?
            if (isset($my_users[$uid])) {
                $users[$uid]->info = $my_users[$uid];
            }
            else {
                //Call another function to load user info
                $my_users[$uid] = load_user_info($uid);
                $users[$uid]->info = $my_users[$uid];
            }
        }
    }
}

Basically, the variable $my_users on the first time I load the user profile page, will be an empty array and I have to call the load_user_info() function to fill the array with the info.  If I refresh the user profile page again, this function will run a second time, and the following if (isset($my_users[$uid])) code should evaluate to true and so it won't have to go to the else statement and run the load_user_info() function again.  However, it is not working.  Basically, each time hook_user_load runs, the $my_users variable is empty, meaning it is getting initialized each time.  Isn't a static variable supposed to be only initialized once?

Would appreciate any help on this.  Thanks.

Static variables are initialised once per page build. As soon as you refresh the page you'll lose any vars declared in your page build, including static ones.

If you want to persist data between page loads you need to use session storage


How to pass arguments to a view from Rules? I am trying to use a view which depends on arguments but somehow it seems that the arguments are not passed to the view since I am getting no results. The view works when executed directly.
The rule is triggered by Cron. Does Cron require any special permission to access the view?
Any other ideas on solving this would be much appreciated

Rules is version 7.x-2.10
Views is version 7.x-3.16
Views Bulk Operation is 7.x-3.4+13-dev

{ "rules_send_reminder_1" : {
"LABEL" : "Send Reminder 1",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "Reminder" ],
"REQUIRES" : [ "rules", "views_bulk_operations" ],
"ON" : { "cron" : [] },
"DO" : [
  { "data_calc" : {
      "USING" : { "input_1" : [ "site:current-date" ], "op" : "+", "input_2" : 7776000 },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "drupal_message" : { "message" : "Fetching licenses that expire \u003C [result:value] and with status = 1" } },
  { "views_bulk_operations_action_load_list" : {
      "USING" : { "view" : "licence_reminder|default", "args" : "[result:value]\r\n1" },
      "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-list" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "drupal_message" : { "message" : "Processing licence with id : [list-item:license-id]" } },
        { "component_rules_reminder_1" : { "license" : [ "list-item" ], "status" : "1" } }
      ]
    }
  }
]
}
}

Note:  I am hoping to find users that hold an expiring license, and that have been issued a new invoice which remains unpaid with the view (each user holds a status that indicates if the invoice has been issued and if it is paid or not). Then I will send the user a reminder email.

I think you're making it too complicated. As per the "Any other ideas on solving this would be much appreciated ..." in your question, I'd rather use the Views Rules module (instead of VBO), as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of the users you're interested in. I.e. "those users that hold an expiring license, and that have been issued a new invoice which remains unpaid" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

3. Create a rule using the view of display type 'Rules'
Create a rule with the appropriate Rules Actions in it, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.

4. Use the 'Rules Once per Day' module
Use the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

Easy, no?


New Base URL is not working I have a site "damo1.com" now I want to use my drupal site in "damo.com", so I just change $base_url in sites/default/settings.php. And I still can see my homepage very good, but I cannot check the others views or access to the site as user.

Do I need to do one more step? Thx

In your sites/default/settings.php file, comment the $base_url line, you don't need to specify one, Drupal can do it for you.
In your .htaccess, uncomment RewriteEngine on
In the same file, RewriteBase / must be  also uncommented, and if your website is hosted under a subfolder of your root web folder, you must specify your folder  here. Eg: RewriteBase /subfolder/
Activate clean URL's in admin/config/search/clean-urls
In apache httpd.conf file, check if mod_rewrite is enabled


Is Drupal contact form securely encrypted? In Germany, it is mandatory to by law to use secure contact forms (secured by TLS for example) when you are a website owner. Is the Drupal 7 contact form secure in this regard?

No. No form, in any website, is inherently "secure" or encrypted. If your requirement is to serve and submit the form over TLS, you'll need to set that up on your server/host as a separate task.

Once you have, Drupal will happily serve any page over https, and submit forms in the same manner.

The only thing you might want to consider from a Drupal point of view is to un-comment the lines in the default .htaccess which force-upgrade all requests to https. If your server isn't Apache that'll have to be done elsewhere.


Paypal payments pro integration with drupal 6 I have a drupal 6 website which has the following workflow:

User logs into site.
User creates content through a custom module that I built.
This content is not a content-type, its custom content.
The user saves this content type, but cannot yet publish it.
User then hits publish.
He is asked how long he wants to publish the content for.
User selects from 15 days, 1 month, 2 months etc.
Depending on his selection he is provided a price for publishing the content for the interval.
If the user pays the amount shown, his content is published.
For each content page that he wishes to publish he will be provided the same options of selecting the interval and paying the price for the same.

I have three questions about this:

1: Are there any existing modules that would let me achieve this? (I did search and couldn't find any. My initial instinct was of-course ubercart, ecommerce etc... but I can't figure out how I would implement this specific workflow in any of these.)

2: If there aren't any existing modules for this, how would I integrate Paypal payments pro in my custom module? I can't find a straightforward tutorial anywhere.

3: Is it possible to use the payment backends of any other modules. I know ubecart provides a bunch of different payment methods. Is it possible to use these modules without ubercart and call them in a custom module?

For a quick win on this on Drupal 6 I would use Ubercart, it ships with paypal pro integration. And http://drupal.org/project/scheduler

It uses conditional actions to assign roles, give access to file downloads etc. A simple, if perhaps slightly inelegant way would be to pass the node ID of the unpublished content to a product as an free value attribute, then upon successful purchase use conditional actions to publish it, setting an expiry date time on the object properties scheduler uses before saving the node. You should not give users permissions to use scheduler, and I'm assuming you have cron up and running.

Sounds bodgy, but you could get it up and running very fast like that. Check if you like it and still have time to look at other solutions if not.

Commerce module might also be good but haven't used it on d6


Remove added URLs after link when printing a page I am using the Print module, but the links in the body of my articles are followed by their URL. How can I remove the URL when I am printing a page?

What I have now is some test with some URL (http://www.somewebsite.com/article2) to show, and some more (http://www.somewebsite.com/article8) text to demonstrate.

What I want is some test with some URL to show, and some more text to demonstrate.

I tried changing sites/all/modules/contrib/print/css/print.css without success.

.item-body  {
      a[href]:after { content: none !important; }
     /* img[src]:after { content: none !important; }
      a[href]:after { content: ""; /* hide visible URL after links. */ }
      /* a[href]:after {
      content: " (" attr(href) ")";*/
  }
}

update
The part i want to remove is in bold.
   contributor helping  report. It’s the latest nightmare.some text for the url to be removed (http://url-to-be-removed) then some more text.

a[href]:after { content: none !important; }

update

The CSS :after selector inserts something after the content of each selected element(s).

Use the content property to specify the content to insert. content: none is for explicitly preventing the after selector (pseudo-element) from being generated (really only used to override another style that would have generated content).

a[href]:after { content: none !important; } will mean remove content after each link.


Image widget crop not returning multiple derivatives in JSON API I'm using below modules for image crop

https://www.drupal.org/project/image_widget_crop
https://www.drupal.org/project/cloudinary
https://www.drupal.org/project/consumers
https://www.drupal.org/project/consumer_image_styles
https://www.drupal.org/project/jsonapi

Returning data in JSON API.

Using multiple paragraphs for images. I have 1 image as logo & 1 image as content.

For 1 image it's showing correct image width & height, X & Y co-ordinates (derivatives).

But for multiple image it copy same height, width, x, y co-ordinates to other images.

So it's not showing image wise derivatives for multiple images.

Once image is uploaded it saved to cloudinary.

{
"meta": {
"derivatives": {
"box": "http://res.cloudinary.com/XXX/image/upload/s--CJHoE3mM--/c_crop,h_400,w_400,x_29,y_46/test.jpg?itok=4GARJEFS",
"thumbnail": "http://res.cloudinary.com/XXX/image/upload/s--vlxu-1hL--/c_fit,h_100,w_100/test.jpg?itok=hed-1-Mh",
"wide": "http://res.cloudinary.com/XXX/image/upload/s--4-Vk3FhO--/c_crop,h_200,w_356,x_76,y_86/test.jpg?itok=GOzme5ht"
}
}

Does anyone faced this issue?

You can try the code

use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;

$filed_images = $paragraphs->get('field_image')->getValue();
 $images =[];
 foreach ($filed_images as $image) {
            $images[] = ImageStyle::load('273x273')
              ->buildUrl(File::load($image['target_id'])
                ->getFileUri());
          }


Pages are created for each image The Drupal 7.59 installation we have a new page for each uploaded image in the files directory. (It's been like this at least since Drupal 7.39 when I joined this project.)

If the image is awesome-photo-by-Robin.jpg, we will get www.ourdomain.com/files/awesome-photo-by-robinjpg. (The missing period before the extension is not a typo.)

The problem is that these pages get indexed by search engines, and because they have no content except header, image and footer, they get very low ranking and clutters our SEO results.

Obviously, these are automatically created during the upload process, where you have no possibility to disable or choose this. However, afterwards, one can go through /admin/content/file and edit the file and voilá, some information appears.

Removing the alias doesn't help, since the page remain anyway. (I also cleared the Drupal cache to make sure.)

Can these auto-generated pages be disabled somehow?
If they can't be disabled, we're considering adding Disallow: /files/* to the robots.txt file. Do you think that would work at all to amend this issue, or maybe cause other issues down the road?
What is the actual purpose of these pages?

This is the HTML that's surrounding the IMG tag, maybe it can give you any clues?

Don't think this is to do with core. Do you have the "File entity" module installed by any chance?

There's a permission of "View files" that anonymous users will have ticked in. If you untick that any of those /files/* will get access denied for annon users


Is the homepage considered in_active_trail? I'm learning Drupal 8, so still very new to it. I'm working on customizing the main menu. I've been able to add Twitter Bootstrap to my custom theme.  I've made a custom menu--main.html.twig file.

I'm trying to change the "is-active" class to "active" using what Drupal has available.  I see when I click to my About page that they About link is highlighted with the active link class.  Great!

What I can't seem to figure out is how do I get the Home page to get the active class too?  It looks like it is being treated differently.

I tried adding a new page called Homepage, but that didn't work either.

Here is my twig file, which i took pieces from another theme that use twitter bootstrap to try to compile it together.

{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
    {%
      set classes = [
        menu_level ? 'dropdown-item' : 'nav-item',
        item.is_expanded ? 'menu-item--expanded',
        item.is_collapsed ? 'menu-item--collapsed',
        item.in_active_trail ? 'active',
        item.below ? 'dropdown',
      ]
    %}

      {%
          set link_classes = [
            not menu_level ? 'nav-link',
            item.in_active_trail ? 'active',
            item.below ? 'dropdown-toggle',
            item.url.getOption('attributes').class ? item.url.getOption('attributes').class | join(' '),
          ]
        %}
        {% if item.below %}
          {{ link(item.title, item.url, {'class': link_classes, 'data-toggle': 'dropdown', 'aria-expanded': 'false', 'aria-haspopup': 'true' }) }}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% else %}
          {{ link(item.title, item.url, {'class': link_classes}) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

Update:  I went into Views in my admin panel and edited the Frontpage.  I noticed that it was not assigned to any menus.  I changed that by adding it to the main menu.  Looked at my homepage and the Home link is now highlighted as the active page.

So, what worked is adding it through the view page.  What did not work was adding the homepage from the "menu" screen where you build the menu. Clearly the homepage is treated differently from other pages in the menu and if you add it via the menu panel, it is not considered as part of in_active_trail.  I don't totally understand so I am hoping that someone can explain this to me.

Now, my question is did i do this right?

Update #3
I check my "Home" link in my main navigation.  The original "Home" link says "This link is provided by the Standard module. The title and path cannot be edited."  This link will not add the active class when I use "in_active_trail".

I had manually added a link via the Menu -> Main Navigation -> Add New Link.  I gave it a title called "Homepage" and the link "".  This link did not accept the "active" class either.

From what I can gather, the only way to get it to repsect "in_active_trail" is y using the Views -> Front page and then configure the menu setting.  That did the trick.

As mentioned here, it might be because you are pointing your menu link to "" instead of <front>.

There is also a module called menu by trail path, which might also solve your problem. That module sets the menu item to active if its the page you are currently on.


Multi-site, multiple database and 1 shared database I want to develop drupal multi-site with this structure:

One shared codebase drupal 7 multi-site, each web site has own database.
One master web site that has some tables shared.
Each multi site instances read some tables from master's database, not own database. For example conntent types, fields, views, rules and related configirations read only master's database. So I can develop all sites on one place.

As a result each site must use same content types, views, rules but different contents. I am user 1 of all sites. Sub site editors has create content and user permisions only. I dont want to share users accross sites. So I cant use domain acceess. Is it possible that?

Thanks for your helps.

If your need is

  each site must use same content types, views, rules but different contents

Domain Access is simplest answer:

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

Of course it uses one database, but end-user experience you need is covered.


Is there a good way to inspect objects whose type is derived from the EntityDrupalWrapper class? I'm sure this question applies to other complex object types, but EntityDrupalWrapper is the one I'm currently working with. This is the type of object returned by entity_metadata_wrapper() (and probably others).

When using code like the following:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order_object);
dpm($order_wrapper);

the output from Devel is none too helpful:

It doesn't show what you'd expect to see for a call to dpm() with, for example, a stdClass object.

A similar call to dvm() does print the object, but in a manner I'm not familiar with, and it's not very readable.

I've tried debug() and it produces a PHP user notice that looks something like this:

Incidentally the HTML output contained in that warning is the same output that dvm() prints to the screen.

How can I inspect these types of objects (preferably with Krumo), so I can see what properties are available? Or am I stuck using dvm()?

Use dpm($wrapper->getPropertyInfo());

It's in the docs.


SearchApiException: Unknown or invalid item type node I was working on site, when I got this error:

  WD php: SearchApiException: Unknown or invalid item type node. in
  [error] search_api_get_datasource_controller() (line 1396 of
  /var/www/luken/shop/sites/all/modules/search_api/search_api.module).
  SearchApiException: Unknown or invalid item type node. w
  search_api_get_datasource_controller() (linia 1396 z
  /var/www/luken/shop/sites/all/modules/search_api/search_api.module).
  Drush command terminated abnormally due to an unrecoverable error.
  [error]

Site is telling me about "Unexpected error", the above error I'm getting thanks to the Drush. Last thing that I did, was:

Removing one Product Display content type (I'm using Commerce),
Changing indexed fields in Search API,
Clearing the cache - after that, site was down.

I even don't know where to start with fixing this. I was trying to disable Search API module with Drush, but it appeared that I can't, because I'm getting above error all the time. I can access to /admin/modules but still I cannot disable Search API, because of unexpected error.

What can I do to fix this?

Added:
I deleted my search index, now I was able to disable Search API, but error still appears when entering the site. I checked log, there is an error:

  EntityMetadataWrapperException: Unknown data property
  commerce_product. w EntityStructureWrapper->getPropertyInfo() (linia
  339 z
  /var/www/luken/shop/sites/all/modules/entity/includes/entity.wrapper.inc).

I managed to fix the site with the help of Commerce Repair:

  This module is designed to repair missing fields from various commerce entities. After installing, visit the menu item that does the repair, admin->store->config->Repair Commerce Fields (admin/commerce/config/repair). Once you've done that you can uninstall the module.


Expose a view filter that lists usernames of a specific roll in a roll down menu I have a view on one of my sites that list a table of content that is connected to (entity reference) a user with a specific role.

Is it possible to make an exposed filter that lists all users of role X in a roll down menu?

It is easy , add new filter , choose your field (the field which takes the user) , in filter settings limit users to users in your specific roles (1 or more roles could be selected) and then expose filter with equal operator for user , and user can restrict shown content to a specific user .


Why can't I see the settings for the customfilter module in the Drupal admin? I'm following this tutorial to add a custom filter using the Custom Filter module. I've installed and enabled the module.

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

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

when I try to navigate to /admin/settings/filters like it suggests

I'm not sure where you've seen that, but looking at the code, it's wrong. Maybe you're following a tutorial for a previous version of Drupal.

Either way, the config path for the D7 version is admin/settings/customfilter.


hook_flag_flag() is not working I am working in one of the project using the Flag module. I want to add custom event when user flag any content. I am trying to use hook_flag_flag() but it is not working.
This is the code I am using in a module file.

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Drupal\flag\Plugin\Flag\EntityFlagType;
use Drupal\flag\FlagInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\Core\Session\AccountInterface;

function nppe_custom_flag_flag( $flag, $entity_id, $account, $flagging) {
  drupal_set_message("This is custom message after Flag.");
}

Is there anything I am missing?

To add some custom event on flag/unflag actions in Drupal 8 you need to use Event subscriber:

public static function getSubscribedEvents() {
    $events = [];
    $events[FlagEvents::ENTITY_FLAGGED][] = ['onFlag'];
    $events[FlagEvents::ENTITY_UNFLAGGED][] = ['onUnflag'];
    return $events;
}

And then in onFlag() and onUnflag() methods you can implement your custom logic.

I just wrote a blog post with some code examples: http://dev.studiopresent.com/blog/back-end/perform-actions-flag-unflag-drupal-8


can't find how to use Backup and Migrate module I've installed the module and enabled it.. the brief readme instructs me to go to mysite.com/admin/content/backup_migrate but when I go there I just see the same content as mysite.com/admin/content/ how am I supposed to use this module?

Any idea what might be wrong?

In Drupal 7 it is mysite.com/admin/config/system/backup_migrate


Default tab by date or day I'm building a TV listing and I'm using quicktabs module with tabs:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Every tab shows a node that have a TV listing.

Is it possible these tabs to be shown by date/day?

Example: today is Monday, so when a user enters the page for TV schedule the active tab will be Monday.

I've inspected the tab links and I find out that every tab has additional link to the main URL.

Example: The first tab (in mine case - Monday) has /program?qt-quicktabs_tv_schedule=0#qt-quicktabs_tv_schedule

The second tab (in my case - Tuesday) has /program?qt-quicktabs_tv_schedule=1#qt-quicktabs_tv_schedule

etc.

EDIT:

I've tried this code:

(function($){

$(document).ready(function(){
var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('#quicktabs-tab-quicktabs_tv_schedule-0' + n).parent().addClass('active');

});
})(jQuery);

The removing active class is working, but the days changing based on

var d = new Date();
var n = d.getDay();

it's not working. Maybe I'm missing something...

EDIT 2:

Here's what I've tried:

     (function($){

        $(document).ready(function(){
        var d = new Date();
        var n = d.getDay()-1;
        if ( n == -1) {
        n = 6;
        };

        $(".quicktabs-tabs li").removeClass('active');
        $('#quicktabs-tab-quicktabs_tv_schedule' + n).parent().addClass('active');
        $('.quicktabs-tabpage').addClass('quicktabs-hide');
        $('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

        });

})(jQuery);

With this code it simply hides the default tab.

You can use javascript for this.

Each quicktab "A" tag has an ID something like quicktabs-tab-name-0 (replace name with the quicktab name you have given)

You can use some thing like the below code to get the current day of the week

var d = new Date();
var n = d.getDay();

this would return a number which would be something from 0 to 6 where 0 Represents Sunday and so on.

The active class is set to li tag with in which the a tag is placed.

So first we need to remove the active class from all the li with in quick tab this can be done with

$(".quicktabs-tabs li").removeClass('active');

Next we need to add the active class to the current day's tab for which you could do something like.

$('#quicktabs-tab-name-' + n).parent().addClass('active');
// n is the day number we got from the code above.

Next you need to enable the tab page for the corresponding tab for that you would do the following. The first one would add the hide class to all tab pages and the second code removes the hide class from the current div.

$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

That should do it.

Just make sure that the tabs are arranged form Sunday to Saturday. So that quicktab ids also get the same numbering. If you want a different order then you can offset the number accordingly by adding the offset value and then getting the reminder value of a division by 7.

So in effect the complete code would be

var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('quicktabs-tab-name-' + n).parent().addClass('active');
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

This would go inside the document ready function.


How to display date and time picker for base field on custom entity I've made a base field on a custom entity with type "datetime" using "datetime_default" for the form display. It's displaying as only a date picker, with no time component, whereas I want it to look like this:

If I create a field in the GUI I can select between "date only" or "date and time". (The image above is the result of picking "date and time"). But I can't work out how to do this programmatically. I've tried creating fields of both types and exporting the config, but there is no difference between them, which is a mystery.

I suspect I need to put something other than "datetime_default" but I can't find any documentation on how to programmatically refer to the various date and time widgets.

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);

$fields['activity_date_time'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date and time'))
  ->setDescription('')
  ->setRevisionable(TRUE)
  ->setRequired(TRUE)
  ->setSettings([
    'datetime_type' => 'date'
  ])
  ->setDefaultValueCallback('Drupal\opencase_entities\Entity\OCActivity::currentDateTime')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'datetime_default',
    'settings' => [
      'format_type' => 'medium',
    ],
    'weight' => -3,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => -3,
  ]);

setSettings(['datetime_type' => 'date']) - this seems to be to blame. See the switch in the source here which effectively says if type is 'date' (implemented as a const) then only show the date form element, otherwise show the date + time elements.


Memory requirement of Ubercart? I am setting up a shopping cart for a client and will host the new site on a separate VPS. What is the typical memory required to run a Ubercart site? We are targeting a few thousand users, around a hundred products, and under ten concurrent users.

Drupal 7 requires a minimum of 32MB (see - http://drupal.org/requirements/php) however in reality it will require much more, simple sites with a few contributed modules should be around 96MB.

Personally I'd recommend 128MB minimum and then tweak as required.

You can use the Devel module to output the pages memory usage to help you.


When does the computed field get calculated? I don't understand when a computed field computes. Does it compute when the fields it draws on are updated or when someone views the node it's used in?

From  Computed Field Module:

Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

In the documentation page ( http://drupal.org/node/126522 ) it also says:

When is the field actually computed?

If you wish to store the values in the database then you have to update or re-submit the node to compute the value of the field.

If it is not stored in the database then the value computes when the node loads and only when the node is loaded. The field will not work in views nor will it function properly if it depends on other non-stored computed fields.

More information from drupal.org and what appears to be a good page of snippets is http://drupal.org/node/149228


Validation plugin for a Boolean field I want to contextually filter my View with a boolean field, for which the "On" value is "New," so using a URL like /view/url/new.

I first tried basic validation, but that would only work if my URL were /view/url/1.

So I wrote my own validation plugin to validate "New" as if it were "1".

<?php

namespace Drupal\my_module_validation\Plugin\views\argument_validator;

use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;

/**
 * Validate the New boolean.
 *
 * @ingroup views_argument_validate_plugins
 *
 * @ViewsArgumentValidator(
 *   id = "my_module_validation",
 *   title = @Translation("MYMODULE Validation")
 * )
 */
class MyModuleValidation extends ArgumentValidatorPluginBase {

  public function validateArgument($argument) {
    if($argument == 'new' || $argument == 'New' || $argument == '1') {
      return TRUE;
    }
    return FALSE;
  }
}

So I'm able to apply this fine (and I can tell it's being used with a drupal_set_message() thrown inside that block), but it still doesn't work. Results only appear if I add the /view/url/1 and not the /view/url/new like I want.

Please help me understand what I've done wrong and how I can fix it.

If I add $this->argument->argument = '1'; to the above code, it works:

<?php

namespace Drupal\my_module_validation\Plugin\views\argument_validator;

use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;

/**
 * Validate the New boolean.
 *
 * @ingroup views_argument_validate_plugins
 *
 * @ViewsArgumentValidator(
 *   id = "my_module_validation",
 *   title = @Translation("MYMODULE Validation")
 * )
 */
class MyModuleValidation extends ArgumentValidatorPluginBase {

  public function validateArgument($argument) {
    if($argument == 'new' || $argument == 'New' || $argument == '1') {
      $this->argument->argument = '1';
      return TRUE;
    }
    return FALSE;
  }
}


php code to load latest posts from a term How can I load 10 latest posts from a term using a PHP code, I know how to display latest titles but I need latest nodes body or teaser too.

How is that possible? (title and body)

One way would be to use taxonomy_select_nodes() to build and run the query for you, it orders by n.sticky DESC, n.created DESC by default but you can change that to just n.created DESC if you need to by passing the 5th argument to the function.

It also limits the query to the number of records found in the default_nodes_main variable, which defaults to 10.

$tids = array(1); // 1 is the term id (tid)
$result = taxonomy_select_nodes($tids);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid);

  $title = $node->title;
  // etc...
}


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

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

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

You find the block_content entity in the template variable elements to get the ID:

block.html.twig:

{{ elements.content['#block_content'].id() }}


Drupal 6 Site Duplication - Looks Like My Theme is Broken My goal is to duplicate a Drupal 6 site to a new host, but I am having some problems.

  New host - 198.20.226.199/~paul8226/ -- No name resolution setup yet.
  Old host - www.egcasting.com/

I performed a fresh Drupal 6 install on the new Host Gator account using the same database name, username/password as my existing site (clean URLs worked.) Then I imported the database from the existing site, and copied over sites/default (except settings.php) and all of sites/all. It looks like the site totally functions, except the theme is not styling anything at all.

Google Chrome developer tools is telling me I am missing the below CSS files, both of which are on my file system:

http://198.20.226.199/~paul8226/sites/default/files/css/css_89883be7e51f5fd34095c91a397aee3c.css
http://198.20.226.199/~paul8226/sites/default/files/css/css_6ca651b4b42888393291ef9ea27101fa.css
.
.
.

-rw-rw-r-- 1 paul8226 paul8226 39K May 13 15:57 css_89883be7e51f5fd34095c91a397aee3c.css
-rw-rw-r-- 1 paul8226 paul8226 549 May 13 15:57 css_6ca651b4b42888393291ef9ea27101fa.css

The CSS on the old host is working fine. So far, I have looked at the file, and directory, permissions going all the way up. I also tried turning on and off the CSS compression. Turning off CSS compression made the site styling look totally off in another way. When I look at the themes option, it looks like the custom theme I am trying to copy over is having some serious issues:

Broken Theme

Working Theme

I also looked through the theme permissions, and they look like what I think they should be.

 # pwd
 /home/paul8226/public_html/sites/all/themes
drwx--x--x 4 paul8226 paul8226 4.0K Aug 25  2009 eg_prod/
.
.
.
# cd eg_prod
# ls -laSh
total 260K
-rw-r--r-- 1 paul8226 paul8226  42K May 13  2009 theme-settings.php
-rw-r--r-- 1 paul8226 paul8226  37K Sep  9  2009 style.css
-rw-r--r-- 1 paul8226 paul8226  32K Aug 21  2009 template.php
-rw-r--r-- 1 paul8226 paul8226  15K Apr 23  2006 LICENSE.txt
-rw-r--r-- 1 paul8226 paul8226 7.8K Apr 20  2009 style-rtl.css

Thank you very much for taking the time to help me with this. Normally this 'thanks' section gets edited out, but oh well. Thanks!

/sites/*/files/css/ and /sites/*/files/js should be empty just after migration - do not copy their contend. Clear them.
Before making original site database snapshot, turn off css and js aggregation. If you didn't, turn it off now. If you don't, the duplicated site will be looking for the aggregated content which may, or may not be available on the new site.
On new site, make sure /sites/*/files/ directories are writeable by your php scripts, and that php can delete files too.
Search all theme files for not-relative URIs. There shouldn't be any.
Fix one problem at a time. First, make it work without aggregation (most probably it's URI problem), and only then attempt to fix aggregation issues.
At the end, if you still have problem - disable and then enable theme. This should ensure all theme-related caches are regenerated and theme settings variables refreshed.


How to create a chart system with Date ranges like Google Analytics? I want to create a chart system for my website, for the apparel trend forecasting company. To do so, I want to add trends of sales based on today, yesterday, this week, this month, and year trend.

I have created the chart, but can't find any module to solve my purpose. I tried the Date Facets module, but I don't know why I cannot get it to work, even though I have installed the Facet API too.

Is there any similar module to make this work?

Some more details about what I'm trying to do:

suppose it's a chart about shirt trends.
about these types of shirts: sleeveless, half sleeve, or full sleeve.
filtered by Today, Yesterday, This week, This month, this year.

Consider looking at the Comparison of Charting modules. Here is a quote from it:

  There are a variety of modules that facilitate the creation of charts. When it comes to charting in Drupal, the saying "There's a module for it" doesn't really apply. In this case, it's more accurate to say, "There are plenty of modules for it" ...

  These modules support for various charting libraries that may be desirable based on a site's desired appearance, feature-set, and licensing needs.

Using the Charts module is one of the options to consider. Here is part of what's currently included in that link (its project page):

  Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.

  Features

  Wide chart type support: Pie, Line, Bar, Column, Area or Scatter charts.
  API: A Drupal-friendly syntax for creating charts easily, regardless of the underlying library.
  Views integration: Display the Views results as charts.
  Examples: The module includes lots of example charts for you to reference when building your own charts or chart library integration.
  Supported charting libraries: out of the box, you may use either (the new) Google Charts (GC for short) or Highcharts  (HC for short) as the charting library.

For 'documentation' about the charts module, you may want to start from its community documentation.

There is an issue also that might be worth looking at, about Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields'.

Disclosure: I'm the author of the comparison (+ co-maintainer of the charts module), I hope this does not violate the site's policy on self-promotion.