file name constraint in form I've got a basic field constraint figured out (per question here: Validation constraints on form fields ignored )

Next, I want to constrain the main image field to limit the file name. For example, if someone uploads a file named "1234-shutterstock.jpg" I want to detect that the file name contains "shutterstock" and add that violation.

But I have no clue how to tackle the syntax for this. Maybe someone can point me in the right direction?

I've started with something like this. I know this is wrong.

            <?php
            namespace Drupal\custom_validation\Plugin\Validation\Constraint;

            use Symfony\Component\Validator\Constraint;
            use Symfony\Component\Validator\ConstraintValidator;

            /**
             * Validates the Image constraint.
             */
            class MainImageConstraintValidator extends ConstraintValidator {

              /**
               * {@inheritdoc}
               */
              public function validate($items, Constraint $constraint) {
                foreach ($items as $item) {
                  if (strpos($item->value, 'shutterstock') !== false) {
                    $this->context->addViolation($constraint->wrongImageName, ['%value' => $item->value]);
                  }

                }
              }

            }

Per Clive's comment above, it works with this:

        namespace Drupal\custom_validation\Plugin\Validation\Constraint;

        use Symfony\Component\Validator\Constraint;
        use Symfony\Component\Validator\ConstraintValidator;

        /**
         * Validates the Image constraint.
         */
        class MainImageConstraintValidator extends ConstraintValidator {

          /**
           * {@inheritdoc}
           */
          public function validate($items, Constraint $constraint) {
            foreach ($items as $item) {
              if (strpos($item->entity->filename->value, 'shutterstock') !== false) {
                $this->context->addViolation($constraint->wrongImageName, ['%value' => $item->value]);
              }

            }
          }

        }


Results of GET Request inside block are being cached and not updating when GET request values are changed I have a block plugin that contains a form that performs a get request and reloads the current page. Currently it's set to allow a user to submit a state from a drop down box to be used as a filter.

This issue I'm having is the results from the get request are cached. It works after clearing the cache but right after, once I submit again with a new value for the dropdown the results do not update on the page, even though I can clearly see that the get request has changed. Below is the code I currently have

public function build() {
    $request = \Drupal::request();
    /* GET Variables */
    $state = (empty($request->get('state')))?'':$request->get('state');

    $render = '
    <form method="GET" class="relief-network-form">

    State:

    <select class="state" name="state">
        <option value="">Pick One</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
    </select>

    <input type="submit" value="Filter">
    </form>';
    return array(
        'test'    => [
            '#type'  => 'html_tag',
            '#tag'   => 'p',
            '#value' => 'State:'.$state.'-',
        ],
        'form'       => [
            '#type'     => 'inline_template',
            '#template' => $render,
        ],
    );
}

When submitting this form after the cache is cleared it displays the proper state in the p tag above the form, but afterwards it never changes. I have a feeling it has to do with using cache tags after reading the documentation here https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays
but to be honest I'm having trouble making sense of it, and I'm not sure how I would apply the examples to the current situation.
Is there a way to prevent the results of a GET request inside a block plugin from being cached?

You don't need cache tags, you need a cache context for the query key state:

$build['#cache']['contexts'][] = 'url.query_args:state';


How to run check on each page load? I would like to run a check on each page load.  This only concerns the front end and not the admin dashboard.

Basically what I would like to do is:
1) User hits a URL in the drupal site.
2) A server-side check is ran. If the check passes, run some logic.

How would I accomplish this?

I'm guessing that I can use a hook, but what hook would that be?

Thanks.

hook_init() is run on every page load except for cached pages, so depending on your use case that might be an option.

function MYMODULE_init() {
  // Custom logic
}

hook_boot() is run on every page, including cached pages, so might be more useful (again depending on your use case). However if you have complex logic to process this will obviously slow down the build of every page, even those that are cached.

function MYMODULE_boot() {
  // Custom logic
}

If you want to check whether or not the current path falls under '/admin' you can use a check like this in either function:

if (arg(0) == 'admin') {
  // ...
}

This won't work for node edit pages, for example, who's path doesn't have '/admin' in it; but short of invoking hook_admin_paths() and testing the current URL against each of the paths returned, I'm not sure how you'd reliably test for that anyway.


