Is it possible to change how entity reference field is displayed?

You just need to set the cardinality of the field.

->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

Note that you need to re-install (to be safe, uninstall before making the change) or write an update function to convert the database structure if you make this change.


Update node with services doesn't work for text_list widget

Maybe how you are updating the node i.e node_save() , The $node object that needs to be passed might not have the correct structure for the select list,

$node->body[LANGUAGE_NONE][0]['format'] = 'something';

You can always try to node_load($nid) and watchdog it to see the structure of your select field, and then verify if you are creating the $node object correctly before doing node_save().

This is just my guess, I can provide more correct answer once I can see the relevant code.

Cheers


You have to check the libraries for ckeditor in your drupal site.

sites/all/libraries/ckeditor

In D7 the CKEditor contain the libraries for editor. if you don't have then download the module and library from http://ckeditor.com/download


How to deal with unverified users in Drupal?

you should try the Logingtoboggon module. it has this feature

  Allow users to login using either their username OR their e-mail address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log
  in". The other brings the user to a separate page, but returns the
  user to their original page upon login.
  Customize the registration form with two e-mail fields to ensure accuracy.
  Optionally redirect the user to a specific page when using the 'immediate login' feature.
  Optionally redirect the user to a specific page upon validation of their e-mail address.
  Optionally display a user message indicating a successful login.
  Optionally combine both the login and registration form on one page.
  Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt
  for important information on configuring this feature!).
  Integrates with Rules module to do various tasks when a user validates via    email validation process (see
  http://drupal.org/node/880904 for an example)

I have put the feature you are looking for in bold.


How do I unset the comment form in Drupal 7?

Go to "Structure > Content types", "Content type > Comment settings", and uncheck "Show reply form on same page as comments."


How to migrate files together with additional fields

The YML code is correct. But there is an issue in Drupal core: https://www.drupal.org/project/drupal/issues/2822545

There is also a patch. I have tested the patch and it works:
https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch

The patch can be installed with Composer:

{
    ...
    "require": {
        "cweagans/composer-patches": "~1.0",
        "drupal/core": "8.4.6",
        ...
    },
    ...
    "extra": {
        "patches": {
           "drupal/core": {
             "Solve the issue when migrating files with additional fields": "https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch"
            }
        }
    }
}


Drupal and jQuery Plugins (ie tools) - overlay - mask isn't working - suspect javascript issue

I had a similar problem where the overlay was displayed in IE7, no elements on the page displayed, including close button. All elements were behind the mask. Adding this in the overlay() settings solved the issue:

onLoad:  function() {
  this.getOverlay().insertAfter('#exposeMask');
}

now the login popup in my site riparotto works fine.


When you configure the visibility of the block in UI you can use a standard region and the standard page template.

If you want to do this with a specific page template similar to the question, add a region download to the theme, place the view block in this region and render the region in the page template specific to the node page--node--13.html.twig:

{{ page.download }}


disabled="disabled" on a checkbox entity field

The BooleanCheckboxWidget has no settings for HTML attributes. You either have to create your own Widget or use hook_field_widget_WIDGET_TYPE_form_alter to add the disabled attribute.

Not tested personally, but you might also take a look at the Read-only Field Widget, could save you some coding: setDisplayOptions('form', ['type' => 'readonly_field_widget', ...])


The link (Link) render element type is used to render an anchor element on a page, and not used to provide an input element in a form that is constrained for URLs.

As an example you may look at LinkWidget::formElement, which shows how that field widget creates form elements for a Link field. And the way it does this is to use the url (Url) form element, which will provide an input element that validates URLs. Make sure that the #url property is a valid (Url) object.

$form['test_ink'] = [
  '#type' => 'url',
  '#title' => $this->t('Link title'),
  // Example of a Url object from a route. See the documentation
  // for more methods that may help generate a Url object.
  '#url' => Url::fromRoute('entity.node.canonical', ['node' => 1]),
];

Edit:

Added @imclean's suggestion to the answer for readability


How to apply patches that are created in core-dev

If the patch weren't already committed, you would need to reroll the desired patch against your Drupal Core version. This can be done by cloning the git repository of Drupal Core and generating a patch against the relevant revision of your version of Drupal.
The Drupal Core git repository can be found at https://www.drupal.org/project/drupal/git-instructions
See Making a patch on how to create a patch.
However in this case we can see that the issue has already been marked as "Fixed" and the patch of comment #19 was committed, so if you are on Drupal Core 8.1.x or up, you should already have the changes from that patch on your Drupal site.


I had exactly the same problem few days ago.
Do you have the devel module install?

For me it was the problem, i can't explain why but when i desintalled it, all worked fine.

So maybe, try to desactivate and unistall it and maybe your page permission will work again.

PS: i just re-install the devel module to make a test and i have exatly the same permission page than you. For me it's the devel module the problem. (I'm new in Drupal so i had certainly make a mistake somewhere)


Webform's schema makes it fairly painful, but this should fetch all of the submitted data for any submission where the field with key status has a value of 1:

$nid = 25;
$form_key = 'status';
$data = '1';

$query = db_select('webform_submitted_data','n');
$query->leftJoin('webform_component', 'wc', 'wc.cid = n.cid AND wc.nid=n.nid');
$query->innerJoin('webform_component', 'wc_filter', "wc_filter.nid=n.nid AND wc_filter.form_key=:form_key", array(':form_key' => $form_key));
$query->innerJoin('webform_submitted_data', 'n_filter', 'wc_filter.cid = n_filter.cid AND n.sid=n_filter.sid AND n_filter.data=:data', array(':data' => $data));

$query->fields('n', array('sid','data','cid'));
$query->fields('wc', array('form_key','cid'))
  ->condition('n.nid', $nid);

There may be performance implications doing this if you have more than a few records...

You could simplify a bit by looking up ahead of time the cid of the data component, or just hardcoding it.


