Get custom fields assigned to taxonomy How to get custom fields assigned to taxonomy in Drupal 8.
What I have done so far is:

$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');

$contact_countries now holds taxonomies, I can get name of taxonomy and ID, but I also created custom field in taxonomy, how can I get it?

With this code

foreach($contact_countries as $contact_countrie) {
        $terms[] = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid);
        $variables['contact_countries'] = $terms;
    }

I'm getting object(Drupal\taxonomy\Entity\Term) with protected values. I can see my custom fields values there but can't access it.

I done it like this:

$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');

$terms = array();

foreach($contact_countries as $contact_countrie) {
    $terms[] = array(
        'contact_country' => $contact_countrie->name,
        'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
        'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,
    );
}

Here I have fields field_phone (text field) and field_category_flag (file field).


How to redirect comment form? I want to redirect to a node after comment form submit.
But I tried  using hook_form_alter hook,the redirect not happen.
function pf_core_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
 if($form_id=='comment_comment_form'){
   $form['#submit'][] = 'pf_core_comment_comment_form_submit';
 }
}

function pf_core_comment_comment_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setRedirectUrl('<front>');
}

Please help me to fix this issue.

$nid = 1; // lets pretend the node ID you want to redirect is 1.

$url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$form_state->setRedirectUrl($url);


Change weight of CSS file loaded in custom module with #attached? Im working on a custom module which loads a CSS file:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
);

How can I change the weight of the file so that its loaded after the other CSS files? I thought it would be something like this:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  'weight' => 1000,
);

Or this:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  '#weight' => 1000,
);

You want something more like this:

$content['#attached']['css'] = array(
  array(
    'data' => path_to_theme() . '/new.css',
    'type' => 'file',
    'weight' => 1000,
  ),
);


Is there a way to style the main-container without it effecting ALL the site? I am using the bootstrap subtheme.

I was wondering if there was a way to style the main-container in relation to a particular node or section of the site, rather than it styling it the same everywhere. The reason I want to do this is because I want to setup multiple small mini-sites with different themes. Sort of like a show-case of what I can do in web-design.

The problem though is I can style the main-container, but it will style it everywhere for every page. Is there a way I can make it target specific only pages?

In this example: I want to style the white space BUT it only be done on my "mech" page. To my current knowledge, if I target .main-container it will style it everywhere on every page, which is what I do not want.

You can do it using the CSS. First on whichever node you want to do, find its specific class given when you create that node (How: right click on the page and Inspect element in the code ........., you will find the several class, one of which is specific for that node). Now take that class. Now suppose if you want to change the main-content with that node only and do not want to change other, use following selector in css,

.specific-page-node-class #main-content {your css code}

This will apply change to main content of that specified node only and do not change to other.

Credit: Link for detail question and answer which I asked on same topic on the Drupal answer, I have summaried above


How do I group my fields in a view? I have a content type (Staff Member) with many fields, such as portrait, name, and bio. The name and bio fields are grouped together under the field group _text_fields_.

I have created a view for this content type.

The view renders each content node like this.

John Doe

John Doe has been with us for 800 years.

However, I want grouped fields to be grouped like this.

John Doe

John Doe has been with us for 800 years.

I've tried writing a views-view--staff-members.tpl.php template file, but it receives all of the .views-row items as a HTML string.

How might I accomplish this?

You don't need to modify your .tpl, you only need the Field Group module to group your fields together. With this module you have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

You can read the documentation where you will find some examples.


Non-static method view::load_views() should not be called statically with VIEWS When I copied my Drupal 6 web site to another server with a higher version ofPHP, I get this problem on all pages that have views:

strict warning: Non-static method view::load_views() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\views.module on line 864.
strict warning: Non-static method view::db_objects() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\includes\view.inc on line 1417.
strict warning: Declaration of calendar_plugin_display_page::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_page::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_block::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_block.inc on line 78.
strict warning: Declaration of calendar_plugin_display_attachment::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_attachment::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_ical::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\calendar_ical\calendar_plugin_display_ical.inc on line 217.
strict warning: Declaration of views_content_plugin_display_panel_pane::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\ctools\views_content\plugins\views\views_content_plugin_display_panel_pane.inc on line 40

These errors, at least those coming from Views, does not really have a proper solution, because the versions of Views and Calendar that cause them, are no longer being updated.

Views 2 is officially not being updated anymore, and I doubt anything but serious security problems is going to change that. Calendar could potentially have the problem fixed, but this is also a module with a great deal of issues, and for an old version, I simply wouldn't expect these problems to be prioritized enough to get fixed.

Your basic options:

Upgrade to Views 3, and the corresponding Calendar version.
Disable E_STRICT error reporting.
Simply accept that the errors are there.

A more sophisticated and perhaps better solution would be to locate the relevant patches in the issue queues, and apply them in your drush make file.


User is notified when new content is created using Rules I created two groups in one group type.

Job Post
Business

Each group has its own content type(same label) and group permissions.

User Story:

"As a user(Job Post) I would like to be able to create a job. A job should contain a description and a job type - for example, plumbing."

As a plumber(Business) I would like to be notified every time a new job is posted that is for plumbing, but not for any other types of work."

How specifically can this be achieve using Rules as I'm a newbie on this module and still trying hard to make setup on this problem.

It really depends on your setup. A simple way to achieve this would be to assign business users with a role let's say "Business". Once that's done you can create a trigger on creation of new node, set conditions based on your requirement e.g. user role = "Business" and category = "Plumber" and action to send out an email.

You might need additional modules if you're looking at sending out HTML emails.

Let me know if you need any help.

Thanks


Different ways to template a node I'm pretty new at Drupal (about two weeks), but I'm starting to see the huge amount of possibilities. It is a fine piece of engineering.

I've got a content type, called Products, which is shown in a panel pane and also has a page for itself. I want to output fields differently in both situations, but tweaking the node--product.tpl.php I've realized that I modify both the node in the content pane AND the page.

Is there any way that I can template the two of them in different ways?

Thanks,
Hector

I have been working on Drupal for about 2 years and I have found these two modules to be absolutely the best tools to template a node:

Display Suite: https://drupal.org/project/ds
Panelizer: https://drupal.org/project/panelizer


How to add one more field in disqus form i have been installed disqus module in my drupal setup.it gives only one textarea field how to i add one more field to get subject from user.

Disqus does not provide titles, therefore, it is not possible.

What the Disqus module does is embed the Disqus chat/comments as an iframe. For security reasons, you cannot modify/alter anything that is inside an iframe.


How can I override a module-defined view and export to code? I'm using nrembrowser to provide a media library and allow users to insert media via a wysiwyg interface. The module provides its own view which I've altered. I keep my views in code (using features) but I don't know any way to override an existing module-defined view via code (ie something similar to strongarm, but instead of overriding a variable, it's overriding a view). I've solved the problem by using a nrembrowser hook to change the view to my custom one, but I'd be interested in knowing if I could've overridden the module's default view in some way.

Using hook_views_default_views_alter(). There's a page on this on drupal.org. As far as I know there's no way to have features automatically export an overridden view and put it in a hook_views_default_views_alter(), and it looks like there's actually an issue with using features together with this hook.


Why is my subtheme screenshot not appearing? I have created a subtheme, and it shows up correctly on the admin/appearance page, but I can't seem to get my screenshot to appear.  It only displays the screenshot from the base theme.  I have declared the screenshot in mytheme.info, and the PNG file is sized to exactly 294 x 219.  Any ideas?

Thanks!

Sub theme by default inherit the screenshot from base theme.You can override the screen shot by simply adding screenshot of your sub theme in your sub theme directory

  The optional screenshot key tells Drupal where to find the theme's
  thumbnail image, used on the theme selection page
  (admin/build/themes). If this key is omitted from the .info file,
  Drupal uses the "screenshot.png" file in the theme's directory.

  Use this key only if your thumbnail file is not called
  "screenshot.png" or if you want to place it in a directory outside of
  your theme's base directory (e.g. screenshot = images/screenshot.png).

screenshot = screenshot.png

Reference: https://drupal.org/node/171205#screenshot

Other things which may help.

As Jhilke comment try clearing your caches.
Check the screenshot file permission it should readable by web-server.


Why do I get the "could not find the controller" error? I'm trying to setup DrupalGap with Commerce following this tutorial, but I get this error:

  404 not found: could not find the controller.

I've manually confirmed Services are set up properly with Advanced REST client (Chrome), with this instructions. All seems OK; the endpoint/resource is operating and I receive a 200 OK response, but when I try to test the application from admin/config/services/drupalgap, I always get this error.

I use Services frequently and I can confirm It's working good on this site. I also verified DrupalGap is working too.

What could it be?

A 301 is a redirect, so it sounds like you have the Global Redirect module enabled. See this issue for details: https://www.drupal.org/node/1927336

The patch allows you to declare paths that should be ignored by the Global Redirect module so it doesn't hijack Service calls to your Drupal site. You'll input something like this into the configuration text area once the patch has been applied:

drupalgap/*


Slow "Add another item" with unlimited valued fields In Drupal 7, when you have node with field which has unlimited values (let's say, image field), "add another item" response time becomes very slow after you added 10 - 20 items. How do you fight this problem? Have you ever encountered this problem?

I created a project, where user can add up to 100 values of an image field which in theory has unlimited values setting. But, after you add a dozen of images, every new click on "Add another item" becomes slower than previous. I know this happens because of the fact, that Drupal rebuilds this field and all its values after each ajax request, so the more values you added the more work Drupal has to do on every "ajax" request, but, actually, this is not quite great thing.

Are there any approaches on how to change/override such a behaviour?

building on the answer by Charlie, I found that it takes about the same amount of time to reload the block if you are adding 1 or 100 items, so here is a trick to add a select list of numbers in the form next to 'add more' so you can choose how many you are adding. This saves a lot of time and is still flexible.
Could be wrapped in to a little module

<?php
/**
* Implements hook_field_attach_form()
*/
function village_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode){
  $options = array('language' => field_valid_language($langcode));
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
    'deleted' => FALSE,
    'language' => NULL,
  );
  $options += $default_options;
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  // Iterate through the instances.
  $return = array();
  foreach ($instances as $instance) {
    // field_info_field() is not available for deleted fields, so use
    // field_info_field_by_id().
    $field = field_info_field_by_id($instance['field_id']);
    $field_name = $field['field_name'];
    //If we are looking at our field type and specific widget type, and we are multiple entries
    if($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED){
      //Check just in case the button is here, and add another #submit function
      if(isset($form[$field['field_name']]['und']['add_more'])){
        // add a simple select list, this defaults to numb 3
        $form[$field['field_name']]['add_more_number'] = array(
          '#type' => 'select',
          '#title' => t('Add more no.'),
          '#options' => drupal_map_assoc(range(0, 50)),
          '#default_value' => 2,
        );
        $form[$field['field_name']]['und']['add_more']['#submit'][] = 'village_field_add_more_submit';
        $form[$field['field_name']]['und']['add_more']['#value'] = 'Add more rows';
      }
    }
  }
}
function village_field_add_more_submit($form, &$form_state){
  $button = $form_state['triggering_element'];
  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];
  // Alter the number of widgets to show. items_count = 0 means 1.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  //get the number from the select
  $numbtoadd = $form[$field_name]['add_more_number']['#value'];
  if($numbtoadd){
    $field_state['items_count'] += $numbtoadd;
    field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
    $form_state['rebuild'] = TRUE;
  }
}
?>

I also posted the suggestion on Drupal.org at https://drupal.org/node/1394184#comment-8252701
where the op had a similar issue.


What values can I use for _entity_access in a configuration entity I am developing? Looking at search.routing.yml, I noticed it contains the following code.

entity.search_page.enable:
  path: '/admin/config/search/pages/manage/{search_page}/enable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'enable'
  requirements:
    _entity_access: 'search_page.update'
    _csrf_token: 'TRUE'

entity.search_page.disable:
  path: '/admin/config/search/pages/manage/{search_page}/disable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'disable'
  requirements:
    _entity_access: 'search_page.disable'
    _csrf_token: 'TRUE'

While it's clear that the first part of the _entity_access value is the ID of the configuration entity used in the annotation for the class implementing it, I don't understand what I can use as part after the dot. Is it restricted to a set of values (e.g. add, update, use, delete), or is it a value the access controller class for that entity handle?

According to the Drupal 8 documentation:

  _entity_access: In the case where an entity is part of a route, can check a certain access level before granting access (e.g.,
  _entity_access: 'node.view').

The part after the dot is the type of access you want to check on the entity. To find the full set of possible values, you have to look at the code of the entity (in your case, in \Drupal\search\Entity\SearchPage). The default possible values are view, update, delete, create. Entities implemented by SearchPage can also be disabled and enabled. (See search.routing.yml and SearchController.)

See also EntityAccessCheck::access().


What is needed to keep parent menu element active while browsing subpages (Bartik Theme) Let's say we have 2 sections with pages like this structure:

/section1 *
/section1/page1-1 **
/section1/page1-1/page1-1-1 **
/section1/page1-1/page1-1-2 **
/section1/page1-2 **
/section1/page1-3 **

/section2 *
/section2/page2-1 **
/section2/page2-2 **

= Link in main menu / ** = Link in custom menu (sidebar)

and so on.

The main menu of Bartik theme is not supporting sub-links, so I created custom menus, which are visible to each section (content type pages) in the sidebar.

Now I want to have the main navigation element of section1 root (/section1) be always having css-class "active" if any subpage of section1 is being browsed.

Any tips? I'm new to Drupal and don't want to mess up my installation.

There are differences in how to handle navigation levels between Drupal 7 and 8.

It's customary in both versions to create one menu even when you have "sub-items", you just indent the sub-items so they "belong" to another item as a "child-parent" relationship (use the Edit > Parent Link and Show row weights if you're not using drag and drop (javascript) in your interface).

Use Menu settings in Drupal 7

In Drupal 7 you have Menu settings where you can choose which Menu to use as Main links and which to use as Secondary links. In the case where you created one menu for both you select the same Menu for both options:

Use Block Menu levels in Drupal 8

In Drupal 8 there are no Menu settings for navigation levels. Instead, you configure the Blocks for your Menu with the Menu levels options:

Initial visibility level
Number of levels to display

Add the same Menu Block twice, but configure the levels differently.

For the first level of navigation those Block Menu level numbers should be:

1
1

and for the Secondary level that only shows up when the "parent" is active they should be:

2
2

You can read a bit more in this article: Primary and Secondary Navigation in Drupal 8


Add class to links in delete page I want to add a class to the link in my delete content page, currently the 'delete' button itself is styled because it falls under the styling for input[type=submit] in my CSS, but the 'cancel' button is just regular text.

I also have the webform edit page with links for 'clone', 'edit' and 'delete' how would I go about adding classes to these as well?

I don't want to just add a class for all links because thats overkill in my scenario

Thanks

Using the FAPI in a hook_form_alter() function:

$form['buttons']['delete']['#attributes']['class'] = 'my-class';


Accessing fields from view template I have a block view which filters for a specifiy content-type. I'd like to fully style it myself and also write the html myself it outputs. So I went and created the file views-view-fields-header-image-slider--block.tpl.php in /templates.

Now, I do have the $view object but no $field etc. Also var_dump($view->field['description_title']); result in Null.

I'm a bit confused how I can access the fields nor properly so I can render the image + description and all the other stuff.

If you haven't already, look at the theme information in the Advanced section on your Views admin page. It's near the bottom.

You should see a list of theme templates for each field, along with a row style that should have information for each row. Each field is also linked to a sample template, and you will also notice the list of file names the view is searching for, from general to specific. I've attached an example of what it looks like.

Looking at my own now... You might also want to try the "style output," though in my case I did everything through the field content template.

Edited to add:

I don't have enough reputation to comment yet, but it looks like there is some useful info on How do I access a field value in the $row variable in a field view theme template?

Simply out, here are the two approaches from over there:

$field = $row->{$field->field_alias}
$rendered_field = $view->render_field($fieldname, $view->row_index);


URL Link to Calendar Month view from Existing View I have a page with some global header text. The page lists some events in a tabular format. I'd like to add a link (url) to my calendar within the text. I've tried to code a "<a href>" tag with what I thought was an appropriate url, but, I get the following:

  Warning: Creating default object from empty value in
  calendar_plugin_row->pre_render() (line 312 of
  /home3/hartfos4/public_html/mysitename/sites/all/modules/calendar/includes/calendar_plugin_row.inc).

followed by:

  'calendar_plugin_style: A date argument is required when using the
  calendar style, but it is missing or is not using the default date.'
  in calendar_plugin_style->render() (line 238 of
  /home3/hartfos4/public_html/mysitename/sites/all/modules/calendar/includes/calendar_plugin_style.inc).

Is there any way to compose a url to link to the calendar month?

I was able to resolve this. I was trying to redirect to a second calendar from the global header text of another calendar.  I took a closer look at the second calendar and noticed that it did not have a default date in the contextual filter.  It may have gotten deleted after the fact.  I deleted the second calendar view and recreated it according to required specifications. I then edited the first calendar's global header text to use "<a href=>" and it successfully redirected to the second calendar.


Check not NULL in entityfieldquery propertyCondition I want to only return results in entityfieldquery that have a propertyCondition of 'field_entry_path' that is not empty.

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'example')
        ->propertyCondition('field_entry_path', '', 'NOT IN');
  $result = $query->execute();

Thanks.

Unfortunately, it is impossible at the moment. See the workaround described on http://drupal.org/node/1226622.


Why is search disabled by default for anonymous users? I noticed that search is only permitted to logged in users on drupal.org and I'm wondering why. Apparently it's also disabled for anonymous by default in Drupal 7, and I see people discussing how to enable it to anonymous users, but no-one explains why this default setting exists.