How to do a Library Override in my theme for dialog.ajax.js I’m trying to do a libraries-override to the dialog.ajax.js file appearing in /core/misc/dialog/. (Want to replace it with a js file from my theme, let's say at mytheme/js/dialog.ajax.js)
In my theme’s  *info.yml file, I tried
libraries-override:
  drupal.dialog.ajax:
    js:
      assets/js/dialog.ajax.js: false

as another post suggested (just to try and disable it). Didn't work.
My confusion comes from not knowing how to correctly target the /core/misc/dialog/dialog.ajax.js file within my override, and then correctly target my mytheme/js/dialog.ajax.js as a replacement.
I reviewed the documentation, but it's still quite unclear. Any tips? Thanks!

Looks like you're just missing the core/ prefix:
libraries-override:
  core/drupal.dialog.ajax:
    js:
      assets/js/dialog.ajax.js: false


How can I fix a pager limited to 2 pages? The pager on the home page of my website is limited to 2 pages, ie the paging links are only for page 1 and 2 and both next and last point to page 2, but there are a lot more pages than that.

Is there some setting which controls this?

You can set items per page for the Home page at Configuration/System/Site information/FRONT PAGE as shown in following image:

And you can check also how many nodes you have promoted to the frontpage  at Admin/Content. So these two settings will allow you set all this. Hope this will work.

Additional:

If you want more settings for the FrontPage, you can go to Admin/Structure/Views/ and you can see a view named FrontPage, that is by default disabled. But you can enable. And that view works as a FrontPage. So in views setting you can set as you want.


Taxonomy terms view sorting results numerically I have a taxonomy that's comprised entirely of numeric term names, 1 through 1200 (with a few numbers missing in between). I created a new "Taxonomy terms" view to show all terms in this vocabulary. When I look at the view results, I'd like to see the terms sorted numerically, however the view is displaying the terms alphabetically. I understand the reason for this is because term names are strings, but I'm hoping someone has an answer of how to make the query treat the term names as integers.

Here's an example of the view results as they are displayed now:

1
10
100
1000
1001
1005
101
1014
1015
1016
1019
102
1020
1024
103
1034
104

Normally in MySQL, you could write SELECT name FROM {taxonomy_term_data} ORDER BY CAST(name AS UNSIGNED). Is there a way to get this same type of CAST() happening in views?

Try using Views Natural Sort

This allows you to emulate MYSQL's behavior of CAST() in order to treat the integers as pure values to sort by.

From the documentation:

Natural Sort also supports Numbers.

Normal Sort:

1 apple
10 apples
2 apples

Natural Sort:

1 apple
2 apples
10 apples


Error When Changing User Role in Drush? I wanted to see if there is a way to change a user role using drush. I found this post explaining how to do it but I get an error. I replaced the actual username with "USERNAME".

drush user-add-role administrator USERNAME

> exception 'Drush\Role\RoleException' with message 'Could not find the
> role:      [error] administrator' in
> /usr/local/src/drush/lib/Drush/Role/RoleBase.php:46 Stack trace:
> #0 [internal function]: Drush\Role\RoleBase->__construct('administrator')
> #1 /usr/local/src/drush/includes/drush.inc(113): ReflectionClass->newInstanceArgs(Array)
> #2 /usr/local/src/drush/commands/core/role.drush.inc(273): drush_get_class('Drush\\Role\\Role', Array)
> #3 /usr/local/src/drush/commands/user/user.drush.inc(281): drush_role_get_class('administrator')
> #4 [internal function]: drush_user_add_role('administrator', 'USERNAME')
> #5 /usr/local/src/drush/includes/command.inc(368): call_user_func_array('drush_user_add_...', Array)
> #6 /usr/local/src/drush/includes/command.inc(219): _drush_invoke_hooks(Array, Array)
> #7 [internal function]: drush_command('administrator', 'USERNAME')
> #8 /usr/local/src/drush/includes/command.inc(187): call_user_func_array('drush_command', Array)
> #9 /usr/local/src/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
> #10 /usr/local/src/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
> #11 /usr/local/src/drush/drush.php(11): drush_main()
> #12 {main}

I am using Drupal Commons 7.50 and Drush 7.0.0.

Edit: Things I have tried:

spelling role correctly and making sure it exists
clearing cache

Syntax was wrong. It needed quotes and capitalization definitely matters.

drush user-add-role "administrator" USERNAME


hook_schema duplicate unique keys I am reading book 'Drupal 7 module development'.

I am try to follow book to create a hook_schema (I delete some line for better read):

function artwork_schema() {
     $schema['artwork'] = array(
       'unique keys' => array(
         'aid_vid' => array('aid', 'vid'), // there is an 'aid'
         'aid'     => array('aid') // there is also an 'aid'
         ),
     );
     return $schema;
   }

what it is the meaning of the 2 aid?

Does mysql can create duplicate unique index?

A field that is not defined as unique key or primary key is allowed to have the same value in different records of that database table. So, if you don't want to have the same value of aid in two different records, you need to define it as unique key, if it is not already the primary key.

Notice that the line defining aid_vid as unique key would allow the following records.

aid  | vid  ! other_field
-------------------------
1      3      10
1      4      22
2      4      14

Only the line defining aid as unique key avoids two records have the same value for the aid field.


How do I set the text format used in a message (from the Message module)? I'm using the Message module on a site that has both the Filtered HTML and Full HTML text formats. By default, Message appears to use Filtered HTML, but I would like to use Full HTML instead.

However, I couldn't find an option for changing text formats in the UI. I have exported my message types to a feature using the Features module, so instead I tried changing the format from "filtered_html" to "full_html" in the feature and reverting, but this didn't work, either.

Is is possible to change the text format used to display messages, and if so, how?

(Also asked in the module's issue queue.  When I get an answer, I will update both.)

You can set the permission for user role to use filtered_html or full_html in Administer -> people -> permission.


Inject a file record through SQL I am currently trying to inject a value and file into a user field called "field_user_pdf".

I am adding values to the following tables which is successful initally:

field_data_field_user_pdf
field_revision_field_user_pdf
file_managed
file_usage

The user is then able to see the file on their user profile. The user does not have permission to add/edit the file themselves, only an admin does, using the field_permissions module.

However if they edit and save their profile, all record of the file is deleted from the database.

This behaviour does NOT occur if the file was added to the user by an admin in the CMS, it only occurs when the file is inserted in MySQL by circumventing Drupal.

I have come to the above tables by both scrutinizing MySQL Insert logs as well as MySQL Database Dump diffs before and after.

Is there a table or column I am overlooking? Is there any where I can view the SQL Schema for inserting SQL for file fields?

What you are doing, sorry, is plain wrong. There is a field API and you should use it instead of messing around with the SQL tables. If you are going around the field API and it breaks, you truly get to keep both parts. I find it astonishing you expect support for going around such a complex API.


Creating a node programmatically for a user who doesn't have the permission to create nodes of that content type Let's say user X does not have the permission to create nodes of the content type Y, but the user does something which triggers an action, and this action is supposed to create a node of type Y. Will this be possible?

I want to do this because I don't want the user to manually create content as he could mess things up; I'd rather have this automatically done, hence the user not having permissions to create this type of node.

I'm using Drupal 6.

If the code calls node_save() passing to the function a node object that is associated to user Y (i.e., the value of node->uid is the user ID of user Y), the function will save  the node without checking if a node of that content type can be created from the user. It is the code that calls node_save() that eventually checks if the user has the permission of creating that content type, or it's the code that shows the link to the form for creating a node of a content type that makes the link visible only to users who has the permission to create nodes of that content type.

node_save() allows you to save a node that is associated to a user who don't have the permission to create a node of the content type Y; the problem is eventually when the user X doesn't have the permission to update nodes of the content type Y, which would not allow the user to update the node that has been created for him.


How do I implement a clickable JavaScript map? I've found a great clickable map over at code canyon which includes all the JavaScript, CSS, and XML to make it happen. A demo of the map can be viewed here.

I figure the best way to accomplish this would be to create a custom module and load the JavaScript, XML, and CSS files via the .info file.

The code to display the map is a simple html statement or two that could be placed on a basic page.

Would it be better to create a page template specific to the node?
How does one load the CSS and JavaScript from the module to the page?

You can use drupal_add_js() and drupal_add_css() in the menu call back function to add js and css files on the specific page.

Adding in the .info file would add js and css on all the pages.

You can also use hook_library() to define the library of js files and its dependancy with jquery or core js files.


Clear views cache on specific node I want to clear the cache of specific node's view. In my database in cache_views_data table I found the cid of my view and the format is like
"views_name:display:hash" but I cannot find this hash where is reffering to.

Here's how you can clear cache of specific view:

cache_clear_all('ctools_export:views_view:' . $NAME_OF_YOUR_VIEW, 'cache_views', TRUE);
cache_clear_all($NAME_OF_YOUR_VIEW, 'cache_views_data', TRUE);


How to remove target id from selected term reference field While selecting taxonomy from autocomplete term reference field, its target id also get displayed. How to remove target id from display?

In picture displayed, I want only 23456789 not bracket part i.e. (19) from display.

You need alter autocomplete js like this

 function theme_name_js_alter(&$javascript,
  \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $path = \Drupal::service('path.current')->getPath();
  $path_args = explode('/', $path);
   if($path_args[1] == 'twc-partners'){
   //kint($javascript);
     $javascript['core/misc/autocomplete.js']['data'] = drupal_get_path('theme', 'theme_name') . '/js/autocomplete-custom.js';
 }
}

This code add in theme file .Please download file from here.


Why are default values in a checkboxes $form not displayed? I'm having a drupal form (7.x) of type checkboxes.

I have an array of values for my checkboxes.

$options = array(
    'uid'         => 'UID',
    'name'        => 'Name',
    'mail'        => 'E-mail',
    'created'     => 'Created',
    'edit_node'   => 'Edit',
    'cancel_node' => 'Cancel',
);

I have an array of default selected values.

$defaults = array(
    'uid'         => 'UID',
    'name'        => 'Name',
);

And now I try to make the default values selected by default, like this:

$form['dynamic_user_fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t("Dynamic User Fields"),
    '#options' => $options,
    '#default_value' => $defaults,
    '#description' => t("Select the fields to display in the view."),
);

But this is not working, all checkboxes are unchecked by default. Where is my mistake?

What is not working so far: I've seen this related question but the answers do not work.

What I've tried:

(1) using numeric keys does not work.

'#default_value' => array(1, 2),

(2) using array keys does not work.

'#default_value' => array('uid', 'name'),

(3) using array structure does not work.

'#default_value' => array('uid' => 'UID', 'name' => 'Name')

Any ideas?

References

This is the full code I'm Using: views_handler_filter_dynamic_fields.inc#l317
This is a demo site: drupal-7/dynamic-user-fields
Related issue: #1245838 Default fields should be checked initially

I stepped up to maintain this module but the code base is a migrated D6 module.

For form elements expecting multi-value defaults, Drupal expects an array where keys and values are equal to the keys in your options array. Something like the following should work:

$defaults = array(
    'uid' => 'uid',
    'name' => 'name',
);

You may also use $defaults = drupal_map_assoc(array('uid', 'name'));.


Create an order as administrator user and let users continue with the checkout I am using Drupal 7 and the Drupal Commerce module. I need the ability to create an order as administrator user and let users continue with the checkout.
What I have tried:

Get the order ID and send the link to the user (for example,  http://example.com/checkout/1234/payment). It redirects to front page.
Use the Mail order link https://github.com/sjsam/Drupal-MOPL.
Use the module Commerce Checkout URL, which sends the link but doesn't work.

Do you have any idea?

Could you create a new "shopper" user for this customer, then assign the order to them? Make sure the role has proper permissions, workflow, etc. But then they will be the owner of the order and should be able to complete payment (and all the other checkout features like confirmation email).


Set up a Git version control repository that integrates with OpenAtrium Is it possible to have OpenAtrium function like the git repository on Drupal.org?

If so, then how can I do it?

Check out the "What theme and modules does Drupal.org use?" page.

Specifically for Git repository management, you'll want to use this set of modules:

http://drupal.org/project/versioncontrol
http://drupal.org/project/versioncontrol_git

And if you want a project release / issue tracking section like drupal.org, see:

http://drupal.org/project/project
http://drupal.org/project/project_issue
http://drupal.org/project/versioncontrol_project


How to track site search with using Google Analytics without installing additional modules? I need to enable the tracking of site searches in Drupal 7 using Google Analytics without installing the additional "google_analytics" module.

So far, I find some info (some previous question in this site, in example) about performing this task using that module, I just want to know if I can do that without it?

(Edited to add.) I found some info regading the "query parameter" to set in the GA site. I found it is recommended (http://www.wesjones.net/home/2010/11/track-drupal-site-search-in-google-analytics) to use "search" as query parameter, but I was thinking that the parameters would be something like "search/node" and "search/user". Any ideas D7-related?

(Edited to add.) I select the first reply as it effectively solves my initial question. Later I added a second one but it is kind of a different one. And maybe it is valuable to not mix things up.

I think the module serves well, but if you don't want to use the module for some reason, you can always create a new block and copy/paste the code provided by Google Analytics in there. Make sure you select the Text Format as Full HTML or similar which doesn't strip out <script> tags.

And of course, enable the block and move it to a footer region.


Views Remember Last Selection Back Button D8 I am having trouble with "Remember last selection" on views in D8. If I click a link away from the view and click back it does not remember my last selection. If I then refresh the page it does. This view does use Ajax and I cannot change that. Also I read somewhere that it may be due to caching from the headers.

If so what is the best way to add / change headers on a View response?

Looks like you have to subscribe to an event and manipulate the headers from there. I originally found this answer on how to manipulate headers in D8 here.

This will force a request to the server:

This file will go into your mymodule/src/EventSubscriber folder.

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class NoCacheSubscriber implements EventSubscriberInterface {

  public function RemoveCacheHeaders(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Cache-Control', 'private, must-revalidate, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('RemoveCacheHeaders', -10);
    return $events;
  }
}

Then this will go into the your mymodule folder as mymodule.services.yml

    services:
  remove_cache_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\NoCacheSubscriber
    tags:
      - { name: event_subscriber }


How do I export calendar? I am using the calendar module and I have added many events to it like a timetable.

How can I export these events as an excel format? So that I can see the whole calendar events in the excel file when I need.

Thank you in advance.

You can also create a view of calendar event data and export data in excel format by the help of view_data_export


Exclude node referenced from Related Views I have a view which show 4 related nodes based on category. Issue is that there is an entity reference product_group, in the node, and I want to show only those nodes which are not in product_group reference field.

This only involves one content type.

THis things might be solved in many ways, but the 2 solutions which we can use is.

We can add entity reference filter in Filter section of view. Entity Reference Filter is a view of type entity reference, and it should return node id based on arguments, and in our parent view, we can apply condition, that is not one of.
We can add a contextual filter of NID, with option of provide default value >> fixed value, and under more section, we can check exclude checkbox. After that we can use hook_views_pre_view, to set the argument, if it is first contextual filter, then using $arg[0], if it is second contextual filter, then using $arg[1].


How do I hide 'recent content'? On each article page I have an annoying 'recent content' part underneath the articles written, along with an extra title (see screenshot). Is there a way to not show the recent content? (I've just started out so if the answer could not involve code that would be great) I've had this issue from the start, as far as I remember, and I've changed themes a few times, which didn't help. Display Suite doesn't do anything to hide / change position either.

That extra title by the way, also appears on the basic pages--only then it's the only title and it's still on the bottom of the page.

I'd be ever so happy if someone could help me out. Thanks in advance! :)

http://img560.imageshack.us/img560/5093/recentcontent.png

Take a look under admin/structure/block and check if there's a block that's set to show in your Content region.


How to remove required field from nodes I'm displaying jobs in my site but after expiry of last date of application of job, I want to archive it for a month or so and then delete it.

So after last date of application I don't want to be listed in me Menu block and Taxonomy blocks: http://bit.ly/WB59KX . As if the (optional/required) term reference field value has been removed.

In short if Accountant term has been selected in a field( named profession) then after last date of application, clicking Accountant term should not display this node.

I don't want to unpublish expired jobs though.

How can I achieve this?

The way I'd do this would be to use Views to override the default taxonomy listing, then add a filter to the view so that the application date must not be in the past.

Life gets a little more complicated if you have multiple vocabularies and this rule won't work with all of them. Ctools page manager will let you load a different view per taxonomy.


How can I theme a single value from a multi-value theme? I'm trying to output a single piece of text from a multi-value text field (unlimited # of values) in my node template and I can't for the life of me figure out how to do it AND apply the THEME to it.

If I just do this:

render($content['field_hero_slideshow_header_text'][0])

I get the plain old markup for the field. However I want it to be run through the filters and have the theme template applied to it just as if I were rendering the full field with all the values like so:

render($content['field_hero_slideshow_header_text'])

I've tinkered with passing the #theme values and other vars to the array and using the theme() function also. but I can't quite seem to get it. What am I missing?

It seems like there are properties in $content['field_hero_slideshow_header_text'] which determine how it's themed. Perhaps a '#theme'.

Can you try making a copy of the entire field with just the value you want?

$content['field_hero_slideshow_header_text_copy'] = $content['field_hero_slideshow_header_text'];

// Unset all multi values, they have integer keys.
foreach($content['field_hero_slideshow_header_text_copy'] as $k => $v) {
  if (is_int($k)) { unset($content['field_hero_slideshow_header_text_copy'][$k]; }
}

// Add just the one we want back in.
$content['field_hero_slideshow_header_text_copy'][0] = $content['field_hero_slideshow_header_text'][0];

// Output single field.
render($content['field_hero_slideshow_header_text_copy']);

// Do you need to remove the field from the original array?
unset(render($content['field_hero_slideshow_header_text'][0]);

Not the nicest way I know. You could try copying properties from the parent to the child and it might output correctly, though I don't think so because the theme function probably expects data in a parent > child format.


making a views grid go from right to left? I have views, that I need placed differently. normally the images in a grid view show from left to right, but I need them the other way. How can i set a grid to show starting from right to left instead of left to right?

As far as I am aware, there are no settings in views to change this behaviour. However you can change the view format to "Unformatted" and give the .views-row a width and float:right (tweak as desired). This will line them up as a grid rtl.


Displaying URL taxonomy term as page title How can I display a taxonomy term in the url [example.com/taxonomy/% (% being the term)] of a page as title for that page - no view involved?

I assume it will require a block with some PHP or some hacking of a template.

In either case, what's the PHP and where do I put it?

I use D7 and Bartik.

Thanks. :)

Taxonomy Title is the only module that let's you control that title individually for every term. (You can also override the title generally by using a view or a pannel.) An additional "Taxonomy Term Page - heading" field wil appear on the taxonomy term edit form, allowing administrators to configure a specific heading for each term page.

  The taxonomy title module also provides tokens which can be used in
  conjunction with the Page title and Meta tags modules.

  This module was designed to update the heading tag at the top of the
  taxonomy term page. The contents of this H1 (or sometimes H2) tag are
  extremely important for SEO (Search Engine Optimization). People interested in SEO may prefer to add more user-friendly, keyword-rich,
  and descriptive words to this heading element.


Page arguments - hook_menu I have this two test menu items:

  $items['test/%id'] = array(
    'title' => 'Test',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form', 1),
    'load arguments' => array('%map'),
    'access arguments' => array(1),
  );

  $items['test/new/%new_id'] = array(
    'title' => 'Test',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form', 2),
    'load arguments' => array('%map'),
    'access arguments' => array(2),
  );

Here is the fr_module_form function:

function my_module_form($form, &$form_state, $id = NULL, $new_id = NULL) {
  dsm($id, 'id');
  dsm($new_id, 'new_id');
  return '';
}

Here is the problem. When I visit (for instance): test/my-test-var
dsm(1) function returns $id => my-test-var
dsm(2) function returns $new_id =>

but when I visit: test/new/my-test-var
dsm(1) function returns the same as above which is:
$id => my-test-var so it's not $new_id as I've expected.
dsm(2) is still empty

Moreover if I visit /test/new/my-test-var/my-second-test-var I get:
dsm(1): $id => my-test-var
dsm(2): $new_id => my-second-test-var

Why do I 'tell' drupal in 'page arguments' which argument should be used? I always get the first argument from my_module_form.

How to separate it?

Path parts are passed to the menu callback function with a zero index as the first path part i.e.

First url:
array(0 => 'test', 1 => '%id')

Second url:
array(0 => 'test', 1 => 'new', 2 => '%new_id')

Your form function expects two arguments but you only ever give it one.

In your form function arguments, this: $id = NULL, $new_id = NULL corresponds to this array('my_module_form', first_argument, second_argument) in your menu callback args. So you are only ever giving your form function one argument from the menu.
Try this in your second menu item:

'page arguments' => array('my_module_form', 1, 2),

This will provide two arguments for the form callback function. Your first menu item will return null for $new_id, because you don't have further path parts to provide from the url.


Display one image of commerce product in product display view I have created a view which display indexed nodes (product displays) in teaser mode.
The commerce product entity has a field called field_images which contain several images.

In teaser display mode of the commerce product, I choose to display Images.
On the views, for each commerce product, all images are displayed.
I'd like only the first to be displayed.
Unfortunately, I can't set a delta in the teaser display mode form.
I could have set the delta to 0.

I will seems reasonable to me, but I can't find an easy way to fix it.
How can I achieve this ?

I used the Image Delta Formatter module : https://www.drupal.org/project/image_delta_formatter and set the delta to 0 in the product commerce display teaser


Syntax for using getValue to get value in an array I created a form for a block plugin. I'm attempting to save the values to the form after submitting. However I'm having trouble saving the values if they are within an array.

For instance

public function blockForm($form, FormStateInterface $form_state){
    $form['plugins_string_text'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#format' => 'full_html',
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['plugins_string_text-submit'],
    );

    $form['header']['margin-top'] = array(
        '#type' => 'textfield',
        '#title' => t('Margin Top (pixels)'),
        '#default_value' => $this->configuration['header']['margin-top-submit'],
        );
    $form['header']['margin-bottom'] = array(
        '#type' => 'textfield',
        '#title' => t('Margin Bottom (pixels)'),
        '#default_value' => $this->configuration['header']['margin-bottom-submit'],
        );
    $form['header']['margin-left'] = array(
        '#type' => 'textfield',
        '#title' => t('Margin Left (pixels)'),
        '#default_value' => $this->configuration['header']['margin-left-submit'],
        );
    $form['header']['margin-right'] = array(
        '#type' => 'textfield',
        '#title' => t('Margin Right (pixels)'),
        '#default_value' => $this->configuration['header']['margin-right-submit'],
        );
}

    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['plugins_string_text-submit']  = $form_state->getValue('plugins_string_text');
        $this->configuration['header']['margin-top-submit'] = $form_state->getValue('header','margin-top');
        $this->configuration['header']['margin-bottom-submit'] = $form_state->getValue('header','margin-bottom');
        $this->configuration['header']['margin-right-submit'] = $form_state->getValue('header','margin-right');
        $this->configuration['header']['margin-left-submit'] = $form_state->getValue('header','margin-left');
}

This is saved to the form properly

$this->configuration['plugins_string_text-submit']  = $form_state->getValue('plugins_string_text');

However each of the lines below display the entirety of the 'header' array instead of the individual margin values.

$this->configuration['header']['margin-top-submit'] = $form_state->getValue('header','margin-top');
$this->configuration['header']['margin-bottom-submit'] = $form_state->getValue('header','margin-bottom');
$this->configuration['header']['margin-right-submit'] = $form_state->getValue('header','margin-right');
$this->configuration['header']['margin-left-submit'] = $form_state->getValue('header','margin-left');

What is the proper way to use getValue to reach an element within an array. Or is there another function I should be using?

Put the keys in an array, for example:

$this->configuration['header']['margin-top-submit'] = $form_state->getValue(['header','margin-top']);


Filter criteria affecting different displays in same view I have a view that displays content in a table form so admins can quickly look through the content. There are two displays (pages).

Page1: Lists all content and exposes the filters for type and published to the user so they can narrow down there view. But initially all content should be displayed.

Page2: Has criteria set to show only type=photo and published=no.(not exposed)

Everything else is the same between the two.

The filters on page2 are affecting page1. When you first land on page1, the filter controls say -any- and -any- but the view is filtered to type=photo and published=no (page2 filters). If you hit apply the filters are removed, but you can see how this could be confusing to users.

How can I prevent the filters on page2 of the view from affecting page1.

Whenever you apply any filter criteria / sort criteria / contextual filters / relationships; you have to make sure you apply settings to current display (page/block) only. In this way the current setting doesn't interfere with other displays.


Black bars in media-vimeo plugin Hi is it possible to remove black bars in media-vimeo plugin? There is line in player.css style which controls it, but I can't edit it, because this file is loaded inside of iframe.

No this is a video scaling and proportion issue for the player (or your embed code size). If Vimeo allows you to not show these black bars (you'd have to goto the Vimeo site and compare many many videos) ... you would need to figure out the correct aspect ratio to record you're video at so that these bars are not needed in the embed width of the player.


jQuery conflict issues with client embed code I am trying to use jQuery.noConflict so that I can use a 3rd party chat system that uses jQuery. This chat system loads in 1.72 while my current installation of drupal is using 1.12. After some hours of debugging and moving scripts around while trying to use noConflict(), I am at my wits end.

I believe the issue is that while trying to implement the 3rd party "click to chat" system for the client, it breaks IPE. This is being added via an embed field in a custom module I created. This embed field is being outputted via a twig variable in html.html.twig after

    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
  {{ embed|raw }} //Embed code here
</html>

My current error is as follows while trying to "edit" with the IPE.

jquery-ui.js:905 Uncaught TypeError: Cannot read property 'call' of undefined
    at a.(/web/anonymous function).(anonymous function)._trigger (https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js:905:38)
    at a.(/web/anonymous function).(anonymous function)._trigger (https://www.example.com/web/core/assets/vendor/jquery.ui/ui/widget-min.js?v=1.12.1:4:1094)
    at a.(/web/anonymous function).(anonymous function)._createWidget (https://www.example.com/web/core/assets/vendor/jquery.ui/ui/widget-min.js?v=1.12.1:4:3317)
    at new a.(/web/anonymous function).(anonymous function) (https://www.example.com/web/core/assets/vendor/jquery.ui/ui/widget-min.js?v=1.12.1:4:661)
    at HTMLDivElement.<anonymous> (widget-min.js?v=1.12.1:4)
    at Function.each (jquery.min.js?v=3.2.1:2)
    at r.fn.init.each (jquery.min.js?v=3.2.1:2)
    at r.fn.init.a.fn.(/franchise/anonymous function) [as draggable] (https://www.example.com/web/core/assets/vendor/jquery.ui/ui/widget-min.js?v=1.12.1:4:2374)
    at n.render (BlockView.js?v=8.4.5:95)
    at n.<anonymous> (LayoutView.js?v=8.4.5:146)

This currently renders the IPE completely broken. What would be the correct way to implement a 3rd party system that loads its own version of jquery, while not being able to change the source code of this 3rd party system?

This is what I have read/tried so far:

https://api.jquery.com/jquery.noconflict/

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

Similar but I also tried this:

https://stackoverflow.com/questions/2812359/mootools-and-jquery-conflict-despite-dollar-safe-mode

I was able to fix this conflict by only displaying this embed code to users who are not logged in. This resolved the conflicts with the in place editor.

In my twig file where I was outputting the embed code, I wrapped it in:

{% if not logged_in %}
  {{ embed|raw }}
{% endif %}


Commerce order mail is empty for anonymous users In the function below, there is the problem of sending email to anonymous users, the email sending only for users logged and to complete checkout and payment.

I get the following error message:

Error sending e-mail (from admin@mysite.com to ).

My Module:

function mymodule_commerce_checkout_complete($order){
            // send mails
            mymodule_send_order_emails($order);
    }

function mymodule_send_order_emails($order = NULL) {
    $module = 'mymodule';
    $key = 'my_message';
    $from = variable_get('site_mail', 'info@mysite.com');
    $language = language_default();
    $values['html'] = 'Html text value.';
    $params = $values;
    $send = TRUE;

    // load profile
    $profile = commerce_customer_profile_load($order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id']);

    // load user
    $user = user_load($order->uid);
    //$user->name;
    $to = $user->mail;

    $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
}

You have anonymous orders so your code doing the loading of the user account obviously wont work as they dont have a user account:

 // load user
$user = user_load($order->uid);
//$user->name;
$to = $user->mail;

The above won't work for anonymous users as they don't have an account so the uid is always 0. I think the $order object has $order->mail to get the actual email address used on the order regardless if it was a full user or anonymous


7 Ubercart hook_order for PayPal Paments Pro payment received I've got Ubercart set up with Paypal Payments Pro and it is all working well, however, I want to set up the system so that when a payment is received (captured) in PayPal (after which the site successfully receives an IPN), an email is sent to our manufacturing plant to fulfill the order (including the order details, shipping address, etc.).

I am aware of hook_order but I'm not sure how to use it in this scenario (i.e., upon IPN), or whether there might be an easier way to accomplish this (without code, i.e., using Actions). It is OK if we have to code it, that is not a problem. Only want to know my options.

IMHO the easiest way is to use Rules. There's a default rule you can clone and tune for your needs: uc_payment_received.

I would clone that rule, add the condition to ensure it's a payment coming from PayPal, then replace the action with "Send an order email". The you should be able to customize the email.

Writing a custom module for this task is a bit overkill.


Using view arguments for taxonomy term I have a url structured as such:

http://www.example.com/blog/unimportant-term/taxonomy-term

(is it a term or alias when the - dash has been added?)

I need to filter my result set based on the taxonomy term, and I don't know how to set that up in my view arguments.

Basically my view is getting all my blog posts, and depending on if there's a taxonomy term present, it will use that argument to filter the posts.

That should be rather easy.  You have to use two arguments, a regular taxonomy argument for your important term, and the global "Null argument" to ignore the unimportant term.  The null argument is added the same way as all other arguments, just have a look through the list.

I assume you know, that you have to set-up a "page" display, specify a path and insert the argument placeholders.


DS link to content - how to change the link? I am using D7. I want to do simple thing with Views and DS: I have view with list of content type teasers and another view with list of the same content type full articles. In DS there is an option to link teaser's Title to it's content, so when pressed user can get the full content of that content type. But I want all teaser titles to link to the same page - to the View with all content types listed.

Do I have to alter any tpl for this, or is there any other way to do this?
Maybe it will sound silly, but I really don't get it, so please help me :)

thank you!
Ben

Maybe display suite extras can help you achieve this with a combination of tokens.

After you enable the Display Suite Extras you could go to admin/structure/ds/fields and create a new code field.
Label your code field and tell you will be using tokens.

3 In manage Display of your content type disable the title and enable your new field that it was created by Display Suite Extras.

This tutorial helped me in doing something similar that you are trying to do.
Customize ULR/link display suite and tokens . I hope it helps :)


Remove Admin Toolbar "Manage" item if User has No Access I have created Tours for my users and allowed them to see the Admin Toolbar as a result. However, I have the following unpleasant toolbar:

I would like the "Manage" item to be gone altogether when there's only the Logout & Home link. How could I achieve such behavior?

Note: I've tried disabling the Tools item in the Administrative menu UI and that kinda works, but the Manage item is still displayed.

TLTTP;

Is a core bug since 6.4 version (https://www.drupal.org/node/296693) you can use the latest version of admin_toolbar (https://drupal.org/project/admin_toolbar) which haves a submodule specific for that issue. Unfortunately this only works for 'admin_menu' menu but not the toolbar menu (the black bar on top). To hide specific toolbar elements or toolbar element tray links (toolbar element links) you can implement hook_toolbar_alter(&$items) hook (https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/8.5.x).

Hope it helps someone.


Fatal error: Call to undefined function _ds_inception_get_overrides() I am trying to run the cron job in a drupal website that my client gave me then I tried to update the cron job for search and after the cron jobs finished then my drupal installation turn into this error.

  Fatal error: Call to undefined function _ds_inception_get_overrides() in C:\Apache24\htdocs\sites\uqsport.com.au\modules\ds_inception\includes\ds_inception.pages.inc on line 37

I have searched everywhere in google but it seems other people don't have this kind of problem before so it kind of make me perplexed as to how this error came upon me?
I just need to know how the above error happened? and what is the solution.
any help would be greatly appreciated. thanks though.

update.

this is what ds_inception.info contains.

 name = Display Suite Inception
description = Create flexible layout pages (Drupal within Drupal) on top of Display Suite.
package = "Display Suite"
core = 7.x
files[] = ds_inception.class.inc
files[] = ds_inception.module
dependencies[] = "ds_inception_fields"
dependencies[] = "ds"
dependencies[] = "ds_extras"
dependencies[] = "views"
dependencies[] = "ctools"
dependencies[] = "entity"
dependencies[] = "list"
configure = admin/config/user-interface/inception

; Information added by cms-build component-build on October 24 2016
version = "7.x-1.0"
core = "7.x"
project = "ds_inception"
datestamp = "201610241316"

When Drupal runs its cron tasks, it runs also every implementation of hook_cron() made from every module, including the core ones. Those implementation can then invoke other hooks, even the ones implemented by modules not implementing hook_cron().

The error you are showing is caused from the module whose machine name is ds_inception. Whenever it is implementing hook_cron() or one of the hooks invoked from hook_cron(), you need to disable that module.

I cannot tell you the name of the module you read in the page listing all the enabled modules, since I didn't find any third-party module with that machine name hosted on drupal.org. I thought it was a sub-module of the Display Suite module, but the 7.x-1.x branch doesn't contain such module, nor does the 7.x-2.x branch. It could also be a custom module developer for that site.
You can still find the readable name of the module in the ds_inception.info file, if you find one. It's the one following name = in that file.


Form alter hook in Drupal 6 I have created a content type in which I have a field that is a select box.
Now I want to change all the default values of that select box.

I know hook_form_alter() will work this, but I have no idea on how to change this.
Is anybody able to give me an idea?

Just adjust the values of the form element to your needs. Check this http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#select to see how selects ar build using FAPI.


Exporting the entire website, except users and content? As the title says. I need to export a whole project I've been working on to a production website in a different location. I need to export the modules, views, blocks, everything BUT the content and the users. I don't want the content as I made dummy content, and the user is a dummy user as well.

I was thinking on making a distro, but then I'd be missing on the structure. I would export the structure, but I need the modules as well. What's the solution for this sort of issues? My other solution is to build everything on production again, which is going to be draining.

I would also use a Dev -> Stage -> Prod workflow, but this will be a one time thing.

I would suggest to put your code in a version control like Git. There are many free services you can use like Github and Bitbucket. With Git you can easily ship your code from one server to another.

  I need to export the modules, views, blocks, everything BUT the
  content and the users. I don't want the content as I made dummy
  content, and the user is a dummy user as well.

You can use Features to export your views, blocks, content types, permission and roles, configuration, and even settings stored in variable table (Strongarm).

With everything in Features you can then run a normal installation in production then enable the features one by one. Here are some execellent tuts about using Feature.

http://mustardseedmedia.com/podcast/episode43
http://sf2010.drupal.org/conference/sessions/managing-and-deploying-configuration-exportables-and-features-module.html
http://www.drupalatlanta.com/event/drupal/april-13-2010

Related modules:

Migrate - Documentation

  My other solution is to build everything on production again, which is
  going to be draining.

One of the great things in Drupal is making the development easier and simple. With Features module, or hook like hook_update_N you will never do the same task on every environment you have. Development must only be done in local machine.

  I would also use a Dev -> Stage -> Prod workflow, but this will be a
  one time thing.

That is what Pantheon and Acquia are doing. You can build your own infra but that's another story.


Drupal Print PDF module with Chinese characters I'm using the Print PDF module, but cannot get Chinese characters to display. I have tried DOMPDF (which displays as ?????), and TCPDF (which displays rectangles). I have tried changing all the settings (Use dompdf's Unicode Mode, dejavusans font etc...) but nothing works. What could I be missing?

I have set up mbstring in my php.ini as follows:

mbstring.detect_order . . . . . . . . . . . . .auto

mbstring.encoding_translation . . . . . . . .On

mbstring.http_input . . . . . . . . . . . . . . .auto

mbstring.http_output . . . . . . . . . . . . . .UTF-8

mbstring.http_output_conv_mimetypes . .text/|application/xhtml+xml

mbstring.internal_encoding . . . . . . . . . .UTF-8

mbstring.language . . . . . . . . . . . . . . . .Neutral

mbstring.strict_detection . . . . . . . . . . .Off

mbstring.substitute_character . . . . . . . .no value

EDIT: It seems that I need to add the Firefly Sung font for this to work, but I still can't figure out how with respect to Drupal. Also - it seems you can only set one font for the entire site - not one font per language, which is what I want?

Thanks

Well I sort of solved it by using @font-face directly in the template file. Not the ideal solution, but it's working.


How to override function system_send_email_action_validate The following is in the core system.module

/**
 * Validate system_send_email_action form submissions.
 */
function system_send_email_action_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient']) && strpos($form_values['recipient'], ':mail') === FALSE) {
    // We want the literal %author placeholder to be emphasized in the error message.
    form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
  }
}

This is stopping VBO send email from sending email to a CCK email field.
How can I override this function? I want to change it to the following...

/**
 * Validate system_send_email_action form submissions.
 */
function system_send_email_action_validate($form, $form_state) {
  $form_values = $form_state['values'];
$has_tokens = count(token_scan($form_values['recipient'])) > 0 ? TRUE : FALSE;
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient']) && !$has_tokens) {
    // We want the literal %author placeholder to be emphasized in the error message.
    form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
  }
}

But without hacking core. Is there a way to do this in my custom module? Im having a bit of trouble understanding how overriding a module function works, in theme functions, I can just replace the function in mt template.php using the name of my theme, however MYMODULE_system_send_email_action doesnt work.


How to add item to $vars[breadcrumb] in Drupal The current breadcrumb only shows 'home'. I would like to update it so it shows 'home>shoes>Tennis Shoe' where 'shoes' is referenced content type(product display) and 'Tennis shoes' the instance(node) title of that content type

Here is how i tried to accomplish this.

I would push additional items(shoes, tennis shoe) into vars[breadcrumb] at page level(theme_preprocess_page) as following:

function THEME_preprocess_page(&$vars, $hook) {
...
$vars['breadcrumb'][] = 'shoes';
$vars['breadcrumb'][] = 'Tennis Shoe';
...
}

And then let my theme_breadcrumb() handle it as it walks through the array:

function THEME_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
        $breadcrumbs = '
';
        $count = count($breadcrumb) - 1;
        foreach ($breadcrumb as $key => $value) {
            if ($count != $key) {
                $breadcrumbs .= '
' . $value . '/
';
            }
            else{
                $breadcrumbs .= '
' . $value . '
';
            }
        }
        $breadcrumbs .= '
';
        return $breadcrumbs;
    }
}

This doesn't work. Whenever I add the items to the vars['breadcrumb'] in the preprocessor function as showed above, it never goes to 'THEME_breadcrumb', instead displays 'array' text. (apparently, it expects non array at vars['breadcrumb']) How do you manipulate breadcrumbs? Whats wrong with my reasoning? Thank You

Drupal 7, base of boostrap theme

I hope that you have set $breadcrumb in page.tpl.php.
Secondly, you do not need to do it by using theme_preprocess_page.

Just implement using THEME_breadcrumb like this:

function theme_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $output = '';
  if ((arg(0) == 'node') && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
    if ($node->type == 'TYPE NAME') {
      $breadcrumb[] = $node->title;
    }
  }
  if (!empty($breadcrumb)) {
    $output.= '
' . implode(' › ', $breadcrumb) . '
';
  }
  return $output;
}


How to prevent an Ajax form from submitting The below code blocks any non-ajax form from submitting.

$(this.form)
  .on('submit', function(event) {
    if (/* Some condition */) {
      event.preventDefault();
    }
  });

In Drupal 8, how can we block an Ajax form from being submitted?

Ajax forms do not trigger a form submit handler and I have not been able to block the click event on an Ajaxified form's submit buttons.

For reference, I am trying to fix Issue #3010084: Form submission finishes before file upload is complete

I found the solution here.

// Add submit handler to form.beforeSend.
// Update Drupal.Ajax.prototype.beforeSend only once.
if (typeof Drupal.Ajax !== 'undefined' && typeof Drupal.Ajax.prototype.beforeSubmitOriginal === 'undefined') {
  Drupal.Ajax.prototype.beforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {
    if (/* Custom condition */) {
      this.ajaxing = false;
      return false;
    }
    return this.beforeSubmitOriginal();
  };
}


Is the Drupal Multisite something automated once its setup? I am looking to create a multisite system that creates websites for users. But I need the users to be able to create their own website.
something like below steps :
Register>add domain>select theme>give donation(optional)>Done

Does the multi site feature allow this? If not, what is the best way to achieve this functionality?

Or what do you recommend we to achieve this?

Thanks

I build a system for a client where the client would deploy sites for his clients.  It was pretty easy with the Aegir system.  Aegir is a drupal site that manages drupal sites and different module configurations as "platforms" for those sites.

Need to depoly security updates?  Make a new platform with the updated modules, and migrate the sites from the existing platform to the new one with the built in migration managment.

A manual multisite install is similar to this, where the /sites/all folder is your platform common to all the sites, and each one has a separate database.

The disadvantage is each site residing on aegir is its own site, with its own database.  If you want nodes or pages common to each site you have to hardcode them into the platform's installation profile.(or make them manually for each new site)  Also, the steps in your question would have to be done in the Aegir level and not in the drupal site.

With the domain module you have multiple sites using the same database, so you can more easily share nodes and content across them.  Also, since it is one site holding different pieces under different subdomains, the ability to add new subdomains is in the drupal menu on the site.

Disadvantage: what affects one site affects them all, since they are all different faces of the same site.  Also, I have had bad experiences with the domain module (especially in conjunction with the commerce modules) and trust it less than other solutions.  Since (sub)domains are content types made by users, it is possible to delete an entire domain and lose all its content when you delete the user account that made it.  I saw a guy get fired for doing that by mistake.


How to set up a recurring payment I need to set up a recurring payment on Drupal 8. I discovered these two possiblity :

https://stripe.com/us/billing
https://www.drupal.org/project/commerce_recurring

What is the difference between these two possiblity ?

The commerce reccuring module looks extremely complex to set up.

It's entirely dependent on your business needs. The advantage of Commerce Recurring is that as part of the Drupal Commerce ecosystem, it gives you a complete toolset for building a subscription management interface in Drupal 8. This will let you completely customize the checkout flow, order receipts, other user interfaces and more, but it does require experience with Drupal 8 to build and maintain. For more information, review the documentation at:

https://docs.drupalcommerce.org/commerce2/developer-guide/recurring

If you just want to embed a Stripe widget, I recommend MoonClerk.


How to trigger email by comparing date value in node? I'm using Drupal 7, with Rules and Rules Scheduler.

I have a content type "Tutorial Class", with fields as below:

Class Date and Time
Feedback requested (Radio button: Yes/No, default
is no)

I would like to create a Rule, so that whenever the cron runs, it will check on all "Tutorial Class" content type.

If current time is larger than "Class Date and Time" field, and "Feedback requested" is no, an email will be triggered and "Feedback requested" will be changed to Yes.

Currently I know how to trigger email after "Tutorial Class" is created, but I can't get the above Rule done.

Any idea of how to set this rule?

Hi You can add a filed in your content type like date_content_type .
a)chose filed type =date  in content type(admin/structure/types/manage/content_type/fields)

b)add a condition in Rule set
c) select condition= data comparison
d) click on continue button
e) select data selector set your custom date type field
f)then add your time() value and save it . now your date condition rule set will be execute
i hope it will help you
Thanks