I would suggest you try Domain CSS module if you are already using Domain Access module. ( https://drupal.org/project/domain_css )

This will give you ability to add additional css per domain so you can keep everything clean and organized.

Another alternative is to write a custom module and get $_SERVER['HTTP_HOST']; which you can run into switch statment to load css.

Similar question: Load domain-specific CSS file on a multisite


Content Pane on Landing Page not getting Context

Ok, the solution is pretty easy, but due to Views complexity it took my some time to figure it out. In my setup, there is no filter available. My mistake was, that I thought there IS a fitler available which is why I did not fill in the upper section. Since my filter is not in the url, I had to select "Load default filter from node page, that's good for related taxonomy terms".

That's all the magic ;)


Trying to Conditionally Add JS File to page if in a paragraph block reference on that page

In Drupal 8 drupal_add_js() as well as drupal_add_library() and drupal_add_css() were removed in favor of #attached. Means you now can use the #attached key in any render array or preprocess or build function to attach your library only where you need it. Please read the following articles on DO:

[Docs] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

[Docs] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

[Forum] Adding js to the block through module Drupal 8


If you want to schedule it every 6 hours, then it's 'crontab' => '0 /6 * * *'
The README.txt contains examples:

 /* Declare scheduler. */

  function example_cron_job_scheduler_info() {
    $schedulers = array();
    $schedulers['example_unpublish'] = array(
      'worker callback' => 'example_unpublish_nodes',
    );
    return $schedulers;
  }

 /* Add a job. */

  $job = array(
    'type' => 'story',
    'id' => 12,
    'crontab' => '0 /6 * * *', // I changed this line.
    'periodic' => TRUE,
  );
  JobScheduler::get('example_unpublish')->set($job);

 /* Work off a job. */

  function example_unpublish_nodes($job) {
    // Do stuff.
  }

 /* Remove a job. */

  $job = array(
    'type' => 'story',
    'id' => 12,
  );
  JobScheduler::get('example_unpublish')->remove($job);

'worker callback' => 'custom_job' it's bad practice to not include the name of your module in your callback. This is to prevent collisions. You should name it module_name_custom_callback. In your case it would be 'callback' => 'jobbank_custom_job'

The Job Scheduler is only going to schedule it, not run it. It will get run whenever cron runs. So if you have cron run set to once a day, it will only run your scheduled task once a day. Therefore, you will have to set cron to run every 6 hours or fewer.

Alternatively, I suggest you use a module like Ultimate   Cron which allows you to schedule different cron run times for different cron tasks. So you can set it to every 6 hours here.

This is the proper Drupal way to programmatically send e-mails How to programmatically send an email?


Is there a way to add node grants to anonymous users?

You might get this to work by using the Group module. Below are some details about how to do so.

1. Configuration

Create a Group Type (pick whatever name you want).
For this case, there is no need for special (custom) Group Roles for the Group Type you created. Since you'll be able to configure what you want by using these Special Global Roles (hardcoded) that come with the Group module (they cannot be defined by the Drupal administrator, and they are always available for any Group Type):

"Outsider": a signed in user that did not join a group.
"Member": a signed in user that did join a group.
"Anonymous": a user that is not signed in.

Create a Group (pick whatever name you want) for the Group Type you created, and let's say you name it "Promoted nodes" (feel free to use another name if you prefer).
Grant the appropriate Group Permissions for the configured Group Type. To do so, you can also configure for each Content Type which Group Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these Group Permissions are not the same permissions (they are specific to the Group module). With the above setup in place, just grant "view" access to the Special Global Role named Anonymous (and pick whatever rights you want for the other roles).

2. Granting access

With the above Group module configuration in place, all you need to do is:

assign each promoted node to the Group "Promoted nodes".
remove the node from the group again if it is no longer promoted.

For sure this assign/remove can be done manually (whenever a node is edited), but it should be straight forward to somehow automate it using "promoted or not" as the trigger to do so (using the API that comes with the Group module).

More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.


Force Drupal to attach Drupal behavior to new ajaxed content [only Drupal.attachBehaviors() is not working the right way]

I've got it.
This is working the right way:

Drupal.behaviors.my_ajax = function (context) {
    $('#content-group-inner a').live('click', function (e) {

        $('#content-group-inner a').addClass('my_ajax-processed');
        var url = $(this).attr('href');
        $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
        $('#content-region-inner').load(url,'ajax=1',function() {
                        Drupal.attachBehaviors('#content-region-inner');
                        });
        return false;
        });
   };

Thank you for all your help.


Migrating files from multiple paths with the migrate module

I believe you need to pass NULL as the first argument to arguments() instead of ''.

$jpg_arguments = MigrateFileFieldHandler::arguments(NULL, 'file_fast', ... etc);


You can use
Meta tags quick
The Meta tags quick module allows you to specify Meta tags based on path for your views

Interesting article on Meta tag generation here


Testing Modules with an External Database

User the setUp and tearDown methods to setup and tear down your external db.

A typical thing would be to write code that first empties the db and then populates it with the test data.


How do I fix the "Access denied" error in Organic Groups when I am logged in as admin?

If you temporarily disable og_workbench and it's still happening, you have a bigger problem.  Was OG upgraded from 1.x -> 2.x?

I've found myself in this situation a few times during og upgrades. First, check to make sure all the OG Migrations have been run at admin/content/migrate.  There is a migration named OgMigrateRoles that is often 0 of 0.  Even though there is nothing to migrate, it still needs to run.  If you do that and you still don't have access, check admin/config/group/permissions/node/[OG-ENABLED-CONTENT-TYPE]

You should see 3 columns w/ checkboxes for roles... NON-MEMBER, MEMBER, and ADMINISTRATOR MEMBER.  If you see the rows permissions, but no checkboxes or roles your og_role table may be "hosed" for lack of a more technical term.

It is possible to manually repair this table by inserting rows for the 3 default roles for each of your og enabled content types.  Something like...

INSERT INTO og_role (rid, gid, name, group_type, group_bundle) VALUES
(1, 0, 'non-member', 'node', 'group'),
(2, 0, 'member', 'node', 'group'),
(3, 0, 'administrator member', 'node', 'group');

The rid must be unique and 'group' should be replaced by your og enabled content type's machine name.  Trying to manually repair the table isn't recommended and should only be used if you can't re-install... and even then only if you know your way around MySQL and on a test version of the site.

The good news is I've always been able to fix this with enough time and comparing the hosed og to a working OG2 install.


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

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


Migrating from Drupal 7: source database does not contain a recognizable Drupal version

I was able to solve this after putting in the correct prefix.  This issue on drupal.org was very helpful: https://www.drupal.org/node/2637870

The correct prefix for anyone with a similar problem is shown here: http://i.imgur.com/MKf6CuG.png


A custom module is the most appropriate, probably only, place for your hook(s).

Most hooks only get run for modules; there are exceptions such as hook_form_alter(), hook_theme() etc. which are also called for themes, but generally speaking you'll need to write a custom module for any hooks you want to implement.

In case you're not familiar with building modules take a look at the Module Developer's Guide.


Here's some code I've used, you can't add the role condition to EntityFieldQuery so the array needs to be filtered afterwards:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
      ->propertyCondition('uid', '1', '>'); // skip the anonymous and admin
  $entities = $query->execute();
  $uids = array_keys($entities['user']);
  $accounts = user_load_multiple($uids);

  // filter the users array by role
  $include_roles = array('my_role', 'my_other_role');
  $filter = function ($value) use ($include_roles) {
        $isect = array_intersect($include_roles, $value->roles);
        return !empty($isect);
      };
  $accounts = array_filter($accounts, $filter);

Then, to add these to your group having id $gid

  foreach ($accounts as $account) {
    og_group($gid, array('entity' => $account, 'state' => OG_STATE_ACTIVE));
  }

Hope this helps. I think this should be doable in Rules, but I'm no expert in that.


In your view, you only need to bring up the node's parent group and display its banner field:

Add relationships: Organic groups: Group node (post)
Add fields: Content: Group banner, Relationship: Group node (post)


How I can create a user programatically using user registration form?

I think you needn't use the registration form as you have mentioned. You can use the following code to create a new user:

if (!user_load_by_mail('email_id')) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $user = \Drupal\user\Entity\User::create();

  //Mandatory settings
  $user->setPassword('your_password');
  $user->enforceIsNew();
  $user->setEmail('email_id');
  $user->setUsername('user_name'); //This username must be unique and accepts only a-Z,0-9, - _ @ .

  //Optional settings
  $user->set("init", 'email');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  //$user->set("setting_name", 'setting_value');
  $user->activate();

  //Save user
  $result = $user->save();
}

You can ensure that an user with same email id doesn't exist using user_load_by_mail(), and then proceed with the user creation.


Unlimited values field in Drupal 7 - how to show extra field in page.tpl.php

The best solution would be to run a foreach:

foreach($node->field_fileupload[$node->language] as $fileupload) {
  echo $fileupload['filename'];
}


The solution is an image field configured in a custom block type.

Block forms are configuration and don't support image fields. Custom block types are content and they support the same field types as nodes.

If you can't do what you want with a custom block type, you can create your own block plugin which uses a block content entity.

For background information see these questions Adding custom block problems and  Blocks: Old vs. "Custom" and Config vs. Fields.


What's the difference between global.css and default.css files in Omega theme?

Ok, this is really one of the confusing aspects of Omega.  Once you grasp it, though, it does make life easier.

The full explanation is found in the Omega Theme Documentation Handbook under How CSS works in Omega - "Ogres are like Onions... They have LAYERS".

global.css applies to all layouts (hence the name).  Since they apply to all layouts, this is the mobile-first sheet.

mytheme-alpha-default.css applies to all of the non-mobile layouts, which is when the grids kick in.

Then the narrow, normal, and wide sheets stack depending on which breakpoint you are on.

So if you are mobile, you just get global.css

Narrow, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css

Normal, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css

Wide, you get global.css + mytheme-alpha-default.css + mytheme-alpha-narrow.css + mytheme-alpha-normal.css + mytheme-alpha-wide.css

The best way to think about this is (in order):

How does my site need to look on mobile?  Make global.css
How do things change when the grid system kicks in?  Make mytheme-alpha-default.css
How does my site look when I am on a portrait table?  Make mytheme-alpha-narrow.css
How do things change when I am on a normal desktop?  Make mytheme-alpha-normal.css
How do things change when I am on a widescreen monitor?  Make mytheme-alpha-wide.css

In other words, don't think of this as four different layouts; think of it as a base layout that you apply changes to as you get wider.


It's actually quite simple. You only have to do like this:

public function patch() {
  // Write your code in here.
}

The patch function uses the canonical link just like get.

 * uri_paths = {
 *   "canonical" = "/path-to-endpoint", // Used for GET, PATCH and DELETE.
 *   "create" = "/path-to-endpoint/post" // Used for POST.
 * }

To get the request object, I think that you can use $request as first argument like this:

use Symfony\Component\HttpFoundation\Request;

public function patch(Request $request) {
  // Write your code in here.
}


Help required to set up multisite using organic groups (OG module)

Ok I have done it using Organic groups, spaces module and PURL.

First Install Spaces module after installing drupal
Then you can install PURL module and then organic groups module and OG theme module. OG theme associates theme to a group. You can also install OG menu if needed.
Once PURL is installed, go to admin/config/search/purl/types, enable subdomain option and domain option if needed.
Now create a content type of Group type or install OG example module (it automatically creates a organic group content type)
Now create a node which is of type group - node/add/group
Fill in the options and enter the Subdomain. For the subdomain to work you should have added ServerAlias *.site.com in your httpd.conf file
Once the node of type group is created your minisite is ready.
Using OG theme you can associate a separate theme for your organic group created.
Using og menu you can associate a separate menu for your organic group.


Show a block on the user registration form depending on destination parameter

As @runswithscissors pointed out this module does the trick Block Conditional Visibility by URI Query Parameters Thank you!

Step 1

Download and enable drush en block_query

Step 2

Go to blocks admin/structure/block and create a block or enable one of your choice. There are no specific configurations elsewhere. It's a very lightweight feature.

Step 3

At the page of your block, under the "Visibility settings" you will now see "Queries" to "show block on specific pages", add the query parameter ONLY.
E.g. if you have a destination parameter that leads to that particular page, only add the part behind the question mark ?, not the entire path.

Test it out

Let us know if it worked for you too.


How do I print the help text description above the field for all textareas?

The description_display property is still working if supported by your active theme and I understand it is. Adding this to your mytheme.theme should do the trick :

function MYTHEME_preprocess_form_element(&$variables) {
  if ($variables['element']['#type'] == 'textarea') {
    $variables['description_display'] = 'before';
  }
}

