When and where should I replace tokens on a custom path for metatag context? I have custom tokens defined in hook_token_info() and hook_tokens().  I need these tokens to populate metatag data for the metagag module on a custom path.  I have the context module installed as well.

The path routes to a callback that loads the object I need to pass to token_replace().

My question is when and where do I call token_replace() so the tokens are available to metatag context on page load?

The correct place to specify the replace data was in hook_tokens().  I did not follow the original tutorial correctly and thought since my tokens were not available I was in the wrong place.

I ended up specifying my tokens as the current-page type.  After I did that, they displayed and I can now use them for my metatags.

As a side note, I did discover you need to run cron after you make changes to hook_token_info().


How can I theme the Views Exposed Filter? I create a view in drupal 7 display a collection of books, and taxonomy for book types .. then I call book type taxonomy in my view and it displayed good .. But because book types taxonomy menu have about 10 items and maybe increased at any time, I want to display 3 items of book types and when click More link display a list of the others, I can't do it in css only, and I can't add a div to group the other part of the list .. so how can I do that?

thank you

when I try to print my exposed filter array

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
     $view = $form_state['view'];

    if ($view->name == 'taxonomybooktype' && $view->current_display == 'taxobooktype') {

        $form['field_book_type_tid']['#options']['All'] = "All";

              echo "<pre>";
      print_r($form['field_book_type_tid']);
      exit;
            }
    }

}

output:

Array
(
  [#type] => select
  [#options] => Array
    (
        [All] => All
        [0] => stdClass Object
            (
                [option] => Array
                    (
                        [7] => Chemical
                    )

            )

        [1] => stdClass Object
            (
                [option] => Array
                    (
                        [1] => computer
                    )

            )

        [2] => stdClass Object
            (
                [option] => Array
                    (
                        [6] => History
                    )

            )
    )
[#size] =>
[#default_value] => All
[#theme] => select_as_links

)

but now how can I group first tow options in a div and remain options in another div or group?

Exposed filters use the form API, so you can implement a hook_form_FORM_ID_alter():

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if ($view->name == 'my_view' && $view->display == 'my_display') {
    // do something awesome
  }
}

Normal Form API procedures then apply.


How do I add a link to an operations dropdown menu in views? I am using Commerce Kickstart 2.

There is a view that lists all of the orders.  On each order, there is a dropdown menu with the options of 'Quick Edit' 'Payment' and 'Delete'.  I want to add my own operation on that order to view just the list of line items plus some custom information in a view.

However, I can't seem to figure out what I need to do to add a link to this dropdown menu and then go to my view when it is chosen.

Add the following to your hook_menu in your module to add an operation to the dropdown pulldown of commerce orders.

$items['admin/commerce/orders/%commerce_order/<your operation>'] = array(
    'title' => 'Your Title',
    'page callback' => 'your_callback_for_the_operation',
    'page arguments' => array(3),
    'access callback' => 'your_access_callback',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
    'context' => MENU_CONTEXT_INLINE,
);


Google showing pages with ?page=2 urls In one Drupal 6 based site there are product pages like : example.com/product1, example.com/product2 etc but in Google search engine result pages(SERP) it is instead taking us on clicking to url's to like : example.com/product1?page=2 or page=1 or other pages and so on.

This site has Nodewords installed and has meta-description defined for each page. But in case of url's like example.com/product1?page=2 meta-description isn't appearing.

The front-page seems to be set to "/node" so I can see in the bottom of the front-page as 1,2,3,4 ... links for pagination.

I simply want Google to index the page like example.com/product1 and not example.com/product1?page=2.

Why this could be happening and how can I resolve it?

Those links appear in Google's index because they're linked to on your site (presumably the pager generates those links for you) and you allow Google to crawl and index them.

If you do not want those pages to be crawled and indexed by Google, then you can disallow it by adding the following to the robots.txt for your site (btw.: this has little to do with Drupal):

Disallow:*?page=*

This will stop googlebot (and msnbot) from crawling the pages that is linked to with a link that contains this pattern.

Note that wildcards are not part of the Robot Exclusion Standards (but are supported by googlebot and msnbot), so don't expect any rule with wildcards to be widely recognised by robots.


How to add addition settings in node edit page on rightside bar I want to add additional settings in node edit page (node/*/edit) on right side bar. How can i achieve this drupal 8?

Update

To be more clear, I have installed url_redirect module and it is showing settings in node edit page in drupal 7. But in drupal 8 there is no such settings. So I want add those settings by myself, but on right side bar.

The key is to implement hook_form_node_form_alter function to add settings to node edit page. I did this by applying patch specified in https://www.drupal.org/project/redirect/issues/2702353.

I specified a wrong module in my question (There were confusion, because both the modules showing same text), actual module that was showing settings in admin pane was redirect module not url_redirect.

I keep this answer here that may help someone who come across the same question I had.


Views PHP filter criteria not working Why would this not work as a Views PHP filter criteria?

if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date('m/d/Y',strtotime('-2 months',strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 < $b2) {
    return TRUE;
  }
}

The code should remove rows that are older than the current node except it doesn't?!

It will remove the rows, when you return FALSE:

if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date('m/d/Y',strtotime('-2 months',strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 >= $b2 && $b3 <= $b1) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}


After importing a content type from Features, What's the correct way to manage it? I've taken control of a project recently, and I see a workflow I've not used before.

The original developer would create content types on his dev machine; use Features to export the content type's code, and upload that as a module (with related functionality) to the production server. Enabling it, the content type is created.

Now that the content type is created, I'd like to add / adjust / delete field configurations. What's the correct workflow to work with the content type from that point? Once the content type is created, is it part of the db as if I had created it normally through the UI? Can I safely delete the Feature generated content type code? Can I manage fields through the UI, or would I have to fiddle with the Feature generated code?

Thanks!

Once the content type is created, is it part of the db as if I had created it normally through the UI?
Yes
Can I safely delete the Feature generated content type code?
No- See this Q/A for a more complete answer.
Can I manage fields through the UI...
Yes - once you have the content type set the way you want it, you should regenerate the feature module so that you have an up-to-date representation of your content type in code.
...or would I have to fiddle with the Feature generated code?
Definitely no

What's the correct workflow to work with the content type from that point?

First, make sure you have a clean starting point by ensuring that all of your features in all of your environments have the "Default" status (this just means that the loaded database configuration of the Feature matches the configuration defined in code in the Features module).

Make changes to the content type through the UI on dev as you normally would.
Once the content type has been modified to your liking, Recreate the Feature by clicking on the "Recreate button". That will generate a tar file. Extract that file in the same directory as the existing Feature module - overwriting the previous version.
Revisit the Features page on dev. The feature that was previously overridden should now be "default".
Assuming you are using git or subversion or similar, commit the changes to the Feature module and pull them to staging. (If you're not using source control, just FTP the changes to the Staging server).
Visit the Features page on staging. The Feature in question should now have a status of overridden. Click on the "Overridden" link, tick the checkboxes on the resulting page and click "Revert". This will update the database settings to match what is defined in the new Features module. The status of the Feature should now be "Default". (Note: sometimes the Features module automatically pulls in the new settings when you visit the Features page, but honestly, I'm not sure what triggers that or when - perhaps someone can add to that).
If all goes well on staging, repeat the same steps on prod.


Where is the Administer menu? I can't find the "Administer" menu or it's members "Content Management" or "Site Building". I've tried disabling and re-enabling the core menu module, but still cannot see these menus. This is what I can see.

Any ideas why? Or a known solution?

The menu structure has changed a bit from Drupal 6 to Drupal 7.

Site building is now called structure, though modules is moved from it into it own top level menu item.
Content management has been split up a bit and have items in content and structure.
For administer you probably want the Configuration item.

Anyways try clicking around and I'm sure you'll find what you need.


Which folders/files in drupal 6 need not executive permission? In order to tighten security of D6 against malicious XSS file uploads, I am wondering what files and folders can have go-x permission where the group is webserver.

All folders need +x perhaps you're referring to +w ? In which case, only the files folder e.g in /sites/default/files needs to be +w by the webserver. All other folders can be owned and writeable by root only.

Here's some find commands to recursively chmod the file/folder permissions correctly

;Change all directories to 755 (-rwxr-xr-x):
find /var/www/mysite -type d -exec chmod 755 {} \;

;Change all files to 644 (-rw-r--r--):
find /var/www/mysite -type f -exec chmod 644 {} \;

;Change ownership of files directory and files to webserver user, e.g www-data
chown -R www-data:www-data sites/default/files

Update: example nginx conf to disallow .php file access in the files directory:

# Do not attempt to serve php files within sites/default/files
location ~* ^/sites/default/files/.*\.php$ {
    return 404;
}


How to add a database index to a base field Goal:

Add a database index to a 'created' field.

Given:

There is a custom entity with a base field created.
The field is stored the entity table.
Field source code of the created field:

$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'))
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'timestamp',
    'weight' => 3,
    'settings' => [
      'date_format' => 'medium',
      'custom_date_format' => '',
      'timezone' => '',
    ],
  ])
  ->setDisplayConfigurable('view', TRUE);

What I researched:

I have not found a way to add index using the \Drupal\Core\Field\BaseFieldDefinition().

As I understand indexes are defined in a @FieldType plugin. The created field is implemented via the \Drupal\Core\Field\Plugin\Field\FieldType\TimestampItem() plugin and obviously does not have have indexes there.

P.S. I know, that I can write an updatescript to add an index to the table manually.

Currently the only way to do that is to create your own storage_schema entity handler.

See Node as an example, the annotation:

*     "storage_schema" = "Drupal\node\NodeStorageSchema",

There you can alter both the schema for a while table, or you can do it for a specific field. NodeStorageSchema does both:

  /**
   * {@inheritdoc}
   */
  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
    $schema = parent::getEntitySchema($entity_type, $reset);

    $schema['node_field_data']['indexes'] += array(
      'node__frontpage' => array('promote', 'status', 'sticky', 'created'),
      'node__status_type' => array('status', 'type', 'nid'),
      'node__title_type' => array('title', array('type', 4)),
    );

    return $schema;
  }

And below in getSharedTableFieldSchema():

if ($table_name == 'node_revision') {
  switch ($field_name) {
    case 'langcode':
      $this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
      break;

    case 'revision_uid':
      $this->addSharedTableFieldForeignKey($storage_definition, $schema, 'users', 'uid');
      break;
  }
}


How to locate the Entry Points of a Drupal 8 Core module? I'm to perform a security audit on the Drupal 8 Core modules, and was curious if there were any telltale signs of Entry Points (ie, how a module communicates with an external module and vice-versa).

OWASP defines an Entry Point as "the interfaces through which potential attackers can interact with the application or supply it with data."

I assume this is not very different from Entry Points of standard web applications (forms, HTTP packets, etc.), but I am interested in knowing whether or not Drupal has its own standard as to where these Entry Points are located. Are there specific snippets of code I should be looking for?

I do intend on reviewing the modules manually and in-depth, but figured someone on here may have some advice to help lessen the steep learning curve.

Any and all help is appreciated!

Cheers! :)

Entry points will equate to routes in Drupal.

Modules will normally define their routes in a YML file named MODULE_NAME.routing.yml, but routes can be defined programmatically as well, check out this article from Acquia about routes:
 https://dev.acquia.com/blog/coding-drupal-8/defining-and-altering-routes-in-drupal-8/22/03/2016/9891

Also the 'routing' table in the database lists all the paths and their corresponding routes (I believe all).  Note the use of '%' and '{some_value}' to indicate dynamic route values.

Hope that gets you started.


Drush css-js cache clear error There are times when I run drush cc css-js and I get the following error:

'css-js' cache is not a valid cache type

Does anyone know why this may happen?

Thanks,

The latest dev releases of Drush (both 8.x-6.x and 7.x-5.x) now provide a better error message when attempting to select a specific cache type (e.g. css-js) without first selecting a working Drupal site.  c.f. http://drupal.org/node/1954552

Note also that when selecting a Drupal site, cd /path/to/drupal/root only works if settings.php is stored in a directory called "default".  Otherwise, you will need to instead cd /path/to/drupal/root/sites/mysite.com before using drush cc css-js.  You can also use the --root and --uri parameters, e.g. drush --root=/path/to/drupal/root --uri=http://mysite.com cc css-js


Drush Open-Source License What open-source license is Drush licensed under?

I've checked GitHub including the README (https://github.com/drush-ops/drush/blob/master/README.md) and it isn't stated anywhere.

The last version of Drush on drupal.org has a GPL v2 license in it.  The license itself is not in the repository.  Modules and themes on drupal.org automagically get LICENSE.txt added by the packaging script (the automated process that creates the tarballs and zips from central git repo).

This means that drush is technically still GPL v2, even though it doesn't have an explicit license in it.  There is talk about relicensing drush, though.


Can a content type have default input in fields Is there a way for a user to add new content and have some of the fields already pre populated with default text/input.

That way the user can amend what changes are required for a node without having to copy and paste what will be very similar details into the add content screen node/add/[content type]?

Hope that makes sense.

Yes almost all fields have a section to add default content.
Go to "Structure" > "Content Types" > Your content type > "Manage Fields" then select edit on the field that you want to add the default text to


What's the right way to have Drush make automatically add version numbers to my info files? Everything I read says Drush should be able to automatically rewrite my info files to add version numbers (and the only switch I see is the switch to disable this, --no-gitinfofile), yet nothing I am doing seems to make this work.

The Drush make command being run is:

drush make --working-copy --no-core -y --contrib-destination=. profile.make

A sample project in the make file would look like this:

; Sample Project
projects[sample_project][type] = "module"
projects[sample_project][download][type] = "git"
projects[sample_project][download][url] = "gitlab@git.example.com:cms/sample_project.git"
projects[sample_project][download][tag] = "7.x-1.5"
projects[sample_project][subdir] = "custom"

Googling around, I found the following options to maybe try, none of which worked:

projects[sample_project][download][version] = "7.x-1.5"
projects[sample_project][download][full_version] = "7.x-1.5"
projects[sample_project][version] = "7.x-1.5"
projects[sample_project][full_version] = "7.x-1.5"

The Drush version is 6.2.0.

I have this in my makefile:

api = 2
core = 7.x

projects[drupal][version] = "7.26"

;===============================================================================
; Ctools
;===============================================================================

projects[ctools][type] = module
projects[ctools][subdir] = "contrib"
projects[ctools][download][type] = git
projects[ctools][download][revision] = e720f61
projects[ctools][download][branch] = 7.x-1.x
projects[ctools][download][full_version] = 7.x-1.x-dev

I run it like so:
drush make --working-copy --no-cache --no-core my_make_file.make

For a good overview of the drush make flags:
http://www.drushcommands.com/drush-6x/make/make

In my case version info wasn't written because I had --no-gitinfofile in my script for some reason. I hope this helps!


an entity_metadata_wrapper for a form_content in form alter hook? There a few days ago, someone in this website advised me to use the function entity_metadata_wrapper. Thanks that, I can get and set fields of entity without use heavy code.

Now, I would like find the equivalent when I use a form_content from an alter form hook. After several google research, I didn't find the equivalent... can you help me ? =)

Concretely, When I get a fields, i do :

$exemple = $form_state['field']['field_one']['und']['entity'][2]->sub_field['und'][0]['value'];

(my form content contains a collection field).
It's very ugly...

If you've got a complete entity in that form, or some type of structure that the Entity API knows about, because it's been defined in hook_entity_info and/or hook_property_info, you can wrap virtually anything, for example:

$data = array('pears', 'apples', 'oranges');
$wrapper = entity_metadata_wrapper('struct', $data);
dpm($wrapper->value());

But you won't have all the goodies of the wrappers, which are the smart metadata information about the values you're retrieving, you can find how to build your own in the entity module, for example in entity_metadata_site_wrapper:

function entity_metadata_site_wrapper() {
  $site_info = entity_get_property_info('site');
  $info['property info'] = $site_info['properties'];
  return entity_metadata_wrapper('site', FALSE, $info);
}

site is not an entity or field structure at all, but it has been defined by a hook_entity_property_info, in entity_metadata_system_entity_property_info so you can wrap it normally and Entity API will go and fetch the properties you define by using the callbacks you've defined:

function entity_metadata_system_entity_property_info() {
  $info = array();

  // There is no site entity, but still add metadata for global site properties
  // here. That way modules can alter and add further properties at this place.
  // In order to make use of this metadata modules may use the wrapper returned
  // by entity_metadata_site_wrapper().
  $properties = &$info['site']['properties'];
  $properties['name'] = array(
    'label' => t("Name"),
    'description' => t("The name of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
  $properties['slogan'] = array(
    'label' => t("Slogan"),
    'description' => t("The slogan of the site."),
    'getter callback' => 'entity_metadata_system_get_properties',
    'sanitize' => 'check_plain',
  );
(...)

So if you've got an entity (saved or not, this only will limit how the data is accessed), you can wrap it normally and access to it, and if you have another type of structure, Entity Metadata Wrappers will still know how to deal with this if you or another module defines so.


Transferring default user picture field to new user picture field Drupal 7.

I have a site where users can upload a picture of themselves (default Drupal field: user picture.) This field is used in different views.

I would like to use the User Picture Field module and use the field provided by the module instead of the default Drupal user picture field.

Switching fields in the views is a simple operation and it works well with newly uploaded pictures. However, with pictures uploaded before the installation of the module, the pictures displayed are no longer the users' pictures but the default "no photo" image.

Is there a way to have the (older) photos of the default user picture field transferred to (or at least displayed by) the new field?

Thanks. :)

I think the easiest way would be to do it at the database level. Copy the old field contents into the new field.


Saving the URL during registration So I have created a drupal multisite install with a shared user database and I would like to store the site the user has signed up on.

I have also created a view of user and I would like to filter them by site. Ideally I would like the view filter to be a dropdown, but it isn't essential.

I am already overriding the user_register_form via the template.php file, would it best to create a new text field for the user then hide and set it to the current domain via the template.php file?

Hope this will help you,

In Drupal 7

The best way to do is to create a new field for user registration form. Lets call the field as domain.

Steps:

Go to admin/config + Account settings + Manage Fields
Add new field

After adding

If you want to show this field in registration then check this

NOTE: If prefer do not show on registration form. May be there a chance to edit. Even though if your making it as disable, it can be change.

When ever the user registration form load, alter the form using hook_form_alter and give the default value for it.

function mymodule_form_alter(&$form, $form_state, $form_id)  {
switch ($form_id)  {
    case 'user_register_form':
       //get field language
       $field_lang = field_language('user', 'field_user_domain');
       //assign default value
       $form['field_user_domain'][$field_lang['field_user_domain']][0]['#default_value'] = $_SERVER['HTTP_HOST'];
    break;
 }
}

When ever the users register the domain also saved.

You can use this field in views as per your requirement.


How to create Content Types with Drush Is it possible to create content types with Drush? Such as a new Galery content type?

I created a content type manually via web interface and checked the changes in database. However, there are quite a lot of changes - some changes are also in blob fields.

How do you do this?

If you want to re-create content-types you have created in other drupal-installations you can use the features module:

This module allows you to export content-types to code (called features). Those features can be copied to other sites like normal modules and then be activated via drush using

drush en -y feature_name


Is it possible to use another menu as a submenu of a menu? Is there a setting or a module, this would facilitate re-use of menus...

For example:

Menu 1
  option A
  option B
  option C
  option D

Menu 2
  option 1
  option 2
  option 3
  option 4

Full Main Menu
  option A (use menu 2 for sub menu options)
    option 1
    option 2
    option 3
    option 4
  option B
  option C
  option D

There are not settings I am aware. I have not done an exahaustive search for a module. However, you could write your own implementation with a custom module implementing hook_menu(). Simply put, you would create a new menu. Then, you would iterate through the other menu's in your implementation adding each element to the new menu.


How to programmatically create an entity and fill in entity reference fields I'm trying to create an entity that has a number of entity refernce fields, and I'm confused about the best way to do that. so far I've gotten as far as this

$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('value' => "2")));

Creating the entity works fine, but I can't for the life of me figure out how to fill in the entity references.

The column name for a field isn't always value; in the case of entity references it's target_id if I remember rightly.

Try this:

$entity = entity_create('mytype', $values);
$entity->field_ref = array('und' => array(0 => array('target_id' => "2")));


How might a user configure which video is shown on page without editing the page? A Drupal 7 site has an embedded YouTube video on the home page. It is not always displayed. Sometimes the video being displayed is changed. The home page is arranged by a Page Manager Variant, and the container with the video is "Custom Content". When someone wants to hide/show the video or change the link, they have to ask me because the Page Manager can only be accessed by an administrator. I want to give certain users the ability to show/hide the video and change the video to which it links, but without changing other content on the home page or modifying the layout of the site.

I don't really know what I'm doing when it comes to Drupal, and I'm having trouble figuring out the right things to search for to accomplish this.

I want the appropriate users to be able to choose which YouTube video is embedded and whether it is shown. What is the best way to do that?

Step 1

Create a content type: e.g. "Home Page Video".
Add fields: YouTube, text area, image, etc. Basically all the fields you would want to structure that "section" on the home page.
Give permissions for the fields with field permissions (additional security measure, you'll see why later)

Step 2

Create a few nodes for "Home Page Video"
Set your view modes

Step 3

Create a View to show only "Home Page Video" content.
Choose Bootstrap Grid (Views Bootstrap module and Bootstrap Field
Group module) and add fields
OR
Choose unformatted list: Rendered
entity and a View Mode
Set a filter: "promoted to front page"
Set a Pager: Display a specified number of items and choose 1, More
link: no
Set a sort criteria: "Content: Updated date" (The date the content
was last updated.) and set it to "descending"
Create a pane view from this view.
Save

Step 4

Enable: System - page_manager - node_edit - Node add/edit form -
/node/%node/edit
Create a new variant of node_edit template in Page Manager
Selection rule: Node being edited is bundle "Home Page Video"
Selection rule: Logged in user has one of "my user role"
Content: Add the form fields you want this user to edit AND add the
base form (General Form) in order to get the submit button. If you
have set certain fields to be required on your Home Page Video
content type, they will show in the base form UNLESS you add them in
through the cog wheel "Add content" and choose FORM and then choose
the specific form field that is required. Like that you have the
ability to choose where that field goes in your edit form layout.
More control.
Save

Step 5

Add your pane view of "Home Page Video" to your Home Page Page Variant at the position where you want it to show up on your Home Page.
In order for your pane view to show up, you might have to clear the cache. If you use Drush, simply type: drush cc all
Go look again for that pane view and add it.
Save

Et voilá.
No need for a custom module. Permissions are dealt with by the 'selection rules' in your node_edit page variant.


Use Webform Results in another webform content type I am creating a website for my department at work using Drupal 7. I have a webform designed in a page named Registration in the website. When a user fills this form in and submits, it  sends a confirmation to me. I am also able to view the submissions using the Results tab in the webform using admin rights.

Now I am creating an other page(named 'approve request') for an editor role who approves the submission of the user. This Approve request page has been created in the content type that enables the webform. Now, I need the webform results from the Registration page to appear in the Approve request page. This will enable the Editor to view the Registration results and approve them.

How do I retrieve the results from the registration page to the Approval page? I looked at various sources and could not find a good answer. Please let me know.

Thanks in advance!

You can programmatically modify the form of Approve Request webform using hook_form_alter() function. In this form you can retrieve the previous webform submission entries and append in the Approve Request form.

You can retrieve previous webform submission using following snippet:

include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1); // need to hard-code nid if this is a custom page you can manage dynamically also
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);


How to “filter” out one specific user in a view? I’ve a question regarding some of my blocks which I’ve made in views (using Drupal 6 and Views 2). One of the users on the site is the sites “manager” and so this user of cause writes a lot of posts, comment on a lot of posts and “likes” a lot of posts.

In some of my blocks I display the most contributing users and this “manager” is almost always on top of the list and I would like to display the most contributing users, but “ignore” this user.

My views are very simple and basic created. For example in one I list the most commenting users right now (that be, the last 24 hours) and I sort according to the comment count.
In this example, how do I “filter” out the one user?

Thanks

Sincere
- Mestika

In your view filter out the user:

Add relationships: Node revision: User
Label: user
Require this relationship: (checked)
Add filters: User: Name
Relationship: user
Is not one of: manager


How to fetch content data based on Node reference field into a view i am attempting to fetch the records based on node reference fields into a content type page.

i added node reference fields "news" & "Articles" (and many more) into my "Industry" Content type:

Now i've created a view with a filter (Content type= industries). Find the snap of the view here:

i want to list down all the selected/inserted news and articles (along with their content data) into the view. (currently its fetching only titles but with lot of repetition of the titles from both content types.)

I think you can either construct your news and article views as attachments and attach them to your view, or you can bring the content for news and articles in field by field in the main view.

Using attachments might help you to end up with less repetition without having to use query aggregation.


Create a path to node/add in twig Can I use the path() function in twig to create a link to a non-node entity add form. Taking the group module as an example, if I want to create a link to the 'group/add' page in twig can I use something like:

{{ path('entity.group.add') }}

I know that the above does not work, neither does

{{ path('group.add') }}

Not sure if there is a way to do this with the various twig functions that create links.

According to According to Functions - In Twig Templates just Try

{{ path('node.add', {'node_type' : 'yourcontenttypename'}) }}

as the example for article content type

{{ path('node.add', {'node_type' : 'article'}) }}

Update
Try

{{ path('entity.group.add_form', {'group_type' : 'yourgrouptype' }) }}


How can I rewrite a content link and replace spaces with dashes? In D8, I am struggling to build a link in Views. I keep running into either a missing option or checkboxes ignored.

I have three fields pulled into views:

Content: Title [hidden]  .... token is {{ title }}
Content: Resource Type [hidden]  .... token is {{ field_resource_type }} Pulls values from Taxonomy
Content: Link to Content .... token is {{ view_node }}

I want to rewrite the Content: Link to pass variables. So I'm outputting the URL as text

I essentially want:
"{{ view_node }}?title={{ title }}&type={{ field_resource_type }}

I also want to replace the spaces with dashes, so my end result is:
/resource/article-one-url?title=article-one-title&type=white-paper

But... if I override the output, and make my own URL, the system ignores if I check the box to Replace spaces with dashes

I do this by first checking "Output this field as a custom link," so that I can see and check the "Replace spaces with dashes" option.

I would try to rewrite the URL in the "Output this field as a custom link" section, but the field I thought was supposed to be there, is not.

UPDATE: I also tried this with a custom text field. Within the field settings I checked "Output this field as a custom link" and put the same tokens in, but this does the same thing. Spaces exist in the url.

The field Link to Content can only link to content lol, it doesn't seem you can override the link URL there (that is why there is no Link path field there, Views interface and features can be confusing at times, you have to know a bit of background to understand the less polished parts).

You should Exclude from display the Link to Content field, move the Title field down so it's the last field, and unhide it.

Then you will be able to contruct what you want using the Title field, using the Output this field as a custom link option.

The option Override the output of this field with custom text doesn't provide the option to Replace spaces with dashes.

Make sure that the Link to the Content in the Title field is not ticked, and the Formatter is set to Plain text to avoid clashing between different features when Drupal is constructing the output.


How to make user.html.twig template for two different pages (users)? I want to make user.html.twig template for user ID1 is not such as to all other users. How to?

I tried this code in MYTHEME.theme file:

function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($user = \Drupal::routeMatch()->getParameter('users')) {
    // For make files, like:
    // page--user--[id].html.twig
    $suggestions[] = 'page__user__' . $user->uid();
  }
}

But template page--user--1.html.twig or page--user--%.html.twig don't work. Cache is clear.

Platon, you appear to be mixing up the template for the user itself (user.html.twig) and the overall page template (page.html.twig).

If you want to override the user template then you need to implement hook_theme_suggestions_HOOK where "HOOK" is "user" which is the theme hook you are overriding.

Here is an example of what that code would look like if you were using Bartik (but of course in practice you should be using your own subtheme rather than hacking core):

function bartik_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $suggestions[] =  'user__' . $variables['elements']['#user']->id();
  return $suggestions;
}