I assume there's a performance issue or opening for a DOS attack?

I'm particularly interested at the moment because we're currently having DB issues (overloading the max permitted connections) and we have D7 with search enabled for anonymous users.

In Drupal almost all permissions other than access comments, view published content and exceptionally use text format filtered_html are disabled by default for anonymous users. There is no specific reason for search other than the rest.

It is up to you and the purpose of the site you want to build, which permissions you want to give the users.


When I should create a new permission in my custom module? Once I create a custom module where I'll have some kind of administrative tasks like configurations should I create a new permission or just use any available permission?

This question comes to my mind because when we create a custom module for the community we can imagine how this module will be used, but maybe in some scenarios some admins need to give specific permission to others users to configure the site and in this case if we have specific permission for this tasks made this work is very easy, if not this admins need to create a new custom module to handle this situation.

But in the other hand if we create one permission for each administrative task in our custom module maybe we are overloading the site with permission that are rarely used.

When I should create a new permission in my custom module?

Note: I'm not trying to create primarily opinion-based question here, if some user feel this, please help me to improve the question.

If you are creating a custom module for a client-only (or yourself), then you can do whatever is appropriate for the situation.

When creating a contrib module, you have to consider that you probably don't know all of the potential uses.  In general, I would make your own permission; typically as a project reviewer, this is something I point out as part of peer review.

I do not see too-many-permissions as a problem.  In fact, I see it as a benefit.  When I build sites for clients, I try to build out roles that can stack (users can have multiple roles) and roles have the minimum permissions needed to meet the needs of that role.

One common complaint about Drupal is that it is too complicated.  By using roles and permissions, you can limit what users can do, and minimize the complexity to exactly what they need to do (no more, no less).  When you gang up tasks into a single permission, you may give the option to people to do things that they may not need or want to do.

Another way to look at this, is that permissions can be used as a security method to limit what uses can do.  They can also be used by an organization to limit what users need to do as part of their job function.


Advice - Forms and Credit Card Security I'm working on a website for a client where he wants a order form created and e-mailed back to him.  Because of the nature of the business, the card cannot be charged until the order is verified that all the items are in stock and the shipping cost verified - then they charge the card themselves.  So the form is supposed to gather the card numbers.  The problem is that when I use a webform, it actually SAVES the credit card number!  YIKES!! I've created a PDF interactive form, which I think is a much better and safer option, but I can't get the PDF to display on the page like the customer wants.
Does anyone have any advice on what I should do or look into??
Thanks so much!!

It's not secure at all to store or send credit card numbers in the database and via plain text email. Without careful consideration bad practice to do so.

I think you need to rethink the order fulfilment process.

You should instead consider using the refund feature of your payment gateway to refund payment after the transaction is completed, if it fails validation.

Alternatively, look at providing some sort of API process so the stock and shipping details can be verified during the checkout process, prior to payment.

There's also an option of "Authorize" vs "Capture" payment modes provided by some payment gateways to allow delayed payment capture.

In the meantime, please review PCI Compliance requirements:

http://en.wikipedia.org/wiki/Payment_Card_Industry_Data_Security_Standard
https://www.pcisecuritystandards.org/security_standards/why_comply.php
https://www.pcisecuritystandards.org/pdfs/pci_ssc_quick_guide.pdf


Is it possible to include countdowns in nodes? I need to include countdowns in nodes of a particular content type

I looked around but couldn't find a countdown module that allows simultaneous active countdowns.

Any ideas, suggestions are welcome

There is jquery_countdown for general purpose countdown display, though the way you would integrate this depends on what you want to countdown. Using this module it is quite easy to display a countdown based on a node field value. Unfortunately there is no display configuration in the UI. But you could use hook_node_view() to add a countdown to a node view like this:

$node->content['countdown'] = theme('jquery_countdown', array(
  'id' => 'jquery_countdown-' . $node->nid,
  'options' => array(
    'until' => date("F d, Y g:i:s a", $some_timestamp),
    'format' => 'dHMS',
    'compact' => TRUE,
  ),
));


Can I edit Content Y within Content X Edit Form using Rules? I have created a content type VIP PAGE, and another content VIP IMAGE. Now I want to allow the user to upload 5 VIP IMAGES at the same time as creating the VIP PAGE content.

So what I did was to add 5 Image fields to the VIP PAGE content type, then I created 5 Rules, which trigger when content type of VIP PAGE is created and it takes those 5 images and creates 5 VIP IMAGES content and uses Entity Reference field to connect the IMAGES to the PAGE.

Now this all works fine, until a user decides to Edit one of their images. I want to still use a single page (VIP PAGE Edit Form) to handle images being edited. Can anyone recommend a good way to achieve this?

I can't figure out how to tell Rules which of the images it is that was edited.

Entity reference and Inline entity form could help you.

Entity Reference:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes)
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a configurable view mode.

  Integration with Views (for both forward and backward references).
  Integration with Entity Metadata (and as a consequence with Search API and the like).
  Integration with Devel generate.
  Integration with Feeds and Migrate (>= 2.3) for painless data import.

Inline Entity Form:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.
  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
  Existing entities can also be referenced. Supports commerce_product_reference, commerce_line_item_reference and entity reference fields. Read the documentation here.


8 - Hide title in render array i must render entities but it render the node title / author / creation_date etc... and i want to show only fields of my node. In D7 we can set a #access property to not render the field but in D8, i don't know how to do this. Can you help me please ?

I render my entities by this way :

// Get all content observable
            $query = \Drupal::entityQuery('node');
            $query->condition('status', 1);
            $query->condition('type', $ctype_observable);
            $query->condition('field_scm_tag', $this->getPluginDefinition()['tag']['machine_name']);
            $entity_ids = $query->execute();
            $entities = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);

            // render the entity
            $view_mode = 'default';
            $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
            foreach ($entities as $nid => $entity) {
                $build = $view_builder->view($entity, $view_mode);
                //kint($build['#node']);
                dsmr($build['#node']->get('title'));
                $build['content'][$nid]['#markup'] = render($build);
            }

This doesn't work anymore like this and the reason is render caching.

After calling view(), you only get a minimal render array, that will use #pre_render callbacks to complete itself in case of a cache miss. On a cache hit, it will return the cached HTML, without having to build all the fields.

The information you want to hide is in the template, both the title and the authored by information (which can be hidden for a node type for all bundles but not per view-mode).

The correct way to deal with that is to define your own view mode (default is wrong anyway, you should use 'full', not 'default', default is the fallback view display, not a view mode).

For that view mode, you can then provide a template/preprocess hook/hook_entity_view/hook_entity_view_alter hook, use any of those or a combination of it to achieve the desired result. To not show the authored by information, you can for example unset $variables['display_submitted'] as it uses that in the default node.html.twig template. Or provide a template suggestion for your view mode that removes that part completely. Both work, a preprocess is a bit easier from a module.

The important part is that you need your own view mode for that unless it is ok that full should never show that information, then that's fine too. The default cache key is entity type/entity id/view mode. There are other ways, you could add a cache context or you could even add another cache key, but you still need to do it within those hooks/template and the most obvious way to flag it for that is a view mode, that's what they exist for.


Programatically remove field content from all nodes where content equals 'string'? I am doing a migration from D7 to D8. Due to various issues in the initial site, I am doing content migration through CSV import rather than the direct drupal to drupal migration that's built in.

My content type has a Video Embed Field in it, which was throwing errors on migration unless it was filled. As such, I had to throw in a placeholder video URL for all nodes that didn't have the node filled.

Is there a way to (within drupal, or via a SQL query) programatically remove the field content from all nodes where the url is "youtube.com/myPlaceholderVideo"? All the content is in, but now I'm stuck with ~450 nodes with this placeholder URL.

The video_embed_field module adds a simple field based on whatever you named it.  So if your field is named "field_youtube_embed_test", you'd get a field on your content type that is a standard drupal field, with a table "node__field_youtube_embed_test" and a revision table "node_revision__field_youtube_embed_test".  You can run a query to delete all entries based on bundle as that is one of the columns on both tables.  So you can run a query for each.

DELETE from node__field_youtube_embed_test where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

DELETE from node_revision__field_video_embed where field_youtube_embed_test_value = 'youtube.com/myPlaceholderVideo' and bundle = 'article';

Or if you want to delete everything from those tables, you just use the truncate command:

TRUNCATE node__field_youtube_embed_test;

TRUNCATE node_revision__field_video_embed;

Using a query works for simple fields such as textfields, booleans, etc, but it doesn't work for more complex structures such as field collections or paragraphs.  For those, you would probably want to iterate through them programmatically and unset the value and then save the node.


Drupal 7 and Image Style problems I have created several image styles in Drupal 7 (thumbnail, medium, large and xlarge). I also have created a script that imports data from a CSV-file, and copy images to the system.

The script seems to work fine and all images are attached to nodes correctly. Using Views I have created a block that shows nodes of a certain node type, and thumbnails attached to said node. Links to the images is OK in HTML.