Note that this might not work with formatted fields from the field API as the description field is in a parent template, see text-format-wrapper.html.twig. It would be a little more complicated to have this working for those fields.


Importing CSV file to Generate Orders in Drupal Commerce

You can do this with the migrate module: https://drupal.org/project/migrate and the add-on module commerce migrate: https://drupal.org/project/commerce_migrate .

This is a coding solution, but I can't think of any other way you could do this without some coding of your own.


Can't use node_page_edit in ajax callback function

My solution:

/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}


Here is what I would do:

Create that many entites as you would like to able to submit with entityTypeManager (members)

Create their form objects with EntityFormBuilder->getForm($entity)

Set out all the elements you don't need (their submit buttons)

Add them to form like this:
$form[$custom_form_id] = array(
'#type' => 'markup',
'#markup' => render($created_form),
'#prefix' => '',
'#suffix' => ''
);

In your submit, call the children form submit functions.


How to compare current year with an integer field in Rules?

Add the rule as follows:

Event

Your event
Conditions:

a. Entity has field

-> Data Selector = node

-> Field Value = your date field (mine is field_bp_year)

b. Execute custom PHP code

-> Value =

return intval([node:field-bp-year]) < intval(date("Y"));

where you add the replacement pattern for your date field (mine was field-bp-year)
Actions:

Your action

NOTE: I treated my year as four digits. If you only want 2 digits then use date("y").


Drupal 7 and taxonomy views - sorting by number in URLs

Your data is being sorted alphabetically rather than numerically.

The simplest solution would be to store the 'Issue numbers' as an integer rather than as a sting.  Views will sort numeric fields the way you're looking to sort them without any fuss.

This obviously won't work if you ever have issue numbers that contain anything but but numbers.


Print object in template_preprocess_page

you can use :

dpm($variables['node']->toArray());


Is there any built in function to render image file extension like jpg, png etc?

image_get_info() should do the trick.

//if you want to get the extension of image1.jpg
$filepath = "sites/default/files/images/image1.jpg";
$info_var = image_get_info($filepath, FALSE);
echo "the image extension is ".$info_var['extension'];


How can I implement 3-way relationship (reference) between entities?

The Relation module should be ideal for that. It allows you to create a single relation entity that links 3 (or more) entities together. It's in beta and you may have to do some work to get the user interface you need (I say that based on the Relation session at DrupalCon London), but it's flexibility is superior to any other relation/reference module out there.


Drupal gives me a blank page after moving from localhost to server

With the limited amount of details provided it is really hard to guess what might be causing it. So here are some things you may want to check:

look in your webserver logs if any error is shown there.
make sure you granted the appropriate file permissions.
not enough PHP memory.

If you add more details to the question (like which OS, which webserver, etc) we might provide more answers also ...


How do I render a field on a node twice with two different field formatters?

You can output the field twice, using different formatters in the template

e.g, in node.tpl.php something like:

$output = array();
$email = field_get_items('node', $node, 'field_email');
$output[] = field_view_value('node', $node, 'field_email', $email[0], array(
            'type' => 'email_contact'));
$output[] = field_view_value('node', $node, 'field_email', $email[0],array(
            'type' => 'email_default'));
print implode(PHP_EOL, $output);


Commerce - delete products that do not reference a node

Try the Views Bulk Operations module.

You can create a View that lists Commerce Products

Use the Table format, showing fields.

Add a filter for the reference field and for the operator choose "Is empty (NULL)".

Add a field to the View, look for "Bulk operations: Commerce Product"

When the field settings come up, in the "Selected bulk operations" field set, check the "Delete Item" checkbox.
Arrange this field to be the first one in the list.

Save the view.

Now you will see all products that do not have a value for your reference field. The Bulk Operations: Commerce Product field will make a checkbox display for each row, and you can select one or more products to delete.

You can also check the text box in the table header, and that will "select all" products listed on the page. If you have more than one page worth of products, a button will appear that will let you select all products in the view.

Choose the "Delete Item" option from the drop down above the view and hit the button, and it will start the delete process, after a confirmation.


Try this command:

drush role-add-perm 'user-role' 'permission'


Using tokens or variables in Views "No Result Text" field

As I understand, in that field you should be able to use only fields and arguments tokens provide by Views only.

Unfortunately you can't use regular tokens  on that field. Maybe you should ask this directely on that issue your request to add support of tokens (that make sense actually).


Sheetnode Multisite Javascript error message: 'Unknow line type '' '

SOLUTION:

It seems obvious now but... if you have the same problem with any other module, just look at the source code.

If you see a lot of white space at the beginning, it's a clue.

Someone might have inadvertently left a closing php tag ('?>') somewhere in his code.

Someone doing copy/paste from online example/sources....

Anyway..I pulled my hair but learned some knowledge. No hard feeling to my colleagues ! ;)


I have managed to find an answer to my question

What I am doing wrong:

$path need set before.

In the value: [data:component-value]
Named the variable (ex: link_from_hell)

So, the next action you can manipulate the $patch.


In views, show the number of users who have subscribed to the organic group

This is how to get the OG membership ID:s to start with.

Add new view. Show -> OG membership (important!)
Then in some display add a contextual filter -> OG membership: Entity id.
Provide default value -> Type -> User ID from logged in user.
Override title: %1's groups. Specify validation criteria -> User.

Now you have the list of ID's.

Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title. Relationship -> Group node from OG membership.

Now you get the titles too. For test add some filters and sort criteria.


What is wrong with the following api call to logout user?

I encountered this error with angularjs(D8.5). This code works for me.

getUserLogout(logoutToken,csrfToken) {
  // post logout
  return this.http.get(
    'http://localhost:8082/d8/api/user/logout?_format=json&token='+logoutToken,
    {
      headers:
      {
        'X-CSRF-Token': csrfToken
      },
      withCredentials: true
    }
  );
}


Go get pathauto http://drupal.org/project/pathauto
With pathauto you can set up automatic path aliases to do exactly what you want. It will basically allow you to set up patterns for how to build token based paths for new pages at the time of their creation. It's one of the most widely used Drupal modules and is an absolute necessity for any site.

Also, once it's enabled and you've set up your paths the way you want them you can regenerate existing aliases in bulk at the content overview page.


Is it possible to use an image in my themes directory as the default image of an image field?

You could make a module whose sole purpose in life is to copy an image into the appropriate place in the file system. Then it would be in code and versionable, independent of what you did with the theme.


Theming the node edit forms  to open them within Lightbox

If installing one or 2 additional module is an option then you can check Popups API (Ajax Dialogs). When I last checked, the module had functionality of opening forms in popups, which you can theme. I also feel that, in the way Drupal form API works, there is more to done then just adding classes and JavaScript to make Drupal forms work in Lightbox.


You need to define your own access call back for the menu items.
For example: implement hook_menu_alter and changes the access callback for item['user/%user/edit'] and item['user/%user/cancel'] to your own custom access callback. I have not tried this myself yet, but it is something along these lines:

/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
}
/**
 * Callback to disallow access for the anonymous user.
 */
function MYMODULE_access_callback(){
  global $user;
  // if the global user (current user) satisfy the criteria
  // then return true else false.
  // you might not have to load the user from the menu item
  // as it may be already loaded and passed to the page and access callback
  // see hook_menu
}

It might be a better idea though to define your own menu items and handle the operations on your own instead of altering the user menu items.


It is the Advanced Forum module that is causing the problem.  Once I disabled it, it displayed as a teaser.  Now, I need to figure out just why.  Thanks for your help, Alex, really appreciate it.


If you disable email notification of new accounts, the OpenID module will set a random password when users register. See openid_form_user_register_form_alter(). If that is not what you want, you use hook_form_alter() to do the same thing under your desired conditions.
If you want to intercept user_pass_reset() so it cannot reset passwords, try using hook_form_alter() to add a form validation function.


Uncaught TypeError jquery function is not read anymore

You got it - basically it means the function isn't defined or is conflicting. You have to load the jQuery file that you're going to use and not multiple or you'll get that type of strange behavior.

The workaround I've used, which does work -- assuming you're not using that particular function -- is to define the function yourself as an empty function and it'll reference that and just keep on going. This came up in the Adobe Edge beta as fnCycle() was giving the same error. After putting the empty function in my own .tpl.php is solved and didn't kill the js execution.

Note though that while this may work for that one situation, you will have others if you leave conflicting versions of jQuery in there.


What is the equivalent of #page & #page-wrapper in Bootstrap theme?

After several try and error method, I did find the solution for this.

For a note, I am using LESS.

Step-1: Add a
 to page.tpl.php

Add following code in the page.tpl.php file of your sub-theme.

Step-2: Add the following CSS in the style.less of your sub-theme.

@media(min-width:@screen-sm-min) {
      #page-wrapper {
      width: @container-tablet;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red; }
    }
@media(min-width:@screen-md-min) {
      #page-wrapper {
      width: @container-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }
@media(min-width:@screen-lg-min) {
      #page-wrapper {
      width: @container-large-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }

So, this way, the added
 will be in harmony of Responsive theme of bootstrap and it will not displace any other container in the site and will not interfere with the native responsive design of Bootstrap.

Further Any suggestion or comment are welcome.


How many times drupal calls hook_node_presave for a node?