Adding workflow to files I'm working on a site that should let users to publish files (images), but I would to add a kind of workflow for these files.
Is there a way? I was thinking to use private/public files, in this way:

by default files are stored in "private" mode (so only certain users can see them)
create a module that simulates a workflow that "publish" a file, moving it to the "public" mode

Could be a solution?

The easiest way would be to create a content type called images, remove all the clutter and just add an image field. Since your images are now nodes, you can use any workflow module that you generally use. (Note you will have a overhead of one node for every image you upload)

If you don't want to follow the above approach then you can consider using rules and VBO module along with the the private folder options in image field settings.


How to rebuild everything that can be rebuild during module development? During module development, Drupal does not use all relevant information provided by a module on every HTTP request. Examples:

Changes to an implementation of hook_menu() are only used after calling menu_rebuild().
Changes to implementations of hook_node_access_records() and hook_node_grants() are only used after calling node_access_rebuild().
Classes referenced in the files[] array of the .info file are only rebuild after enabling the module. During module development, this means it has to be disabled first, along with all other modules that depend on it.

This list might not be exhaustive.

Is there a way to update all these information in the database in one go. Preferably via a Drush command?

drush cc all

Catches most of it. Registry/files[] changes can be tricky, but should work as well in most cases.

Node access records are not rebuilt by that, that wouldn't make sense to me. Unless working on a node access module, you don't want to have that rebuilt, as there could possibly be many nodes which means that this process could take a very long time.