Now the problem starts. Some images (thumbnails and large) get created, but some doesn't.

I can not find a reason why the images that doesn't get created should not be created. At first I thought maybe the image size was to big, but this isn't the case. Some images that gets created are bigger than ones that doesn't, and all images are bellow the systems 32 MB limit (from 3 to about 15 MB).

I have no idea where to start looking. All images copied during the import seems fine when opening on my system (OS X).

Can anyone point me to where I can get started at finding what the problem might be?

Thanks!

As I commented on the question, this was a file permission problem..


Keyboard hotkey for "Flush all caches"? Is there any easy way to create a keyboard hotkey to flush all caches in a Drupal site?, instead of going to Admin menu Drupal icon and click that time and again? Thx.

If you've enabled the search bar component on Admin menu you can search your way to it.

Enable the Search Bar component on the configuration page (/admin/config/administration/admin_menu).
Type "flu.." or enough characters to list only the "Flush all caches" menu item.
Press the tab key to highlight and the enter key to trigger the "Flush all caches" menu item.


How to disable a module dependents module? Not the module but the feature Hello I have the module BEF better exposed filters installed and enabled and together with it is the BEF Test Content module (feature of BEF better exposed filters moduke).

I just enable the features so BEF Test Content for making tests and now when I want to disable it shows on the screen like red and when i try to disable and save configuration... i can not...

also i tried through drush by using:

drush dis better_exposed_filters

but logically it says that it will disable the BEF Test Content module extension but also it will disable together with the BEF Better exposed filters too...

is there a way to disable only the dependent module? how about with drush?

thanks!

If you mean

  Can I disable/uninstall the BEF module without first disabling/uninstalling the BEF Test Content module (or any other modules that depend on it)

Then no, that's not possible.

"Dependency" means that one module cannot function without the other. In this case, the BEF Test Content module will be unable to function unless the BEF module is also installed and enabled.

Drupal understands this constraint, and makes sure the you can't break your site by removing functionality from one module that is required by another.

If you mean

  Can I disable/uninstall the BEF Test Content module without disabling/uninstalling the BEF module

Then yes, you can either disable/uninstall it through the UI as normal, or use Drush. BEF doesn't have a dependency on BEF Test Content, so Drupal won't stop you from removing it.

The only caveat to that is if there are other constraints introduced by the BEF Test Content module. For example, if it provides a field type which is in use, the module cannot be disabled until the field is detached from all entities. But the admin UI will tell you explicitly if that's the case


Webform A partially-completed form was found. Please complete the remaining portions I'm seeing this message on my webforms:

  A partially-completed form was found. Please complete the
  remaining portions

How can I suppress this message for Webform version 7.x-4.10?

This is shown if you have the Show "Save draft" button option ticked in any webform and is hardcoded into the Webform form builder. If you want to override the message display the Disable Message module can help you here.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.


Core patching and version controlling across multiple versions of the same site How can I propagate core updates from an installation of a Drupal site to other installations of the same site?

I maintain a private Drupal site which the owners now want to make public. As a result, there are concerns about hacking due to lapses in the core.

In addition, there is a DEV, STAGING and a LIVE version of this site. Nothing makes it to the LIVE site without having being tested in staging and those changes always initiate in the DEV site.

Code changes are only made within the sites/all directory, nothing in Drupal core is tampered with. The changes are version controlled via GIT.
So I push up changes to the sites/all files and subdirectories to STAGING and then the LIVE sites.

This is where my problem begins: how can I patch the core code for the DEV site and propagate those changes to my STAGING and LIVE sites?

I am aware, I can of course apply the patches directly on STAGING and LIVE but those two sites are very tightly controlled by firewalls so they don't have unrestricted access to the Internet like DEV does.

Can I only accomplish this by using more version control and push up core OR is there another way?

Drupal has a good guide for this. A general summary for updating would be:

Delete everything except sites
Unpack the latest Drupal in the same place
Run the updater via update.php.
Check for breakage.
Update modules if necessary. They'll most likely be outdated too.

When all is good, commit all the updated code. Ideally you'd have separate commits for the core update, and for each module you updated. Then push up your code to your remote repo.

Now over to your environments, you simply do a git pull. If your remote repo is the filesystem of the remote environment (i.e. Acquia, Pantheon), then pulling isn't required. Set the site to maintenance mode, and run the updater. Ideally, you'll have this automated. If you use Drush, then it's just the following commands:

drush vset maintenance_mode 1 # enable maintenance mode
git pull                      # pull in the latest code
drush updb                    # perform updates
drush vset maintenance_mode 0 # disable maintenance mode


Javascript is not loading in Zen custom theme I'm not able to get my custom theme to run javascript on all pages. My code is as follows. My Custom module is enabled, and Component Libraries module is installed and enabled.

custom_theme.Libraries.yml

scripts:
  # If this library had JavaScript you could specify it like this:
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

global-scripts:
  version: 1.x
  js:
    js/script.js: {}

custom_theme.info.yml

    libraries:
  - custom_theme/base
  # @TODO Remove these libraries and use attach_library() for all component styles.
  - custom_theme/scripts
  - custom_theme/global-scripts
  - custom_theme/box
  - custom_theme/comment
  - custom_theme/header
  - custom_theme/hidden
  - custom_theme/inline-links
  - custom_theme/inline-sibling
  - custom_theme/print-none
  - custom_theme/responsive-video
  - custom_theme/wireframe
  - custom_theme/autocomplete
  - custom_theme/collapsible-fieldset
  - custom_theme/form-item
  - custom_theme/form-table
  - custom_theme/progress-bar
  - custom_theme/progress-throbber
  - custom_theme/resizable-textarea
  - custom_theme/table-drag
  - custom_theme/nav-menu
  - custom_theme/navbar
  - custom_theme/pager

script.js

/**
 * @file
 * A JavaScript file for the theme.
 *
 * In order for this JavaScript to be loaded on pages, see the instructions in
 * the README.txt next to this file.
 */

(function (Drupal) {

  'use strict';

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

      console.log("Hello World");

    }
  };
})(Drupal);

The script.js started working after I cleared all caches.

If you're having this problem and followed Drupal's official documentation then login to your Drupal site as admin and In Performance section click clear all caches

navigate to: Home >> Administration >> Configuration >> Development


Can't save any changes on the Content Language & Translation page I'm using Drupal 8 and when I go to /admin/config/regional/content-language and try to turn on "Custom menu link", it doesn't save, and it just reloads unchecked.

I saw here that you need to check the actual items, as well, to get it to save, but that doesn't work either: https://www.drupal.org/forum/support/translations/2016-09-07/i-cant-save...

Then I realized that I can't save ANY changes to this page.

I see the warning "(* unsupported) Paragraphs fields do not support translation. See the online documentation.", which was red before I turned off translation for all Paragraph fields, and then the warning turned orange but remained. I had to go to the actual Content Type edit page to turn off translation from paragraph fields to get those changes to save.

Nothing is saving and I'm not seeing anything in the dblog. It just reloads as it was. I'm not even sure where to start on this. Any help would be greatly appreciated.

I tried the max_input_vars fix and that didnt work.
I had to check the entity, pretend it was called MyCustomEntity in 'Custom language settings' at the top... but also scroll down to the individual MyCustomEntity settings further down on the page, and also check that checkbox. When I saved, now it worked


How do I change the overridden feature to default I got "overridden" for two settings. I wanted to know why this is happening, and how to get rid of it in a proper way.

Features takes configuration from the database, and stores it as code. When a feature is "Overridden", this means there's a difference between what is stored in the database, and what is stored in the files.

This can happen because you've made changes directly to, for example, the Views that are exported. However, it can happen for less obvious reasons.

Sometimes, when you enable a new module, this module may add additional data with a default value to the export of a module. This suddently means that when Features compares the db and files, there's more data in the db, and you have an overridden feature.

Because there are a large number of reasons you can end up with overriddes, there's no surefire way of handling them. You need to install the diff module to inspect that the difference actually is. Then you can determine if you want to "Revert" the feature (copy the Feature file data into the database), or "Re-create" it (create new Feature files, which you can then overwrite the original feature with).


How can I programmatically place blocks? I'm migrating a Drupal 7 site to Drupal 8.

The old site uses $ drush block_configure (available in Drush extras) to put blocks in regions while deploying, as well as $ drush block-disable to remove unwanted blocks. Unfortunately, Drush extras is no longer available for Drush 8, which seems to be the first version supporting Drupal 8.

The site will be deployed multiple times by multiple people, so adjusting region settings manually in admin view is not a solution. Everything needs to be done in an Ansible playbook so it can be passed on easily.

It seems that configuration management can be used to move blocks, but this would require all the environments to have up-to-date copies of a master database. While this is not impossible, it does feel like a hassle and a possible security risk. The developers don't really need to have all production data in their dev environments, and I wouldn't want to put production data on servers using developmental (and possibly vulnerable) code.

Twig Tweak seems to have an option to render a block anywhere regardless of regions. However, if I hardcode all blocks on templates, admins can no longer use admin block management.