Once.

If it's called multiple times then you your node is saved multiple times.

This might be because you have some rules or other code that e.g. resaves the node in a hook_node_insert()/update().

To find out what and where, enable devel.module if you haven't already and add a ddebug_backtrace() call to your hook. That will give you the backtrace on how your function was called and you can identify who is calling node_save().


How can I get file field url in drupal 7 from views of its content type?

It's not really clear what you mean by 'access' in this context, but if you're looking to get the details for a file uploaded through a file field:

$node = node_load(1);
if ( ($field_items = field_get_items('node', $node, 'field_file')) ) {
  $file = file_load($field_items[0]['fid']);

  $uri = $file->uri;
  $external_url = file_create_url($uri);
}

Or to grab the external URL directly with an EntityMetadataWrapper:

$node = node_load(1);
$wrapper = entity_metadata_wrapper('node', $node);
$external_url = $wrapper->field_files[0]->file->url->value();


How can I setup a site with Acquia Dev Desktop 2 beta?

To do this, I used dev desktop to create the site instance (instantiating the database and vhost files within Apache) than overwrote that with the install I wanted. Specifically,

I created my site instance normally, selecting "Acquia Drupal" or any of the installations when it asked me to choose a distribution.

For my site settings, I changed it from the long name to 'drupal8' for simplicity

then I went to my local sites directory through terminal and removed the Drupal 8 installation it created (these commands assume OS X environment)

cd ~/Sites/Dev\ Desktop/
rm -rf ./drupal8

Now I can add whatever I like back into this directory, making sure I create it with the same name:

git clone --branch 8.x http://git.drupal.org/project/drupal.git ./drupal8

Now we should be able to install this normally with a couple changes at the install stage. For the database settings, you can use

username: drupaluser
password: <blank>

as Dev Desktop uses these credentials for all the databases.

Under advanced configuration there were two other settings you need to get this to work:

port: 33067
localhost: 127.0.0.1


What is going wrong with the file_field_path redirect for my files?

It turned out that what was happening is that the old redirects were never being deleted when I rolled back my migrations.  When I did a reimport, the source for the redirect already existed so new ones weren't being created.  To solve this I implemented hook_node_delete as follows (I need to delete redirects to system/files/publication_documents/{either int or pub}/{the value of a field}/{node id}) :

function MYMODULE_node_delete($node){
    // Delete alias.
    $nid = $node->nid;

    $type = $node->{'field_doc_type_' . $node->type}[LANGUAGE_NONE][0]['value'];
    foreach (array('pub', 'int') as $status) {
        redirect_delete_by_path('system/files/publication_documents/' . $status . '/' . $type . '/' . $nid);
    }
}

This works when the redirects have been created with the current $nid, but this wasn't true for any of the existing redirects in the system, so I wrote remove_redirects.php:

<?php
redirect_delete_by_path('system');

and then I rolled back my entire migration and ran drush scr remove_redirects

This cleared out the existing redirects, so I can run the migration again, and future rollbacks will get rid of the redirects too.


How to render a node image separately from the rest of the node content

What you need is the machine name for your field. This can be found by browsing to the content type in the admin, and seeing the value in the machine name column in the table. Within your node.tpl.php you can then access it using:

 print render($content['field_machine_name']);

By way of a more comprehensive description of how to render different elements of your node within the node.tpl.php, please see the rest of this answer.

You can implement this in a corresponding node template for your theme: In your theme directory, copy the default node.tpl.php from Drupal itself (resides in root_directory/modules/node/node.tpl.php, then make a second copy, node--content_machine_name.tpl.php. The variable you're interested in is an array which contains all the contents of the node you're about to display (from the Drupal API docs):

  $content: An array of node items. Use render($content) to print them
  all, or print a subset such as render($content['field_example']).

Using the $content array within this template then allows you to print either sections of the array (field by field for example), or to print the whole array, or to hide sections in the print of the whole array to display later.

By way of a couple of examples:

To print a specific field output:

<div class="example_field">
    <?php print render($content['field_name']); ?>
</div>

Or to delay the printing of a field until after you've printed the rest of the content. (This is used in the default node.tpl.php to print comments after the article content .

<?php
    // Don't print the comments during the main content run
    hide($content['comments']);

    // Render the main content array
    print render($content);

    // Then render the comments last
    print render($content['comments']);
?>

Which will print the field after the main content block. For more information check out the node.tpl.php docs.


Have a look at Freelinking Casetracker.

Drupal.org itself also automatically converts [#nid] found in issue comments to Node links, but I'm not sure if they're using this module or another similar input filter.

Writing your own input filter is pretty straightforward if those don't exactly match your needs.


Using user_load() and user_save() to change the status of a logged out user

In order to achieve that, I've tried
  using the following code in a page
  called auth.php I placed under my
  theme's root directory.

Normally in Drupal you don't create php files which are called externally. This can be done in some very rare cases. But most of the time you would define a menu callback in a module and have that call a function which you put your code in.

One of the issues that you have found is that Drupal is not bootstrapped from a generic PHP file.

It is fairly straightforward to do this.

Create a module, with a .module file and a .info file.
Turn on this module via the admin interface.
In your module implement hook_menu() and provide a path to be called, in your example this could be 'mymodule/auth'.
Create a function which will be called when your menu hook is fired.

There is a more in-depth tutorial here.


Limiting number of multiples in a drupal webform in an ajax callback

It is very difficult and sometimes impossible to alter a form via an Ajax callback.  Generally, an Ajax callback just returns the updated form element from the $form render array.

The Examples for Developers module includes several Ajax form examples that you can use as a starting point.


It shows you the Notice because somewhere in your data array you have missing data for a specific node. As for being correct, yes, it is a good way to alter the output. Try checking the data before printing it.

Something like

if(isset($row->field_field_twitter_screen_name[0]['rendered']['#markup'])) {
  //do custom action here
}

Edit: You can also make good use of $content variable here.


Having trouble seeing YouTube video in Drupal 7 using Media and Media YouTube

For future reference, the video_embed_field module now works well for youtube and vimeo videos.


Drupal 7 Apache solr - how to index pages content instead of nodes content

If I get you right, you don't want to show nodes in search results which are only used to be referenced to from another node, correct?

First of all, you need to define which Content Types should be indexed by SOLR. For this go to your SOLR settings page and untick all Content Types you don't want to show up in your search results.

After this done, I would highly recommend you to install the Display Suite module. This Module allows you to create different View-Modes. Built in and among many others which are available when you enable them, is the "Search Index" View-Mode. After enabling it for your Content-Type you can set it up the way SOLR should index it. So in your case probably the best would be to show the full content of the referenced node in the search index.

I hope this brief hints and tipps will help you ... To explain the Display Suite with all its possibilities is not possible in one post, but you really should try it.


How to disable form button on ajax callback?

In your ajax callback function write the code to disable button. like:

public function ajax_function(array &$form, FormStateInterface $form_state) {
    $form['my_button']['#attributes']['disabled'] = true;
    return $form['my_button'];
}

Hope it helps!


You could (a) try changing the granularity of the date field in your content type (b) override the theme function. (ref)


What is the difference between drupal_get_form and drupal_retrieve_form?

The difference is that drupal_get_form() handles retrieving, processing, and displaying a rendered HTML form for modules automatically, while drupal_retrieve_form() returns the structured array that defines a form.

Retrieving the form

drupal_get_form() first checks if the form is present in the form cache with form_get_cache(); if it isn't present, it calls drupal_retrieve_form(), and drupal_prepare_form().

Processing the form

drupal_get_form() calls drupal_process_form(), which is the function that calls drupal_validate_form(), and that invokes the submission handlers with form_execute_handlers().

Rendering the form

The rendering is done from drupal_process_form(), which calls form_builder().

In most of the cases, drupal_get_form() is the function to use, such as in the following code.

function node_menu() {
  $items['admin/content'] = array(
    'title' => 'Content',
    'description' => 'Find and manage content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_admin_content'),
    'access arguments' => array('access content overview'),
    'weight' => -10,
    'file' => 'node.admin.inc',
  );

  // …

  return $items;
}

The only module I found that is calling drupal_retrieve_form() directly is the Mollom module in mollom_moderate(), which uses it for automatically submitting a form. The code could use drupal_form_submit(), but (as a comment says), "Programmatic form submissions are not able to automatically use the primary form submit button/action, so we need to resemble drupal_form_submit()."

  $form_id = $form_info['delete form'];
  $form_state = form_state_defaults();
  // We assume that all delete confirmation forms take the fully loaded
  // entity as (only) argument.
  $messages[] = "Attempt to load $form_info[entity] entity via entity_load().";
  $entities = entity_load($data->entity, array($data->id));
  $form_state['build_info']['args'][] = $entities[$data->id];
  $form = drupal_retrieve_form($form_id, $form_state);

  $form_state['values'] = array();
  $form_state['values']['mollom']['feedback'] = '';
  // Take over the primary submit button of confirm_form().
  $form_state['values']['op'] = $form['actions']['submit']['#value'];

  $form_state['input'] = $form_state['values'];
  $form_state['programmed'] = TRUE;
  // Programmed forms are always submitted.
  $form_state['submitted'] = TRUE;

  // Reset form validation.
  $form_state['must_validate'] = TRUE;
  form_clear_error();

  drupal_prepare_form($form_id, $form, $form_state);
  drupal_process_form($form_id, $form, $form_state);

  $result = $form_state['executed'];


Drupal 7 Views 3 exposed filter preselected

Use a custom module for this

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if (!isset($form_state['view']->exposed_input['<filter_field>'])) {
    // OK to set the default value
    $form_state['input']['<filter_field>'] = '<new_default_value>';
  }
}

