Save image to node via form API I am having trouble figuring out how to attach an uploaded image to a node in my form submit handler. I've been searching for a while now and nothing I've tried has worked. For instance:

$image = $form_state['storage']['image'];
unset($form_state['storage']['image']);
$image->status = FILE_STATUS_PERMANENT;
$file = file_save($image);
$node->field_image['und'][0] = $file;

does not work.

Any help on this would be much appreciated. Thanks.

It's been a while since I've done this but this link should be a good start. File Load

Assuming $form_state['storage']['image'] is the image's fid, what you may want to do is.

$image = $form_state['storage']['image'];
$file = file_load($image);

// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Save.
file_save($file);

// add image back
$node->field_image['und'][0] = $image;

Depending on what your doing you may want to add the file to the usage table. Details here.
File Usage Add


Add items to batch queue operations on the fly I have some code which generates a batch with a single operation; to go off to an API and get some data. This data could be any number of items.

I would like to be able to populate the rest of the batch's operations during the first operation.

I have tried this, but it doesn't seem to work...

Batch initialisation (drush command callback):

function example_drush_sync_entries() {
  $batch = array(
    'operations' => array(
      array('_example_fetch_data', array())
    ),
    'finished' => '_example_batch_finished',
    'title' => t('Processing'),
    'progress_message' => '',
    'error_message' => t('The update has encountered an error.'),
  );

  batch_set($batch);
  $batch = &batch_get();
  $batch['progressive'] = FALSE;

  drush_backend_batch_process();
}

function _example_fetch_data(&$context) {
  $response = drupal_http_request('http://blah.com/data');
  $data = $response->data;
  $data = drupal_json_decode($data);

  $batch = &batch_get();
  $batch_set = &$batch['sets'][$batch['current_set']];
  foreach ($data as $entry) {
    $batch_set['operations'][] = array('_example_process_entry', array($entry));
  }
  print_r($batch);

  _batch_populate_queue($batch, $batch['current_set']);
}

function _example_process_entry($entry, &$context) {
  print_r(func_get_args());
}

I can see $batch has a load of new operations in it, however _example_process_entry never seems to fire.

Is it possible to dynamically add items to the batch queue while its processing?

I was really quite close! As always, asking the question on here caused the answer to reveal itself.

function example_drush_sync_entries() {
  $batch = array(
    'operations' => array(
      array('_example_fetch_data', array())
    ),
    'finished' => '_example_batch_finished',
    'title' => t('Processing'),
    'progress_message' => '',
    'error_message' => t('The update has encountered an error.'),
  );

  batch_set($batch);
  $batch = &batch_get();
  $batch['progressive'] = FALSE;

  drush_backend_batch_process();
}

function _example_fetch_data(&$context) {
  $response = drupal_http_request('http://blah.com/data');
  $data = $response->data;
  $data = drupal_json_decode($data);

  $batch = &batch_get();
  $batch_next_set = $batch['current_set'] + 1;
  $batch_set = &$batch['sets'][$batch_next_set];
  foreach ($data as $entry) {
    $batch_set['operations'][] = array('_example_process_entry', array($entry));
  }
  $batch_set['total'] = count($batch_set['operations']);
  $batch_set['count'] = $batch_set['total'];

  _batch_populate_queue($batch, $batch_next_set);
}

function _example_process_entry($entry, &$context) {
  var_dump($entry['id']);
}

Notable differences:
* The operations need to be added to the next set, not the current one.
* You need to define a total and count, otherwise the percentage progress is considered 100% and, therefore, complete before it even starts.

I hope this helps other people :)


How to show message to user when page is in a filtered state? I have a view with a few exposed filters and it uses ajax. It is set to remember their last selection. Is there any way to ensure that the user is aware the the view still has applied filters? (i.e. Some users may not be ware that the list is still filtered and they need to hit the reset button).

Edit

To further clarify:

The issue is that if the user is not aware that the list is in a filtered state that they should reset it before starting another drill down

Basically I need it to say "Hey you! this list is in a filtered state. You need to hit the reset button before doing another search!"

In views, to remember the user entry, Views uses sessions. It uses different variables for each view. If you print the $_SESSION variable you can see that.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-test-page'){ //your exposed form's id

      print_r($_SESSION);
   }
}

Now you can see that a structure like below

[views] =&gt; Array
    (
        [test] =&gt; Array
            (
                [default] =&gt; Array
                    (
                        [title] =&gt; Page
                    )

            )

    )

So if you check value exists for this variable,  you can perform your task

ie:

if ($form['#id'] == 'views-exposed-form-test-page'){
//check is it exists, if so perform your task
 if($_SESSION['views']['test']['default']['title'] != ''){
    // "need to reset";
          //here using jquery or css, show or hide your message
        $script="(function ($) {
                //action to do here
        })(jQuery);";
        drupal_add_js($script,'inline');
 }
}

Hope this may helps you


Is there anything wrong w giving a node a status other than 0 or 1? Is there anything wrong w giving a node a status other than 0 or 1?  I want to have several different statuses for a content type im working with.

I would keep $node->status to 0 or 1 doing a grep in a couple of installs there are some explicit checks for it. (not in core but in contrib). While there is nothing to stop you, you won't guarantee that things will work with it.

You can create your own field which represents another status and use that for your own needs.


Display node through panels but limit/deny access directly I have a panel that displays a webform node depending on the fulfillment of certain selection rules (visibility rules) within the panel.  However, I want to be able to prevent access to the webform directly.  I have tried to unpublish the node, but this affects the display in the panel as well.

Edit: I'd also like to avoid adding code into template files etc.

By

  Edit: I'd also like to avoid adding code into template files etc.

do you mean that you want a existing module / UI only solution?  If so, I can't help you with that.

If you don't mind doing a small custom module, this is a somewhat common task that has been answered a few times on this site, and the main SO site, under slightly different titles.

Essentially, you want to redirect a node page to another page or you want to not have a node every viewable on its own.

Two questions worth reading are

Redirect node type to a view

How to prevent access to Views-only content?

Those two solutions can be adapted to your needs.


Problem with updating modules (check updates) I have Drupal 7.26 with Commons 7.x-3.9. Recentyl manual update of modules is not working. When going to "Modules" - "Update" I'm getting something like:

 Last checked: 4 days 58 min ago (Check manually)

and this is the last time I've been able to check updates (just before Durpal core update).

When I use "Check manually", the page with progress bar appears where progress bar is always "100%" and messages say:

Trying to check available update data ...
Checking available update data ...

After short while it returns to "Update" page with:

 Last checked: 8 hours 5 min ago (Check manually)
There was a problem getting update information. Try again later.

No updates visible, no errors in log.

Any ideas?

Problem solved through cleaning cache_update table (execute SQL query "delete from cache_update;" through phpmyadmin or mysql workbench)


GoDaddy Application vs Manual Install I would like to setup a Drupal site with my existing GoDaddy Hosting Plan.

Do you recommend using the Drupal Application (provided by GoDaddy) or installing Drupal (core) manually into the hosting account?  Why?

Assuming this is what you are talking about Godaddy Application for Drupal

I would highly suggest to install Drupal on your own. That version is two releases behind with Drupal 7.34 addressing another recently found security issue with HTTPS websites.


"Convert Media tags to markup" in CKEditor is not working I have a strange problem when trying to add an image by 'Add media' in CKEditor 4.3.1. I know that this topic is very frequent. In most cases the resolution is to check "Convert Media tags to markup" in Text formats configuration... but I have checked this and it's still not working.

I can add an image to media library, after this I can choose an image format, but finally when I try to add the image it's not showing neither in the editor window nor on front.

Seems that no code is adding or the media tags are not converted to markup.

Do you have any ideas?

This is most often caused by the order of the filters. Try to set this filter as the last (or first) one.

Another alternative is CKeditor's ACF (advanced content filter). This should be fixed in the latest Wysiwyg module release.


Embedding images in a block from url How do I embed a URL in a block which is displayed as the linked image on the site?

For any source or path of any thing in drupal site use src like this. It will work everywhere.

<?php $src = base_path() .'sites/files/logo.png'; ?>

This src use like

<img alt="logo" src=" <?php echo $src ; ?>">

Enable PHP filter module that come with core module.

and in Block Body Choose Text format as PHP CODE.

I assuming block is created using Block module(Block UI)


How to add list of children in webform I am using webform module to create a form for enrollment. End user will need to add the list of children. Since number of children is unknown for the users, I was trying to add "add child" button to add more children. I used webform add more module but it has known issue. I added a field set component in which I have name, age, ssn fields. Now, I am stuck how to add "add child" button under the fieldset for public to add childs as many as they need. How can I add "add child" button under fieldset component or is there other way I could accomplish that using the webform module?

For D7, you will need to use a contrib module.

https://www.drupal.org/project/wfm
https://www.drupal.org/project/webform_addmore

For D8, you can use a 'Custom composite' element.


No Result from taxonomy API function I want to output all the node IDs which belong to a taxonomy term ID. I use the following code in page--taxonomy.tpl.php.

$a = taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));

When on the parent term page, print_r($a) shows an empty array. Why does this happen?

Under the parent term, there are two child terms which have some articles. How do I get the node ID?

taxonomy_select_nodes() is returning an empty array because there aren't nodes using that taxonomy term, since that function doesn't return the nodes using any children of the taxonomy term passed as argument. This is also what a taxonomy term page does.

It could be the database table used from the function doesn't contain any data, simply for the fact the taxonomy_maintain_index_table persistent variable is not set to TRUE. If that is the case, then variable_get('taxonomy_maintain_index_table') returns FALSE (or an equivalent value). A persistent variable can be overridden from the settings.php file; that is the reason I am not suggesting to check the database.

As side notes:

The page--taxonomy.tpl.php template is used not only for taxonomy/term/<term id>, but for any path under taxonomy, for which there isn't a taxonomy term associated. I would rather use page--taxonomy--term--%.tpl.php that is surely associated with a taxonomy term.
If you are calling a function, and want to use the default value for some of its parameters, just leave them off. Instead of calling taxonomy_select_nodes() as taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')), call it as taxonomy_select_nodes(arg(2)). What you are doing is assigning TRUE to the $pager local variable, FALSE to $limit (another local variable), and an array to $order; those values are also passed as arguments to the function. So you are setting local variables to pass arguments to a function, and you are passing the default values for those arguments. Keep in mind that in PHP, a function arguments are only positional, differently from Ruby, for example.


How to deal with too much product variations / attributes? I'm quite new to Drupal Commerce, but I've seen some Drupal before (not actually a guru).

Dealing now with handmade models, each product has 9 sizes, 6 colors, 6 materials. They have now about 130 models. I started dealing with it creating a product per variation (commerce_bpc). But 300+ variations per product display became a little unbearable, because it was intended for a local shop and they should be able to create new models and edit old ones a little bit faster.

We decided to make the products just size dependant (price changes only according to size, and there would be no special images for colors and materials).

So, my first approach was to use the image as a product display field. But:

What about the attributes? Is the correct way to use material and color as select list in the Display, too? Will I be able to use them later in the checkout and the orders?
Or should I stick to 1 product per variation and handle them in some other way? I think that's the NATURAL way, but it just feels like overkilling.

Also, any insight on how to handle a large list of products (edit, bulk actions, add them to display, etc..)?

Views Bulk Operations? There is also the Commerce Bulk Product Creation. Some more details about it (from its project page):

This module facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.
The module also provides various ways to create display nodes for the newly-created products:

Redirect user to node creation form (with title and product reference filled in).
Silently create display node referencing all created products.
Silently create one display node for each created product.

This will greatly speed up the task of adding numerous products at once.


Programmatically set the front page per site? I have a site that is using a 'fake' multi-site instance (I think, someone else implemented it). We created 3 directories in sites:

sites/site1
sites/site2
sites/site3

and in each settings.php inside these directories it includes the original settings.php from the default directory.

I am overriding the theme successfully in these files by doing $config['system.theme']['default'] = 'theme2';

When I try doing $config['system.site']['page']['front'] = '/node/239';
it works only on cache flush.

For example if I am on site 1 I see the front page set in the UI.
Then when I switch to site2.example.test I still see the default front page instead of what is on /node/239.
When I flush the cache, the reverse happens; site 2 homepage shows /node/239 and so does site 1.

I have also tried setting this in an event listener:

public function kernel_request(Event $event) {
    $config = \Drupal::configFactory()->getEditable('system.site');
    $site_path = \Drupal::service('site.path');
    $site_path = explode('/', $site_path);
    $site_name = $site_path[1];

    if ($site_name === 'site2' && $event->getRequest()->getPathInfo() == '/') {
      $config->set('page.front', '/node/239')->save();
    }
    else {
      $config->set('page.front', '/home-content')->save();

    }
  }

This now does the right thing, but only after loading the page and then refreshing.

Could anyone tell me what the "correct" way of doing this would be that wont be cached?

Thanks to everyone for your responses.
I looked in to using the Domain module but am avoiding for 2 reasons:

It is still in Alpha14 and this is going to be a business critical site
I couldn't work out how to set the domain specific configurations

However, installing the Domain Module and looking at the README file pointed me in the right direction.

For anyone else who is looking to achieve setting a different Front Page per domain:

I used the Drupal Console to generate an Event Subscriber for Kernal.request
In the getSubscribedEvents method you need to set the weight to something greater than 30 which overrides the Page Cache and Dynamic Cache.

$events['kernel.request'] = ['kernel_request', '35'];

I got the editable configuration for the site settings from

$config = \Drupal::configFactory()->getEditable('system.site');

and the site name added in sites.php by doing:

$site_path = \Drupal::service('site.path');
$site_path = explode('/', $site_path);
$site_name = $site_path[1];

Then added the logic:

if ($site_name === 'site2') {
  $config->set('page.front', '/node/239')->save();
}
else {
  $config->set('page.front', '/main-content')->save();
}