How can I set specific download URI for file? Here is my problem. I've got file (eg. some.xml) and multisite Drupal 7 installation.
How can I allow to download this xml from my-multi-site.domain/some.xml?
Is there any way to do it without writing custom module with hook_menu?

P.S. this file should be different for every site on multisite installation

The proper solution is a hook_menu, which I believe is also going to be a requirement to make this reasonable when several sites want separate names.

I workaround would be to just symlink it to your Drupal root.

ln -s sites/example.com/files/somefile.xml some.xml

But if it's a requirement to have each filename only available on one domain, apache would need to have logic to block the "wrong" names, which is inconvenient.

A third possibility would be to rewrite the URL in apache, but I don't exactly know the syntax for this.


How to debug "undefined" 404 error in console on front page I'm getting a strange 404 error on the front page only, which seems to be causing some other issues for me. I'm hopeful if I solve this it will take care of those, too.

On the front page only, when I load the console, I see the following error:

I am not sure what would be causing this as the page appears to load correctly and it isn't giving much of a clue as to what it is trying to load.

How do I debug from this point?

Thanks for the tips Clive and Beebee!

By trial and error I disabled or removed various components until I found one that made the error go away. In this case it seems to be a problem with Flexslider and Views that was used in a Views block -- I haven't solved it yet but have isolated it at least!