Where filter_field is the name of the exposed filter and new_default_value is the key of the value you want as the default.

Got the idea from this article


User login API for social login from mobile apps

I was also looking for functionality that you needs, but after wards i tried to implement service for social sign in using Hybridauth module and i succeed.

Try this https://github.com/rathodhiren9/hybridauth-service.git

Note : Its my own implementation and working fine using Poster/Postman. But you need to test in mobile application on your own.

Place this module folder in /sites/all/modules/custom and give full permissions if you are using Linux/Unix.
Look for Hybridauth Services in you all module list from Admin pannel of drupal 7 and install/activate it.
Now goto structure/services and add new endpoint if you don't have (remember Path to endpoint will be used in your URL call of service from mobile app).

After that you need to add Resources as per you requirement and for this service you need to check "hybridauth" resource and "connect" action from available resources and save the configuration.
Now this service will work from URL like /domainname/path-to-endpoint/hybridauth/connect. Be sure that url of your domain must match with your social media app's url that you are using for facebook or google
If your done well all the steps then you surly will test the service from Postman or Poster tools, But you need to get access token which will be an array of user data came from Facebook or Google and you will easily get it by debugging Hybridauth module's hybridauth.pages.inc file.

Hope this may be helpful.


Can't declare uniquely named class.. because it's "in use"

For PS4 class autodiscovery to work, your file name needs to be the same as your class name. From reading the error message, it appears that your file name is TransformLabels.php, but you've named your class transform_labels. You need to change your class name to TransformLabels:

class TransformLabels extends ProcessorPluginBase implements BuildProcessorInterface {

One other question I have is, did you create the facets processor plugin type? Or was it a 3rd party?


Change language for date cck field of a webform in drupal7?

go to /admin/config/regional/date-time/locale/es/edit and change the date format to month first for the long, short and medium dates


Change formset default from collapsed to exanded?

A simple hook_form_BASE_FORM_ID_alter() invocation can alter the default properties of the form. If you inspect the form array you'll see that the fieldset is stored in $form['subscribe']['subscribed']. By setting the #collapsible element to FALSE, the or #collapsed element to FALSE (if you want to retain collapsibility), the default behavior will be to keep the fieldset open.

For example:

function MYMODULE_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // Replace #collapsible with #collapsed to retain collapsibility.
  $form['subscribe']['subscribed']['#collapsible'] = FALSE;
}


Protect site from flooding when user login is attacked by brute force

The type malicious bots you describe can connect through open proxies all over the world (typically without permission), each having different IP addresses. They can also use trojans and viruses on hijacked client computers/servers to do their work.  In other words, Drupal's built-in flood control system, that uses IP-addresses for blocking, is no good for dealing with this type of attack.  If the flood system causes problems for you ("locks everyone out"), you need to reconfigure it or turn it off.

You can do this by adding one or both of the following pair of configuration settings to your site's settings.php file:

// Set per-IP failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;
$conf['user_failed_login_ip_window'] = 5;

// Set per-user failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;

In that way, no-one will be locked out.

Instead of using the built-in flood control in Drupal, try using Apache ModSecurity to limit bots access to your server, filtering on content (POST requests), instead of IP-address.

From its documentation on HTTP Traffic Logging:

  Web servers are typically well-equipped to log traffic in a form
  useful for marketing analyses, but fall short logging traffic to web
  applications. In particular, most are not capable of logging the
  request bodies. Your adversaries know this, and that is why most
  attacks are now carried out via POST requests, rendering your systems
  blind. ModSecurity makes full HTTP transaction logging possible,
  allowing complete requests and responses to be logged. Its logging
  facilities also allow fine-grained decisions to be made about exactly
  what is logged and when, ensuring only the relevant data is recorded.

First discover the pattern in the POST requests the bots make, and use Apache to block them.


Looping through an array using Migrate Plus

Thank you so much. I got it to work by creating a custom process plugin using "in_array", as suggested. If anyone's interested, here's the plugin I created:

namespace Drupal\migrate_veezi\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Check if value exists in array
 *
 * @MigrateProcessPlugin(
 *   id = "in_array"
 * )
 *
 * To check if value is in array, use the following:
 *
 * @code
 * field_text:
 *   plugin: in_array
 *   source: array
 *   search: 'string'
 * @endcode
 *
 */

class InArray extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $search = $this->configuration['search'];

    if ($search) {
      if (is_array($value) || $value instanceof \Traversable) {
        return in_array($search, $value);
      }
      else {
        throw new MigrateException(sprintf('%s is not traversable', var_export($value, TRUE)));
      }
    }
    else {
      throw new MigrateException(sprintf('search value is not set'));
    }
  }

}

And then I used it like this:

field_closed_caption:
    -
      plugin: single_value
      source: attributes
    -
      plugin: in_array
      search: '0000000007'


Create dummy instances of custom entity with dummy field data?

My created entities were not listed by the EntityFieldQuery above because of this issue: Make EntityFieldQuery::fieldOrderBy include NULL field values

My new entities did not include a date field that was used to sort the table. So, the table didn't include the null-field entries.

I didn't figure out how to specify the bundle for my new entities but there is only one bundle defined, so it is the default. I'm still interested in a function that would be able to create random field data valid for each type of field. Heading over to look at Devel module for that function.


This is not a problem with entities stored in the database, it is is a version conflict between the module Ctools and Drupal core.

When you install the current version of Ctools with composer require 'drupal/ctools:^3.4' you see that __construct() is calling the parent constructor providing a parameter EntityTypeManagerInterface.

modules/contrib/ctools/modules/ctools_views/src/Plugin/Display/Block.php

  /**
   * Constructs a new Block instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
   *   The block manager.
   * @param \Drupal\views\Plugin\ViewsHandlerManager $filter_manager
   *   The views filter plugin manager.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, BlockManagerInterface $block_manager, ViewsHandlerManager $filter_manager, Request $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $block_manager);

    $this->filterManager = $filter_manager;
    $this->request = $request;
  }

This requires that your core version has this code change:

https://git.drupalcode.org/project/drupal/-/commit/12d7ed53087a469ef8f87476c2849f7b24bfbbb7#140e79af0797f7f25fd1f20e2ebc697be118fea6

So you have to make sure you are using a current core version 8.8.x or you have to downgrade Ctools to a version not having this change.


Private files won't be saved anymore in their intended location? (D7)

You spoted your problem in your apache log file : Apache is forbiding access.

You have 2 options here :

If you want apache to allow access to these files then add this to apache conf file :

<Directory /home/sitio/public_html/files/private/curso>
  AllowOverride None
  Order Allow,Deny
  Allow From All
</Directory>

then restart apache and I guess you should be ok to access your file.

But if you want these files to be private then you want to restrict access rather than open it, so

Alternatively,

you let apache restrict access to these files, and you set drupal serve these files via alternative drupal-generated links. Check the documentation for setting up access to private files here, look for the section on "Accessing Private Files".

If you've got no .htaccess file for the folder as you said then create one with :

Deny from all
Options None
Options +FollowSymLinks


Can't re-import a majority of products in CSV file

There is a bug report about Importing Large CSV document (downloaded and processed in the background).

Also, take a look at Feeds large CSV import.

So if your CSV files are too big, parhaps cutting them down into multiple smaller CSV's will likely fix your problem OR You could try using the Drush Feeds sandbox as mentioned in the first comment.


How to print add/remove link for user relationships module?

Install Devel module and add dpm statements in a progressive fashion. For instance: After you load the account, add : dmp (arg(1)) (and no other statements following). Inspect the dpm output for correctness and go onto the next statement, ie. dpm($account(arg(1)) and so forth.


Output JSON views_field_view with Services?

This was an issue with custom fields in Services Views that has been fixed in the latest dev version.

https://drupal.org/node/1647270


extracting data from webform and parsing it

You can use token for that purpose. Webform do have a facility to add token in mail template. But this would be default mail template using dynamic value of submitted form.

There you can find all field component available in webform.


I needed something similar, I solved it by first making a rollback and then I launched the original command.

drush mr

You can find more information about the command on this link  https://drushcommands.com/drush-8x/migrate/migrate-rollback/


Migrating data from Drupal 6 to 7 with a twist

In my experience the Migrate Module works really well for this.

In your migration you could use Preparerow() method to modify the fields you want to change before the import.

You can find more documentation on it here:
Advanced Field Mapping
Drupal Migration Documentation

Hope it helps :)


Override one line in core tabelselect jQuery behavior so custom checkboxes aren't affected

I ended up doing what I suggested, and overriding with my own custom version of tableselect.js

/**
 * Implements hook_js_alter().
 */
function language_dashboard_js_alter(&$javascript) {
  // Override core tableselect.js with custom version.
  $javascript['misc/tableselect.js']['data'] = drupal_get_path('module', 'language_dashboard') . '/js/language_dashboard_tableselect.js';
}