download a file from a link using DrupalWebTestCase? I'm building a module that has a file download as part of its functionality. The data in it is dynamically populated from the use of forms.

Is there a method in DrupalWebTestCase that will allow me to download it? Or do I resort to wget?

The class DrupalWebTestCase has the method DrupalWebTestCase::curlExec(), which accepts an array containing the same values used by curl_setopt().


Removing access by role restriction I have a View with a Page display that only allows the returned data to be linked if the user is authenticated/logged in. I'm not using any extra modules that I can see (inherited site) that would enable access like this.

I simply want to remove that restriction. There is another view that looks the same except it's for Public and shows all the same data but not linked. (the data are pdf files).

On the authenticated display, next to Access in the Basic Settings it has authenticated user. If I click that user role (not the gear for options), then I'm shown a list of user roles to use for access restrictions. I click "None" and save, but the links are not there as an anon visitor. Same if I try by changing the user to Anonymous User. Note: In the permissions, anon has the right to see webfm attachments.

I noticed the URL is documents-public or documents-auth; so I made it just documents. No luck.

I visited the actual custom-page-type which puts the View in a content pane. I re-ordered the variants, removed all Selection Rules and that didn't do anything either.

I flushed all caches.

Somewhere, the view is still only showing a view based on whether a user is authenticated or not even though I've removed the access (it says "unrestricted" next to access) on both displays and removed all selection rules on the actual page.