UPDATE: It seems to be a bug related to the navigation in the Flexslider module (Views integration). If I set the Flexslider style not to include navigation, it is fine.


Fatal error: Call to undefined function ctools_include()  While implementing Drupal 6 Multistep Form Using Chaos Tools I would like to implement a multi-step user registration form. After a long time googling, I found Intro to Drupal 6 Multistep Form Domination Using Chaos Tools. While I was trying to implement the suggested code, I got the following error:

  Fatal error: Call to undefined function ctools_include() in var/www/WC/drupal_website/sites/all/modules/wombat/wombat/wombat.module on line 26

How do I solve it?

As the Chaos tools suite module defines ctools_include() in ctools.module, the only reason I can think of what would explain the error is that you didn't install the module. The other reason could be that you are trying to access the function when the module is still not loaded; for example, if you call the function inside hook_boot(), then you would get that error.


How to use media field with entity browser widget in a frontend theme? I have created a media field in my content type. In the manage form display, I have selected entity browser as display instead of media library.

When I open the node form as admin in an admin theme like adminimal or seven, and upload an image to the field, I can see it thumbnail after upload and other information. I can see that its markup comes from the media.html.twig file of the classy theme.

But when I do the same steps in a frontend theme, I can't see the thumbnails and other information after upload.

What can be the reason? I also copied the media.html.twig file from classy theme to my custom theme but it did not work.

I am also using the dropzonejs module if that help someone.

Here are the screen shots. The first screenshot is from the admin theme, You can see that the admin, the date, the thumbnail and then use selected button.

The 2nd screenshot is from the frontend theme, there is no such markup after uploading an image.

Any one who can help?

I found the solution.

I just copied the media.html.twig template from classy theme to my custom theme which did not work.

We need to copy this file also container.html.twig to our custom theme's templates directory then it will work.


Move block level configuration also in Features I am building features. Can I add blocks ans block level configuration in Features?


Linking content types Can someone please tell me if this is possible? I have 2 content types, with the following fields.

Asset

Title
Serial Number
Model

Event

Title
Event Type (taxonomy)
Asset ID (a plain text field used to store links to Asset nodes)

Is there a way in views 3 to create a view that looks like Asset Title : Asset Serial Number : Asset Model : Event Type, basically a view linking both content types on one line. I've heard you need to use relationships, but I can't seem to get anything working.

A better way to do it is replacing the asset ID field with an entity reference field which refers to the other content type (Asset) and use view relations to get the relation. In short, create a relation between the content types, and you will be able to use view relations.

For advanced uses, you can take a look to the Relation module, which I don't recommend, in your case.


Taxonomy terms are not linked to nodes I have a content type with a field term reference to a vocabulary using selection list widget.
When i fill the content type, i get in the output the term selected.
But i click on that term i have the message :
There is currently no content classified with this term.

Any help please ?

I think you have multi language site.
I suggest you use the Taxonomy display module, here is a quote from its project page:

  The taxonomy display module allows administrative configurable term
  display pages. This allows administrators to override the default
  presentation of taxonomy term pages per vocabulary through the
  taxonomy term page's manage display form.


Commerce: Show taxes on checkout I am having problems with a porjectr of mine. Seems the taxes are not showing up until AFTER the order is put through. Here is a screenshot of what I mean.

I would like to have taxes show up at the button right before total. Can anyone point me in the right direction? Thank you.

i.stack.imgur.com/3hMWC.png

Taxes are dependent on shipping address so adding a tax line item to the cart does not make sense. Try looking at one of the tax rules on /admin/config/workflow/rules/components to see how the tax line item is added to an order. By default, tax line item is added in the pane that comes after a customer has entered her shipping address and before payment is submitted. Adding a tax line item to a cart requires a custom line-item type and a shipping address to be provided for tax calculation.


How to add javascript library that does not need a module, but is required by modules? I have a JavaScript library written for my project. It is just that - helper library without configuration. I don't like the idea of empty .module file loading each time. On the other hand, I need it to be versioned and I need to be able to require it in other modules, with version specification. Libraries API looks like a bit of overkill as my script is from the ground written for Drupal and is no way "external" - and using empty .module file would be easier and faster anyway.

So, what's the best practice to include JS-only code?

How to include a JavaScript library, with CSS, in Drupal 7 without using a module? is about JavaScript needed by theme, so it looks similar but is unrelated to my question.

A module is really the only appropriate place for something like that; Drupal doesn't provide any way of making a module dependant on a JS library. You can only make a module dependant on another module, so if you want to enforce a dependancy to your JS code you'll have to create a module to contain/reference it.

If you're worried about having an empty module file, don't be...to formalise your library and describe it to the system properly, most likely you should be implementing the core hook_library() anyway. Then your dependant modules can simply call

drupal_add_library('mymodule', 'library');

to add your library. Putting the JS library files themselves into the sites/all/libraries folder, and referring to them from hook_library(), would probably be the best solution.


How to assign a CKEditor profile to a specific field? I'm learning Drupal and right now CKEditor.
I want my website to have a blog, with a complex editor for the articles, and a much simpler one for the comments. I have created two different profiles in CKEditor, but now I'm stuck and don't know what to do next...

Thanks for your help.

CKeditor profiles are assigned to text formats (admin/config/content/formats).

Ckeditor is available for "Long text" fields. When editing the field, you have to choose "Filtered text", so, if a Ckeditor profile is assigned to this format, when creating or editing the node, Ckeditor appears.


How to alter the visibility of a menu tab for a page created in Views? I have a View that is a primary tab on the user profile page. The user profile tabs look like this view | edit | menu-item-to-hide. If the person viewing the page is does not have role of admin or the owner of the profile page then they should not see the tab.

I assume that I use hook_menu_alter() but I'm not sure what the code should be.

I created a mini module called helper.

In helper.info I put

name = "Helper"
description = "Provides custom support functions."
core = "7.x"

First we need to get the helper_menu_alter() to be called after views_menu_alter so we use hook_module_implements_alter to pull the value of our module in the array and put it back in which will always be done at the end of the array.

<?php

function helper_menu_alter(&$items){
  $items['user/%/workbench']['access callback'] = 'helper_access';
  $items['user/%/workbench']['access arguments'] = array(1);
  $items['user/%/workbench/drafts']['access callback'] = 'helper_access';
  $items['user/%/workbench/drafts']['access arguments'] = array(1);
  $items['user/%/workbench/needs-review']['access callback'] = 'helper_access';
  $items['user/%/workbench/needs-review']['access arguments'] = array(1);
}

/**
 * Helper access callback.
 */
function helper_access($uid) {
  if ($uid) {
    if ($GLOBALS['user']->uid == $uid || user_access('view all unpublished content')) {
      return TRUE;
    }
  }
  return FALSE;
}

function helper_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move helper_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['helper'];
    unset($implementations['helper']);
    $implementations['helper'] = $group;
  }
}


How can I create page.tpl for user’s profile page? Searching in Google I found user-profile.tpl.php , but in fact this is the node of profile page while I want to create page.tpl.php foe the profile page.
Also page-user.tpl.php includes login page, register page and all the pages belong to a user which I do not consider, I need to create page.tpl for profile page

Try this...

page--user-profile.tpl.php

[page]--[node].tpl.php

or actually...

page--user.tpl.php

To see available templates for this page simply do the following in your themes template.php

function YOURTHEME_preprocess_page(&$variables) {
   echo '<pre>'; var_dump($variables['theme_hook_suggestions']); echo '</pre>';
}

If nothing were in there (doubtful), then just add your own...

if ($SOME_CONDITION) {
    $variables['theme_hook_suggestions'][] = 'page--user-profile.tpl.php';
}


D7: How to loop an array as form elements? I have the following hook_form (below) which colect data from $_POST and then send them via email. The problem is $jcartItemName and $jcartItemPrice are arrays so I need to loop through them and display the form items accordingly. I expect this could be done via a

foreach($jcartItemName as $value) {
    $form['jcartItemName'] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
    );
}

but how do I do that effectively. Thanks!

function checkout_form($form, &$form_state) {
     $jcartItemName = $_POST['jcartItemName'];//array
     $jcartItemPrice = $_POST['jcartItemPrice'];//array
     $jcartTotalPrice = array_sum($jcartItemPrice);//integer
     $form = array();
     $form['#action'] = "";

    $form['jcartItemName'] = array(
    '#type' => 'textfield',
    '#value' => isset($jcartItemName) ? $jcartItemName : '',
    );

    $form['jcartTotalPrice'] = array(
    '#title' => t('TotalPrice'),
    '#type' => 'textfield',
    '#value' => isset($jcartTotalPrice) ? $jcartTotalPrice : '',

    );

        $form['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail'),
        '#default_value' => "",

        '#description' => "Please enter your e-mail for order to be sent.",

    );

    $form['send-order'] = array(
        '#type' => 'submit',
        '#name' => 'send-order',
        '#value' => t('Send Order'),
        '#class' => 'button',
    );

    return $form;
  }