just to tweak this one line from this:

checkboxes = $('td input:checkbox:enabled', table).click(function (e)

to this:

checkboxes = $('td input:checkbox:enabled', table).not("input[id*='staging_only']").click(function (e)

by adding the .not() selector. It seems like a lot of code copying just for that one modification, but as of now, I don't see any other way.


Display contact information for each car owner

How do you gather the contact information? Is it profile fields or a node connected to the user account?

Regardless of the method you can create a view that will use the author of the node as the argument of the view (D6) or contextual filter (D7) to bring the contact information for the user. One thing to consider is that you might have to create a relationship to the entity or method you used to collect the information.

After the view is created the next thing will be to decide how to present it, maybe you want to create a block, or attach it at the end of the car content type or make it a tab, all those options are available in views as well.


Knocked out my own admin recongizion on my own site

If u are able to create account,create it and in the database for the 'users' table update '1' to the 'uid' field for the account you created and if you are unable to create a account then create a account manually in the database

INSERT INTO users (uid, name, pass) VALUES ('1', 'yourname',> md5('yourpassword'));


Can't choose checkboxes as field widget in d7

Set "Type of data to store" to List (text), List (integer) or List (float) and Check boxes will be default widget. If you can't see them, make sure List module is enabled.


How to reference existing Paragraph entity?

Re-using paragraphs is not supported/allowed. Each paragraph has a reference to the host entity it is being used in and only supports one such reference.

If you need re-usable content in paragraphs, you need to have another entity type or bundle that you reference from a paragraph type.


Display expiry date of licence in list of orders

I simply added a relation and it worked! Thanks Neograph734


How to display link to the next/previous most recent node from current node (if it does not belong to a book)?

You can do it with db_query in your node--content_type.tpl.php. Get all nids for content type in array. Match the current nid position in array. Like if Position is array[3] the Previous nid link should be array[2] and next should be array[4].


Views Search Ignoring Custom Node Access permissions

It seems that a better way to control node access is through hook_node_access_records and hook_node_grants as described here http://drupal.org/node/1260948. This works with views properly.

I wrote this simple module based on the instructions in the link above:

define('MYMOD_REALM', 'mymod');
define('MYMOD_GRANT_ID_PUBLIC', 0);
define('MYMOD_GRANT_ID_MEMBER', 1);
define('MYMOD_GRANT_ID_BOARD', 2);
define('MYMOD_BOARD_MEMBER_RID', 7);
define('MYMOD_MEMBER_TID', 69);
define('MYMOD_BOARD_MEMBER_TID', 68);

/**
  * Implementation of hook_node_grants().
  */
function mymod_node_grants($account, $op) {

  if ($op == 'view') {
    $grants[MYMOD_REALM] = array( MYMOD_GRANT_ID_PUBLIC );
    if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_MEMBER );
    }
    if (array_key_exists(MYMOD_BOARD_MEMBER_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_BOARD );
    }
    return $grants;
  }
}

/**
 * Implementation of hook_node_access_records().
 */
function mymod_node_access_records($node) {

  $grant = array(
      'realm' => MYMOD_REALM,
      'gid' => MYMOD_GRANT_ID_PUBLIC,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  if (in_array($node->type, array('page','publication'))){
    $access_level = field_get_items('node', $node, 'field_access_level');
    if (count($access_level)){
      $access_level = (int)$access_level[0]['tid'];

      switch ($access_level) {
        case MYMOD_BOARD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_BOARD;
          break;
        case MYMOD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_MEMBER;
          break;
      }
    }
  }
  $grants[] = $grant;

  return $grants;
}


Working with a checkbox and EntityFieldQuery

You can add tag to your query and use hook_query_TAG_alter() to add additional conditions. Here's an example:

function mymodule_get_nodes() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->addTag('node_is_not_tagged');
  return $query->execute();
}

/**
 * Implements hook_query_TAG_alter().
 */
function mymodule_query_node_is_not_tagged_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_hide_panel', 'hp', 'node.nid = hp.entity_id AND hp.entity_type = :entity_type');
  $or = db_or()
    ->condition('hp.field_hide_panel', 0)
    ->isNull('hp.field_hide_panel');
  $query->condition($or);
}

Link to relative issue: https://www.drupal.org/node/1157006


all my edit button cannot work and got "Invalid form POST data" AJAX error

An AJAX HTTP error occurred is very general error and it can be related to many things.

Based on your provided information we can say it's a core callback (/system/ajax) and the callback exists (Result code: 200).

The main problem is that it returns the empty response. This is most likely caused by WSOD (white screen of death) which can be related to:

out of memory issue (increase memory_limit in your php.ini),
timeout issue (increase max_execution_time in your php.ini),
code issue (make sure you don't have any exit() or die() which terminates your code),
cache issue (so please clear your cache, including memcached/redit if you're using it).

To debug this, you should:

Check your watchdog table for any errors (e.g. drush ws --tail --full).
Check your PHP error log for any PHP errors.
Use XDebug PHP extension, after configuring it enable xdebug.auto_trace parameter (only temporary), then reproduce the problem and check the trace file for more details.


Some of the pending updates cannot be applied because their dependencies were not met

This may help: http://drupal.org/node/915216

Others that are more module specific may be:

http://drupal.org/node/1190294
http://drupal.org/node/1111524


How to assign blocks to particular regions on theme install?

First of all, you should change each desired block region you want manually at Administration>Structure>Block layout Tab and then go to the config export function at:
Administration>Configuration>Development>Configuration synchronization>Export Tab>Single item to export each the block settings for your theme.
Then you should take a look at to the generated YAML files and placed that in a new folder within your theme at /config/install. you then uninstalled the theme and then reinstalled it as the default.

Summary:
1. Install MY_THEME
2. Place the blocks in the desired regions
3. Export config files and remove from them uuid and core config hash
for example Site Branding block block.block.MY_THEME_branding.yml file

langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - DEPENDENT_THEME
id: MY_THEME_branding
theme: MY_THEME
region: site_branding
weight: 0
provider: null
plugin: system_branding_block
settings:
  id: system_branding_block
  label: 'Site branding'
  provider: system
  label_display: '0'
  use_site_logo: true
  use_site_name: true
  use_site_slogan: true
visibility: {  }

Place config files to MY_THEME/config/optional or MY_THEME/config/install directory (if you're absolutely sure all dependencies are met)
Uninstall MY_THEME and clear all caches
Reinstall MY_THEME again


how to add fields for drupal registration form internally souce code of drupal7.17 application

To add the fields to user profile you should use Profile2 module.

With profile2 user account settings and user profiles are
conceptually different things, e.g. with the "Profile pages" module
enabled users get two separate menu links "My account" and "My
profile".
Profile2 allows for creating multiple profile types, which may be
assigned to roles via permissions (e.g. a general profile + a
customer profile)
Profile2 supports private profile fields, which are only shown to the
user owning the profile and to administrators.


The code doesn't work because the build() method doesn't return anything, which for PHP is like returning NULL. (In other words, you are telling Drupal not to render anything.)
If you fix that, then you would also have to attach the library to the same variable to which you attach the settings.

public function build() {
  $build = [];
  // get the variable from field_test
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $build['#attached']['library'][] = 'mycustomblock/custom';
    $build['#attached']['drupalSettings']['mycustomblock']['test'] = $node->field_test->value;
  }

  return $build;
}

As side note, as per Drupal coding standards, class names should follow the UpperCamel naming, a.k.a. PascalCase.

As for the JavaScript code, take node.js as guide.

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.nodeDetailsSummaries = {
    attach: function attach(context) {
      var $context = $(context);

      $context.find('.node-form-author').drupalSetSummary(function (context) {
        var $authorContext = $(context);
        var name = $authorContext.find('.field--name-uid input').val();
        var date = $authorContext.find('.field--name-created input').val();

        if (name && date) {
          return Drupal.t('By @name on @date', { '@name': name, '@date': date });
        } else if (name) {
          return Drupal.t('By @name', { '@name': name });
        } else if (date) {
          return Drupal.t('Authored on @date', { '@date': date });
        }
      });

      $context.find('.node-form-options').drupalSetSummary(function (context) {
        var $optionsContext = $(context);
        var vals = [];

        if ($optionsContext.find('input').is(':checked')) {
          $optionsContext.find('input:checked').next('label').each(function () {
            vals.push(Drupal.checkPlain($.trim($(this).text())));
          });
          return vals.join(', ');
        }

        return Drupal.t('Not promoted');
      });
    }
  };
})(jQuery, Drupal, drupalSettings);

Drupal modules should use behaviors.

See the first and the last line of the code I copied here. Your JavaScript code should use the same lines, and access the settings with drupalSettings.mycustomblock.test.


Latest tweets from a specific user (bonus: rotating slideshow)

Here's how I would implement this:

Use Feeds to aggregate your tweets to a custom content type, map tweet id to node title and tweet body to node body.
Create a View to display x amount of tweets from the custom content type.
Use Views Slideshow to rotate the content.


Using arguments is deprecated.

Now you can migrate geofields without migrate_extras.

$this->addFieldMapping('field_location', 'point');

And in your prepare row

public function prepareRow($row) {
 $row->point = 'POINT (' . $row->longitude . ' ' . $row->latitude. ')';
}