Would it be possible to write a custom module and use block alter functions to set regions on blocks created by core modules? Are there any examples of this?

Are there more ways I'm not aware of? What is the best practice?

I was able to accomplish what I wanted using theme config, as described in How to assign blocks to particular regions on theme install? . This solution works for me, because my site will only ever use one (custom) theme, and I don't mind configuring all blocks this way.

I created a config file (this one is for a language switcher, provided by language module) and put it in MYTHEME/config/install/block.block.MYTHEME_BLOCKNAME.yml. It's just what you would export from configuration management, without uuid.

langcode: en
status: true
dependencies:
  module:
    - language
  theme:
    - MYTHEME
id: MYTHEME_BLOCKNAME
theme: MYTHEME
region: header
weight: -6
provider: null
plugin: 'language_block:language_interface'
settings:
  id: 'language_block:language_interface'
  label: 'Language switcher'
  provider: language
  label_display: '0'
visibility: {  }


How to inline edit node fields in a view I have a table view of content node fields, and I need to be able to edit them inline.  It looks like the Edit module would work, but I'm not sure if it works with views.  When the user clicks on a field in a result row, they should be able to enter the new value, and the data for that field in that node should be updated.  It also needs to be compatible with the Field Validation module.

EDIT: This also needs to work with the Addressfield module.

Use the Editable Views module for inline editing

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.


manipulate form variables before render() I have the following line of code in a user-profile-form.tpl.php which Drupal uses to render an input field in the user's edit profile page.

print render($form['field_machine_name']);
// this field can be found in the database table field_data_field_machine_name

The issue is that I want to run the value field_machine_name through a function like $form['field_machine_name'] = make_seo_url($form['field_machine_name']) before I run the render() function.  But this totally breaks the form because $form['field_machine_name'] is some very large array and render() output html input tag instead of the actual field_machine_name itself.

How does one actually go about massaging values in the $form variable before outputting it as an html field in render()?

Additionally, i want to make sure anytime field_machine_name is printed anywhere on the drupal site, i want it to run through the make_seo_url() function.  Is there a global place i can do this?

The Form API has #pre_render per element. You can use hook_form_alter to add your pre-render function to the list of functions that need to be called to show the value.

  #pre_render

  Used by: All elements and forms.

  Description: Function(s) to call before rendering in drupal_render()
  has occured. The function(s) provided in #pre_render receive the
  element as an argument and must return the altered element.

  Values: An array of function names to call.

  Note: If you are altering an existing form via hook_form_alter() or a
  similar means, be careful with this property! As demonstrated here,
  you will probably want to add to the existing array rather than
  writing over it.