For those of you who face the same issue: I found the answer:

foreach($jcartItemName as $key => $value) {
$form['jcartItemName'][$key] = array(
'#type' => 'textfield',
'#value' => isset($value) ? $value : '',
);


How to call disclaimer page on all media files in Drupal? I want to display a terms n condition page on every media of website. I collect all media from file managed table of database. I also convert fid to url. Now for each media url I need a disclaimer page.

My issue is something related to this link.

For example:

When I click on each report of news table shown below, on clicking of (say) linux-minimal.pdf , it first redirect to some node which is my disclaimer url, and then pdf open.

How can I achieve this?

I have tried some code which is actually not working. It is:

function hook_init(){
    $get_current_path_media = $GLOBALS['base_url'].'/'.current_path();
    if($get_current_path_media == 'http://my-website/sites/default/files/569338.pdf'){
        drupal_goto('disclaimer');
    }
}

Here is an example

bitcoin.pdf

SEE A DEMO HERE

In Drupal to use jQuery you need to wrap it in

(function ($) {

    //code goes here

})(jQuery);

so your code should look like this

(function ($) {
  $( document ).ready(function() {
    $('.test').click(function() {
        alert('your disclamer goes here');
    });
  });
})(jQuery);

PS: If your div class is outside the

bitcoin.pdf

then use it like this


Content Translation : Language filter not available in views I use a view to show a list of nodes flagged by a global flag (any user, any language) and would like to return only current language related nodes.

For that I should be able to add a filter in the View which is something like "Content Translation: Language". However no such filter seems to be available. Any idea why this filter is missing?

Between the filters you should see 'Content Translation: User's Current Language'. Also check out the Internationalization Views module for more translation options for views.

  Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet.

  This module has been moved from Internationalization package so we can have different branches compatible with each of the Views versions. Use the same branch of the Views version you are using (2.x. 3.x).


Drupal 8, use "query api" with "collection fields" (not via FieldCollectionItem::load) I added a field collection to the user 'manage field' page, the field machine name is 'houses'. The user may add as many home he want.

This field collection regroup :

- a sample text plain field (the name of the house), the machine name "house_name"
- a sample integer field (the size of the house), the machine name "house_size"

In a custom module, I want check if the current user have a house with a size = 4 (if in collection fields, there is a house with "house_size = 4"), how can I do that via the Drupal 8 Query Api ?

I found several example of Drupal "Query API", but nothing with collections fields..

I can use the function load of the class FieldCollectionItem, but I want use a fastest way for get the information I want.

Thanks you :)

Try to query the fields of the FieldCollectionItem with .entity:

 $user_ids = \Drupal::entityQuery('user')
    ->condition('houses.entity.house_size', 4)
    ->execute();


How to rename uploaded files Using Drupal 8, I want to rename and clean all filenames, e.g. If someone uploads file named like this Screen Shot 2016-03-29 at 1.13.21 PM.jpg, I want to clean it so that convert all spaces to dashes - and make everything lowercase, So I should get screen-shot-2016-03-29-at-1.13.21-pm.jpg.

I want to do this on image upload dialog form of CKEditor.

Curently is not possible using core to transliterate uploaded filenames (referer to this and this core issues). To solve this you need to use the Transliterate filenames for uploads module. Check the comments from above.


If parent feeds (import) node is unpublished, how do I not include it in the import schedule? If the parent feed imports a node (the form/node to input the feed URL, not the feeds importer) that is unpublished, I'd like to have it (the feed URL) not be included in the cron schedule to update/import the feed items. How is this done? For example, a user submits a feed, but the administrator needs to verify it before publishing, and importing it.

See also Don't import items if parent feed is unpublished.

It looks like, when a node is saved, Feeds module starts importing the feed from that node.

function feeds_node_insert($node) {
  // Source attached to node.
  feeds_node_update($node);
  if (isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type)) {
    $source = feeds_source($importer_id, $node->nid);
    // Start import if requested.
    if (feeds_importer($importer_id)->config['import_on_create'] && !isset($node->feeds['suppress_import'])) {
      $source->startImport();
    }
    // Schedule source and importer.
    $source->schedule();
    feeds_importer($importer_id)->schedule();
  }
}

There is an option in the importer's setting page called Import on submission. If you uncheck this box, hopefully your feed won't be imported.  Feeds maintainer still need to make changes in feed_cron() so that it won't fetch the unpublished nodes.

While you wait for a better fix from module maintainers, you can quickly fix this code by changing the first if statement to add $node->status==1  condition as follows:

if ($node->status==1 && isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type))


View node public OR only to verified/role by choice user It's possible to set the permission to view for a Content type. But how can i let the choice to view to public OR only verified users/role to the user?

Making 2 different Content types would be an easy solution, but is not convenient.
Also, Node Access is to difficult for users (too many choices). Need just a button or check box to hide or view the node public. If it's hidden for public, it should be visible to registered users.

Found a way to do this with tags. Feel free to add information about doing this with tags:

Added a taxonomy 'visibility' with 2 tags: public and closed.
Added to Contenttype a field with a selection-list (so, a user can only choose one).

(set it to requiered to only have 2 options.)
(in my case, i set the default to public.)

Enabled taxonomy-module 'Taxonomy Access Control'
go to admin/config/people/taxonomy_access >> anonymous >> choose [edit access rule]