I'm stuck on where else to look.

For whatever whack reason, I had to click on the file-name in the views, which was already set to "output with links", change it to without links then back and it works.

Thanks you, JimaJamma and jerdiggity; your answers made me focus on the field in the view.


Changing permission on node access that linked with other nodes I have a Jobs type content which include a user reference field

I have another content type called Applications which includes a node reference field that links to Jobs.

Register applicants can apply for Jobs via Applications, permissions have been set so only individual applicants can view their own applications and not anyone's else.

I want to set permissions so recruiters can only view applications to their own Job content type and not anyone's else. I can do this in views but if a recruiter knows another recruiters Application url (i.e /application/4) then the recruiter can view that application as well, in this example change the url to /application/5.

You can do this in hook_node_access().

You didn't mentioned if this is for D7 or D8, but this hook is available in both.

This hook provides the node and the account object. So you have all data you need to calculate the permission.


How to remove Submission information from webfrom module I am using webform module and when I get an email from a user it is displayed with this information:

Submitted on

Submitted by user:

Submitted values are:

I don't want to this information I just want to display form information only  .

Follow these steps to modify the email content, which comes to you on webform submission :

Login to the system by Admin credentials.
Go to webform page.
Click the Webform tab.
Click the E-Mails tab inside Webform tab.
Click Edit in Operation column infront of email address set by you for mail.
Find E-mail template & edit the content which goes to the email address set by you.