The Key thing I was missing was setting the Cache Context for sites.
You need to duplicate the default.services.yml from the sites/default directory and rename it to services.yml (if you don't already have this file).

Then you will need to add url.site to the required_cache_contexts array so that is becomes something similar to:

required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site']

Remember to flush the cache and this should work!


Notice: Undefined index: allowed_values in list_allowed_values() I am getting this error

Notice: Undefined index: allowed_values_function in list_allowed_values() (line 239 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values in list_allowed_values() (line 248 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values_function in list_allowed_values() (line 239 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values in list_allowed_values() (line 248 of /var/www/html/drupal/modules/field/modules/list/list.module).

In my view I have added filters "a" and "b".

In content type "a" is list(text) with default value none. and "b" is also list(text) with default value none.

If default value is not none then I am not getting the notice.

I want the default value to be none for the fields.

What should be done so that these "Notice" do not appear.

This can happen if you delete a field from the definition of a custom content type and that field is still referenced by a View.  Even if you added a new field with the same name as the one you deleted the problem will persist. You need to remove the old field from the View definition and then add the new field to the View.


How to add custom entities to group types? I'd like to add my custom content entity to my group types, just like the module's "group node" plugin does already with nodes bundles. Has anyone done this? There does not seem to be much progress other than the documentation request about Document making custom entity types available as content for group types.

Here's how I've solved it in the end. Although in my example I'm adding user entities, you can add whatever custom-entity you want, the approach is the same. What I needed was to add users to a group not as members (as already provided by the group module), but as pure user entities (group content). My answer is a basic example. See /group/src/Plugin/GroupContentEnablerInterface.php for a detailed description what methods etc. are available to refine the whole thing. You basically need 2 files

module_name\src\Plugin\GroupContentEnabler\UserEntity.php

<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\group\Plugin\GroupContentEnablerBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a content enabler for user entities.
 *
 * @GroupContentEnabler(
 *   id = "group_entity_user",
 *   label = @Translation("User"),
 *   description = @Translation("Adds users to groups as pure entities and not as members."),
 *   entity_type_id = "user",
 *   entity_access = TRUE,
 *   pretty_path_key = "user",
 *   reference_label = @Translation("Username"),
 *   reference_description = @Translation("The name of the user (entity) to add to the group (not as a member)"),
 *   deriver = "Drupal\module_name\Plugin\GroupContentEnabler\UserEntityDeriver"
 * )
 */
class UserEntity extends GroupContentEnablerBase {

/**
 * {@inheritdoc}
 *
 */
 public function defaultConfiguration() {
   $config = parent::defaultConfiguration();
   $config['entity_cardinality'] = 1;
   return $config;
 }

 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
   $form = parent::buildConfigurationForm($form, $form_state);
   // Disable the entity cardinality field as the functionality of this module
   // relies on a cardinality of 1. We don't just hide it, though, to keep a UI
   // that's consistent with other content enabler plugins.
   $info = $this->t("This field has been disabled by the plugin to guarantee the functionality that's expected of it.");
   $form['entity_cardinality']['#disabled'] = TRUE;
   $form['entity_cardinality']['#description'] .= '
' . $info . '';

   return $form;
 }

 /**
  * {@inheritdoc}
  */
  public function calculateDependencies() {
   return ['module' => ['user']];
  }

}

and the second file module_name\src\Plugin\GroupContentEnabler\UserEntityDeriver.php

<?php

namespace Drupal\module_name\Plugin\GroupContentEnabler;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class UserEntityDeriver extends DeriverBase {

  /**
   * {@inheritdoc}.
   */
   public function getDerivativeDefinitions($base_plugin_definition) {
     // I used to set 'entity_bundle' to 'user' and the autocomplete for the user name never worked.
     // Checking a user with devel, the bundle is  always empty.
     // So leave it empty and specify the entity_type_id = "user" in the docblock
     // of UserEntity.php
     $this->derivatives['user'] = [
       'entity_bundle' => '',
       'label' => t('Group entity (user)'),
       'description' => t('Adds users to groups as pure entities and not as members.'),
     ] + $base_plugin_definition;
     return $this->derivatives;
    }
}

This can now be installed just like all the other group-content types. The plugin_id of this user-entity group content type is group_entity_user:user. Again, see the group module's source code, as the documentation is good and lot's of additional methods can be used to refine this approach.

As a warning, be very careful when creating these custom plugins as it can cause a lot of trouble when not propery configured/tested. (see my previous question)


What are the best e-commerce modules/setups? Googling for "Drupal E-commerce" brings up a ton of old results, and I wanted to weed out all the garbage. I'm a regular on SO but I thought that I might get better insight/advice here.

Running Drupal 7.9 (multiple sites will be installed but running their own Drupal install), what e-commerce packages should I install (shopping cart and payment options)?
What are the pitfalls to look out for?
What theme do you suggest, that is geared towards E-commerce?

I have not yet built an e-commerce site on D7, so I cannot get really specific.

That said, the obvious starting point for e-commerce on Drupal 7 is the Drupal Commerce package. Just start with the basic package, see if it fits your needs, and install add-ons if you need them. There even is a dedicated Drupal Commerce website with documentation, a forum and more.

There are a couple of themes that are specifically geared towards e-commerce, for instance Acquia Prosper and AT Commerce.


Do we upgrade core or PHP first? We have Drupal 7 running on PHP 5.6. Do we upgrade to PHP 7 first, or do we first upgrade Drupal?

Drupal 7 can run on any PHP version between PHP 5.6 and PHP 7.3. For running on PHP 7.4, it's required at least Drupal 7.71.
Drupal 8 can run on any PHP version that is newer than PHP 5.6. For running on PHP 7.4, it's required at least Drupal 8.8.3.
If the site is running a version of Drupal that is older than Drupal 7.71, I would first upgrade PHP to PHP 7.3, and then upgrade to Drupal 8.
If the site is running on Drupal 7.71 or any newer version, you can upgrade to PHP 7.4, if you mean to upgrade Drupal to Drupal 8.8.3 or a newer version.
I would also test the upgrade on a local test site, as third-party modules you are using could cause problems with newer PHP versions.
It should be safer to upgrade to PHP 7.3, as there are backward incompatible changes in PHP 7.4 that required changing the code in Drupal 7; it's probable the same changes are required in third-party modules, but those changes are still to be applied to those modules.


Error class not being set on form fields I have a complex for that for various reasons I am validating in the _submit hook instead of the _validate. This is working great with the exception that the error class isn't getting added to the form elements.

Is there something simple I am missing or do I need to use form_get_errors and set the classes myself?

(The reason I am doing validation in submit is because I want to save the form data regardless of if it is valid or not.)

The easiest thing to do, would be to save the form data in the validation step if the form has errors.

function form_validate(&$form, &$form_state) {
  // Validate
  if (form_get_errors()) {
    // This code is only run if the form has errors.
    // Save the form data
    db_query("...");
  }
}

Then you could raise the errors and let drupal do it's thing, and use the submit function for it's intended use: handle valid form data.

If you need to process the data this can be done in the validation step as well, as the info in the $form_state array will be carried to the form submit handler.


Does Commerce Override Username Or Is Username Linked To A Node? Commerce Kickstart 2.

I used the included Feed to import users. I applied this patch: https://www.drupal.org/node/1570544 so I could keep the existing UIDs. Seemed to work OK.

I then wrote a script to import sales orders from an external db. That too seemed to go OK, except that the Username displayed on all reports, views, in fact -anywhere- that the field User:Name is displayed, it shows the First Name/Last Name of the billing profile of the last linked order. eg.

The username is 'MEGACORP'. But 'Frank Smith' is displayed as the User Name because that was the First/Last name of the imported order. -And- the link to the user account profile is users/frank_smith

The weird thing is that when people log in, they log in with the -correct- Username, ie. megacorp, -not- Frank_Smith

I looked at the SQL table Users and the Username is correct. (ie. megacorp)

AND I stumbled on creating a view of users, but as a wild-ass-guess set a relation to node entity reference and the Title field is 'Megacorp'.

Here are my field mappings in my customer profile import:

// Full Name(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $name;
// Country(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $row->country_iso_code_2;
// Address 1(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $row->billing_street1;
// Address 2
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $row->billing_street2;
// City(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $row->billing_city;
// State(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $row->zone_code;
// Postal Code(Required)
$profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $row->billing_postal_code;
//Business name(Required)
$profile_billing->field_business_name[LANGUAGE_NONE][0]['value'] = $row->billing_company;
 // Phone(Required)
$profile_billing->field_phone_number[LANGUAGE_NONE][0]['value'] = $row->billing_phone;`

So...
1. why is Username not pulling from the Users SQL table?

Is the above behaviour something Commerce does? If so, can I turn it -off-?
Is there -always- a related node for each user?
The field billing_company doesn't seem to display on any view, even though it is available to import. How do I access -that-? I guess -that- is what I expected to appear on various forms/reports (eg. the invoice)

Commerce Kickstart 2 includes the following function, which uses hook_username_alter() to alter the display of the username to be the billing name, which is what it sounds like you're seeing here.

The easiest way around this would be to just delete this function, which is located in "/profiles/commerce_kickstart/modules/commerce_kickstart/commerce_kickstart_user/commerce_kickstart_user.module" from you're Drupal site's root directory.

/**
 * Implements hook_username_alter().
 */
function commerce_kickstart_user_username_alter(&$name, $account) {
  if (!empty($account->uid) && module_exists('commerce_addressbook')) {
    if ($billing_profile_id = commerce_addressbook_get_default_profile_id($account->uid, 'billing')) {
      $billing_profile = commerce_customer_profile_load($billing_profile_id);
      if (!empty($billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'])) {
        $name = $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'];
      }
    }
  }
}


Updating to PHP 5.4 breaks Drupal 7.25 with Strict warning: Declaration on bootstrap.inc I tried updating to PHP 5.4, but got a few errors. These aren't critical errors right? seems like its only warnings.

I'm using Drupal 7.20 What do the following errors mean exactly? And how can they be resolved? Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

Strict warning: Declaration of Messaging_User_Destination::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_User_Destination::format_address() should be compatible with Messaging_Destination::format_address($address, $format = MESSAGING_FORMAT_PLAIN, $type = NULL) in _registry_check_code() (line 3080 of /home/xxx/public_html/includes/bootstrap.inc).

Strict warning: Declaration of Messaging_Mail_Address::validate_address() should be compatible with Messaging_Destination::validate_address($address, $type = NULL) in require_once() (line 208 of /home/xxx/public_html/sites/all/modules/messaging/messaging_mail/messaging_mail.inc).

These aren't critical errors right?

No, it's just a warning. Not fatal. It comes from the E_STRICT error constant, which as of PHP5.4 was included in E_ALL. It's quite common to see those errors after upgrading 5.3 to 5.4 (not just for Drupal), as most people copy the bulk of their config from the previous version.

The constant itself provides this to error reporting:

  Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

  What do the following errors mean exactly?

In Drupal terms, it means one or more contrib modules you have installed contain code that targets older version of PHP (or at least hasn't been updated recently). Specifically, PHP is complaining that the arguments or access modification of a method on a child class doesn't match the same method on the parent class.

  Can I just upgrade my Drupal 7 to the latest 7.31 as of 2014-09-24 to fix these issues?

In your case the warning is being caused by the messaging_mail module, so updating core won't do anything (though you should update ASAP, you're a long way behind). You could disable strict errors if you just want to hide the warning, but the best way forward is to report this as a bug to the appropriate module.


The right form to work with pages Reciently, I'm starting to work with Drupal 8, but I have some problems working with main pages. I can create a content type for all pages, but, the fields I use in to create this, must be content all posible options to input in all pages, and, for the final user, this solution can be a little confusing.

For instance, in one page I need to create a field to related another content type, with unlimited inputs, to display in this page. But, in another page, I need another related content type, with only one input.

The same case happenend for static blocks or similar.

Of course, I can create a content type for each diferent pages, but sounds like a horrible solution (I think).

I Acquainted with the suggestion template system, and I use it, but not satisfy this casuistic.

Perhaps, I'm totally wrong with the workflow of drupal and the solution is work totally diferent.

Thank you in advance.

You don't need to create a content type for each different page. You need some tools for site building. I think in your case Paragraphs will be the best solution.

You can for example create different paragraph types with a reference field, one to a content type with one input and one to another content type with unlimited inputs. You can define as many paragraphs types as you want.

Then you put a paragraph field in the page content type and the user can fill this field with the paragraphs he needs to build the content, so that each page can have a different layout.


Title encoding to display correctly foreign characters In my html.tpl.php file in the <head> tag
I display the page title as follows:

<title><?php print $head_title; ?></title>

This displays the foreign characters not correctly when watching the pages
in the browser.

I tried to add the
<meta charset="utf-8" /> but it didn't help.

Caches were cleared.

What else could you change so that the foreign characters are encoded correctly?

Instead of trying this.

<?php print $head_title; ?>

try this and check.

<?php print html_entity_decode($head_title); ?>


Fetch a view into hook_preprcess_node and then put it in a block I want to fetch a view in my template_preprocess_node function and then put in in a block, so I can diplay it in the sidebars of my page. I have the view (the code below) but don't know how to put it in a block. Thank you for your help in advance!

    $view = views_get_view('playlist');
    $view->set_display('block');
    $view->set_arguments(array($course));
    $view->pre_execute();
    $view->execute();
    $variables['content']['playlist'] = $view->render();

If you want to draw a view of content based on a node, then you should build a module that declared hook_block(), and that hook_block gets the current node with menu_get_object(), and form the desired view.

At the theming layer, when your node is preprocessed for theming, it's not a good place to construct any blocks. Hope this helps.


Brightcove Connects breaks site after core upgrade to 8.5.x in Acquia Cloud After upgrading core to 8.5.2, and eploying to Acqui Cloud, Brightcove causes a fatal error. Note, the code works as expected in my local DevDesktop environment, and I am unable to recreate the error locally.

Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveCmsEntity' not found in /mnt/www/html/xxx/docroot/modules/contrib/brightcove/src/Entity/BrightcovePlayer.php on line 30

The error is thrown via http and drush commands

I discovered the issue. Case-sensitivity of the class names. Class "brightcove/src/Entity/BrightcovePlayer.php" extends "BrightcoveCmsEntity", while class "brightcove/src/Entity/BrightcoveCMSEntity.php" is named as "BrightcoveCMSEntity".

I replaced all instances of "BrightcoveCmsEntity" with "BrightcoveCMSEntity", and the issue was resolved, it exposed the same issue with "BrightcoveVideoPlaylistCmsEntity".

Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveVideoPlaylistCmsEntity' not found in /mnt/www/html/nhradev/docroot/modules/contrib/brightcove/src/Entity/BrightcoveVideo.php on line 75

Replacing all instances of "BrightcoveVideoPlaylistCmsEntity" with "BrightcoveVideoPlaylistCMSEntity" resolved all issues.

The plugin now works as expected in Acquia Cloud.

NOTE, the code worked locally because I am developing on Windows.

Files touched:
brightcove/src/Entity/BrightcoveCMSEntity.php
brightcove/src/Entity/BrightcoveCustomField.php
brightcove/src/Entity/BrightcovePlayer.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php

brightcove/src/Entity/BrightcovePlaylist.php
brightcove/src/Entity/BrightcoveVideo.php
brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php
brightcove/src/Form/BrightcoveVideoPlaylistForm.php

Reference: https://www.drupal.org/project/brightcove/issues/2969674


getting rid of Media Module Message "Media Folder: Media Root" Why is the message "Media Folder  - Media Root" appearing on this article, and not on the other articles and pages that also use media to insert images on my site? How can i get rid of it, i don't like it.
http://notesmusic.be/node/3

A similar problem came up for me when upgrading a Drupal site to Drupal 7.53. I found that the "media folder" field suddenly started appearing on all images on the site.

What fixed it for me was hiding the media folder field from the file type generated by the file entity module (which makes files fieldable). Here are the steps to do that on your Drupal site:

Go to Home » Administration » Structure (admin/structure/file-types).
Click "Manage display" for the affected file type.
Change the label and format to "hidden" for the "Media folder" field and click save.
While you are at it, repeat steps 1 and 2 for all the file types on your site.
Clear your caches.


how to apply CSS for a Custom Block/View Like your tutorial a lot. I am really brand new into Drupal and PHP and i am trying to learn to apply and suggest product for my work. Recently, i have installed Drupal 7 and installed many modules to play with. I have looked over online tutorial and i have few drupal7 books, but i haven't find any answer about my needs.

My question is, suppose i create a simple block to display a list of news items how can i apply css for this block. Where can i add css codes? Is there any specific css file in a certain directory?

Please let me know if you can help me on that. if you already have  a question thread opened or answered before, you can point me the url. i couldn't find the answer yet.

It depends on what theme you're using. The core Drupal themes are stored under /themes/. If you have a custom theme, it should probably be installed in /sites/all/themes/. Different themes may name their main CSS file differently, but look for .css files within your theme's directory or a subdirectory beneath it.

From there, you'll need to know what ID or class name is associated with the particular block.  You can right click in somewhere in the block and choose "Inspect Element" to examine the source file. Or for even more power, I'd recommend installing the Firebug extension for Firefox. You can find out more about Firebug in this screencast.

For more complicated theming, I'd recommend also installing the Theme Developer module. It will allow you to see what theme file or function is currently outputting a specific area of the page, as well as what files or functions can be used to override it. See the screencast for more detailed information.


Hook active trail path I' am trying to make a custom module to set an active trail path to a menu. I created a views page. The active trail must be to a node or taxonmy term. When I open the pages created by the view the active trail is not active.

I wrote the script here below but it doesn't work, can somebody please help???

function mymodule_views_default_views(&$view, &$display_id, &$args){
  if( $view->name = 'productdetail';)
    {menu_tree_set_path('menu-categorie', 'node/39');
 }
}

I found the answer to my own question.

In the view I added a field with the taxonomy term ID / node ID which is although used for my menu and hide the output and do a rewrite of the output.
I pasted the following code in the text field for rewrite; field_categorie-tid is my reference term from the menu.

menu_tree_set_path('menu-categorie', 'taxonomy/term/[field_categorie-tid]');

Instead of taxonomy/term/[field_categorie-tid] you can also use node/[nid].

I added in the head section a global field with PHP and token, and put <?php [field_categorie]?>.

That's all; no hooks nor custom scripting in the template.


Changing product price depending on node field in commerce node checkout i am using comerce_node_checkout with drupal_commerce

I want to change product price depending on node field .

eg,

I have a field as field_gender if we select male then price will be 1000.00 or if we select female then it will be 500.

Any help is most appriciable.

Thanks in advance .

Ohhh!!!!!!!!

Power Of Rules

 { "rules_update_amount_female" : {
    "LABEL" : "Update amount Female",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Update amount" ],
    "REQUIRES" : [
      "rules",
      "commerce_line_item",
      "commerce_product_reference",
      "commerce_cart"
    ],
    "ON" : {
      "commerce_product_calculate_sell_price" : [],
      "commerce_cart_product_prepare" : []
    },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item" ],
          "field" : "commerce_node_checkout_node"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-node-checkout-node" ],
          "field" : "field_ap_gender"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-node-checkout-node:field-ap-gender" ],
          "value" : "Female"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "500",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


How to manage contextual filters for a simple date-based view I'm building a simple view to show content of X type, filtered by date. I want this view to be available via URLs like:

/events/2012       - Show all content for this year only
/events/2012/11    - Show all content for this year and month only
/events/2012/11/28 - Show all content for this exact day only

These URLs form part of this section's hierarchy so the patterns are non-negotiable.

The date I'm filtering on is a date field provided by the Date module, and has an optional end date.

I've tried setting the path of the view to /events/%/%/%, and have added three contextual filters for the date field. The granularity for each of the filters is set correctly to the respective date part for that filter.

However, none of that works; I either get all event content, regardless of year, for the year filter, or no content at all if I include the other filters.

There are several related questions (none with answers as it happens):

https://drupal.stackexchange.com/questions/29663/contextual-filters-and-year-by-date-module
Creating a contextual filter for a view based on month and day
Use date as Views Contextual filters

But nothing that covers exactly what I'm looking to do.

How do I tame these contextual filters, without resorting to the PHP filter which is simply not an option? I can't believe that there's no way to do this just with the UI, it seems like one of the most obvious use-cases.

UPDATE

I tried using a filter with a granularity of month, and changed the argument to 2012-11...and it worked.

So I think the answer is simply that the date filter handlers don't work as I expected.

Here is the one approach,

First create a custom call back for /events
Remove the date contextual filters from your view
Add only one filter(not contextual filter) to your view for that date field, accept the default values and save the view
Then use the following code in your custom callback to execute the view

function get_events($year = '', $month = '', $day = '')
{
  // Display ID of the view.
  $display_id = 'default';
  // get the view object.
  $view = views_get_view('events_views'); //Replace with your view name
  $filter = $view->get_item($display_id, 'filter', 'field_event_date_value');
  if ($year) {
    $filter['value']['value'] = $year;
    $filter['granularity'] = 'year';
  }
  if ($year && $month) {
    $filter['value']['value'] = $year . '-' . $month;
    $filter['granularity'] = 'month';
  }
  if ($year && $month && $day) {
    $filter['value']['value'] = $year . '-' . $month . '-' . $day;
    $filter['granularity'] = 'day';
  }
  $view->set_item($display_id, 'filter', 'field_event_date_value', $filter);
  // If you have any other arguments read from the URL and pass it here as part of args array
  $result = $view->execute_display($display_id, $args);
}

Hope you are aware of how to pass arguments to the view programatically. This is what we are using for complex date filters in views which lacks lot of support for date functionality, however we haven't tried with granularity. This is un tested and not optimized. Modify it according to your need.


Filter condition like "from now to now+1 year" on a date field in Views I have a custom entity with (among others) a field defined this way:

$fields['datedistribution'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date distribution'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'weight' => 2,
  ))
  ->setDisplayOptions('form', array(
    'weight' => 2,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

The values of this field are stored in the database in YYYY-MM-DD format.
I designed a View on this custom entity displaying (among others) this 'datedistribution' field and I use it as a filter criterion.
I would like to a filter condition like "from now to now+1 year".
The available operators being

how can I do that?

I believe I can help, if I understand your question correctly.
First you should make sure that when you set the filter up, it's in Select form.

Then you can select the operator as "is between"
Then you select "Enter a relative date" in the dropdown, and you can put now and now+1 year. Not sure if your date fields have a start and end date...


Add images from external URL in WYSIWYG Editor I am new to Drupal 8, and having some trouble with inline images.

Need

I store my images on Flickr, and want add them as inline images (in editor) in articles on my Drupal 8 site. I also need to set captions, and alignment for those images.

I don't need Drupal to manage the image files for me.

Problem

Drupal 8 uses a customized CKEditor Image Upload dialog, which does not support inserting images from a URL and only supports uploading images to the web server.
When I double clicked on a Flickr image added via HTML code, the image dialog won't show up.

My current workaround

In Configuration -> Text formats and editors:

Disable image uploads;
Turn off the filters Track images uploaded via a Text Editor, Caption images and Align images;
Allow align attributes for , allow
 and
 tag. (Or just use Full HTML and don't filter tags)

Hard-core the image () via Source in CKEditor;
Switch to WYSIWYG, double click on the image. Now the origin CKEditor image dialog (not the Drupal one) will show up which allows me to add captions or set alignment.

Further Observations

Images added this way will have code like

Caption

 even in editing mode.

Images managed by Drupal (if Caption images and Align images are on) will have alignment and caption added as data-caption and data-align attributes on  (no
 in editing, but will expand into that structure when viewing).

My Questions

How to disable the DrupalImage and DrupalImageCaption plugins (at core/modules/ckeditor/src/Plugin/CKEditorPlugin)? (I guess disabling them will solve this problem once for all.)
Are there any better ways to achieve my needs, for example a media library module that can support a range of image storing services. (But that will also need some hack into the CKEditor, right?)

This question was answer in the Drupal issue queue - https://www.drupal.org/node/2119379

  Reusing existing images will be possible in Drupal 8 contrib by
  overriding the managed_file element, which is the element that renders
  the image upload button. E.g.
  https://drupal.org/project/filefield_sources does that: it provides a
  "Reference existing" option.

  When you disable image uploads, you can insert image URLs. It's either
  of the two, not both. If you want both, then again something like
  https://drupal.org/project/filefield_sources provides the solution.


Why are some CKEditor configurations working and not others? I am using CKEditor 4 in Drupal 7 using the CKEditor module. I have the following configuration at /admin/config/content/ckeditor/edit/[profile]:

config.stylesCombo_stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.stylesSet = 'my_styles:/sites/all/libraries/ckeditor-styles.js';
config.fillEmptyBlocks = false; // Prevent filler nodes
config.language_list = [ "en:English", "es:Spanish", "zh:Chinese", "ar:Arabic:rtl", "fil:Filipino", "fr:French", "ja:Japanese", "ko:Korean", "ru:Russian", "th:Thai", "vi:Vietnamese" ];
CKEDITOR.on('instanceReady', function(ev) {
  ev.editor.on('paste', function(evt) {
    evt.data.dataValue = evt.data.dataValue.replace(/&nbsp;/g,' ');
     evt.data.dataValue = evt.data.dataValue.replace(/<p> *<\/p>/g,'');
    console.log(evt.data.dataValue);
  }, null, null, 9);
});

The fillEmptyBlocks configuration is working. Extra returns are removed on save and on paste from Word.

However, the dropdown for the language icon only contains the CKEditor default of Arabic, French, and Spanish, not the list of 11 languages that I've supplied.

And pasting A[tab]B[tab]C[tab]D[tab]E from Word, which converts the tabs to a series of non-breaking spaces, retains the non-breaking spaces.

Any ideas why these configurations are being overlooked and how to make them work?

There was an error in my code. The config statments needed to be surrounded by:

CKEDITOR.editorConfig = function(config) {

and

}

which I discovered by looking at ckeditor.config.js in the CKEditor module.


Custom css is not applying to bootstrap subtheme I followed the step by step to create a subtheme of bootstrap theme. Now, I am not able to apply my custom css to my page.

I took the below steps:

A) Downloaded  Bootstrap project (7.x-3.0). Placed the bootstrap folder in sites/all/themes/.

B) Downloaded jQuery Update project, which is required by Bootstrap. In ../admin/config/development/jquery_update and set the default jQuery version to 1.10.

C) From bootstrap folder, moved the bootstrap_subtheme folder to sites/all/themes/ and name it bootsub

D) In bootsub directory, renamed the bootstrap_subtheme.info.starterkit file to bootsub.info. I edited the content and it looks as below:

name = bootsub
description = A Bootstrap Sub-theme.
core = 7.x
base theme = bootstrap
;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'
regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

;;;;;;;;;;;;;;;;;;;;;
;; Stylesheets
;;;;;;;;;;;;;;;;;;;;;

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

; For information on choosing the desired method, please read the Drupal
; Bootstrap sub-theme "how-to" documentation:
; https://drupal.org/node/1978010

; ;----------------------------------
; ; METHOD 1: Bootstrap Source Files
; ;----------------------------------
;
; ;;;;;;;;;;;;;;;;;;;;;
; ;; Scripts
; ;;;;;;;;;;;;;;;;;;;;;
;
; scripts[] = 'bootstrap/css/style.css'
; scripts[] = 'bootstrap/js/affix.js'
; scripts[] = 'bootstrap/js/alert.js'
; scripts[] = 'bootstrap/js/button.js'
; scripts[] = 'bootstrap/js/carousel.js'
; scripts[] = 'bootstrap/js/collapse.js'
; scripts[] = 'bootstrap/js/dropdown.js'
; scripts[] = 'bootstrap/js/modal.js'
; scripts[] = 'bootstrap/js/tooltip.js'
; scripts[] = 'bootstrap/js/popover.js'
; scripts[] = 'bootstrap/js/scrollspy.js'
; scripts[] = 'bootstrap/js/tab.js'
; scripts[] = 'bootstrap/js/transition.js'
;
; ; Disable BootstrapCDN if using Bootstrap source files in your sub-theme.
; settings[bootstrap_cdn] = ''

; ;-------------------------
; ; METHOD 2: Bootstrap CDN
; ;-------------------------
;
; Method 2 uses BootstrapCDN, the only thing you might need to provide here
; is overrides to Bootstrap theme settings. Copy them here from the base theme
; to override.

E) I enabled the bootsub subtheme.

F) Sites/all/themes/bootsub/css, I added bootsub.css file. I added some styling in the css file.

G) I inspected my page using chrome and I see that styling is not coming from bootsub.css file and instead it is coming from

"netdna.bootstrapcdn.com.......bootstrap.min.css.."

Do you know why custom css file is not applying the styling on my page?

Further Notes

Using CDN method
Cache has been cleared
Aggregation is OFF
"View source" in browser does not show bootsub.css had been loaded
Using shared hosting

link

I found the link which does not allow me to comment. Link says:

  I had the same issue few days ago and I fixed with the template
  preprocess function. Just put the following function inside your
  template.php

function YOUR_THEME_preprocess_html(&$variables) {
 drupal_add_css('/PATH_TO_THEME/custom-style.css'); }

I tried to follow the above steps and did not work. I have the subtheme in sites>all>themes. In sites>all>themes>subtheme, I have template.php. I added the below code in template.php:

<?php
function subtheme_preprocess_html(&$variables) {
  drupal_add_css('/sites/all/themes/subtheme/css/subtheme.css');
}

?>

Do you know if i followed the steps correctly or anything else you would like to recommend to resolve this issue?

site

In the Theme settings Under Bootstrap Settings, Go to Advanced -> BootstrapCDN and choose Disabled from the dropdown.

Then in the theme info file uncomment the Method 1 section. Download the bootstrap files from Bootstrap Download and extract it to the subtheme folder. The extracted folder should be named - bootstrap and should contain all the necessary bootstrap js, css files.

You may get more info from this link Bootstrap sub-theming "how to"


Taxonomy, views and menu I have a content type "basic".

That content type is using 3 taxonomy vocabularies.

Vocabulary 1 - 5 terms
Vocabulary 2 - 3 terms (term1, term2, term3)
Vocabulary 3 - 6 terms

I have a view that displays all the content from this content type. There are three exposed filters for the three vocabularies, they are displayed as a exposed filter block top of the content and they are working great.

From a left side I have menu links that show the three terms of Vocabulary 2 and it looks like this:

Term1
Term2
Term3

Now the problem is if I select Term2 menu link that shows the content related to that taxonomy term and use some of the exposed filter, there are no results displayed.

I mean I'm selecting a menu link Term2 from left and than I check some term, lets say from the third exposed filter and the result is nothing, even if there's a content that belongs to that term.

Is it possible that menu to not interfere the filter results?

Exposed filter you can use only with views. yoursite.com/taxonomy/term/13 is not a view page. You can expose the filter as a block. And assign the block at the top of content.


Slow Loading Forms (submission ok) Hello i was wondering if anyone could suggest anything for me with this problem i have with my forms. (add/node) Ive turned CCK and all my modules off but still when i go to the node/add page the form is taking ages to load (20secs+) even for a simple submission form with no fields etc.

Generally my website http://onlinebanter.com runs ok and i do my best to keep my module lust down.

Is there any code or diagnostic tools i could use to see why my forms are talking so long to load.

Thanks

I found that it was because i was using an old version of pressflow it must have had some security problems with the other modules. Updated and things running like a dream :)


Why is my custom module not being recognised? I am trying to create a simple module by following the instructions in http://websmiths.co/blog/very-introduction-drupals-hookformalter.

I've created the following two files along with the content in them as below:

mysite_simplenews.info

name = Custom Example
description = Just a simple example module
version = 0.1
core = 7.x
package = Alpha Custom Modules

mysite_simplenews.module

<?php

I've uploaded the module to the server, but it is not being picked up in the list of modules.

Is this because I am running Drupal 7 and the tutorial is for drupal 6? Is it because of the <?php line in my .module file?

Take a look at Creating Drupal 7.x modules

Writing module .info files (Drupal 7.x)

Example
The following is a sample .info file:

name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example


jQuery dialog is duplicated when set on a form that uses AJAX Im using jQuery dialog on my form.

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

    $('.form-container').once('form-cont', function () {
      Drupal.custom.modalLinks();
    });

    $('.my-form').once('my-form', function () {
       Drupal.custom.setModal(this);
    });

);

  Drupal.custom.modalLinks = function () {
    $('body').on('click', '.modal-link', function (e) {
      var id = $(this).data('modal-id');
      var className = $(this).data('modal-class');
      var $modal = $('.modal--' + id);

      $modal.dialog('widget').
        addClass('modal__wrap--' + className).
        addClass('modal__wrap');
      $modal.dialog('open');

      e.preventDefault();
    });
  };

Drupal.custom.setModal = function (container) {

    var $container = $(container);

    $container.find('.my-modal').
      dialog({
        autoOpen: false,
        draggable: false,
        width: 900,
        minHeight: 120,
        modal: true
    });

};

This is working fine when the page is first loaded. However my form has AJAX submission. When submitted the form then returns a new form which also has a dialog modal link.

If I submit the form then when it reloads with AJAX then the jQuery dialog modal is duplicated (not visible but I can see with dev tools). If I open the dialog now then 2 modals are opened.

From reading about duplicate dialogs (but not for Drupal specifically) it seems the solution is to use remove or destroy on the modal. However when I try this is always completely disables the modal, it doesn't just remove the duplicates.
https://stackoverflow.com/questions/2864740/jquery-how-to-completely-remove-a-dialog-on-close

The behavior you describe is not related to the dialog function. From your provided code you can see that dialogs are created with all elements that have the identifier ".my-modal".

So I suppose within your AJAX call the original dialog element is not replaced by another version of the dialog, but a further element having the class "my-modal" is added to your markup.

You should investigate your AJAX callback function, whether it replaces the original markup or adds elements.


allow specific user to access specific pages in custom module I have created a custom module with custom database table in drupal 8 site.
It has add, update, list and search pages.

I want to restrict as only admin or sub-admin can access the add, edit, list pages. Any user(non-registered also) can access the search page.

How to achieve this in the module i have developed itself in drupal 8? Or is there any common way in drupal 8 to add permission for a particular URL?

I did that through routing.yml file. Thanks for the comments. I posted this just for reference that may help someone else.

notices.notices_form:
  path: '/notices/addupdate'
  defaults:
    _form: '\Drupal\notices\Form\NoticesAddUpdateForm'
    _title: 'Notices Form'
  requirements:
    _role: 'administrator'

notices.notices_search_form:
  path: '/notices/search'
  defaults:
    _form: '\Drupal\notices\Form\NoticesSearchForm'
    _title: 'Search Notices'
  requirements:
    _access: 'TRUE'


2 Pagers showing for Views Block I created a Custom View block in  Drupal 7 which it is simply pulling random "Did you know Tips" for visitors. I created a mini pager for the block to allow visitors to toggle through them (Ajax enable as well for the asynchronous refresh of the block)

Everything is working accordingly except one tiny issue... I have 2 Pagers on my home page??? One is the mini pager under the block which is desired, but an additional Full pager is created at the bottom of my main page. Oddly, it's only found on the main page!!! No other nodes pages have this issue.

It seems that the behavior is along the lines that the additional pager is being "promoted to the front page" however, the content type has that excluded. Is there a way to hide this additional pager in template.php / views-view.tpl.php? Perhaps I missed something along the way?

In investigating this issue further, I resided to installing the Views Litepager module as it's an increase in performance and it resolved my issue as well with the 2 pagers.


Select list with input fields I would like to have the following field widgets:

I would like to give the user the possibility to give in 4 nicknames and select the default one that will be shown to other users.

Is there a module for this or something I can work with?

I've searched google but with no success ... .

Try the Double field module.

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

I used it for one of my project and works well.


How to add existing product variations to a new product? I have products with the same variation.
From product edit form I can only add new variation.
In variations field form setting i haven't "Allow users to add existing products."

how can i have this option or How can add existing variations?

The option you're looking for is not present on purpose (and the widget itself is different despite how it worked in Drupal 7). Every product has its own variations that cannot be shared, so there's no way to reference the same variation from multiple products.

If you need to sell the same thing from multiple contexts, what you probably need is some other entity that references the same product, not a standalone variation. Products:variations have a very clear parent:child relationship ... they're "variations" of the main "product".


How can I run client side validation before a Drupal AJAX submit call? I'm trying to perform client side validation using jquery.validate.js on a form submitted via Ajax (using form actions), but for some reason, the client side validation is not being triggered.

This is what I have in my template.php file in order to trigger an ajax call for login:

$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
'wrapper' => 'user-login-form',
    'event' => 'mousedown',
 );

And here's my js to trigger the client side validation:

(function ($) {
Drupal.loginAjax = {
    form_id: 'user-login-form'
};
Drupal.behaviors.loginAjax = {
    attach: function (context ,settings) {
         Drupal.loginAjax.beforeSubmit = function (form_values, form, options) {
                $("form#user-login-form", context).validate({
                    rules: {
                        edit_pass: "required",
                        edit_name: "required"
                    },
                    messages: {
                        edit_name: {
                            required: "E-mail Address is required"
                        }
                    }
                });
        }

        for (ajax_el in settings.ajax) {
            if (Drupal.ajax[ajax_el].element.form) {
                if (Drupal.ajax[ajax_el].element.form.id == Drupal.loginAjax.form_id) {
                    Drupal.ajax[ajax_el].beforeSubmit = Drupal.loginAjax.beforeSubmit;
                }
            }
        }

    }
};
})(jQuery);

The beforeSubmit method is being triggered because when I print to the console, I do get a value.

On a sidenote, I've tried doing this using the beforeSend instead. The client side validation does trigger, but the submit is not being halted.

Any pointers please?

I would attempt to hijack the submit form by changing the event type and triggering the submission yourself.

For example:

$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
'wrapper' => 'user-login-form',
    'event' => 'submitmyform',
 );

Then just add your own click or form handler. Once you happy with the validation simply trigger the event "submitmyform". For example:

Drupal.behaviors.loginAjax = {
  attach: function (context ,settings) {
    // Cache the form object
    var $form = $("form#user-login-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
      .once('loginAjax')
      .off('submit')
      .on('submit', function(e){
      e.preventDefault();
      var $form = $(this);

      // Run validation on $form object.

      // If success, trigger event on button
      if(valid) {
        $submitButton.trigger('submitmyform');
      }
    });
  }
}

I have not tested this code but in essence this is how I recommend you approach it rather than messing around with the ajax object itself.


Creating custom button that gets a certain views block on the database Is there a way to create a custom button that gets a certain views block on the database upon click?

I want to write a custom function button that upon click, connects to the database, retrieve a certain view block, and displays it in a .tpl page.

Thanks.

All you need to use modal form which uses ctool suites. Install exapmple and dependant module. Try create link or button just same as ajax form.


Is there a 'official' place to put PHP snippets? If I wanted all PHP removed from the front end (meaning not in views, not in the body of blocks), but someplace hidden in the background, is there a 'official' recommendation for doing so?

Drupal's framework is PHP so I figured it would have some sort of standard for this type of thing, but it doesn't appear to be the case.

I would quickly answer no to your question (and explain myself below).

The only thing that comes to my mind as a kind of answer is "place it in a hook".
But as you probably know, there are tons of these.
So, there is not one single "official" place, if I get your point right.
Plus, using a hook means placing your PHP Snippets in files.
Is that in agreement with your question? Or, is your question better phrased as "Is there a 'official' place in the configuration to put PHP snippets?"

Well, hope this explained the "no" answer some, if I am off, please do elaborate some more.

Cheers!

P.S.1: Sounds interesting, sounds like you have something specific in mind. :-)
P.S.2: It's worth mentioning that there are even some modules like the Computed Field that guide you (through naming conventions) to place your snippets inside specific functions.
This is similar to the hook idea, but fantastically presented and suggested in the field's configuration.
It's one of the reasons I am so very fond of the Computed Field


How to convert a command line table (drush output) to any spreadsheet? (csv,excel,ods) I often use commands like drush pm-list or drush views-list to get some listings of what my current project is using and for sake of usability I would like to import that stuff in a spreadsheet programm (I dont care which, csv can be imported bascially everywhere).

I digged into drush code and find out that it uses Console_Table for generating table like output. Maybe someone has an idea how to implement/ find a generic way to get a csv output from it.

Check out this new feature from the latest dev version of Drush 8.x-6.x:

$ drush @dev pm-list --format=csv
Administration,Actions permissions (VBO) (actions_permissions),Module,Not installed,7.x-3.1
Administration,Administration Development tools (admin_devel),Module,Not installed,7.x-3.0-rc4
Administration,Administration menu (admin_menu),Module,Enabled,7.x-3.0-rc4
Administration,Administration menu Toolbar style (admin_menu_toolbar),Module,Not installed,7.x-3.0-rc4
Administration,Administration views (admin_views),Module,Enabled,7.x-1.1
CCK,CCK (cck),Module,Enabled,7.x-2.x-dev
CCK,Content Migrate (content_migrate),Module,Disabled,7.x-2.x-dev
CCK,Location CCK (location_cck),Module,Enabled,7.x-3.0-alpha1
... etc.

If you are at all wary about using a dev version of Drush, you could check it out following the version control instructions at http://drupal.org/project/drush/git-instructions.  Then, you can use git checkout 7.x-5.8 to go back to latest stable, and git checkout 8.x-6.x to go back to latest dev, and use stable most of the time, and the dev version when you want to output something in another data format.

Update:  Note also that Drush 8.x-6.x-rc4 is out now, which is pretty well fit for general consumption.

Update 2: Note that this is a standard feature now in Drush 6 and Drush 7 (master branch of Drush on github)


Linking to a php site located in a subdirectory of the Drupal site So I've taken part in a very interesting Drupal project that has a multilingual Drupal 7 site and three sub-sites (all using the same domain) in sub-directories of the main Drupal site. So it's kind of like this:

http://example.com <- main Drupal site
http://example.com/site1 <- php site that doesn't use Drupal
http://example.com/site2 <- php site that doesn't use Drupal
http://example.com/site3 <- php site that doesn't use Drupal

Now I can create relative links to these sites on the Drupal site by adding links like

Site 1

And that works when I'm on the homepage, but since this is a multilingual site, any other page I go on uses a language prefix on the URI like this:

http://example.com/en/contact

If I try to click on the Site 1 link I made above while on the contact page, it takes me to:

http://example.com/en/site1

and displays a 404 error.

Currently, the site uses hard-coded absolute links to get around this issue, but it's becoming a real pain to use this in our local and testing environments and I've been asked to remove the absolute urls from these links.

I've tried a few different things like using Token Filter with [site:url]/site1, but it still tries to add the language prefix and gives me the same 404 error. I thought of trying to use a module to look for these specific links and set them accordingly, but I can't think of an efficient way of doing it. Other ideas like using JavaScript to edit the links after the page loads or redirecting to the right page just smell so bad I don't want to try them.

Any ideas on how I can create links to these sub-directories without hard-coding them?

Well, I ended up going the JavaScript approach. I don't know how to get around using absolute links to the subsites without doing something pretty hacky, so I created a module that adds a javascript file when NOT in the production environment. The javascript searches all links for hrefs with the production domain and changes them to use the current page's domain.

Hence, in production the module does nothing, but in any other environment it replaces the absolute links.

Not optimal, but a workable solution for my case...


How do I enable the "extra" stuff in the OpenPublic distribution? OpenPublic is a Drupal distribution that is supposed to be for NGOs (and government).  I've downloaded and installed the distribution as a tarball from their site using the big download button.

The tarball is about twice the size of a basic Drupal 7.22 core tarball, so I assume there are some extra stuff included in this distribution.

However, after following the instructions for installation (they refer to the standard instructions for installing Drupal 7), I am looking at a completely plain vanilla Drupal 7 website.  No additional themes, no additional content types, no additional functionality.

I've been hunting high and low for documentation for what to do post-installation with this distribution and come up with nothing.

There is a support group for the distribution at groups.drupal.org, but it is not very responsive, for instance, this question was asked on Jan 18th, with no reply yet.

I am asking here, hoping that someone here is familiar with this distribution and can provide me with the recipe of how about to "unlock" whatever this distribution has to offer, or—even better—provide a link to the missing manual.

It sounds like you've just installed the wrong profile. At the first step of the installation you get a choice like

Once you choose OpenPublic and follow the installation through, you won't have a vanilla Drupal install any more. For example your home page looks like this:

Don't forget it's still in beta so you're likely to see warnings/notices around the place; I wouldn't recommend using it for a production site yet. It's also pretty sluggish compared to a normal Drupal install so make sure you profile it before deciding whether or not to use it.


Drupal site returning 404 error for all pages besides the main page I have two completely independent Drupal installations on the same server. Both have https enabled in the settings file, and the Apache configuration was literally copied from one file to the other. However, one of them works under HTTPS and the other does not. The broken site will open the front page successfully, but, for example, https://www.example.com/user will return a 404. https://www.example.com/index.php?q=user works fine.

I opened the apache config of the WORKING site, and changed the DocumentRoot to the directory of the BROKEN site, and tried the site using the working URL, and I see the broken site...and it IS STILL broken.  This leads me to believe that it is not Apache, but something in the Drupal installation or configuration which is misbehaving.

Both installations have an .htaccess file in the base directory, and in sites/default/files, and the files are identical.

The apache error logs for both sites have the same errors:

server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)

and

server certificate does NOT include an ID which matches the server name

Any advice on where to look next?

I copied and pasted the <VirtualHost *:443>
section several times...and every time I changed the ServerName and ServerAlias...but didn't change the <Directory /var/www/example.com>

I hang my head in shame and embarrassment.


Host doesn't support nested folder structures for deployment. How do I adjust Composer? So, I have to deploy a drupal 8 site to a host which doesn't provide functionality to specify an entry point for a Drupal site which is nested below the site root folder. How can I update the folder structure to have everything in the server's site root?
What I tried initially was to move the contents of the site_root/web/ folder up to the site root, but this causes 500 errors. I'm not sure since I can't see the errors on the host server, but replicating the scenario on my dev machine points to the autoloader.php file looking in the wrong place PHP Fatal error:  require(): Failed opening required '/var/www/html/ab-test/../vendor/autoload.php'.

I have tried to resolve this by first following the suggestion to re-run composer install from the site root but that doesn't seem to help. When I manually update where the autoloader.php should be looking, I then get this errorPHP Warning:  require(/var/www/html/ab-test/vendor/composer/../../load.environment.php) which again suggests that the file/folder structure is being set somewhere I'm not thinking of or don't have enough experience to check.
So, my convoluted question comes down to how do I switch from a nested to a non-nested folder structure without everything freaking out?

As you are using an Apache server, you may try to set the Drupal root folder using an .htaccess file in your site_root:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]

(Replace example.com with your actual domain name.)

This way, you can keep the "nested" folder structure created using Composer and serve all requests for your domain with the web sub folder.


Efficient and easy Drupal 7 Development to Production workflow How would you put large existing Drupal 7 production site in some simple Development-Staging-Production workflow ?

I read through various documentation about the issue, but would like to know more efficient real life examples.

It is environment where only one person changes Drupal code (for now), and several editors do content publishing (they can edit content on live site and it seems it is ok to allow them).

I have in control Debian box with admin privleges (production site), and recently I did set up local Development/Staging Server (also a Debian box).

I am fond to Drush (haven't took advantage of drush make, though, but I had migrated some Drupal sites from server to server). I haven't used Features module, but I could implement it if neccessary. I have not used GIT yet, but I had read about it in theory. I am not sure is it a must for me to go with GIT, considering only one developer commits code.

My concern is about database updating, as I understood, GIT does not do that, and there could be enormous and critical differences between dev and production DB (settings change, site user inputs (registrations, comments etc, node creation etc)

Any advices?

In short, I would:

Use features to get my configuration in code.
Use git to manage my code.
Use drush to manage my databases.

Why to use git to manage code:

Drupal.org uses git to manage the Drupal project and all the modules.
Version control of code allows you to easily see what changes have been made to your code over time.  Without this, debugging/rolling back to a known good state is much harder.

When using git, I personally avoid complicated features (like submodules for Drupal modules) and simply commit all my code (Drupal core, contrib modules, patches, and my features) to a single repository.

If you already have dev and staging servers set up, getting git to push code to all three machines shouldn't be too hard to set up.

Why to use features to get configuration into code:

If you do dev/staging/live, you are going to have three sites now, not just one.  Keeping track of configuration changes among three sites is a mess.

You basically have two options:

Write down all your changes in a text file and apply them site-by-site manually.
Use features.

Although #2 is harder to set up, it's much easier to deal with in the long run.  A command like drush @mylivesite fd will quickly reveal how the configuration on your live site differs from the code in the features (managed by git).

In addition, as an added benefit of getting everything in features, you can edit the features code directly with a text editor; sometimes this is faster than using the Drupal admin UI.

Why to use Drush to manage databases:

Drush has a number of commands for syncing databases.  It can be a bit of pain to get your servers set up to do this, but once you do, the time savings are tremendous.  Google for tutorials for details.

In conclusion:

With this setup, most of your configuration will be in code (thanks to features).  Your code will be version-controlled and easily pushed between servers (via git).  What git can't handle, the database, will be taken care of with drush.


Entity browser not showing image after selecting an entity (Drupal 8) I'm using drupal 8 entity browser to select entities/images. I cannot figure out how I can show a thumbnail or rendered image after selecting an entity. Below is an image that only shows the label of the entity after selecting

I have already checked the View and Entity Browser but couldn't not find an option to display the image after selecting

Go to Manage Display of your media bundle. You may have disabled the image from Manage Display, you can enable it and update the format to Image / Responsive Image or whatever best suits you. Please check the attached screenshot


How do I print out a embed video? I have a paragraph which can either contain an image or a video. When I let the output just come out in {{item.content}} the actual youtube iframe is output. However when I start parsing things to detect if a video or image is there I seem to lose this functionality.

I can still manually grab the URL output. However, Drupal seems to have some inbuilt features that I'd like to preserve. For example, the Youtube link ends with watch? which Drupal knows to convert to embed?, otherwise Youtube will refuse the iframe connection.

This is what I'm currently doing.

{% for item in items %}

{{ item.content['#paragraph'].field_content_2_headline.value }}

{{ item.content['#paragraph'].field_content_2_content.value|raw }}

        {% if item.content['#paragraph'].field_content_2_media.0.entity.field_media_oembed_video is not empty%}
            {{  item.content['#paragraph'].field_content_2_media.0.entity.field_media_oembed_video.value }}
        {% else %}
            {% for list in item.content['#paragraph'].field_content_2_media.0.entity.field_media_image_1 %}

            {% endfor %}
        {% endif %}

{% endfor %}

If I just output item.content['#paragraph'].field_content_2_media when there's a video detected, I get an error that I'm trying to print a field list item.

Is there a way to reference the iframe functionality that Drupal seems to have?

Use field formatters instead of printing raw values. With Twig Tweak module it can be done as follows:

{{ item.content['#paragraph'].field_content_2_media|view }}


Understanding theme hooks and template preprocessors In hook_theme for the poll module in drupal 7 the following is defined:

function poll_theme() {
  $theme_hooks = array(
    'poll_vote' => array(
      'template' => 'poll-vote',
      'render element' => 'form',
    ),
    'poll_choices' => array(
      'render element' => 'form',
    ),
    'poll_results' => array(
      'template' => 'poll-results',
      'variables' => array('raw_title' => NULL, 'results' => NULL, 'votes' => NULL, 'raw_links' => NULL, 'block' => NULL, 'nid' => NULL, 'vote' => NULL),
    ),
    'poll_bar' => array(
      'template' => 'poll-bar',
      'variables' => array('title' => NULL, 'votes' => NULL, 'total_votes' => NULL, 'vote' => NULL, 'block' => NULL),
    ),
  );
  // The theme system automatically discovers the theme's functions and
  // templates that implement more targeted "suggestions" of generic theme
  // hooks. But suggestions implemented by a module must be explicitly
  // registered.
  $theme_hooks += array(
    'poll_results__block' => array(
      'template' => 'poll-results--block',
      'variables' => $theme_hooks['poll_results']['variables'],
    ),
    'poll_bar__block' => array(
      'template' => 'poll-bar--block',
      'variables' => $theme_hooks['poll_bar']['variables'],
    ),
  );
  return $theme_hooks;
}

In function poll_view_voting($form, &$form_state, $node, $block = FALSE) { there is $form['#theme'] = 'poll_vote';

How does this work and what does this to?

Also there is this function:

function template_preprocess_poll_vote(&$variables) {
  $form = $variables['form'];
  $variables['choice'] = drupal_render($form['choice']);
  $variables['title'] = check_plain($form['#node']->title);
  $variables['vote'] = drupal_render($form['vote']);
  $variables['rest'] = drupal_render_children($form);
  $variables['block'] = $form['#block'];
  if ($variables['block']) {
    $variables['theme_hook_suggestions'][] = 'poll_vote__block';
  }
}

I was able to create a function theme_preprocess_poll_vote(&$variables) which I was able to change the output. Is their a document that explains how this all works?

I'd suggest you read everything you can in the Theming guide.  It looks like you're specifically looking for this part of it though.


How to execute VBO list of nodes in Rules on After updating an existing user account event? I have a VBO of all the unpublished nodes of the user, and I want to publish all of them based on user role change that happens via Rules.

I created a component of rule to list the nodes of that user but since my Event is After updating an existing user account in my actions section, when I add the component, there's no Node related parameters to pass so I can publish those nodes.

Update: Pierre's answer actually defines the steps that I've already taken, the last part that puzzles me is that how can I add the component to be triggered to an After updating an existing user account event where there's no node defined in it.

What you actually need to do is similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

  You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
  However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
  You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
  The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from your VBO list of the unpublished nodes of the user. And for each node in the list you want the rules action to be "publish node" (instead of "remove sticky").

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in that video also. I'm assuming your VBO view also requires the userid already.

The Rules component that you create as described above, should then become the action to be performed by a rule that is triggered by the event "After updating an existing account". This is what differs from what is shown in the video, starting from 11:30 (in the video the Rules component is triggered daily, via the Rules Scheduler).

Should you need any other rules "conditions" (eg: only for selected roles), you can add them to the rules component you created.


Alter field content inside modules hook_node_view I'd like to alter, but not save, a fields output.  I've got a MODULE_node_view already setup.  Is there a way to do this?  I don't want to save the output permanently.

In HOOK_node_view() you can alter your fields like this:

function MODULE_node_view($node, $view_mode, $langcode) {
  //be sure to be in full page mode, but you can also user 'teaser'
  if ($view_mode == 'full' && node_is_page($node)) {
    //kpr($node); => use devel module and kpr() to inspect your node.
    //Change the title of the node
    $node->title = 'New title';

    //Change the "text" field
    $lang = field_language('node', $node, 'field_text');
    $node->field_text[$lang][0]['value'] = 'New field text value';

    //Change the "body" field which has a slightly different syntax
    $lang = field_language('node', $node, 'body');
    $node->body[$lang][0]['value'] = 'New body value';
  }
}

Note the usage of field_language() to retrieve the correct value for each field.


Limit duration (length / time) of Uploaded Video I have a website that uses the Video module to allow users to upload videos. I want to limit the duration(both minimum and maximum) of the video that the user uploads.

For Example:

Users cannot upload videos that are more than 10mins and less than 5mins. So the duration of their videos should be in-between 5 to 10mins.

Thanks in advance...

You can't do that at the moment, but you can set up your presets to limit the length of the transcoded video. I hope that is sufficient for you.


Add a variable amount of time to a date field via rules I'm trying to add a time duration field value (integer type representing seconds) to a date field using rules, but I'm not able to reference the duration field when it comes time to calculate/edit the date value (presumably because they are of different field types).  I can do things like "+30 days", but really what I want to do is "+$x days".

The interval module provides an action "Apply an interval to a date" (you find it in the "data"-section of the action list). The module supplies a "interval field", but surprisingly, instead of providing integration between rules and that field, it provides that action, which provides integration between rules and an integer field. The action allows you to specify a data value and specify which interval that number is to be interpreted as (days, months, ...)


Is there a way to send a newsletter to those users who share a taxonomy term in there profile I need to be able to collect newsletters for a specific type of content. This content will have tags that the user will also check on when the sign up or edit their account information. I then need to send this newsletter to all those associated with that taxonomy list.

It sounds like you want something that simplenews doesnt do right out of the box. You can create newsletters (and a block for subscription links) -- but it doesnt appear to based off of Taxonomy terms directly.

Simplenews supports Rules, you could maybe define rules that achieve your goal.

I have not used simplenews, but I have a website for student surveys which has various email templates that remind students if they have additional surveys to complete, all running off of cron tasks -- you could code this type of newsletter functionality by hand without many helper modules if need be.

Sometimes manipulating a contributed module to suite your needs is harder than just doing it yourself for your project.


Path alias tokens and node references I'm trying to figure out if path aliases are even capable of what I'm trying to do, or if I need some other sort of module.

I have a content type "project" and a content type "mockup". A "project" references a User. A "mockup" references a "project". I'd like the path pattern for a mockup to look something like (I'm making up the token names, but you get the idea)

[referenced_project's_reference_user]/[referenced_project's_title]/[node:title]

Now another thing is that the project path already looks like the first part of the mockup's path:

[project's_referenced_user]/[node:title]

So I'm wondering if there's a way for a token to get the url of the referenced node or something? I was hoping you could stack tokens something like: [[related_project]:url] but that doesn't work.

If you can't tell, I'm using the "references" module.

You certainly can.

You need Entity and Entity Token (comes with Entity module) modules.

Clear cache after enabling them. The referencing node info will be available to you.

For the 'referencing' functionality, I use Entity Reference instead of Node Reference which will most probably be deprecated in the near future in favor of Entity Reference.    (but I remember node reference info is also available in Pathauto pattern, you may try yourself)


How do I remove comments from an existing webform? After the fact, I learned how to make comments <hidden> by default for new webforms. However, for the forms I've already created, there is no option to remove comments. How do I remove comments for these already published forms? Do I have to make a whole new form, or edit the database directly somehow?

Thanks for any help, and please let me know if there is any other information I need to provide.

No need to do either; you can edit any existing webform and toggle the Comment settings menu to Hidden on each published form.


Quick edit destroys CKEditor formatting... any way to avoid it? Quick edit doesn't bring up CKEditor buttons, and clears immediately all previous formatting (like numbered lists), which can lead to serious data lost, in my case.
Is there any patch to have Quickedit SKIP those textareas at all, while allowing it to interfere in those more simple fields?
Using 7.x-1.5 module version, Drupal 7.41
thanks

If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.


Is there a way to make sure an autocomplete field as an actual match? I have an entity reference field in a content type in D7 set with an autocomplete widget. This is a required field, however if you type in something that doesn't have a match, it will still submit and save anyway.

Is there a way to make sure an actual match is found before allowing it to save?

Per the comments above, this is a bug with Entity Reference Fields and is being engaged per the Issue Queue at:

https://drupal.org/project/issues/entityreference?text=autocomplete&status=All

Patches for the Simple batch seem to work from this thread:
https://drupal.org/node/1974202

Patches for the Views reference seem to work from this thread:
https://drupal.org/node/1702172


Backup and migrate exhausts memory I have a new Drupal 8 site, where I installed few minor modules and Commerce 2.0 beta3, but the site has only 2 nodes so far, even the commerce tables are empty.
However even with PHP memory limit set to 2048M it exhausts it all giving me this message:
Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 10464376 bytes) in /var/www/website/public_html/modules/backup_migrate/vendor/backupmigrate/core/src/Source/MySQLiSource.php on line 347

For this example the PHP memory limit was 1024M, I tried database only backup with cashe tables excluded.
I remember being able to run B&M with 256M allocation on D7 and hundreds of nodes, loads of modules and content types.
As I don't see this issue anywhere on the internet or reported as an issue on the module page, I'm left to believe there has to be something specific to what I may have done wrong?
In the log I also find the following (with full error reporting on):
Notice: Undefined index: settings_profile_id in Drupal\backup_migrate\Form\BackupMigrateQuickBackupForm->submitForm() (line 84 of /var/www/website/public_html/modules/backup_migrate/src/Form/BackupMigrateQuickBackupForm.php)

System specs:

Ubuntu server 16.04
Running Apache server
With PHP7
Drupal version 8.2.3

EDIT:
I found a few extra errors on different tests:
Notice: Undefined index: groups in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 91 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

Warning: Invalid argument supplied for foreach() in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 91 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

Notice: Undefined index: #description in BackupMigrate\Drupal\Config\DrupalConfigHelper::addFieldsFromSchema() (line 116 of /var/www/website/public_html/modules/backup_migrate/src/Config/DrupalConfigHelper.php)

Where the last one appears twice in a row every error sequence.
Appreciate all help!
Alari

I managed to reduce the memory exhaustion with remedying the last edit's errors in the following matter:

I added a not empty check for the "groups" index in the array around the foreach function on the 91-st line of code in DrupalConfigHelper.php

static public function addFieldsFromSchema(&$form, $schema, ConfigInterface $config, $parents = []) {
// Add the specified groups.
// Temp fix for "Undefined index: groups..."
if(isset($schema['groups']) && !empty($schema['groups'])){
  foreach ($schema['groups'] as $group_key => $item) {
    // If the group is just called 'default' then use the key from the plugin as the group key.
    // @TODO: make this less ugly.
    if ($group_key == 'default' && $parents) {
      $group_key = end($parents);
    }
    if (!isset($form[$group_key])) {
      $form[$group_key] = [
        '#type' => 'fieldset',
        '#title' => $item['title'],
        '#tree' => FALSE,
      ];
    }
  }
}

And fixed the "undefined index #description" error on line 116 by checking if the "#description" index exists, and if not create it with empty value to be processed on the initial 116 line.

switch ($item['type']) {
    case 'text':
      $form_item['#type'] = 'textfield';
      if (!empty($item['multiple'])) {
        $form_item['#type'] = 'textarea';
        // Temp fix for "Undefined index #description..."
        if (!isset($form_item['##description'])) {
          $form_item['##description'] = '';
        }
        $form_item['#description'] .= ' ' . t('Add one item per line.');
        $form_item['#element_validate'] = ['BackupMigrate\Drupal\Config\DrupalConfigHelper::validateMultiText'];
        $value  = implode("\n", $value);
      }
      if (!empty($item['multiline'])) {
        $form_item['#type'] = 'textarea';
      }
...

Now backup works nicely.