(in my case it's admin/config/people/taxonomy_access/role/1/edit)

Under New >> choose the term 'closed' (or your equivalent like 'not for mother-in-law ;-) ).
Set everything to D (Deny)
When Content Access is also on, set grant priority to -1 on the   contenttype-page (admin/structure/types/manage/[contenttype]/access


Include third party JS library into my drupal module I want to include this library into my drupal module. Now I have two problems.

I wanted to use composer manager to get this library, but it's not available on packagist.org. So, I've tried to put it there manually to do not stuck on it. Path is MY_DRUPAL/vendor/malsup/jQuery.blockUI/jquery.blockUI.js
I want to attach this library via hook_page_attachments, but seems I don't know how to define this library in libraries.yml. The problem is that I cannot specify path to folder vendor/ from my_module.libraries.yml, because vendor/ located in root of drupal.

Could somebody give me an advice?

Thanks in advance.

You still put them in the libraries folder (now you can also use a top-level /librariesfolder).

You need the libraries module, just like in 7.x. I'm also not 100% sure how well it works now in 8.x, in the JW Player module, I'm just using it to detect the location of the files: http://cgit.drupalcode.org/jw_player/tree/jw_player.module?h=8.x-1.x#n206


implementing user has password in hook menu we are implementing a web service for a Drupal 7 site (the web service code is not part of drupal installation folder).

one of the web services needs to sign up the user on the site.
the main hurdle was getting  a hashed password that Drupal will also recognize.

for that , am following a suggestion made on stack overflow to Implement a REST service inside drupal and call that from the outside service code . (that part also seems possible and achieveable).

have implemented a password hashing service with following code:

function GetHashedPassword($string)
{
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

    $hashedpw = user_hash_password($string);

    $data = array(
        'password' => $hashedpw
    );

    header("Access-Control-Allow-Origin: *");

    drupal_json_output($data);
    drupal_exit();
}

the main issue now is that whenever this service is called even with same string , it returns a new hashed value each time..

kindly assist if what we need is actually even possible and if so, then what could be fixed in the above code

any help appreciated

If you check the functions being called, you'll there's a randomness in generating the hash for security reasons. I think that is not a problem. Have you tried using that as the stored password and logging in afterwards?


No HREF on Content menu on admin toolbar I have a very odd problem that cropped up yesterday on one my sites.  The site is Drupal 7 with the stock toolbar module installed.  When you access the site for the first time logged in as an admin user, the Content menu link does not work.  All the other menu links work fine.  When you go to the Structure page next, the Content menu works correctly.

Looking at the source, the A tag for the Content menu does not have an HREF attribute. All the other menu links do.  When you go to the Structure page, the Content menu has an HREF attribute as expected.

I looked at the menu_links table and everything looks good.

I ran debug through the toolbar.module and the array data is correct.

I ran debug into the toolbar.tpl.php file calling render($toolbar['toolbar_menu']).  The array data is correct.

I'm now looking to see what else might be causing the HREF to "disappear" from the Content menu.

Has anyone seen this before?

The first commenter mentioned looking at the static page source (great idea...DevTools has made me lazy ;) )

Content
(Find and manage content.)

So the HREF is in the A tag. I'm looking at all the Javascript on the site now.

** UPDATED **
I added the following code (from http://addyosmani.com/blog/mutation-observers/):

var observer = new MutationObserver(function (mutations) {
  // Whether you iterate over mutations..
  mutations.forEach(function (mutation) {
  // or use all mutation records is entirely up to you
    var entry = {
      mutation: mutation,
      el: mutation.target,
      value: mutation.target.textContent,
      oldValue: mutation.oldValue
   };
   console.log('Recording mutation:', entry);
  });
});
var options = {
  childList: true,
  attributes: true,
  characterData: true,
  subtree: true,
  attributeOldValue: true,
  characterDataOldValue: true,
  attributeFilter: null
};
var target = document.querySelector('#toolbar-link-admin-content');
observer.observe(target,options);

This is the output which confirms that something is modifying the DOM.

Recording mutation: Object {mutation: MutationRecord, el: a#toolbar-link-admin-content, value: "Content (Find and manage content.)", oldValue: "/admin/content"}
Recording mutation: Object {mutation: MutationRecord, el: a#toolbar-link-admin-content, value: "Content (Find and manage content.)", oldValue: ""}

How do I go about finding what is causing the change? What code fired the observer?

I found the answer to my original problem.

I went through the .info file and commented out JS files until the console no longer reported a mutation event.  Turns out that there was some odd JS code:

jQuery( "li:nth-of-type(2) > a" ).removeAttr("href");

The selector is too vague. Guess what number the LI containing the Content menu is?  It's 2! And this little bit o'code took the HREF right off!

Thanks to @Clive for suggesting mutation observers.  Learned a lot from this bug.


Show block only on "Page Not Found"? Using a Block's visibility setting of Show block on specific pages: Pages on which this PHP code returns TRUE (experts only)...

...what PHP would I write that returns TRUE so that the block only shows on "Page Not Found" pages?

Can I recommend not doing it with PHP?

I would suggest making a page (via Admin->Content->Add Content), this assumes that you have the node module installed.

And then set that page as your "Default 404 (not found) page" in Admin->Configuration->System->Site Information

And then you can use that page's path in the block set up, but list under "Only the listed pages"


Deleting all Webform Submissions and Content from specific IP Is there a great way to delete all content and webform submissions from a specific IP address? I'm sure it can be done with MySQL commands, but I'm hoping there's a 'safer' way to do it than manipulating the database by hand.

Thanks!

Drupal 7.50 Commons

You could use Views Bulk Operations.

Add Bulk operations: Content as a field and check mark Delete item under Selected Bulk Operations. Make your view format as Table.

You could try using IP Address manager or User IP Log and hopefully one of these modules will allow you to add IP address as a field to your view.

In your View, under Advanced, you may possibly need to add a relationship of author to your view so you can access user fields (IP Field).


How to use exchange rate from Currency Api in a field? I've installed Currency Api Module + Yahoo! Finance currency converter and
made with "Currency Filter" a new field (using Markup module) in my content named "latest_exchange_rate" with the value of latest USD-EUR exchange rate coming from Yahoo!Finance;
in the same content, there is a decimal field named "usd_value" filled with a value during content creation;
additionally I created also a Computed field named "eur_value" which is a multiplication = "latest_exchange_rate * usd_value";

The problem is that the computed field seems not able to read the value of "latest_exchange_rate" field, and the result is always 0.00.

I am not a coder, can you please help me to solve this problem?
If my approach is not correct, how can I use an exchange value from Currency API to make conversions between different currencies?

Thank you in advance for attention, Francesco in Cina

Here is a much leaner version of your setup:

In order to get your node to always display the current converted usd_value to EUROs, you will need only one computed field (no markup field required).
You just will need to place the following in the "Display Code (PHP)" textarea:

$conversion_factor = CurrencyYahooFinanceCurrencyExchanger::load('USD','EUR');
$node_usd_value = $entity->field_usd_value[LANGUAGE_NONE][0]['value'];
$euro_value_live = $conversion_factor * $node_usd_value;
$display_output = number_format($euro_value_live,2);

That should be all, just tried it and I am getting the following to display. My computed field is called "EUR Value (Live)":

Hope this does the trick for you!


entity eck create new property type or/and behaviour I guess everyone here has done what I want multiple times and I am probably just stupid but I can't seem to find it.

So in my drupal 7 installation I want to create an entity with a date property(so all bundles have a date that is set by a user). Perfect scenario is that this date is like the date field with calender to select a date.

I can't find how to do this but that's probably because I have no idea what to look for.

Can someone put me in the right direction for this?

Making it more clear:
I could just add a date field in all bundles but that seems not the best way to me and I would like to learn drupal in it's best practice.

thanks in advance

You can follow the documentation of eck modules. https://www.drupal.org/node/1370980
The last version introduces the concept of behaviour and you can create your own.

Install the module date_popup
Implement the hook hook_ctools_plugin_directory()
Create your plugin
In the default_widget callback return a renderable array where the #type is date_popup


Build menu like this in drupal 7 I have always been working on drop down menus which nice menus or sucker fish menus was satisfying. I have a new kind of menus to be satisfied.  As show in the image. When destination is hovered its should bring out drop down in that manner.

I would use the Superfish module (http://drupal.org/project/superfish), recently this has added an option for megamenu which will allow you to build a display much like your screenshot. You will need to tweak the css to get the display how you would like it.

Demo: http://mehrpadin.net/demo/superfish/ (hover over "products" in the very bottom menu)


The PUT request shows "HTTP/1.0 406 Not Acceptable: Missing node type" I have been trying to update a node data from the PUT request using cURL. bit due to some reason its showing "HTTP/1.0 406 Not Acceptable: Missing node type", I think the request is done proper but the data is not in proper format. Below is my code.

        $newSketchBoard = array(
          'title' => $title,
          'type' => 'rest_sketchboard_user',
          'field_sketchboarduser_user_id[und][0][value]'=>$data['uid'],
          'field_sketchboard_paintjob_id[und]' => $data['paintjobid'],
          'field_sketchboard_template_id[und][0][value]' => $data['templateid'],
          'field_sketchboard_user_color_id1[und]' => $data['colorid1'],
          'field_sketchboard_user_color_id2[und]' => $data['colorid2'],
          'field_sketchboard_user_color_id3[und]' => $data['colorid3'],
          'field_sketchboard_user_color_id4[und]' => $data['colorid4'],
        );
        $entity_id=$sketchboard_data['entity_id'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 600);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIE, "{$session_cookie}");
        curl_setopt($ch, CURLOPT_PUT, 1);
        curl_setopt($ch, CURLOPT_URL, REST_BASE_URL."/node/{$entity_id}");

        $putString = $newSketchBoard;
        // Put string into a temporary file
        $putData = tmpfile();
        // Write the string to the temporary file
        fwrite($putData, $putString);
        // Move back to the beginning of the file
        fseek($putData, 0);
        curl_setopt($ch, CURLOPT_INFILE, $putData); // file pointer
        curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $newSketchBoard);
        $result = curl_exec($ch);
        print_r($result);

I also tried using the following code, but it's not working.

$putString = json_encode($newSketchBoard);
$putString = http_build_query($newSketchBoard);

This ticket might be of some help.
http://drupal.org/node/1191786


How to do translation via csv file imported from PHP my admin I'm experimenting with a variety of modules to translate, but I find that a simple CSV file would be best.

TMGMT doesn't work for me as I get a lot of bugs that I can't resolve.

Is there a way to translate from CSV export from PHP my admin, translate and then re-import?

You can trnslate Po files with  POEDitor but if you insist use csv
I suggest you use csv2po , export drupal translate in po file, convert po file to csv translate them in excel (or anywhere you want) then convert back it to po and import it to your site.

some quote from its documentation

  csv2po allows you to create CSV files from PO files. This allows you
  to send translation work to translators who do not or cannot use PO
  Editors but who can use a Spreadsheet.

  po2csv allows you to send CSV files, which can be edited in any
  spreadsheet, to a translator. This document outlines the process to
  follow from the raw po files -> CSV files -> back to PO. We also look
  at a case where you may have submitted a subset of the PO files for
  translation and you need to integrate these.


Move title display below other fields When viewing a node, I'd like the Title to display below one of the other fields in the Content Type, but it's not available to arrange in the Manage Display tab.

With all of the flexibility and power that Drupal gives me, do I really need to create a custom template for each of my content types? :(

Any help is appreciated!

You can do this in Panels.

First, remove the print title statement from page.tpl.php in your theme.

Usually it looks something like this:

      <?php if ($title): ?>

<?php print $title; ?>

          <?php endif; ?>

This will prevent Drupal from printing the title automatically.

Then open up Panels and activate (if you haven't already) the node override template and the user override template as well as any other places where you need to display the title.

Then add the title where you want it to appear from within the Panels interface (Add content -> Page elements -> Page title).


View / Twig Extension : Display other items with the same field value I work on a view block which displays a list of parts (content Type : parts), here are simplified examples of parts and fields :

part_ref || part_id
ABCD || 10
BCDE || 11
CDEF || 11
DEFG || 11
EFGH || 12

In my View Filters, only one part is displayed, filtered by "part_ref".
What I would like to do is to display other parts with the same "part_id".

For example, "BCDE" is displayed, I would like to display also "CDEF" and "DEFG".

I have created a Twig Extension in order to do something like :
{{ displayRelated(11) }}

But inside my function "displayRelated", Idon't know how to get parts with the passed "part_id".

Does someone have a link or something to guide me ?
I cannot find anything on google.

Or maybe it's not the right approach ?

Thanks in advance.

I finally found a solution with a function in my Twig Extension.
I don't know if it's a clean way to do it but it works.

The function is called from the twig file :

{% set parts = partsSameId(part_id) %}

This is the simplified code inside the twig extension php file :

<?php

public function partsSameId($part_id) {

    // Get nodes with the same part_id
    $nids = \Drupal::entityQuery('node')
      ->condition('type','my_custom_content_type')
      ->condition('my_custom_field_for_part_id',$part_id)
      ->execute();

    // return array
    $html = [];

    // For each node returned, get the title.
    $i = 0;

    foreach ($nids as $the_node){
      $node = \Drupal::entityTypeManager()->getStorage('node')->load($the_node);
      $part_name = $node->getTitle();

      // return array
      $html[$i]['part_name'] = $part_name;

      $i++;
    }

    return $html;
  }


How to implement a text field formatter that renders a URL as the image? If a node has a text field with the url of an image as its value, how can I render this field as the image?

The image does exists it will be given the image url. I have to write that url into the text field.

Now using this url the value of this field should be an image when the node is viewed. But should be again editable textfield when editing the node.

And if in case the image doesn't exits a string can be shown "no image available".

You can follow the Drupal.org example on creating a custom Field Formatter. Inside the viewElements function, you can add an if statement to check if the remote file exist. If it does, assign the url to the markup. If not, assign some text:

viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
        $file = $item->value;
        $file_headers = @get_headers($file);
        if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $url = Url::fromUserInput($file);
            $markup = "<img src={$url->toUriString()} \>";
        }
        else {
            $markup= "File Not Found";
        }
      // Render each element as markup.
      $element[$delta] = ['#markup' => $markup];
    }

    return $element;
  }

Part of this answer is from stackoverflow.
I have not tested this, but it should be close.


dd a class="" to anchor on the "read more" links of a node How I can add a class="" to anchor on the "read more" links of a node.
Im use a bootstrap theme and i need add de btn-default class to anchors, thanks

    <<<<<<<< SET A CLASS IN THIS ANCHOR ? >>>>>>>>>>

      Read more
       sobre Noticia 2

Add template.php file to your theme directory if it doesn't exist. Then, add template_preprocess_node() to it like so, replacing template with your theme name.

function template_preprocess_node(&$variables) {

  $variables['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn-default';
}


EntityFieldQueryException when saving node I have created a node type which I want to use to store events in. I can create new nodes of this type with no problems, but when I want to edit and save a existing node, I get this error:

In english, this means "Unknown field:". However, a field with this name isn't even defined in my node type:

Full size image here: http://d.pr/i/8V36

Do you have any idea what could cause this error?

I would check and see if the field (field_event) exists. Go to Fields list under reports (admin/reports/fields). You can also check the "field_config" table directly and see if the field exists.


How to programmatically update the allowed values of a list field? I have created a select list for a Profile2 account in Drupal 7. In the allowed values list, I have added some values. Now what I would like to do is programmatically update the values in that list (add, delete or update). I don't want to use form_alter as I want these updates committed to the database. My problem is I can't seem to find where these values are stored in the database or how to pull those values from Profile2, update them and then save them.

I have Googled high and low on this particular issue and can't find an answer on how to do this. I hope someone can help me out.

Thanks.

Something along the lines of...

// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);


How to rerun hook_post_update_NAME() Drupal 8 introduced hook_post_update_NAME() which has some benefits over hook_update_n, for updating modules.

Each hook_post_update_NAME() should only run once, but sometimes I want to rerun it, like when I'm debugging the update hook during development. With hook_update_n, you can reset the schema version in the database.

How do you rerun hook_post_update_NAME()?

"post_update" hooks that have been run are stored in the database, in the key_value table, post_update collection, but the data is serialized and awkward to update directly.

I used some of the details from @kiamlaluno's answer to create a drush script which you can use to reset a single hook. Here's a basic version (longer version is here):

#!/usr/bin/env drush

$key_value = \Drupal::keyValue('post_update');
$update_list = $key_value->get('existing_updates');

$choice = drush_choice($update_list, dt('Which post_update hook do you want to reset?'));

if ($choice) {
  $removed_el = $update_list[$choice];
  unset($update_list[$choice]);
  $key_value->set('existing_updates', $update_list);
  drush_print("$removed_el was reset");
} else {
  drush_print("Reset was cancelled");
}

And here's an example of what it looks like when you run it from the command line:

./scripts/reset_hook_post_update_NAME.drush

Which post_update hook do you want to reset?
 [0]   :  Cancel
 [1]   :  system_post_update_add_region_to_entity_displays
 [2]   :  system_post_update_hashes_clear_cache
 [3]   :  system_post_update_recalculate_configuration_entity_dependencies
 [4]   :  system_post_update_timestamp_plugins
 [5]   :  my_module_post_update_example_hook

# The script pauses for user input.
5

my_module_post_update_example_hook was reset


Embedding Views programmatically getting argument overridden title I'm embedding a View inside my custom module, using views_embed_view

From the docs for this function:

  Note that this function does NOT display the title of the view. If you
  want to do that, you will need to do what this function does manually,
  by loading the view, getting the preview and then getting
  $view->get_title().

However, my View has no title, instead I've set my contextual filter to override the title (from the arguments in the url).
How do I get this title?

Thanks

Edit: Here is a screengrab of my contextual filter settings.  I'm actually currently using the default taxonomy_term view that comes with Views out of the box.

Okay I got it...

After executing the view in your code (e.g. with a $view->preview()).
You need to find the argument in the view that sets the title, and then call set_title() on it.

Here's what I did (note that I'm assuming that in the case of multiple arguments setting titles it's the last one that works, hence the array_reverse, haven't tested this yet).

<?php
$view = views_get_view('taxonomy_term');
$view->preview('panel_pane_1', array($tid));
foreach (array_reverse($view->argument) as $argument) {
    if ($argument->options['title_enable']) {
        $page_title = $argument->get_title();
        break;
    }
}
?>

Hope that helps someone else out.


What's the best way to assign variables for use in multiple form modules? We have multiple custom form modules in our Drupal 8 site, and there are variables that are common across them -- like arrays for year, semester and campus, as well as lists of courses (so it's quite a few values, and they have to be updated from time to time). What's the best (most correct) way to define these common variables in a single place so they can be accessed by any module that needs them?

It's hard to say what is the "best", but you can write a class, add the variables as constants, and then import the class wherever you need it.
For example, in MYMODULE/src/MyVariables.php:
<?php

namespace Drupal\MYMODULE\SharedStuff;

/**
 * Defines variables that need to be shared throughout the site.
 */
class MyVariables {

  // Seconds in an hour.
  const HOUR = 60 * 60;
  // Seconds in a day.
  const DAY = 24 * self::HOUR;
  // Seconds in a week.
  const WEEK = 7 * self::DAY;
}

And then in the PHP files where you need the variables:
use Drupal\MYMODULE\SharedStuff\MyVariables;
And then for the variable: MyVariables::HOUR


Drush within Multisites I am using drush on ubuntu 14.04. I have more than 20 site on my localhost /var/www with virtualHost setting. I have a question that whenever i go to /var/www/site1 and run drush dl module_name. It download the module in sites/all/modules directory in site1 folder. Now i cd to /var/www/site2 and run drush dl module_name. It will again download the module in site2 module directory.

In every site i have to do drush dl for same module. Is there any method so that i don't need to do drush dl every time. I just do drush dl module, it will check from all other sites for particular module, if not found then will download from internet. I already doing cp and scp for same module. But i want to do with drush.
I am very greedy to save my internet bandwidth.

Thanks in Advance.

you can use:

drush dl modulename --cache

From drush help dl:

Download Drupal core or projects from drupal.org (Drupal core, modules, themes or profiles) and other sources. It will automatically figure out which project version you want based on its recommended release,
or you may specify a particular version.

...

Examples:

 drush dl webform --cache                  Download webform. Fetch and populate the download cache as needed.

Options:
 --cache                                   Cache release XML and tarballs or git clones. Git clones use git's --reference option.
   --cache-duration-releasexml             Expire duration (in seconds) for release XML. Defaults to 86400 (24 hours).
...


Recommended tools/techniques for monitoring for spam attacks on multi-site and shared servers I'm managing a number of servers with dozens of Drupal sites, some with a single multi-site Drupal installation and others with dozens of separate Drupal installations. We're constantly running into the issue of one site having a lax registration or comment policy and getting overrun with node spam to the detriment of the entire server.

Addressing the spam isn't a problem once we can detect the issue (CAPTCHAs and user registration approval usually knock out most of the attacks) but most of these sites have inexperienced administrators who aren't savvy enough to notice these attacks underway and we only detect them several months in when the damage to performance and SEO has already been done. Better security policies would also obviously help and we usually try and address any potential security issues during the site build but we don't usually try and prevent the client from enabling comments or adding new features, etc.

Any recommendations for how to monitor multiple Drupal sites to detect an attack like this before it gets too far? I've seen a number of 'drupal watch' modules and services like Drupalmonitor.com or NewRelic but they seem more focused on module updates, etc. Possible signatures for a spam attack would probably be an excessive amount of comments or nodes over a given period, coming from the same server, excessive load on a specific table, etc.

ether try the free mollom service or you can blacklist words before they get submitted. Another solution that does well is just use the disqus module to regulate your commenting. i have switched over to disqus completely. but its not seo friendly as its a js script call from what i remember. if you want seo capability best you blacklist words and links. say if someone posts a link it would throw an error. this would deter any link spammers as most bots posts links.


Drush doesn't download module version specified as dependency My module has a dependency to specific version of Media module (7.x-2.0-alpha4) and I have specified that in my info file as documented in Writing module .info files (Drupal 7.x) documentation, just like this:

name = mymodule
description = MyModule description.
package = Media

dependencies[] = file_entity
dependencies[] = media (7.x-2.0-alpha4)
dependencies[] = media_internet
dependencies[] = views

When I try to enable my module with it's dependencies drush en -y mymodule, Drush downloads current stable version of media module (7.x-1.5) instead of the specified one and then enabling my module fails because of unmet dependency. I'm doing this on plain Drupal installation v7.34, DevDesktop stack v 2 RC build Mar 18 2015, Drush v7.0.0-alpha9 (from DevDesktop).

I have also tried to specify the version as (2.0-alpha4) and (2.x) - without success.

What am I doing wrong? Thanks for any hints!

The Drush download code actually pre-dates this feature; as you have observed, it is not supported.

I have posted a feature request in the Drush issue queue, here:

https://github.com/drush-ops/drush/issues/1285


Can't access admin/content When I go to admin/content I'm getting the following error, whereas at the same time node/{node_id} is accessible just fine.

  The website encountered an unexpected error. Please try again later.
      Recoverable fatal error: Argument 1 passed to Drupal\views\Plugin\views\field\EntityOperations::getEntityTranslation()
  must implement interface Drupal\Core\Entity\EntityInterface, null
  given, called in
  /var/www-drupal/core/modules/views/src/Plugin/views/field/EntityOperations.php on line 116 and defined in
  Drupal\views\Plugin\views\field\EntityOperations->getEntityTranslation()
  (line 74 of
  core/modules/views/src/Entity/Render/EntityTranslationRenderTrait.php).

Can someone give me an insight what this error means and how I to solve it?

I understand that this is an old question / thread, but just want to post something that worked for me for future reference. Your mileage may vary.

Take a backup of the 'node_field_data' table.
Search and delete 'orphaned' rows on node_field_data by comparing against the nids on the 'node' table.


Way to show changes to a particular node to users I'm currently looking for a way to show changes that occured on a node and its related nodes.

Currently we are using the diff module and it works great except that it is a bit too advanced on what we show them (ex: html changes).

It there some way or modules to show revisions of a node and it's related nodes in a much simpler way?

You could try Revisioning (integrates with Diff) for both Drupal 7, and Drupal 6.

  Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You use it in scenario's like this:

  Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
  We shouldn't have to grant these roles “god-like” powers (e.g. Drupal 6's "administer nodes" permission) to implement this.


Rules event is not triggering I've created a custom action to fire when the "checkout is complete" event occurs. The front end is a mobile application, where as the back end is Drupal. So I create an order using its API and update the status the of the order to "complete" manually. But the event is not triggering.

Do anyone know what I'm doing wrong? When I've changed the event to when an order is created, the action is performing.

Change the status to "complete" manually may not trigger the rule. Instead, applying a payment for the order manually may work.
See here


How do you allow logged in users to comment via Disqus without extra login? I have a Drupal site that utilizes Disqus commenting, but want users to be able to use commenting function, without having to login to Disqus.

Is there a way to make Disqus automatically inherit the user information of a person already logged onto my Drupal site?

This question is old, but for the sake of the completeness: you have to use Single Sign-On from DISQUS API. In the comment section, logged in users will see themselves connected to the DISQUS system with the cretentials from their Drupal account and will be able to comment directly with no additionnal login. The anonymous users will have to previously connect to DISQUS, Facebook, Twitter or Google before sending their comment.
Note that this question has already bee answered here.


How do I set the default value for results? I'm on Drupal 9 and I have an AJAX view with a page display and an exposed filter block and a single filter exposed, "Search: Fulltext search".
The Search API module is configured to search inside 3 different content types: products, articles and authors.
I've also configured a facet to filter on the content type, using a widget type "links", that let filter one content type at time.
So, initially, the search page shows the results of all the three content types.
After users filter a content type, they can switch only to another one and never return to the no content type chosen situation.
What I need to do is that the results are listed by default with one specific content type. If that content type yield no results, the following content type should be used as filter.
If there are no result, just no result should be shown.
In other words, the no content type chosen situation should be never available.
I've tried to force the filter on content type, if missing, using hook_views_pre_view(), but it doesn't seem to work.
Actually, I've no idea if it is the correct approach or I have to work on different hook\somewhere else.
How do I solve this issue?
This is the hook code.
function my_module_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() === 'search' && $display_id === 'page_1') {
    $active_filters = $view->getExposedInput();
    if (isset($active_filters["search_api_fulltext"]) && !empty($active_filters["search_api_fulltext"])) {
      if (!isset($active_filters["f"])) {
        $active_filters["f"] = ['content_type:product'];
      }
      else {
        $content_type_filter_exists = FALSE;
        foreach ($active_filters["f"] as $facet_filter) {
          $filter_array = explode(':', $facet_filter);
          if ($filter_array[0] === 'content_type') {
            $content_type_filter_exists = TRUE;
            break;
          }
        }
        if (!$content_type_filter_exists) {
          $active_filters["f"] = array_merge($active_filters["f"], ['content_type:product']);
        }
      }
      $view->setExposedInput($active_filters);
    }
  }
  //$view->exposed_raw_input = array_merge($active_filters, (array) $view->exposed_raw_input);
}