I recommend being careful of when your module runs when trying to interact with Forms, Ajax, etc (your modules' weight). If needed I also recommend seeing hook_module_implements_alter if you want to adjust when your hook is called, without affecting your modules' weight.


Modifying Field Values for a Custom Content Type? I have a custom content type that has a field whose values need to be modified. The field in question is a select list and I need to add a new value to the list and re-order the list to satisfy the requirements of the project. The existing list looks like this:

1_Value A|Value A
2_Value B|Value B
3_Value C|Value C

The new list needs to look like this:

1_Value A|Value A
2_Value D|Value D
3_Value B|Value B
4_Value C|Value C

I realize because this field/content type already contains data, that this field cannot be edited. That being said, I suppose my question is two-fold:

How can I easily edit this field? What is the best way to export the data, make my modification and re-import?
Will re-ordering the values have any impact on the existing data associated with this content type?

I just checked a select list I have on a site with text key|value pairs under 'Allowed Values'. Although I had the message at the top that 'There is data for this field in the database. The field settings can no longer be changed.' I went ahead and altered the list, and it took the changes fine.

There should be no impact on the existing data if you change the order. Just be careful you never delete a value.


Display view on custom homepage I have a site with custom home pages depending on role. The homepages are assigned with hook_menu (hook_menu associates a URL with a function that returns a $html string.)

For one particular role, I need to generate a homepage that incorporates a view. I am looking at a list of views hooks, and not sure were to start.

In summary, how do I display a view that is generated from one of my hook_menu functions?

Edit:
I am currently looking into this code example from  http://lucor.github.com/2011/10/drupal7-how-display-block-programmatically/
The view is in now in a block.
I have not yet figured out what I either one of the parameters are suposed to be set to.

$block = block_load($module, $delta);
print render(_block_gAet_renderable_array( _block_render_blocks( array($block) )));

You have many ways to apply what you are looking for.

The easy way is to use Context module with Empty Front Page module

Another way is to write your own module, something like the following code:

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

  $items['frontpage'] = array(
    'title' => 'My homepage',
    'page callback' => 'myfront_front_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function myfront_front_page() {
  global $user;

  if (in_array('administrator', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('authenticated user', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role2', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  if (in_array('role3', array_values($user->roles))) {
    return views_embed_view('view_name', 'display_id');
  }

  return '';
}


drupal HTTP POST data How do i send HTTP POST/GET data to drupal?

for example:
I've got a html form:

<form action="mydrupalcite.com" method="get">
    <input type="text" name="title" />
</form>

how do i get the title 's data into drupal's answers module?(or any module?)

I'm looking for the drupal way of doing this(i'm relatively new to Drupal and how it really works)

Does it have anything to do with Services module?

Drupal's form API has CSRF protection built in, so submitting a form from an external domain won't work. You could either look at disabling the CSRF (very bad idea), or as you suggest, use the Services module.

There's no one-to-one mapping between the services module and forms on the site, rather modules implement resources for certain tasks to be consumed from an external client. You get node, user, taxonomy term, and probably others by default. So you can (for example) add a new node/user/term, but you do so by sending xml/json/etc requests to the server after having authenticated, not by submitting a form as such.

Getting data works in much the same way. You can either use Services to do that, or if you can manage/don't need your own authentication see indrock's answer for a good method.

Services is very extensible, so even if the answers module doesn't implement resources, it's a pretty easy job to add your own that wrap around API functions from the answers (or any other) module.

The documentation for services would probably be a good place to start.


Render array in controller response without surrounding theme I have custom controller in which I would like to take a render array (as such returned by EntityViewBuilderInterface::view) and return it as HTML without anything additional page theming wrapping it. I'm using this with a custom ajax call and would like to fetch html fragments to dynamically render on the page. Is this possible?

There are two ways.

One is, you render it yourself into a string, then build a Response object with it and return it. Drupal won't alter/touch a Response object and return its content as-is.

Second, since you mention ajax, Drupal actually has a built-in mechanism for its own ajax command system. If you pass ?_wrapper_format=drupal_ajax to the request, it will automatically transform it into ajax commands that will take care of not only the html content but also contained assets like css/js and drupal settings that are required to correctly display that HTML.

I don't really know in detail how the JS part works, but it basically all happens in ajax.js, for example in Drupal.Ajax.success, which then triggers the commands defined in Drupal.AjaxCommands (which can be extended), so you could write a more or less generic implementation of dealing with that response.


Unable to save data from custom drupal form I'm unable to save the details into database after the form is submitted in Drupal 7.

Below is the code for my custom form to save the details to DB,

function form_module_menu() {
  $items = array();
  $items['form_module/form'] = array(
    'title' => t('Registration form'),
    'page callback' => 'form_module_form',
    'access arguments' => array('access content'),
    'description' => t('Registration Form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_module_form() {
  // This form calls the form builder function via the
  // drupal_get_form() function which takes the name of this form builder
  // function as an argument. It returns the results to display the form.
  return drupal_get_form('form_module_my_form');
}

function form_module_my_form($form_state) {
  $form = array();
    // This is the first form element. It's a textfield with a label, "fName"
  $form['fName'] = array(
        '#type'      => 'textfield',
        '#title'     => t('First Name'),
        '#required'  => TRUE,
        '#size'      => 60,
        '#maxlength' => 64,
  );
  // This is the lastname form element. It's a textfield with a label, "lName"
  $form['lName'] = array(
        '#type'     => 'textfield',
        '#title'    => t('Last Name'),
  );
  // This is the email address form element. It's a textfield with a label, "email"
  $form['email'] = array(
        '#type'     => 'textfield',
        '#title'    => t('Email'),
        '#required' => TRUE, //must fill this if set to TRUE
        '#rules'    => array(
                            ),
        '#filters'  => array('trim', 'uppercase')
  );
  // This is the password and confirm password form element. It's a textfield with a label, "cpwd"
  $form['cpwd'] = array(
        '#type'     => 'password_confirm',
  );
  $form['submit_button'] = array(
        '#type'     => 'submit',
        '#value'    => t('Submit'),
  );
  $form['clear'] = array(
        '#type'     => 'submit',
        '#value'    => 'Reset form',
        '#validate' => array('my_module_my_form_clear'),
  );
  //print l('return to main home page', '<front>');
  return $form;
}

//Rebuild the form
function my_module_my_form_clear($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
}

function form_module_email_validate($element, &$form_state, $form) {
  //email validation not working how to validate email
  $mail = $form_state['values']['email'];
  if (strpos($mail,'@') !== true) {
    form_error($element, t('Please enter a valid email address.'));
  }
  else{
    form_error($element, t('Please enter a valid email address.'));
  }
}

function form_module_my_form_submit($form, &$form_state) {
    drupal_set_message($form_state['values']['fName'].$form_state['values']['lName'].$form_state['values']['email']);
    $sql = "INSERT INTO {customers} (first_name,last_name,email_addr,password) VALUES('%s', '%s', '%s' , '%s')";
    db_query($sql,
        array('%s' => $form_state['values']['fName']),
        array('%s' => $form_state['values']['lName']),
        array('%s' => $form_state['values']['email']),
        array('%s' => $form_state['values']['cpwd'])
    );
    drupal_set_message(t('Thanks for registering with us. You will receive an email shortly to activate your account.'));
    //after successfully saved how to send mail to user with his login details
}

The submit handler is called and the values are displayed.but in database all rows are filled with '%s'. I new to working in Drupal. How to store passwords and how to save the data and send an email to the user registering..

As stated by @Molot this should not be used generally. Recommended methods would be db_insert and db_merge.

Placeholders are layed wrong, they need to be in single array. Use

 $sql = "INSERT INTO {customers} (first_name,last_name,email_addr,password)
         VALUES(:fName, :lName, :email , :cpwd)";
db_query($sql,
    array(
      ':fName' => $form_state['values']['fName'],
      ':lName' => $form_state['values']['lName'],
      ':email' => $form_state['values']['email'],
      ':cpwd' => $form_state['values']['cpwd'],
   )
);


Specify node.tpl.php file via template.php for a specific node. I have two content types on my site:

NRG Shop display
Links

I have created a tpl.php file for NRG Shop Display and want to re-use this template for node 12 on my site. Node 12 is created from the 'Links' content type.

How can I do this?

I have tried the following:

function mytheme_preprocess_node ( &$vars ) {
  if ($variables['nid'] == '12') {
    $variables["theme_hook_suggestions"][] = "templates/node--nrg_shop_display.tpl.php";
  }
}

However it does not seem to work.

Any pointers?

Try:

if ($variables['nid'] == '12') {
  $variables["theme_hook_suggestions"][] = "node__nrg_shop_display";
}

The templates folder should be checked automatically so you won't need to prepend the path, and you don't need to add tpl.php to the end of the string; the above should work for a template file called node--nrg-shop-display.tpl.php


Dedicated image style for media gallery teaser Is there any possiblity to define another dedicated image style for the teaser of a media gallery node only? I can change the default gallery thumbnail image style but this has also effect on the galleries overview page.

Because I like to create an image slider on the front page with the 5 newest galleries but need the image in another format then the default square thumbnail format.

Is there any possbility to do that so?

You can create your own image style at admin/config/media/image-styles by click "Add style" link.

Use below code in your template file to fetch particular image style.

$my_style = image_style_url('your-img-style', 'image/uri');
<img src=' . $my_style . '/>

More details about image style.


How to know the module package? I need to know the package of a given module to performs some actions inside the implementation of a custom a drush command. So usually you will find that we will found this information in the module_handler service. But there is not method to get the module package.

So, how can I know the module package?

Maybe another simpler way exists, but after a little digging in the core I found that the modules list (admin/modules) with all the information is retrieve from the _system_rebuild_module_data() function that use the
info_parser service to retrieve all the module information.

If you want to know the module package you can use this code:

$module_machine_name = 'views';
$module = \Drupal::service('module_handler')->getModule($module_machine_name);
$module_info = \Drupal::service('info_parser')->parse($module->getPathname());
// To use dpm() you need the devel module.
dpm($module_info['package']);

Output:

  Core


What version is the CKEditor in the CKEditor module? I have installed the CKEditor module for Drupal 7 version 1.14. This version of the module comes with CKEditor already integrated with the module, so I am not sure how to find out exactly which version of the CKEditor this module comes with by default. I need to know this because when adding plugins from the CKEditor website only certain versions of the plugin are compatible with certain versions of the CKEditor. So how can I find this out? I have looked through the different module and JS files but I cannot find this information anywhere.

The library files are linked to directly via CKEditor's own CDN, so the answer can change depending on what their CDN is currently serving.

You can use ckeditor_get_version() to check which version is currently being used:

$current_version = ckeditor_get_version();
// e.g. 4.3.2


copy content-profile elements to another page In my content profile page, I have a set of three elements:  a search field, a set of checkboxes with data, a text area that shows the chosen options. I also have a number of onclick and keyup functions defined in a .js file, that fills the checkbox options, makes sure that entering values in the search field scrolls to the nearest checkbox, and when user checked a value it appears in the text area. So far so good.

How do I "copy" these elements and their functions to a separate page? I want a new page called "update my data" that has the exact same elements and functions, and I would just need to change the submit function. I am new to Drupal and Javascript, so sorry if this is a stupid question...

I tried using the content-profile update page and it doesn't copy the event handlers. Also, it allows the user to update all their data and I want only these elements.

I am using Drupal 6 and Content Profile module.

Thanks!

In the end I used the content-profile edit page, with the following modifications:

It did copy the event handlers but the ajax call was calling the
wrong url becasue of relative path problems. Using an absolute path
instead fixed this issue and the event handlers worked perfectly.
Used JavaScript to add a css class to the elements I wanted hidden, and styled in css that this class should have display:none.
I needed to install a patch on the CCK module to solve an issue with a hidden on/off checkbox.

Thanks!


How to style map popup from GMap module? Does anyone know where I can find, or does anyone have, a solid explanation of how to style the popup that GMap provides when you click on a map marker? I've seen it done on other sites using the GMap module, but I can not for the life of me figure out how to style it myself.

I've done some searching around and found infobubble.js, apparently code made by Google to help with the styling, however I can't figure out how to apply it to Drupal or how to use it.

Any help would be appreciated, I'm at my wits end with this one.

This is Drupal 7 by the way, and the newest version of the GMap module.

infobubble.js is available as a patch: Add more theming options to popup bubble by using infobubble library plugin for Gmap module.

Have a look at it as it allows you to modify several parameters of the popups.

  shadowStyle - Options: 0 (no shadow), 1 (default shadow), 2 (sharp
  shadow)
  padding - Like the css property, the padding of the bubble.
  borderRadius - Like the css property, the radius of the bubble's
  corners.
  borderWidth - Like the css property, the width in pixels of
  the border.
  borderColor - Like the css property, the hex or rgb color
  of the border.
  backgroundColor - This is the background of the content
  of the bubble, but NOT the entire bubble itself.
  bubbleBackgroundClassName - A css class for the entire bubble.
  minWidth - Like the css property, the minimum width of the bubble.
  maxWidth - Like the css property, the maximum width of the bubble.
  minHeight - Like the css property, the maximum height of the bubble.
  arrowSize - The width of the pointer arrow. NOTE: if you choose an
  arrow style that only uses half of the arrow, this number will be
  twice as wide as your arrow at its widest point.
  arrowPosition - The
  percent from the left of the bubble where the arrow will appear.
  arrowStyle - Options: 0 (full triangle), 1 (half triangle leaning
  left), 2 (half triangle leaning right)
  closeImage - The url of the
  image to use as the close button for the bubble An example of most of
  these options can be seen on the infobubble examples page.


How to serve 404s for non existent views paths with facets Is it possible have non-existent views paths 404, but to allow facets and parameter searches?

Most of the answers to this question for base views, are either for Drupal 6, or use Mikeytown's excellent Views404 module.

However this isn't an option if you're using faceted search. Using Views404 will return 404s for all of your faceted pages.

Is there a general way to catch when views isn't hitting a facet or an allowed parameter?

The solution here was to alter the Views404 module.

The module works by running a single hook_views_pre_view. This function runs a series of tests and if none of them pass returns a 404.

I added in an extra set of tests which would pass on my facets and so avoid the 404.

This problem doesn't exist with all facets. The problem comes because I'm using Facet API Pretty Paths. It turns:

https://mysite/view?f[0]=host_entity_node%253Afacet_label%3Afacet_value

Into:

https://mysite/view/facet_label/facet_value

And while views404 will allow para-metered search, it won't allow folders unless they pass one of the tests.

I altered my facet pretty paths in the UI, so one of the labels was country and all the rest began with 'filter':

e.g.

Country Facet: Pretty path alias = country
Every other facet: Pretty path alias = filter_x

I then added the following code to views 404

$args_passed = 0;
foreach($args as $arg) {
  if($arg == 'country') {
    $args_passed++;
  } elseif(is_int(strpos($arg, 'filter'))) {
    $args_passed++;
  }
}

if($args_passed == (count($args)-1)/2) {
  return;
}

Facets always come in pairs, so it goes through every arg and looks for either country or filter. If if finds half of the url arguments are facet_labels then that's a pretty strong indicator this is a genuine path and shouldn't throw a 404.


Webform validate 18 years old (GNU Date Input Format) I'm looking for a valid webform date pattern, to validate a user's birthday (component date).

I want to make sure the person is 18 years of age or older. However, Drupal requires the GNU Date Input Format.

This seems not to work - Drupal shows no error message at all ?

There is also a related answer Field Validation: 18 Years or Older, but this seems to be super complicated and does not affect the webform module.

Here's the solution for this annoying "feature":


how to create a page.tpl.php without $page['content']? The page.tpl.php of my website shouldn't contain <?php print render($page['content']); ?> because it is only set of blocks. The problem is I'm not able to insert comment form into node pages of a website which its page.tpl.php hasn't <?php print render($page['content']); ?> . what shall I do?

You have asked simple question & there is very simple answer for that --

Yes, you can create page.tpl.php without <?php print render($page['content']); ?>. You just have to remove this snippet from the TPL file & it will work.

But then you have explained your issue about comment.

So if you go through the structure of tpl files at theme, you will understand that <?php print render($page['content']); ?> is responsible to print node.tpl.php & that one contains <?php print render($content['comments']); ?>.

So without fetching the things of node.tpl.php you won't get comments. Anyway, how a comment can be associated to a page when there is no node.


Getting default user picture drupal 6 Hi I got neat facebook style chat called arrowchat for my drupal website, however the script was lacking user picture integration. I managed to get user pictures but if user didn't set picture and is using default picture I'm getting broken image and 404 not found in logs. I've tried to fetch gravatar for users without picture set but couldn't make it work..

/**
 * This function returns the URL of the avatar of the specified user ID.
 *
 * @param userid the user ID of the user
 * @param image if the image includes more than just a user ID, this param is passed
 * in from the avatar row in the buddylist and get user details functions.
 * @return the link of the user ID's profile
 */
function get_avatar($image, $user_id, $account)
{
               return "http://mypage.com/files/pictures/picture-" . ($user_id) . ".jpg";

    if (empty($account->picture)) {
    return "http://www.gravatar.com/avfatar/" . md5($image) . "?d=identicon";
     }
}

There is already a Gravatar module out there. I think you would be better off using a vetted, bug tested code than having to build it yourself. Once you have it installed, you can use the function gravatar_get_gravatar($mail, $options = array()) to do exactly what you're wanting.


Where is root directory in Drupal Acquia Desktop? With other systems it's www or htdocs, but what about with Acquia Desktop?

Acquia desktop allows you to use any folder you wish as your root folder hence your site could be on the desktop, or documents. Use the import new site option in the settings tab to point to where drupal folder is located


two-stage user activation from database I'm trying to create a system where, say for a school or other organizations, I can load a ton of users into a database at once, so that they are grouped separately from other databases of users. However, I then want it so that when the user logs in for the first time, it will ask them to fill in all the remaining fields that aren't loaded from the original database, such as a password and email.

is there an easy way to do a two-stage user creation like this?

Always best to include the Drupal version you are making use of, for the purpose of the answer will assume its Drupal 7;

So there are two parts to this;

1) The user data upload to drupal; you could make use of the Migrate module; I would think in the very least you would need to set the username and a temporary password to facilitate the first time login instance.

2) To force the user to fill in his details you could make use of the hook_user_login in a custom module implementation to validate that the user's details have been filled in.


How to add custom metatags in drupal 7? I need to add a custom metatag to D7 site, something like here: http://groups.drupal.org/node/83069. What are the possible options? I know there is a metatag module, but seems it doesn't support custom tags.

I could modify the theme, but I need some user configurable solution.

Metatag does support custom tags by implementing hook_metatag_metatags_view_alter(). See the following hook implementation to add the Open Graph video:duration metatag from a custom entity:

/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 */
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $entity = mycustomentity_load(someid);
    $duration = $entity->duration;
    $output['video:duration']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#theme' => 'metatag_opengraph',
        '#tag' => 'meta',
        '#id' => 'video:duration',
        '#name' => 'video:duration',
        '#value' => $duration,
      ),
      'video:duration',
    );
  }
}


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

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

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

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

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

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

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