How to set Navbar to be a sidebar by default?

I found a way to do this in a very simple custom module without any hacking or patching to Navbar code.

Just create and enable a custom module that contains (assuming your module is called custom):

/**
 * Implements hook_navbar_breakpoints_alter().
 *
 * Nullifies the breakpoint that switches the navbar to horizontal orientation
 */

function custom_navbar_breakpoints_alter( &$data ) {
    $data["wide"] = "not all";
}

The navbar module defines a hook, hook_navbar_breakpoints_alter, using drupal_alter, that allows its hard-coded breakpoints to be overwritten.

not all seems to me the cleanest and most intuitive way to implement an impossible media query condition (related: How to set a media query condition that is never met?).

This makes the switchable horizontal masthead view of the navbar menu, quite literally, the default on not any device.


How to load one certain js before all others?


You will need to make sure that the content type creates a new version with every edit. Then, you should be able to make a Views block that shows node versions and the status field.


How can I prevent an organic group administrator from accessing edit page of a group?

My suggestion would be to use rules to redirect users that aren't admins to another page, or use hook_menu_alter() to alter the access permissions to the page. Alternatively, you can use hook_page_alter() to check the active user's roles and redirect them if they aren't in the admin group.


Proper approach to two different address data sets on the system

I'd just use Commerce Addressbook, it would allow you to have a set of addresses in your user account, from project page:

  Commerce Addressbook is a module that allows authenticated customers
  to reuse previously entered addresses during checkout. They can manage
  all entered addresses in their user panel (user/%user/addressbook).

Seems exactly what you're looking for and is way less complicated that dealing with the addresses and defaults yourself.


Possible to prepopulate an inline entity form multiple with a url parameter?

Please try with Entity reference autofill and Entityreference prepopulate Modules.

Add an entity reference field in your entityform.
The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (?field_name = value)
Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach is,

  If you want to do this by coding, Just pass nid through url and use node_load() to load that node and create an entity form submission. If you want to create entity form with node creation use hook_node_insert or hook_node_presave.

Hope this will help you.


Flush cache on specific drupal 8 page/route

AFAIK, cache invalidation should not depend on the page or route. When an entity (eg. node #5) is changed, it should in validate all caches tagged with "node:5". If the list of entities is correctly tagged with its cache dependencies, you should be fine.

I realize this answer is rather theoretical and not very specific. Hopefully other answers will be more detailed.


Performance: Efficient use of EntityFieldQuery (with node_load OR node_load_multiple) to update thousands of nodes with/without conditions

If you can access the data via SQL then I think the Migrate module can do 80%+ of what you want with relative ease. Your hardest part may be either: 1) getting an SQL dump of the data you want from the remote system, or 2) build an SQL representation of the data from the data you can retrieve from the webservice using a Cron type task.

Assuming you can get an SQL version of your (by the way Migrate and what I'm talking about works on XML, JSON, CSV, text files ... and the framework supports "lists" of data from other sources -- but you'd have to develop some of your own Classes for exotic import sources ... I digress) ... migrate supports querying your objects like "I want to move item(s) from point A to B ... and either update or create them." as of Migrate 2.5+. Most people are comfortable with SQL or CSV files so I'll talk about that here. Being Object Oriented you're free to adjust Migrates behavior of course by extending a classes default behavior.

Once you have the SQL data you can use a Migration to import the data. By using Migrate 2.6's (stable release) track_changes option within a Migration class. The Migrate module will take the fields your migrating from point A to point B of your data and create a hash value of all the data. This hash value is used in subsequent calls to Migrate data to deem whether the given item should be created or updated from the data being fed into the Migration.

An example of this can be seen in this great little blog post:
http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7

The key excerpt enabling track_changes from the blog post is:

class ExampleNodeMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);
   $options = array('track_changes' => 1);
   $this->source = new MigrateSourceSQL($this->query(), $this->fields(), NULL, $options);
}

I say SQL would be easiest for this approach because you could easily build a query for your migration that is basically SELECT id, doi, publication source id, last-modified-timestamp where source being pubmed, scopus, etc  FROM my_remote_data and  put $options = array('track_changes' => 1); and Migrate is basically doing all the work for you -- and should be very little PHP code to consume the data.

I've actually done this process most recently with the Migrate modules default support for CSV files with a Migration that results in 6 different Drupal content types built out from the CSV in dependant-order -- and objects are created/updated on-the-fly using track_changes every time the system does an sync from the remote system ... so it's doable via SQL or CSV easiest I think.

  random tidbit: my CSV file is like 40 columns of data and each
  sub-migration only cares about a limited set of columns in the csv
  file. So I tell each migration to ignore unwanted fields for that
  migration by using PHP's unset function in the prepare for the
  Entity being built. By unsetting the values the hash function only
  hashes the relevant data I care about for that single drupal object
  I'm creating with that migration.

Anyways... I hope this rant helps and offers you a path do this. I've used Migrate on and off for single table or larger migrations of data since the Migrate 1.x days ... it can be complicated to learn if you've never used it.


Example Hook form validate, get all node information after save news field

To grab your information before the node is saved you can use hook_node_presave, then if you want to gather information after its successfully saved simply use hook_node_update.

Also if you are saving it via the entity_metadata_wrapper you should still have access to the data after its saved.

$entity_wrapper->field_name->value(); //Should have field0, field1

//Add your value here

$entity_wrapper->save();

$entity_wrapper->field_name->value(); // Should have field0, field1, field2


For the hidden row, you need a second table which would look like:

// This is the hidden table
$table_hidden = '
';
$table_hidden .= theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));
$table_hidden .= '
';