Initially I tried some different approach:

extending SearchApiString
an event subscriber of KernelEvents::REQUEST altering the incoming url

because by default facets\search api rely on the query_params of the url and the "values" of the relative facets various objects of the modules.
Both of those those approaches kinda failed, because the first didn't update the query params of the request, while the second caused some bugs that I couldn't manage to solve.
The working approach was to extending the default url_processor QueryString - which both initialises the active facets filters and build the url after a search.
Injecting the logic when the class is created allowed to do a minor modification without breaking all the standard functionality.
<?php

namespace Drupal\my_module\Plugin\facets\url_processor;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\facets\Plugin\facets\url_processor\QueryString;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Query string URL processor.
 *
 * @FacetsUrlProcessor(
 *   id = "my_query_string",
 *   label = @Translation("My Query string"),
 *   description = @Translation("Add description")
 * )
 */
class MyQueryString extends QueryString {

  /**
   * A string of how to represent the facet in the url.
   *
   * @var string
   */
  protected $urlAlias;

  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request, EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $eventDispatcher) {
    //this is where I'm adding a default value
    $this->alterRequest($request);
    parent::__construct($configuration, $plugin_id, $plugin_definition, $request, $entity_type_manager, $eventDispatcher);
  }

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   */
  private function alterRequest(Request $request): void {
    $query = $request->query;
    $facet_new_parameters = [];

    if ($facet_parameters = $query->get('f')) {
      $content_type_filter_exists = FALSE;

      foreach ($facet_parameters as $parameter) {
        $sepator = ':';
        $explosion = explode($sepator, $parameter);
        $facet_type = array_shift($explosion);
        if ($facet_type === 'content_type') {
          $content_type_filter_exists = TRUE;
        }
      }

      if (!$content_type_filter_exists) {
        $facet_new_parameters = array_merge($facet_parameters, ['content_type:prodotto']);
      }
    }
    else {
      $facet_new_parameters = ['content_type:prodotto'];
    }

    if (!empty($facet_new_parameters)) {
      $query->set('f', $facet_new_parameters);
    }
  }
}