How can I programmatically save coordinates?

Try this:

$entity->set('field_geofield_name', [sprintf("'POINT (%s %s)'", $longitude, $latitude)]);

Cheers!


Can I add additional module to drupal distribution (all inclusive)? I have a SSO module I need to add to Open Social distribution. Can I add this additional module to the distribution (all inclusive)?

In your installation you can add the module just like any other module yes.

If you want to add id to the distribution itself, you would effectivly make a new distribution based on Open Social with the module added - please read the guidelines here to learn how to add it.


Why is my Datetime field not saved? I use the following code to create a node.

    $datetime = "2016-08-01 12:30:00";
    $values = array(
      'title' => $data['title'],
      'body' => $data['body'],
      'field_client' => $uid,
      'field_appointment_date_time' => $datetime,
      'type' => 'appointment'
   );

  $appointment = Node::create($values);
  $appointment->save();

The problem is that field_appointment_date_time (a Datetime field) is not been saved.

Why does this happen?

The above code is correct, date time was saved into DB.
the problem is frontend.

frontend expected this format:

"2016-08-01T12:30:00", need a "T" as separator.

here is how to put that T as separator,

\DateTime::format("Y-m-d\Th:i:s"), need a escape character in-front of T.

2016-01-22 update:

By the way, I have found out in Drupal 8 , correct way to store datetime is follow:

1> first , find out current user timezone, \Drupal::currentUser()->getTimezone()

2> $given = new \Drupal\Core\Datetime\DrupalDateTime("2016-08-01T12:30:00",$user->getTimezone());

3> $given->setTimezone(new \DateTimeZone("UTC"));

4> then get back formated datetime string $given->format("Y-m-d\Th:i:s");


How to make a node reference field that can also behave as a text field if no reference exists I'm looking for a flexibly way to allow a user to input a a field, but also to have that field be a node node reference if the the node reference already exists. In other words, lets say I have a content type called dog, each dog has a node reference for favorite toy, if the toy exists, this field should be a node reference, otherwise the user should be allowed to fill it in.
     Conceptually I can think of two way to do this. One way, is just to make it a field, and then somehow link to another node if it exists. The other is to make it a node reference, and perhaps somehow auto - create the node when the user fills it in.

Recommendations? (using drupal 7)

instead of node references you could use term references and then use the Autocomplete Deluxe module to have the user select existing terms or add new terms.

Actually, they there is support for references with Autocomplete Deluxe for References.


Different fields per taxonomy term A classified like site requires very different fields per category or taxonomy term.  For example car will need fields like milage, model etc.. while a house will have no. of bedrooms, sqr. feet etc. I am finding different ways to do this but not sure which is scalable.  I will also be using faceted search api.

First Method:
Create a generic entity with common fields and programmatically create custom entity per category which will be related using entity reference.

Second Method:
Create single entity or content type with all fields and write logic to hide and show fields per category.

Third Method
Create content type per category.

If the fields differ markedly, that's a case for a different content type.

e.g "Vehicle" and "House" would be two distinct content types with their own fields - much easier in the long run.


Modifying target vocabulary when migrating taxonomy terms with migrate_d2d I'm working on migrating a D6 site to a nice, shiny, new D7 site, and as part of that migration, I need to split one large vocabulary (approx 12k terms) into two new vocabularies. I have the mapping figured out (done manually, with mappings stored in a custom table), so the only thing left to figure out is how to modify the destination vocabulary as needed.  Here's what I have tried so far.

function nb_migrate_register_migrations() {
  // Define arguments used for all migrations.
  $common_arguments = array(
    'source_connection' => 'legacy',
    'source_version' => 6,
  );
  $vocabulary_arguments = array(
    array(
      'class_name' => 'NBPeopleOrganizationsTermMigration',
      'description' => t('Migration of People and Organizations terms from Drupal 6'),
      'machine_name' => 'PeopleOrganizations',
      'source_vocabulary' => '4',  // D6 Vocabulary ID
      'destination_vocabulary' => 'non_journalists',
    ),
  );
  $common_vocabulary_arguments = $common_arguments + array(
    'soft_dependencies' => array('NBUser'),
  );
  foreach ($vocabulary_arguments as $arguments) {
    $arguments += $common_vocabulary_arguments;
    Migration::registerMigration($arguments['class_name'], $arguments['machine_name'],
      $arguments);
  }
}
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }
    // Check to see if term is in $journalists.  If not, leave it as
    // non_journalists (as defined in migration registration), otherwise
    // change it to journalists.
    if (in_array($row->tid, $journalists)) {
      $this->destinationVocabulary = 'journalists';
    }
  }
}

So I've just defined one of the two new vocabs as the default when registering the migration, and then I want to modify the destination vocabulary if the source term is in my custom table.