Check it as you are done.


How do I remove extra divs added by panels? Panels adds additional classes and divs which are unnecessary for my purpose. How can I remove these?

There are a couple ways you can tackle this.

One option is to simply create your own panel layouts.  I often do this because I like control over the markup and I want to reduce the divitus in my theme.  It also lets me create layouts that more directly match what I need.  It's pretty easy to create your own panel layouts in your theme.  Read more here.

Another option is to override the panel template files in your theme.  Similar to any module that provides a template file, you can copy that template file to your theme and change the markup.  You'll find the panel template files in [path_to_modules]/panels/plugins/layouts/[each_layout].


Call another view with a single exposed filter I have a page view which works fine for two cases in the exposed filter (say school one and school two).

However, if school three is chosen in the exposed filter, I want another view to be displayed instead of the page view for school one and school two.

I don't mind if it's a block view or page. Just to call another view because its display is different (a summary of school one and two in addition to school three)

@No Sssweat

Wao! A brilliant idea. But where do i add the JavaScript? In the
  themes folder or in the created views?

In template.php located in sites/all/themes/yourtheme

Add the following code at the bottom:

function yourtheme_views_pre_render(&$view) {

   if ($view->name == 'view_name') {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/custom.js');
   }
}

replace yourtheme with you actual name of your theme.
replace view_name with your view name.

Also, you'll need to wrap/format your jQuery code like this

/sites/all/themes/yourtheme/js/custom.js

(function($) {

    //your code goes here

})(jQuery);

PS: Don't forget to clear the cache to see the changes.


How to choose the alias used in a menu I'm having a bit of a problem when using multiple aliases regarding which alias appears on a menu.

For example, I have create a page /node/1, give it an alias /page1 and add it into the navigation menu.

Browsing to the index page I can see the page in the navigation at /page1.

I also want the page to be available at another alias /page2 so I add this through the URL aliases functionality. Unfortunately this updates my menu so the link in the menu now points to the URL /page2 instead of /page1.

If I have multiple aliases to a node, how does Drupal decide which is used in a menu and how can I change this

When multiple aliases are available, Drupal uses the most recently created (as determined by the pid column in the url_alias table).

I don't know an easy way to change this behavior.  You could try manually altering the pid value in the database.  Also consider if using a redirect is a better solution than aliasing.


Open messages in Bootstrap modal I use bootstrap theme, and I want to open messages in bootstrap modal; after searching, I found the Bootstrap Modal Messages module, which is not available for Drupal 8.

Is there any way for Drupal messages to appear in a Bootstrap modal?

This can be done by twig template and jquery. Add only 'Status messages' block on 'Highlighted' region. and in the twig template add like below:

{% if page.highlighted %}
          {% block highlighted %}

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      &times;
                    </button>

Message

                    {{ page.highlighted }}

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          {% endblock %}
        {% endif %}

After that in jquery file :

$(window).load(function(){
    if($.trim($("#modal-div .region-highlighted").text()) != ''){//region will be printed even if the highlighted area is blank
        $('#modal-div').modal('show');
    }
});

This will show your messages in modal window.


Calendar Module: Calendar block with mini-calendar to show next month instead of current I am using the Calendar module (http://drupal.org/project/calendar).

One of the default block  (called Block) in the Calendar module gives you the option to embed a mini-calendar as a block on your site. I would like this mini-calendar to show a future month instead of current month.

Does anybody know how to do it?

Thanks.

You can adjust the Contextual Filter for this block. Instead of providing a default value of "Current date" you can set it to "PHP Code" and use the following:

return date('Y-m',strtotime('+1 month'));


Displaying data by views from external API I have made 2 db's one is of Drupal 8 and another is external, that is non-SQL(CouchDB) and to manage this DB I made an API with different endpoint(URLs) witch I can axes them by GET/POST methods. After correct request I get response
 in JSON from my API.

When I create for example a user, content(node) or something else I save some info in my Drupal database and some info in my API db (I made alteration of the forms that create content by hook_form_BASE_FORM_ID_alter and this way I create content in my external DB).

My question is how to Display a data from a views, combining information form two Data-Bases?

If all you need to do is display data from the API, then you don't need to do anything special within views.  Just select that you'd like to view rendered entities of your users with a specific view mode.

In the preprocess function for that view mode, you can hit the API and load the additional data that you need.  Data loaded within a preprocess function should cache, so it shouldn't hit the API on subsequent page loads.

function mymodule_preprocess_user(&$variables) {
  /** @var $account \Drupal\user\UserInterface */
  $account = $variables['elements']['#user'];

  // custom code to hit the 3rd party API


How to add an icon before (or after) the node title if a field is filled? I'm a newbie in Drupal and I want to add an icon before (or after) the node title, if the node have a 'field_fav' filled. I know it can be done using preprocess functions, but I don't know how to append the title's  with the class I desired. Any how to?

Found this : Optionally add image/icon after node title based on boolean content type field? but it only for boolean type value.

I found your answer on drupal.org.

function mytheme_preprocess_page(&$variables) {
  $titleFile = 'myicon.png';
  $titleImage = base_path() . path_to_theme() . "/images/titles/" . $titleFile;

  $newTitle = $variables['title'].' <img alt="' . $variables['title'] .'" src="' . $titleImage.'" />';
  $variables['title'] = $newTitle;
}


download file on form submission I have created a form which has only a submit button. In the submit function I am generating csv file and saving it to the files folder using fputcsv function.

But Now I need extra functionality of submit. After saving the file it should download the file also.

How to do this? Any one have some idea about this?

Attach a form submit handler (code here: Drupal 7 custom form submit handler is not being called).

Then set the file url to $form_state['redirect'].

The file download should begin when submitted.


jQuery problem click function I'm having trouble doing simple stuff in jQuery. What I wanted was to call a function when something was typed in an input field.

Now I'm just trying this: when you click anywhere on the page to call an alert box like this:

(function ($) {
    $('body').click(function() {
        alert('test');
    });
})(jQuery);

This doesn't work ... . But when I do this:

(function ($) {
    alert('test');
})(jQuery);

I get an alert box when I load the page. My js file is loaded like this:

function xmed_preprocess_page(&$vars) {
    $path = current_path();
    if ($path == 'node/add/product') {
        drupal_add_js(drupal_get_path('theme', 'subtheme') . "/js/add.js", array('weight' => 1000));
    }
}

The file is loaded correctly. I'm working with jQuery v1.10.2. What could be the problem?

Try this as per drupal standard

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('body', context).click(function () {
        alert("test");
      });
    }
  };
})(jQuery);