$row2 = array(
  'data' => array(
    array(
      'data' => $table_hidden,
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Option 2, a more module-clean way would be to use hook_theme function and create a simple template file where additional markup is placed like so.

function YOURMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'any_name_you_like' => array(
      'template' => 'hiddentable', // This called hiddentable.tpl.php
      'arguments' => array('table' => null),
    ),
  );
}

Then in your page callback or wherever, you would just need to use your declared theme function like so.

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

$row2 = array(
  'data' => array(
    array(
      'data' => theme('any_name_you_like', array('table' => $table_hidden)),
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Now in your hiddentable.tpl.php

  <?php print $variables['table']; ?>


Why does "my blog" menu link disappear when I use a view with the path blog/%?

The path that the blog module uses is blog/%user .

If you go to blog/1 you will see all posts made by the user with uid equals 1.

So, when you create a views:view that defines the path blog/%, it overrides the default path previously defined by blog and uses the views path.


Using hook_form_alter in overlay admin theme

Thanks to Clive's tip I realized that because my module and theme had the same name, the hook was being applied at the theme level. I renamed my module and now it works!


You don't need to use group_load anymore! Use node_load instead. You gid is equivalent to nid.


Allow different users to upload pdf to nodes privately

Creating two content types "Question" and "Answer" seems to be the right approach per me. These two could be related via entity reference fields. And the storage of the file fields should be "private" for the implementing the access control. I have recently written about private files in my answer you might check out.


You should use the drupal_get_form() to render the node form.
For art content type.

$items['node/add/add-art'] = array(
  'title' => 'Add art work',
  'parent' => 'admin/commerce/manage-products/actions',
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'page callback' => 'drupal_get_form',
  'page arguments' => array('art_node_form'),
  'access callback' => TRUE,
  'file' => drupal_get_path('module', 'node') . '/node.pages.inc'
);


How to edit default Commerce Order status?

Ryan's solution in Change order status string from "Completed" to "Shipped" works finally, my code was wrong.

So, for anyone having the same need, create a mini-custom module using the function hook_commerce_order_status_info_alter (dependencies commerce_order) and paste your new label like it is done for Completed status.

You may find the exact status machine names (e.g. "pending") in commerce_order.module.


Ok, looks like the right approach is not looking for something that changes blocks. I needed to define a content type, then create a view that lists my ads, and apply one of the numerous view-based carousels, like https://www.drupal.org/project/views_slideshow


How can I get an empty region not to render in a field_layout template?

Use this syntax:

{% if content.sidebar %}
  <div class="layout-region layout-region--sidebar col-sm-4">
    {{ content.sidebar }}
 </div>
{% endif %}

It will remove all HTML (such as the s that appear even if the section is empty and then only display if there is some non-HTML present.

NOTE: This will not work properly if a region contains only HTML tags, such as Search Facets that are completely made up of  options. The striptags call will remove everything from these regions, making them appear to be empty and preventing your facets from showing

See also the discussion here: [meta] Themes improperly check renderable arrays when determining visibility.


Adding content type field value to a taxonomy term?

If you are using Select (or Other) module and it does not specifically need to be a taxonomy term, there is an option for exactly this:

On the field edit page, the "Other value as default value" allows you
to select how other will be handled:

Add the values to the other textfield-> store the value but don't
change the list

Append the values to the current list-> store the
value and add to the list attached to the node/user/entity

Append the values to the available options-> store the value and add the value to
the list so that it can be selected on other nodes/users/entities

Ignore the values-> do not store the value

EDIT (courtesy of DuaelFr)
You will need the 7.x-3.x-dev version to be able to use this module on a Taxonomy Reference Widget.


How can I refer to a table to make a level system?

Give it some thought to replace that table you made with:

a new content type (eg called "XP") and
with custom fields as in your question, such as:

level number.
minimum XP.
maximum XP.
some ratios.

That way you could create 1 node for each row in your table, with field values matching the values in those table rows. If appropriate, use the Feeds module to automatically create 1 node for each row in your table.

After you'd have created such nodes, you could use them in combination with the modules you're already using / considering, such as User Points and Rules.

To implement that "level system" (as in your question), you can probably use the Goals module (disclosure: I'm the maintainer of it). If you're not familar with this module, have a look at "How to implement gamification in a Drupal site and award incentives?".

Bonus tip: since you're thinking of using User Points and Rules already, you may also want to look at the answer to "How to access current amount of earned userpoints in a Rules Condition?" (pretty sure you'll need something like that also).

PS: All this only requires site builder skills (no need for any custom coding).


Fixing configuration inspector missing schema errors

Yes, remove that line. Form displays have no label control, only view displays do. Maybe this was copy & pasted somehow by hand when creating that config.


Instead of using a 301 redirect to your custom 404 page, just go to

Admin > Config > System > Site Information

/admin/config/system/site-information

Enter your new path into the 404 error page box, and click "Save configuration".

You might also want to try the CustomError module:
https://www.drupal.org/project/customerror


Gravatar does not work with anonymous accounts

Unfortunately anonymous accounts arn't supported at this time, because they are a special case. Avatar Kit is currently written to work with Drupal user entities, which anonymous accounts are not.

Follow https://github.com/dpi/avatars/issues/30 for progress


Adding some new custom variables to page.tpl.php

Drupal doesn't have code that checks if the theme is adding a new index in the array passed as reference to hook_preprocess_page(); every index added to that array from a preprocess/process function is then passed as PHP variable to the corresponding template file.

If what you are adding is then not passed to the template file, then the possible explanations are:

You are prefixing the function name with something that is not the short name of the theme.
You wrote the preprocess function for the theme that is not currently active. If the theme currently used is the Bartik theme, the preprocess function for a different theme would not be called. Keep in mind that the used theme could be different from the one you are expecting; this is what happens with administration pages, for which the used theme is the one set as administration theme in admin/appearance.

There are also modules that can set a different theme for a page implementing hook_custom_theme().

A possible mistake could be implementing a preprocess function for a theme when a sub-theme is actually used, or (vice versa) implementing a function for a theme when the parent theme is actually used.

References

theme()


How to set content-security-policy header?

I may be a bit biased in thinking that the Content Security Policy module is the best solution for adding a policy to your site, but here are some of the reasons for using the module:

Integration with the Libraries API to automatically generate script and style directives
An admin interface that validates your policy configuration
Provides a reporting endpoint to receive policy violations and add them to your site log, so you don't need to use an external service like Report-URI.com (but it also provides a plugin to use it, if you do).
The Reporting API module is still in beta, but it will have improvements over CSP's reporting handler, and has a plugin to integrate with CSP module.
Some optimizations to shorten your policy where possible (e.g. If a fetch directive like img-src that falls back to default-src has the same value, it is omitted)
In the future modules will be able to integrate with CSP module to alter the policy as needed (enabling additional directives, altering the policy per-page)

There are a couple alternatives to the CSP module, if you don't want all of these additional features:

The Security Kit module allows adding a CSP policy header, but it only allows either an enforced or report-only policy, and it does not have fields for many newer directives.
The HTTP Response Headers module allows you to configure a static value for any HTTP header you want
Set a static header in your own response event subscriber in a custom module.
You can set the header directly in Apache or nginx configuration


How can I display lots of rows of information from a database in my drupal module?

If you're looking to build an HTML table then the theme_table() function will help a lot. See the docs page for full details but this is a basic example:

function MYMODULE_page_callback() {
  // Header for the table
  $header = array('id', 'name');

  // Get your data
  $data = db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();

  // Loop through the data and add rows to the table
  $rows = array();
  foreach ($data as $id => $name) {
    $rows[] = array(
      $id,
      $name
    );
  }

  // Return the themed table
  return theme('table', array('header' => $header, 'rows' => $rows));

  // You could also use:
  return array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows
  );
}


How to check whether the page content is been managed by blocks, views or anything?

If you are logged in as administrator of the site, usually you should see either a edit button (for full nodes) or a contextual link for editing the a view or a node. You will need to have permission to see contextual links.


How replace city text box in shipping address with select component in drupal 7 commerce

In drupal several module can solved your problem:

https://www.drupal.org/project/addressfield_vn

https://www.drupal.org/project/addressfield_cl

https://www.drupal.org/project/addressfield_peru

https://www.drupal.org/project/addressfield_ro

https://www.drupal.org/project/addressfield_hu

you can choose on of them and edit for your country. for example in addressfield_vn change country code «VN» to your country code. and add your province and city name to module.
for iran address i create a module. if you want then email to me.


Change language name based on the domain i'm on

You are looking for url/domain language negociation + url/path language negociation, right ?
You need both of domain+path in /admin/config/regional/language/detection/url to determine wich language to display.

I think you have to implement a new LanguageNegociation plugin in a module which do this. Have a look at :

core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php

You should be able to get your own detector (quiet looking like LanguageNegotiationUrl with both domain+path) by extending LanguageNegotiationMethodBase.


Removing Drupal GET Form apparently unnecessary parameters

Here's a workaround you can use:

    $form['#after_build'][] = 'mymodule_form_modify';

Then:

    function mymodule_form_modify($form){
      unset($form['form_token']);
      unset($form['form_build_id']);
      unset($form['form_id']);
      return $form;
    }

And finally to get rid of the &op parameter:

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

Source.


Yes. MySQL 5.7 is compatible with D7.x. Per the docs:

  Drupal 7 supports MySQL 5.0.15/MySQL 5.1.30/MariaDB 5.1.44/Percona
  Server 5.1.70 or higher, and requires the PDO database extension for
  PHP (see What is PDO?).

Is it safe? Maybe. It depends on your code/infrastructure setup.

Just because a web application is compatible with a version of a DB server, doesn't mean an upgrade will happen flawlessly. There can be many things that could go wrong (e.g. hidden dependencies).

It will probably be fine with a minor version upgrade, but always have a test/backup plan in place when rolling out infrastructure changes.


Difference between bootstrap carousels and how to set up?

Do not use Views Bootstrap module. Rather just display the node (of type Carousel) full content.

Construct your view as follows:

Format: Unformatted list, show Content, Full Content

Filter Criteria: Content:type (= Carousel)

Pager: show 1 item only.

Set jQuery update to 1.9 and load jquery-migrate

Your theme pulls Boostrap from CDN. Bootstrap Carousel requires another Bootstrap library in libraries folder. Is this optimal? I don't think so.


LDAP Feeds example not importing new users - Undefined index: count in FeedsLdapEntryParser

Not sure what exactly resolved this but basically I added GUID as a unique field with a unique number and while manually running the cron job /admin/config/system/cron didn't add the users,

after I went to /import/ldap_data_to_user_data and scheduled the LDAP query for import it worked.

Now it also syncs after I run them manually. Not sure what i did wrong or was missing, slightly confused but happy :)


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

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

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


How to timestamp last block access to profile cck field

The above works fine, however the cck field type needs to be a "Datestamp"


How can I gain access to the path aliases for es and zh-hans?

To get all path alias by language for instance es:

$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path' => '/node/' . $nid,
  'langcode' => 'en'
]);

  I need to delete the duplicate Spanish path alias

$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path'     => '/node/' . $nid,
  'langcode' => 'es',
]);

// Get the actual associated spanish path alias to your node.
$spanish_associated_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid, 'es');
foreach ($alias_objects as $alias_object) {
  // If its not the actual alias delete it.
  if ($alias_object->get('alias')->value !== $spanish_associated_alias ){
    $alias_object->delete();
  }
}


Problem with db_select not returning records sometimes

Turns out addExpression does not return the object, just the alias of the expression. Solution:

$query = db_select('notification_queue', 'nq')
    ->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method');

$query->addExpression('COUNT(*)', 'num');
$rows = $query->execute();


There are more than one way to do what you are  asking note both these will require you to create a custom module. (I assume you know how to do this or can google it)

here need to change to your form id, and your field names..

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // change to your form id
  if ($form_id == 'webform_submission_contact_add_form') {
    //dump($form['elements']);
    $form['elements']['select_me']['#ajax'] = [
      'callback' => 'MYMODULE_callback_ajax',
      'event' => 'change',
      'wrapper' => 'changethis',
      'method' => 'replace',
    ];

   $form['elements']['TEXTFIELDNAME']['#prefix'] = '
';
   $form['elements']['TEXTFIELDNAME']['#suffix'] = '
';
 }
}
// ajax call back
function MYMODULE_callback_ajax(&$form, FormStateInterface $form_state) {
  $value_selected = $form_state->getValue('select_me');
  if (!empty($value_selected)) {
    // Here do queries then set the value of your text field.

    $form['elements']'TEXTFIELDNAME']['#value'] = $value_selected;
    return $form['elements']'subject'];
  }
}


What are Entity tags (Etags) and how do you configure them in relation to your Drupal site's files?

https://en.wikipedia.org/wiki/HTTP_ETag

Inside your .htaccess file add this to the bottom
FileETag MTime Size