Where do I add my own javascript or jquery so that it executes after the DOM is ready in Drupal 7? The site I'm working on is here.  The theme is modified Bartik theme.

Here is the code I ended up with.  The actual script inside the function works in Chrome console.

//Scripts that are required to run after DOM is ready
jQuery(document).ready(function)() {

    // Make the parent menu item of the active sub-menu item also active.
    jQuery('#block-system-main-menu li.active-trail > a').addClass('active');
}

I read a few articles and eventually ended up making a new file here:
/sites/all/themes/brainfx/js/brainfx.js

And I call this file from the theme's template.php file inside the brainfx_preprocess_html function with this code:

drupal_add_js('sites/all/themes/brainfx/js/brainfx.js');

You'll see it shows up in the head tag on the site.  But its not working.  What do I need to do to correct this?

There is a syntax error in above code. Change the js file contents to below. It will work as you expected !

jQuery(document).ready(function () {

    // Make the parent menu item of the active sub-menu item also active.
    jQuery('#block-system-main-menu li.active-trail > a').addClass('active');
});


Adding extra button on node edit form with save functionality enabled I want to add an extra button on the node/edit drupal 7 form.
That can be done by hooking into the form_alter:

$form['actions']['push'] = array(
 '#type' => 'submit',
 '#value' => t('Save && Push'),
 '#callback' => 'my_callback',
);

In my callback I want to run my custom Push function and save the node.

Any ideas how to achieve this?

function my_callback_action(&$form, &$form_state) {
  dpm('my_callback_action');
  return '';
}

You need to add your own extra submit function to your form. The big question is - where is default one?

If default function is attached to form itself, all you need to do is:

$form['#submit'][] = 'my_callback';

Then in callback test if it was your button that triggered it.

If it's attached to button, you need to copy original button's submit array to your button, and attach your callback:

$form['yourbutton']['#submit'] =  $form['originalbutton']['#submit'];
$form['yourbutton']['#submit'][] ='my_callback';

If it's attached to form, but you want yours attached to button, the way is of course:

$form['yourbutton']['#submit'] = $form['#submit'];
$form['yourbutton']['#submit'][] = 'my_callback';


Create a permanent list of a content type I have a content type named "clients" which can be filtered within a view and all can be selected using bulk operations.

What I would like to do is take the filtered list in the view and copy it to a permanent list of content on my site. So that it is saved and can be accessed at a later date without having to go through the filter options again.

For example, to store a list of clients all from one country, say Germany, to a list of these clients named Germany.

Any ideas how I would do this?

Views Save module can help you. The module page says

  This projects allows admins to add a "Save" button to their views (on
  a per-view basis). This button allows logged-in visitors to save their
  current exposed filter settings on the site, so they can later return
  to the same page. The saved views are stored per user, and can be
  listed with Views themselves, to provide users with an overview of all
  their saved views. Saved views can also be overwritten with new
  settings.

  Anonymous users are offered a way to log in or register when trying to
  save a view – if they do, the view is saved to their (possibly new)
  account, otherwise it is purged after a while.