Go through with Managing JavaScript in Drupal 7 for more information


"The website encountered an unexpected error." on front page only We are encountering this error:

Error

The website encountered an unexpected error. Please try again later.

On frontpage only and if the user is anonymous. If logged in, we can view the front page but if not, we see this error.

This is the error message from the error log.

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'node.entity_id' in 'where clause': SELECT COUNT(*) AS expression FROM
  (SELECT 1 AS expression FROM {node} node WHERE (node.nid =
  :db_condition_placeholder_0) AND (node.type IN
  (:db_condition_placeholder_1)) AND(( ( EXISTS (SELECT na.nid AS nid
  FROM {node_access} na WHERE (( (na.gid = :db_condition_placeholder_2)
  AND (na.realm = :db_condition_placeholder_3) )OR( (na.gid =
  :db_condition_placeholder_4) AND (na.realm =
  :db_condition_placeholder_5) ))AND (na.grant_view >=
  :db_condition_placeholder_6) AND (node.entity_id = na.nid) )) AND
  (node.entity_type = :db_condition_placeholder_7) )OR (node.entity_type
  <> :db_condition_placeholder_8) )) subquery; Array (
  [:db_condition_placeholder_0] => -1 [:db_condition_placeholder_1] =>
  evite [:db_condition_placeholder_2] => 0 [:db_condition_placeholder_3]
  => all [:db_condition_placeholder_4] => 0 [:db_condition_placeholder_5] => flag_friend
  [:db_condition_placeholder_6] => 1 [:db_condition_placeholder_7] =>
  node [:db_condition_placeholder_8] => node ) in
  EntityFieldQuery->execute() (line 1154 of
  /var/www/vanille/includes/entity.inc).

Your subquery is returning null, that's why the main query is unable to find entity_id from it. I think you have a wrong query somewhere in your some function, with wrong condition.. Look at this line - WHERE (node.nid = :db_condition_placeholder_0) and actual placeholder - [:db_condition_placeholder_0] => -1 - entity id can not receive negative value. You can install Devel module, enable query log from devel settings page, log in as authenticated user and see what function calls this query..


Make sure content of every view is published I'd like to set a query alter function that checks if the node.status condition is already set in the view's query, and if it's not I'd like to set it to only get published content. The following code doesn't seem to running on my app. Do you have any suggestions to make this work?