The problem I'm having is finding what to modify to change the destination. As you can see above, I tried changing $this->destinationVocabulary, but that doesn't have an effect.  The only other place I can see to change it is in $this->destination->bundle, but that is a protected property of the MigrateDestinationEntity class, and there is no setter function for that property. Looking at the row, I'm seeing that prepareRow isn't the place to do this, since it just has the source data for the term, not where it's going.

All that being said, what do I need to do to modify the destination vocabulary for a term on the fly like this?

Thanks.

After poking around some more, I found my answer in this issue and the Migrate module documentation.  Based on what I found there, this is what I came up with:

/**
 * Override of DrupalTerm6Migration. Only for People and Organizations vocabulary
 * since we need to split terms out to two new vocabularies.
 */
class NBPeopleOrganizationsTermMigration extends DrupalTerm6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Set field mapping for destination vocabulary, since we need to
    // set it on a row by row basis.
    $this->addFieldMapping('vocabulary_machine_name', 'vname');
  }

  /**
   * Implementation of Migration::prepareRow().
   *
   * Need to redirect terms into either Journalists or Non-Journalists vocabularies
   * based on whether term is listed in nb_migrate_journalists table.
   *
   * @param $row
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Create journalists array from nb_migrate_journalists table.
    static $journalists = array();
    if (!$journalists) {
      $sql = "SELECT * FROM nb_migrate_journalists";
      $result = db_query($sql);
      foreach ($result as $record) {
        $journalists[] = $record->tid;
      }
    }

    // Set value for name (mapped in constructor above) based on presence in $journalists array.
    $row->vname = in_array($row->tid, $journalists) ? 'journalists' : 'non_journalists';
  }
}

Basically it just creates a mapping between the destination vocabulary machine name and the vname variable, which is then populated in the prepareRow() method.


Goal: 1 Webform as Block, Multiple Nodes with block in Panel pane I am trying to create a single webform that I can expose as a block and re-use on multiple 'profile' nodes.  These nodes will use Panels and Panel/Panes to display content.

Problem: I need to pass email address(s) stored on the "parent"('profile') node (cck fields perhaps) to the "child" webform so that the form is sent to the address(s).

I've tried following a few articles that said to create a custom module to implement hook_form_alter.  I haven't been able to get it to work.  I'm a bit of a noob at the whole programming side of Drupal so any help would be appreciated.

You can create a view for this web form node, and display it as block.
This will work.


Module hook to add_js to any entity type? I want a hook that will let me conditionally add js/css to the page depending on the type of entity.

Since I am putting this in a module I cannot use a theme hook (because if the theme already defines the hook then Drupal will crash).

Ultimately, I want to do something like:

// SWTICH BY ENTITY TYPE
switch($entity_type){
    case 'eform':  // entity forms
        drupal_add_js( $theme_path . '/scripts/ajax_forms.js');
        break;
    case 'view':  // view pages (making this one up)
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWTICH BY CONTENT TYPE
switch($content_type){
    case 'services':
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWITCH BY NID
switch($nid){
    case '293': // Homepage
        drupal_add_js( $theme_path . '/js/global.js');
        break;
}

Right now I'm using hook_node_view to check content type & nid.  Works great for nodes, but doesn't help me with non-nodes.

hook_entity_view() should do the trick

  Act on entities being assembled before rendering.

e.g.

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  switch ($type) {
    case 'node':
      ...
      break;
  }
}


Add blur effect to images in drupal 7? basically I want to add the ability to add a blur effect style to the image styles in Drupal 7.

I tried the imageCache custom action module but I am not able to add own php code since saving any code causes an error. Ive read that people guess the module itself seems to be buggy.

Is there any way I can add my own effect, a function like those listed in image.inc and add that effect to the dropdown?

EDIT:

thanks to the help of Clive I've actually managed to add a blur effect - wicked! :)

Here's the code:

function image_blur_image_effect_info() {

    return array(
        'image_blur' => array(
            'label' => t('Gaussian Blur'),
            'help' => t('Gaussian blur the image by a given amount.'),
            'effect callback' => 'image_blur_gaussian_blur'
        )
    );
}

function image_blur_gaussian_blur(stdClass $image) {
    $amount = 30;

    for ($i = 0; $i < $amount; $i++) {
        imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
    }

    return imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
}

I just wondered whether this could be done nicer somehow?

Next question: Is it possible to add an input field once the effect is selected sothat the user can type a custom amount of blurriness?

Like so:

function image_blur_gaussian_blur(stdClass $image, $CUSTOMAMOUNT) {
    $amount = $CUSTOMAMOUNT;

    for ($i = 0; $i < $amount; $i++) {
        imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
    }

    return imagefilter($image->resource, IMG_FILTER_GAUSSIAN_BLUR);
}

Sure, you'll need to write a custom module and implement hook_image_effect_info() to register your effect with the system, e.g.:

function MYMODULE_image_effect_info() {
  return array(
    'mymodule_blur' => array(
      'label' => t('Blur'),
      'help' => t('Blur an image.'),
      'effect callback' => 'mymodule_blur_effect',
    )
  );
}

Then implement your callback function (mymodule_blur_effect()) to manipulate the image. Try following the function trail from image_resize() to get some inspiration on exactly how to access the image stream data.


Will "features" be overwritten when there is a distribution update? Example scenario:

I create a site using commerce_kickstart 7x-2.0.
I modify some of the "Features"(ex. commerce_kickstart_user, commerce_kickstart_taxonomy) that are prepackaged with the distribution.

Question:

Will these "Features" be overwritten when an update comes, ex.
commerce_kickstart 7x-2.1 (Not really sure if there is such as a
thing as a distro update. Tried to google, went to issue queues,
IRCs to no avail)
If the answer to #1 is yes,how do you maintain your configurations to the "features" when an update comes? Should they be renamed and moved to "/sites/all/modules/my_features"?

Yes, they will be marked as overriden.
The Features Override was designed for this use case, so try it and report back.


Inside Panelizer, is there a trick to formatting image fields? Summary
In Panelizer, I have created one Panel. In Content for this panel there is an image field. I can find no option to change the image style.

From Manage Display in the content type,  I am able to select Image Style for various display settings but this makes no difference to the image in the Panel in Panelizer.

Where am I not looking?

Details
In Panelizer for Content Type = (Person), first row on the left "Full Page override" I clicked "Panelize" and "Provide Default Panel". I think I have created one Panel. In the Content for this panel, I have placed an image field (field_person_image) in the right column.

In Panelizer on R of field_person_image is a gear listing-
-"Settings". Formatter options for can select This Node, override title, change label position. There is an option for "Select a formatter" but the only option is "Image". There is no option to change the image style.
-Style which offers Pane Style for this node (rounded corners)
-Visibility rules
-Locking
-Caching

In Structure > Content Type > Person > Manage Display,  I am able to select Image Style for various display settings. Changing from Large to Medium to Small (using Default, Full Content) makes no difference to the image in the Default Panel in Panelizer.

This similar sounding question also has no answer. Using Image 7.43. There are no results at Issues for Drupal Core (Drupal.org) about Panelizer and image formatting.

What am I missing?

Although I could swear that I had done this before, I deleted the image in the panel. This time, when I added the image back into the panel, I got image formatter options. Which I set, and the node behaved correctly.

Despite the frustratingly long time I worked on this, it was a non-problem!

AMENDMENT:
When the panel is first created and saved, all of the fields appear in the panel. If the image field is left as is, there are no formatter options. However, if the image field is deleted from the panel and then re-added, then the formatter options appear. This is noteworthy, I think.


How to display flags to anonymous users and redirect to login after clicking a flag? I want to display flag to anonymous user and upon clicking the user should be redirected to register/login page.

I found one answer to this problem in the question about
"How to display a flag to anonymous users?".

I tried this solution but did not work, may be I did not put the code in correct place?

I am using Bartik as my template and I put the code in node.tpl.php.

Any suggestions?

Maybe the Flag anonymous module is what are you looking for.


Dependency injection in a custom class I have a custom module (my_module); Inside this module I have a custom class (MyClass), where I want to use a Drupal service (file_system).

This is my code.

src/MyClass.php

namespace Drupal\my_module;

use Drupal\Core\File\FileSystem;

class MyClass {
  public function __construct(FileSystem $file_system) {
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('file_system')
    );
  }
}

When I instantiate this class (in a controller for example), I get an error.

$my_class = new MyClass();

  TypeError: Argument 1 passed to Drupal\my_module\MyClass::__construct() must be an instance of Drupal\Core\File\FileSystem, none given

What is wrong in my code?

DI requires a bit more effort than that - you haven't told the system about your class; the DI container doesn't know that you've called new MyClass(), and it can't get involved.

You need to create a Service, which you can make depend on other available services, instances of which will be passed to your class using the static create method pattern you're already using.

In this case, that's probably as simple as providing your mymodule.services.yml and adding:

my_service:
    class: Drupal\my_module\MyClass
    arguments: ['@file_system']

When you've correctly registered the class with the system, you'll get an instance of it like so (if you need it in a global function):

$foo = Drupal::service('my_service');

Or if you're consuming it in a container aware class, then you can inject it just like any other service.