function hook_views_query_alter(&$view, &$query) {

    $found = false;

    foreach($query->condition as $condition) {
        if($condition = 'node.status') {
            $found = true;
        }
    }

    if(!$found) {
        $this->query->add_where(
            $this->options['group'],
            db_or()->condition('node.status', 1, '=')
        );
    }

I have > 100 views to implement this change on.

Why not just set a filter in the View configuration and set Status as Published?


looking for a slider module to use in the header what's a good slider for a header in drupal 7 (I would like to have a slider for different content in other blocks/pages of the website, so if the same module could work for both, better)

Try Views Slideshow. It is the most used and most flexible and you can create as many as you need.


hook_menu how to render the layout function test_menu()
{

    $items['test'] = array(
    'page callback' => 'test_test',
    'title' => 'test',
    'menu_name' => 'navigation',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => true
    );

    return $items;
}

function test_test()
{
    echo 555;
}

when I access to url /test, i see '555', but how to render the layout itself and in the content of the page show '555'?

You should change "echo 555;" to "return 555;"


Using integer with multiple values in Form API I have an integer field on a node which can take two values. The nodes are created by the users by submitting a form. I can't work out how to do this for a multiple field text value.

How do I set-up a textfield form element to take multiple values?
How do I then submit it into the node using an entity wrapper?

This is the form element.

function createnode_form($form, &$form_state){
    $form['field_student_age'] = array(
      '#type' => 'textfield',
      '#title' => t('test'),
    ); .....

This is the code that creates the new node.

function postajob_form_submit($form, &$form_state) {

  $entity = entity_create('node', $values);
  $ewrapper = entity_metadata_wrapper('node', $entity);

  $ewrapper->field_salary->set($form_state['values']['field_salary']);

There is no multiple property for textfields. Do I need to open up a different path in the form variable (e.g. $form['field_student_age']['value1'])? I've tried various options but I can't work out what the path would be.

If I do that, can I then just submit it in the wrapper with the extended path?

I got the solution from Save a new value with entity_metadata_wrapper to an entity field which is an array.

I created two separate form fields.

function createnode_form($form, &$form_state){
  $form['field_student_age'] = array(
    '#type' => 'textfield',
    '#title' => t('test'),
  );

  $form['field_student_age2'] = array(
    '#type' => 'textfield',
    '#title' => t('test2'),
  );

Then I stored them using the first method in the post quoted above.

$ewrapper->field_student_age[] = $form_state['values']['field_student_age'];
$ewrapper->field_student_age[] = $form_state['values']['field_student_age2'];

Rather than using set as I'd done with single values, I created a new entry for each value using [] =.


Dont Refresh Drupal's Page after a button is click in Forms API I had started developing a module in Drupal. I made two form controls: a fieldset and a button. The button calls a javascript function "myphoto_options" when it is click. This function only does an alert function. After executing the called function, the page then immediately refreshes the page. How to prevent the page from reloading?

Below are my codes:

function myid_user_page_form(){
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
        '#type' => 'button',
        '#value' => '...',
        '#attributes' => array(
        'onclick' => "myphoto_options();",),
    );
    return $form;
}

Javascript function:

function myphoto_options(){
    alert("Hey");
    return false;
}

Any help would be very much appreciated. Thanks.

You should do something like this:

function myid_user_page_form() {
    $form = array();
    $form['id'] = array(
      '#type' => 'fieldset',
      '#title' => t('ID Information'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
      '#type' => 'button',
      '#value' => '...',
      '#attached' => array(
        'js' => drupal_get_path('module', 'your_module') . '/js/your_file.js'
      ),
    );
    return $form;
}

Then, add a directory "js" in your module and a js file. In that js file use:

(function ($) {
    Drupal.behaviors.yourModule = {
        attach: function (context, settings) {
            $('#your-element').click(function(e){
                e.preventDefault();

                // Your functionality.

                return false;
            });
        }
    };
})(jQuery);


How to add custom HTML to node content? I'm new to Drupal coming from Wordpress, but I was able to put a site up&running. Theming is easy in WP, but I have not figured that out in D7.

I have a Content Type and the node-content output HTML as below. But I wanted to add custom html in-between section of the node-content:

    ....

    ....

I have searched online but I am not getting the basic instructions how to proceed. Presently I'm using a child theme of Zircon.

Any help?

Create a custom template file node--type.tpl.php where type is the machine name of your content type.

Place it in your theme's templates folder /sites/all/themes/YOURTHEME/templates and clear/flush the cache to see changes.

Ex: Article content type: node--article.tpl.php

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

// custom html goes here

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


Why there are random line breaks in emails sent through drupal? I noticed drupal includes line breaks in emails it outputs.

For example in admin/config/people/accounts we can customize message users receive when they signup and/or when they forget their passwords etc..

The thing is, when the emails are sent to the users, they contain line breaks that seem to be completely random and arbitrary.

I first thought the problem came from the webmail provider, so i tried with different services (gmail, hotmail, yahoo etc.. )

Any suggestions on how to fix this ?

Thanks

It seems it's drupal's mail processor that inserts all these line breaks.
I fixed the issue by installing MimeMail (and MailSystem).
It allows the use of html to format all outgoing emails.

I hope this will be helpful to somebody out there.


How to charge a user to post a job listing in D7? I have a job board and want to charge recruiters for each time they post a job listing. I will be using paypal and would not mind using the Commerce module in Drupal 7. I'm comfortable building Rules, even very complex ones. What is the best way to let job recruiters and businesses manage purchasing credits to be granted permission to create a job posting content type?

You can use a combination of Commerce userpoints and Commerce Node Checkout. This will allow them to purchase credits to be applied to publishing nodes.


Display block on first login only I want to display a block on first login only and never after that, is there any module or something possible for that?
I have a block which is visible always on the first page, but what i need is to show the block only once and never ever after. That block contains a link to start a javascript on page for the tour(Joyride Module). The problem is, If i select "Play tour once", It plays the tour once for every session and as soon as user comes after some time, I will restart the tour. I want the tour to start only once after login. I have decided to do it by showing the link to manually start the tour in a block and that block would be visible only after first login. So, is it possible?

First Login Module will do the job for you , this is some description about this module from its page :

  A simple utility module which enables the use of "first logins". With this module the site admin can enable content or do things that appear only on the first login for users by using modules like Context or Views. Couple useful functions are included for use in custom modules.


Is there a way to restore a field (in views) which has been removed using 'this block (override)' I am working with a view that has several sub-views and several fields which are common to all sub-views.  I removes a common field from one of the sub views by selecting it, setting the designation drop-down to 'this block (override)', and clicking the remove button.  This removed the field from the sub view without effecting any of the other sub-views (or the main view.)  I realized the I made a mistake when I removed that field and I would like to restore it.  Is there a way to revert an override on a view field that is no longer available on a sub view?  I would like to avoid re-adding a common filed to a sub-view (which will only be used for that sub view.)

You can basically revert the fields on the sub-view back to the master settings and list by:

-- clicking on the down arrow on the top right of the FIELDS section.

-- In the popup, change the For dropdown value to Revert to Default. This should effectively bring back the master list of fields, assuming that's where your missing field is.

-- any customisation for this specific view's fields must be re-done.

This same process can be done on any of the panes on the view's edit page - /admin/structure/views/view/my-view - if you want to revert anything.


How to customize Number of posts on front page in drupal 8 I went to URL:

admin/config/system/site-information

I can't find Number of posts on front page settings available there like Drupal 7 has.

I am using drupal 8 version : 8.0.0-dev

any help is appreciated.

As the front page is a view now, you can find its settings under /admin/structure/views/view/frontpage.


How can I programmatically restrict node access? I'm using Drupal 8 with the nodeaccess module.

I'm able to set the node grants with the form.

I also have a custom module which imports new nodes. These new nodes should be shown only to certain users.

I know I can insert the corresponding lines into the database tables nodeaccess and node_access. But this might be not consistent.

Is there a way to set the nodeaccess programmatically?

I use a function to build the database rows in node_access and nodeaccess:

  private function set_node_access($nid, $id, $realm='nodeaccess_uid', $view=1, $update=0, $delete=0)
  {
    // ksm("nid: $nid uid: $uid");
    $connection = \Drupal::database();
    $sql = "INSERT INTO nodeaccess (nid, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,$id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete)";
    $connection->query($sql);
    $sql = "INSERT INTO node_access(nid, langcode, fallback, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,'de', 1, $id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete);";
    $connection->query($sql);
  }

That's not the nice way, but it works for me.


How can I reset render cache on an entity for current user in hook_entity_view_alter()? I have Commerce products for which I'm showing or hiding the add-to-cart link, if that product is or isn't in the current cart.  In my code:
function mymodule_commerce_product_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
    $myservice = \Drupal::service('myservice');
    if ($myservice->isProductInCurrentCart($entity->id()) {
        $build['add_to_cart_link']['#access'] = FALSE;
    }
}

That works fine, however, when the product entities are rendered, they retain their cache and will continue to display, or not display, the add-to-cart link until the cache is cleared.
In my view_alter hook, how can I clear the cache for the current user for that entity before it's rendered?  Can I set a cache tag?

At first I disabled the cache for the link, but the entity was cached, preventing the link from being shown or hidden.  Therefore, I disabled the cache for the entity and that worked.
In the alter hook:
$build['#cache']['max-age'] = 0

The entity is now rendered with the proper state of the cart link.


How to update my drupal launched sites I want to ask about how to update Drupal 7 sites. My site is divided into 2 phases, after launching and adding data in the first phase, I now want to update the second phase. I have a lot of new content type, Views and panels. I added a new language and blocks, a lot of things. I can export panel and view but what about the content type, language and any permission or configuration that saved into database.

Use the Features module to export content types and permission. You can go to admin/structure/features/create and the select the features you want to export.


Assign a workflow to a content type I had defined a new workflow which has 3 states and I want to assign it to a content type. I had tried to make a workflow file type in manage field but when I try to edit it I can not choose my workflow type.

I only can select "-Select a value-" but my workflow type defined don´t appear.

Thank you in advanced.

First, I have to make a configuration in "transition" tab (in the same place where I have defined states for my workflow). After that I can choose it.


Rules triggering rules - how to enforce or disable it There are many situations in which a rule could trigger another rule.  For example, If I have a rule that reacts to a Node being created, I can trigger that rule with another rule that created a node.  The same should hold true for flagging nodes, but I have seen cases in which it does not.  I have written 'single flag enforcement' rules that are triggered by a node being flagged, which un-flag all nodes flagged by that user, then re-flag only the triggering node.  This rule should trigger itself over and over infinitely, but it does not.   How does Drupal's Rules handle these situation?  Is there a way to force rules to allow or disallow this form of cascading rule triggering (and potentially cause/prevent an infinite loop?)

It will not trigger recursively, Rules has inbuilt mechanism to prevent this. if you check the function rules_element_invoke_component you can see this.

function rules_element_invoke_component($arguments, RulesPlugin $element) {
  ....
  // Handle recursion prevention.
  if ($state->isBlocked($component)) {
     return rules_log('Not evaluating @plugin %label to prevent recursion.',  $replacements, RulesLog::INFO, $component);
  }
  $state->block($component);
  ....
}


How to add "Size" option in my Commerce Product without adding lot of SKU that differs by size? The same question was "Module Commerce Product Option. Sizes are not active for selection"

I read here Drupal Commerce Custom Sizes that "it requires you to define a SKU for every possible combination - depending on how many measurements options you have"
But I do not want to add many products. I need to add One product display Woman's T-Shirt with 5 SKU with photos:
Blue, White, Yellow, Green, Orange.
In every SKU I want to check the option sizes like:

Blue with option sizes: S, L
White S, M, L, XL,
Yellow XL, XXL, XXXL
Green L, XL, XXXL
Orange S, L

Without adding lot of SKU like: T-Shirt White S, T-Shirt White M, T-Shirt White L.....

The option Sizes should become dropdown or checkboxes when customer is viewing product Womans T-Shirt. How to do this?

Here it is correct: http://demo.commerceguys.com/ck/tops/drupal-commerce-hoodie
The user can choose color and size. Is this really neccessary to add all variations with color and sizes?

How to solve my optimization problem?

You're going to create 5 option set.

White with sizes
Blue with sizes
Green with sizes
Orange with sizes
Yellow with sizes

Each Option set create you created insert your size field (list type)

On your Shirt product type or whatever your product type is, create your sizes option set reference field

So when you create your 5 SKU you're going to choose which option set the user is going to use.

For Example:

Woman's T-Shirt WHITE (PRODUCT)
Option set reference:"White with    sizes"


How to set the breadcrumb for view defined pages I have created a page using views 3 like this

node/%/classroom

How can I set the breadcrumb and title for this page.

I tried to set using views menu option but restricts me to use normal menu for path with %.

Thanks in advance for your help.

Umar

You can set with hook_page_alter()

if (request_path() == 'your/page/path') {
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l('Whatever', 'whatever');
    drupal_set_breadcrumb($breadcrumb);
}


Migrating dependent entities I'm trying to custom-migrate D7 to D8 articles with references to file(images), taxonomy terms, and users(uid). Do i have to migrate the whole group all these entities belong to with

drush migrate_import --group=mygroup

to keep the references all right?

Or is it somehow possible to run one subsidiary migration and still keep the references, i mean

drush migrate_import mymigration

?

I haven't done a D7 to D8 migration, but for a migration to D8 from an sql source, I find it's best to do a "child" migration before its "parent. So do the users, terms, and files before migrating the articles. And then if you roll back, do that in the reverse order: parents before children.

This blog post was helpful to me: http://www.mediacurrent.com/blog/migrating-content-references-drupal-8

This is the way I organize things in my migrations...

In the child migration:

process:
  parent_id:
    plugin: migration_lookup
    migration: parent_migration
    source: my_parent_id

In the parent migration:

process:
# for the label field and any other non-reference fields, create 'stub' values in this manner:
  label_field:
  -
    plugin: get
    source: my_label_field
  -
    plugin: default_value
    default_value: 'Stub Label'
child_items:
  plugin: migration_lookup
  migration: child_migration
  source: my_child_items

Note: if some of your parent entities don't have any child items, you can use the skip_on_empty process plugin as follows to make sure those parent entities are still migrated properly. (If child items are required for all parent entities, you can omit from the migration any parent entities with missing children by changing the 'method' from 'process' to 'row'.)

  child_items:
  -
    plugin: skip_on_empty
    method: process
    source: my_child_items
  -
    plugin: migration_lookup
    migration: child_migration


How to enable bootstrap tooltip and popover (on a bootstrap based theme)? I'm using a theme based on Bootstrap 3.

I want to use Tooltip and Popover features that come with Bootstrap but I couldn't.

It's said on the Bootstrap Javascript page that:

  Opt-in functionality

  For performance reasons, the Tooltip and Popover data-apis are opt-in,
  meaning you must initialize them yourself.

  One way to initialize all tooltips on a page would be to select them
  by their data-toggle attribute:

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

I tried to add the code above to my node.tpl.php (inside of  tags) but it didn't work. I also tried to save that code as script.js and added it to my theme info file but it didn't work.

How can I enable these features? Where to use the above code?

I could enable the tooltip and popover by adding the code below to my node--mytype.tpl.php:

<script>
(function($) {
$(document).ready(function() {
$('[data-toggle=tooltip]').tooltip();
});
})(jQuery);
</script>

I added this JavaScript to my custom node--mytype.tpl.php because I wanted to use tooltip only on that content type.

If you want to use the tooltip anywhere on the website (eg on the blocks), you should add the code above to your theme's html.tpl.php file, just before the closing body tag.