hook_node_insert PDOException exception issue I am attempting to programmatically insert some field data when a new node is being created using the following code:

function mymodule_node_insert($node) {

    $dialects = array('en-AU', 'en-NZ', 'en-US');

    node_object_prepare($node);
    foreach ($dialects as $dialect) {
        $node->translations->data[$dialect]['entity_id'] = $node->nid;
        $node->translations->data[$dialect]['entity_type'] = 'node';
        $node->translations->data[$dialect]['revision_id'] = 3;
        $node->translations->data[$dialect]['language'] = $dialect;
        $node->translations->data[$dialect]['source'] = 'en';
        $node->translations->data[$dialect]['uid'] = 1;
        $node->translations->data[$dialect]['status'] = 1;
        $node->translations->data[$dialect]['translate'] = 0;
        $node->translations->data[$dialect]['created'] = time();
        $node->translations->data[$dialect]['changed'] = time();

        $node->field_page_body[$dialect] = $node->field_page_body['en'];
    }
    node_save($node);
}

However, I recieve the following error:

I understand it's complaining about the same node ID being saved twice but I'm not sure how to avoid this exception and update my new node with the programmatically set data?

It's important I execute my code at hook_node_insert because there are hundreds of nodes to be imported later and they all need the same treatment.

The same code works when tested in mymodule_init().

You cannot call node_save($node) during hook_node_insert($node).

According to the documentation, that hook is invoked during the middle of the database transaction, so the node isn't committed to the database yet. So when you invoke node_save, the old node you're attempting to update doesn't exist yet, and it will attempt to create a new node (with the same ID). Thus, the collision.


hook_views_data TIMESTAMP field is empty I'm using hook_views_data in my custom module to show the formatted date of a table in mysql. Using the example in the api I have text working but my TIMESTAMP in the donationDate column shows up blank.

MySql reports it is a TIMESTAMP field and it's showing me '2015-04-16 18:41:09'. When I change out the below to the string options it shows me the string representation so I know it's passing data from that column. I've played with the options in setting up this custom view but none of the date options seem to make a difference. I've looked at Google but none point me to what I might be doing wrong. How should I troubleshoot it?

function manage_donations_views_data() {
  $data['GeneralDonations']['table']['group'] = t('Donations');
  $data ['GeneralDonations']['table']['base'] = array(
    'field' => 'donationId',
    'help' => t('List of recent donations'),
    'title' => t('All donations'),
    'weight' => -10,
  );

  $data['GeneralDonations']['donationForm'] = array('title' => t('Form'),
    'help' => t('Form and type'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
    ));
  $data['GeneralDonations']['donationId'] = array('title' => t('ID'),
    'help' => t('id'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
    ));
  $data['GeneralDonations']['donationDate'] = array('title' => t('Date'),
    'help' => t('Date'),
    'field' => array(
      'group' => 'donations',
      'handler' => 'views_handler_field_date',
      'click_sortable' => TRUE,
      ),
    'filter' => array(
        'handler' => 'views_handler_filter_date',),
    'sort' => array(
        'handler' => 'views_handler_sort_date',
      ),
    );

  return $data;
}

The column was set up in MySql this way: donationDate TIMESTAMP

I've been using drush to clear all my cache after each code change. I have used all the options. The only one that seems to show anything is the "ago" as it shows 45 years, 4 months so it appears it recognizes the unix epoch?

Still struggling with this. Is it something wrong with how I defined the mysql field, or is it views_handler_field_date? I see some methods but unsure how to troubleshoot this. I'm unsure which to dig into? thx, sam

thx, sam

It appears the API is looking for an integer, particularly Unix timestamp and not the MySql timestamp which is transformed into a string. Looking at how Drupal handles the node table was key to grasping this and the hook_views_data documentation indicates that the field is an integer as well.


Dynamic processing of string field based on user IP I am a relative newbie looking for guidance on how to best tackle a requirement within the Drupal 7 realm. I have an entity defined with a field containing the URL for an external resource and would like to be able to manipulate the URL string programmatically before rendering the field as a hypertext link within a view. I thought about storing the alternate URLs in the database but the format is subject to change so the dynamic approach is more attractive since it would only involve a single edit. I need to first check the $_SERVER['REMOTE_ADDR'] to determine whether or not to execute this code because if the user is requesting the resource from a location off site then a proxy link must be generated for licensing purposes. What approach would make the most sense for this use case?

Store the data in the cleanest way possible and then use something like Custom Formatters
or a custom module to modify the presentation of the stored data.

As for using $_SERVER['REMOTE_ADDR'] I feel that I need more data on how and where this will be used.  Have you considered using the permissions or roles built into Drupal?

You would likely need to place this in a preprocess function to conditionally call it for a specific IP address.

For example.

/**
 * Implements hook_preprocess_node().
 */
function hook_preprocess_node(&$variables) {
    //Obviously a real IP is required above for correct syntax.
    if ($_SERVER['REMOTE_ADDR'] == xxx.xxx.xxx.xxx) {
        //Next you can edit the output of any field you want if your remote address matches.
        $variables['field_myfield'][LANGUAGE_NONE][0]['value'] = 'Something Modified Here';
    }
}


file upload broken on node form on custom page Possible Duplicate:
  D7 Image field upload errors with custom node_add() form

I have a custom page with a node form on it. The problem is that when I try to upload an image I get lots of errors.

The code is like this:

module_load_include('inc', 'node', 'node.pages');
$output = drupal_render(node_add('node_type'));
return $output;

Some of the errors I get are:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of E:\work\my_site\includes\form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of E:\work\my_site\modules\comment\comment.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of E:\work\my_site\modules\menu\menu.module).

The funny thing is that if I return the form array everything works well.

module_load_include('inc', 'node', 'node.pages');
$output = node_add('node_type');
return $output;

Unfortunately this doesn't help me at all.

This is the same problem as in here but the solution there is not an option for me.

Any ideas?
Thanks

Yeah, apparently you should add these line to the menu item array:

'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

it is not enough to just add module_load_include('inc', 'node', 'node.pages'); before printing the form.


Using drush migrate-import --update I created a migrate script to import hundreds of records into a specific content type. A year after, I need to add another field to the content type and import values specific to each record. Because of changes made to some of the records over the past year, I cannot re-import the content from the csv file with the additional column. I am using config-edit to edit the migrate .yml file. Is there a way to rerun the migration to import content for the new field while ignoring all other fields that already have content.

I am using Drupal 8.

Thanks,

I was able to make it work by doing a vigorous edit of the original migrate script, removing all the fields and their mappings, except for the key. Adding the new field, allowed me to rerun the migrate script and the new field was imported while leaving the other content intact. I am still able to use the rollback and other functions of the script.


How do I unpromoted existing node when new node is promoted to front page (Programatically)? In Drupal 8 I want only one node at a time to be promoted to front page. If user promoted new node the existed should un-promoted automatically.

Can we implement this with events in Drupal 8?

The settings for FrontPage is provided by default in Drupal 8. Because the Frontpage in Drupal 8 is a View, so it opens all kind of setting feasibility.

Hence if you go at Admin/structures/views you will find a view named FrontPage.

Hence, you just need to change the Pager setting. Change item 10 to item 1.

And in sort criteria It is already Content: Author on (desc), so it will automatically will show new item first. So as you publish new item it will replaced and you have set item 1 in pager, so only 1 item will be shown on front page which is latest one.


Using Backup and Restore to transfer drupal configurations but not actual data I am trying to use backup and restore to transfer configurations in drupal, but not the actual data. The backup and restore module allows you to do a backup where you exclude data from certain tables. My question is does restoring have a similar option where you don't wipe all the data and just make changes without wiping all the data?

For example, on our staging instance we added a new field to the User Account called field_phone_number. Can I create a backup with the new field configuration on User Account and then "restore" this backup on our production instance without transferring actual user records?

Preferably, I would like to do this via drush so we can implement into our CI/CD process.

For drupal 7 the best way to transfer Drupal configurations but not actual data is to use Features module.
You can create features from your staging env.
and then revert them in production.


osx 10.7.5 built-in apache 403 forbidden for sites/default/files/styles this really drives me crazy .. BTW here is a really nice tutorial i tried - everything. believe me ...
from adding users to groups, running apache as different user, chALOT -R (even chmod a+rwx), copying the original httpd.conf back, enabled UserDir, added attributes like

sudo chmod -R +a "group:_www allow list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,file_inherit,directory_inherit" Sites

but .. i'm not an expirienced sys admin // ---

i try to use both - WebServer and User location as Document root

setup
/etc/apache2/http.conf

setup
/etc/apache2/users/me.conf

and actually all seems to work fine. so AllowOverride and FollowSymLinks set

except: sites/default/files/styles/

image styles do not work i get 403 for requests like

sites/default/files/styles/fancy/public/animage.jpg

original images show up ..

maybe related to the 7.20 issue ?!

how can i properly debug this ?

This is more likely to be the issue with the update of Drupal core from 7.19 to 7.20.
As per the release notes, the update was only targeted to address the Denial-of-Service attack on the sites powered by Drupal.

You can add:

$conf['image_allow_insecure_derivatives'] = TRUE;

in the settings.php, to negate the effect of the update. As per the side effects, this will remove this security fix. I wouldn't recommend you do this on production.

existing patch:

--- a/modules/image/image.module
+++ b/modules/image/image.module
@@ -993,7 +993,7 @@ function image_style_url($style_name, $path) {
// The token query is added even if the 'image_allow_insecure_derivatives'
// variable is TRUE, so that the emitted links remain valid if it is changed
// back to the default FALSE.
-  $token_query = array(IMAGE_DERIVATIVE_TOKEN =>  image_style_path_token($style_name, $path));
+  $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)));

works, and $conf can be removed !

I've answered a similar question here.

Note: I'm making this as community wiki, so that someone working on Drupal security (hopefully from the security team) or anyone who is interested could add more to it.


Allow to filter (in a view) on a datetime field of a custom entity I have created a custom entity as follow:
Here is an extract of my entity definition in  modules/custom/bank_operation/src/Entity/BankOperation.php
Notes:
1- As you can see, I have changed the value of the views_data key
2- The operation_date base field have the datetime type
 * @ContentEntityType(
 *   id = "bank_operation",

 ...

 *     "views_data" = "Drupal\bank_operation\BankOperationViewsData",

 ...

class BankOperation extends ContentEntityBase implements BankOperationInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    ...

    $fields['operation_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t("Operation date"))
      ->setRequired(TRUE)
      ->setSettings([
        'datetime_type' => DateTimeItem::DATETIME_TYPE_DATE,
      ])

    ...
}

Here is an extract of my overrode EntityViewsData in  modules/custom/bank_operation/src/BankOperationViewsData.php
This class is used according to the value of the views_data key. This is my attempt to allow a view to filter on the operation_date field
class BankOperationViewsData extends EntityViewsData {

  public function getViewsData() {
    $data = parent::getViewsData();
    $data['bank_operation']['operation_date']['filter'] = [
      'id' => 'datetime',
      'field' => 'operation_date',
      'table' => 'bank_operation',
      'field_name' => 'operation_date',
      'entity_type' => 'bank_operation',
    ];
    return $data;
  }

}

After that, I have created a view to display my BankOperation entities with an exposed filter on the operation_date field.
Here is the error produced when using this filter (I don't understand why ViewsYearFilterDatetime is called)
Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus->__call() (line 360 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\datetime\Plugin\views\filter\Date->opSimple() (Line: 63)
Drupal\views_year_filter\Plugin\views\filter\ViewsYearFilterDatetime->opSimple() (Line: 330)
Drupal\views\Plugin\views\filter\NumericFilter->query() (Line: 1373)
Drupal\views\ViewExecutable->_build() (Line: 1262)
Drupal\views\ViewExecutable->build() (Line: 390)
Drupal\views\Plugin\views\display\PathPluginBase->execute() (Line: 180)
Drupal\views\Plugin\views\display\Page->execute() (Line: 1630)
Drupal\views\ViewExecutable->executeDisplay() (Line: 77)

I know that there are other questions like this one, but none of them are providing a detailed answer (only links).
I have setup my question to allow people who are facing the same issue to quickly find a path to solve it.

As there are so many difficulties with base fields (sorting, displaying, filter etc in views), I decided to remove all of them and I re-created them back in the field UI.
To allow this, I set fieldable = TRUE, and field_ui_base_route = some_path in the annotations of my entity.
This is of course poor design because each field will create a table on its own but I had no time to spend on this...
Feel free to provide a better answer... I think we need a real how-to to provide the same functionalities we have for fields created in UI then for base fields
Edit to add: I have created an issue to create an help item on this topic: https://www.drupal.org/project/drupal/issues/3213021


Alter views fields using preprocess function before render? How do I edit a views field using preprocess before it is rendered to the screen?
Let's say the field originally outputs something like this:

Note title

now I want to change that adding the number of comments in that node

Node title (4 comments, 1 new)

I know I can achieve this with joining two fields together or altering the template (tpl) files for that particular field but I'd like to learn how to use preprocess function in order to achieve this.

Drupal 7

Either you have to use hook_views_pre_render() or create appropriate TPL file (e.g. views-view-fields--MYVIEW.tpl.php) in your template dir (check Theme:Information in view edit page for more details).

You may also use preprocess theme function to print a single record from a row, with fields which is template_preprocess_views_view_fields().

Related:

_preprocess_views_view__ specify view name
Drupal 7 preprocess_views not working
Specific preprocess functions for theme hook suggestions are not invoked


How can I concatenate two fields in a view? I have a view set up to use the unformatted list type. I'm pulling in about 10 different fields, but would like to concatenate two of them onto a single line in the display. Is this possible?

Example: fields are Content: Session Number, Content: Title, Content: DateTime, Content: Speaker. Right now, all of them render onto separate lines. I'd like for the Session Number  and Title to be concatenated onto a single line, so I get S3 | My Session Title.

Let's say you have field A, and field B.

Make sure A, comes before B in the fields list.
Edit field A, and check "Exclude from display". The field will now no longer show up.
Edit field B, find the checkbox for "Re-write the output of this field".
Below the new textbox, find "Replacement patterns." There you should now be able to find something that looks like [field-A], and [field-B], with possibly many more options.
Enter "[field-A] [field-B]" as the replacement pattern.

And you should have the fields concatenated.

There are some situation, where the markup generated by Views with this configuration is not desirable, as you will now have A "inside" B. If that's a problem, one can add a completely new dummy field, of type "Global: text", and to steps 3, 4 and 5 on that field instead.


Drupal Commerce - Database location of Shipping information I am attempting to migrate the data located on the /admin/commerce/orders page of Drupal Commerce to a custom website that I have created. I am trying to use phpMyAdmin to locate and export any relevant database information in the Drupal database. I have found that the order id/email/timestamp are located in the commerce_order table in the Drupal database. However, I can't find the location (table/table column) of the user's name and shipping information.

Does anyone have an idea of where I could find this information?

I am currently using Drupal 7.53 and Drupal Commerce 7.x-1.13.

Drupal's entity data isn't really meant to be exported directly from the database. Is there no way for you to build a PHP script that uses the Drupal API to load and export these entities instead? Or an existing module like Patrick suggests?

Otherwise, you're going to need to pull information from a variety of tables. Shipping information is stored on an order's shipping customer profile. These are linked to the order via a customer profile reference field (whose table should be field_data_commerce_customer_shipping). From there you can find the customer profile ID you'll need to search for in the address field data, matching the profile ID against the entity_id in the field_data_commerce_customer_address table.


Twig cache files on load-balanced setup The Twig cache key (twig_cache_prefix) is based the modify timestamp of the Twig template file and a randomly generated key. This gives a problem with a load-balanced Drupal setup where every host has it own copy of the Drupal source files, with different timestamps for the same template files across the hosts.

In this setup each Drupal instance keep generating a new prefix for every other request (when the balancer is in round-robin mode).

Is there a workaround for this?

We host a platform in Acquia and we've run into this issue as well. For our needs, we get around it by logging into each webhead and clearing the appropriate cache.

There is an ongoing discussion for this in Drupal issue #2752961.


What is the proper URL to get flag service? I'm running Drupal 7 with the Services module and the Flag Service modules installed  but I'm having trouble trying to figure out how to Get countall for a particular post ? Can anyone please tell me what URL I should use ?

URL to get all posts : http://webaddess/rest/events

URL to get one Post : http://webaddess/rest/node/3591

I had to implement this for DrupalGap/jDrupal:

https://github.com/dontmcyn/flag/blob/master/flag.js#L282

Essentially you make a POST to ?q=rest/flag/countall.json and send along the following data:

var data = {
  flag_name: 'my_flag_name',
  entity_id: 123
}

You may have to JSON.stringify(data) before sending it. And you are right, pass along an X-CSRF-Token header in the POST call, the value of the token can be retrieved here: ?q=services/session/token


How to make an external database available to Views? There's a lot of discussion here and in other places about using external databases in Drupal. What I've figured out from that is:

  The best way to work with data in a database table is to use the Views module. I've installed that and started using it and found it's great for working with a table that I've added to the site's database.
  The easy way to get Views to work with a table that was not created by Drupal is with the Data module. This module treats any table in the site database that is not in use by Drupal as an "orphan table" and allows it to be "adopted" at the click of a button.
  The module "Table Wizard" apparently provides a way to do that with tables that are not in the site's database. But that module is not available for Drupal 7.
  The "settings.php" file, in the section on "Database settings," has detailed documentation on how to define additional databases that the site can work with. But when a database is defined in that way, its tables do not show up in the list of orphan tables in the Data module.

The change that I've made to the database definition in the “settings.php” file of one of my sites is:

$databases = array (
          'default' => array ('default' => array (
                    'database' => 'db_local',
                    'username' => 'db_local',
                    'password' => '_________',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => '',
          ), ),
          'extra'   => array ('default' => array (
                    'database' => 'db__extra',
                    'username' => 'db_admin',
                    'password' => '_________,
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => '',
          ), ), );

I have a table that I want to use in more than one site in my multi-site installation. This means I need to have the table in a database that is accessible to each site. According to the reading I've done, my options for doing that are:

Best, if it's possible: Find out that there's a way to get the Data module to recognize tables in the additional database defined in "settings.php", so it can adopt them.
Use table prefixes to allow all the sites to use one database.
The module “Forena Reports” seemed to do exactly what I need, but when I installed it, I couldn’t get it to work. I submitted issue 2475645 and can’t do much more there unless there’s a fix for that problem.
Write my own module to give Views access to the additional database defined in "settings.php".
Install Drupal 6 with Table Wizard and use that to get Views to see my external table, and then somehow take the result of that and put it into Drupal 7. (This has been suggested in some posts.)
Follow the procedure in https://drupal.stackexchange.com/a/3321/45991 , which starts with installing a patch and seems to also require creating my own module.
I’ve also looked at the modules Feeds, Feeds SQL, Views XML Backend, and Migrate, but none of them say they can connect an external db to Views. Am I missing something? Is one of them the right solution?

Option 2 is not practical because it would result in a huge database with hundreds of tables that would be very difficult to manage. I’ve been making great progress in getting started on Drupal, but I don’t feel up to the task of 4, 5, or 6. Is there any possibility of something like option 1 working? Or is there any other way to get Views to work with a table outside the site database without being able to write my own module?

Two additional details: The first table I need to work with is pretty large, over 6,000 rows and about 20 columns. There is no intention to give visitors to the site access to the database except for information drawn from it for page content.

Thanks for your help.

I've done this successfully a couple of different ways:

Use a SQL View to create a virtual table in db_local that refers to the corresponding table in db__extra. The query to create that would look something like this:

USE db_local;
 CREATE VIEW some_table AS
     SELECT * FROM db__extra.some_table;

You can then refer to this SQL View as if it were a native table in your Drupal database, and you don't even need to add the external database at all in settings.php. Note that this might not be compatible with Data module (see https://www.drupal.org/node/1973806), but you should be able to describe the SQL View to the Drupal Views module by implementing hook_views_data(), and stop using Data module.

Here's another possibility: use selective table prefixes to trick Drupal into rewriting {some_table} to db__extra.some_table. This is not the same as prefixing your Drupal tables.

Your $databases setting would look like this:

$databases = array (
          'default' => array ('default' => array (
                    'database' => 'db_local',
                    'username' => 'db_local',
                    'password' => '_________',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => array(
                            'some_table' => 'db__extra.',
                    ),
          ))
);

Again, I'm not sure if this is compatible with Data module, since I don't use it. But it should work with Views if you implement hook_views_data() yourself.


How to turn off url aliases on dev site? I'm using path auto to automatically generate url aliases. On my dev site it would be convenient to use standard node/123 urls.
Is there a way to do that? Just turning off pathauto and path won't do the trick

I think the problem is that the {url_alias} still has the aliases in it.

My suggestion would be to take a backup, then delete a few manually from "admin/build/path" (Drupal 6) or "admin/config/search/path" (Drupal 7), and then try the "node/nid" paths for the entries you deleted.  Then, take another backup :) and either delete them via the Delete aliases tab.


How make node view return without menu? Perhaps the question is simple, but I can not understand how to return the body of a node without a menu.
I did a module that loads the content of node into the custom area.

function loadnode_in_region_menu_alter(&$items) {
    $items['load_node/%'] = array(
        'page callback' => 'loadnode_in_region_node_page_view',
        'page arguments' => array(1),
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

return $items;
}

function loadnode_in_region_node_page_view($nid) {
    $node = node_load($nid, NULL, false);
    $vnode = node_view($node);
    return drupal_render($vnode);
}

JS looks like

    jQuery.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + 'load_node/' + id,
        dataType: 'html',
        success: function(data){
            jQuery('#ajax-result').html(data);
        },
    });

Result looks like this, with a duplicate menu

If I change line from

    return drupal_render($vnode);

to

    echo drupal_render($vnode); OR print drupal_render($vnode);

The result looks like I would like it, but some fields are not displayed correctly, such as voting and image. Looks as if they are not themed.

How to return themed node body without a menu?

You can create tpl for the menu and render the content and design tpl as required or create tpl for the content type in theme


altering the add content type form I am going to alter the form of add content type form and for that I used the hook_form_FORM_ID_alter()

Here is my code which implement in the module file, but it is not working.

function hc_listings_menu()
{
    $items = array();
    $items['node/add/home-care-popular-search-region']=array(
        'title' => 'Create Home Care Popular Search Region',
        'page callback' => 'drupal_get_form',
        'page arguments'=> array('home_care_popular_search_region_node_form',''),
        'type'=>MENU_NORMAL_ITEM,
    );
    return $items;
}
function hc_listing_home_care_popular_search_region_node_form_alter(&$form, &$form_state, $form_id)
{

    $state_list=['ffff','gggg'];
    $region_list=['1','2','3','4'];
    $form['home_care_popular_search_region']=array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#title' => t('Homeeee Care Popular Search Region'),
        '#description' => t('Home Care Popular Search Region'),
        '#required' => TRUE,

    );
    $form['hc_popular_state']=array(
        '#type' => 'select',
        '#default_value' => $state_list,
        '#title' => t('Popular State'),
        '#description' => t('Home Care Popular State'),
        '#required' => TRUE,
    );
    $form['hc_popular_regions']=array(
        '#type' => 'select',
        '#default_value' => $region_list,
        '#title' => t('Popular Search Region'),
        '#description' => t('Home Care Popular Search Region'),
        '#required' => TRUE,
    );

}

Note: content type is => home_care_popular_search_region

module is => hc_listing

Should I have to remove the details in hook_menu regarding the altering?

First, You need to find out the correct form id for this form and then you can use,

hook_form_FORM_ID_alter there.

Thanks


How to pass wildcard via drush exec? How to pass wildcard via drush exec on remote host (via ssh)?

I've tried already:

$ drush @foo exec 'ls -al *'
$ drush @foo exec "ls -al *"
sh: 1: ls -al *: not found
Command 'ls -al *' failed.
$ drush @foo exec "ls -al \*"
sh: 1: ls -al \*: not found
Command 'ls -al \*' failed.
$ drush @foo exec 'sh -c "ls -al *"'

Local shell is bash, remote shell is sh.

$ drush @foo ssh 'ls -al *' works great, for any @foo alias that is remote.


Migration of data from old site to new I am working on data migration from old site to new site.

Which module i can use for data migration. I am stucked in the issue that fields are not same in the old site and new site. How can i map fields so data can be migrated from old site to new one.

Issues that i am facing:-

1) In old site there are lot of content types and new site there are few. Because fields are managed to merge in few content types.

2) Fields name are not same exactly same like the old site.

3) Few of the fields are converted into taxonomies.

4) Old site contain lot of data as well as images.

So is there any drupal module that i can use or i need to follow some other approach?

Please suggest me some solution.

From experience the Migrate module can do all of this for you if you're willing to sit down and write some PHP code to define Mappings and the necessary individual migrations from/to whatever content you need.

See the project page for alot of introductory information and the /examples directory for sample beer data migrations.

EDIT

the Migrate module is a developer module which you must write PHP classes to define field mappings and source to destination content types. Example migration classes are discussed in the official documentation. There is also a Drupal 2 Drupal migration module that provides some UI to require less custom coding.

At this time I cannot provide additional tutorials/examples -- there are many available on google, eg:

not free:
https://drupalize.me/videos/introduction-migrate-module-series?p=1271

free 45min talk from a DrupalCamp:
http://vimeo.com/54448150


Show Link to Subscribe/Unsubscribe to Nodes in a View I'm creating a view that shows all the nodes of a specific type. I'm looking to also show which of those nodes the current user is subscribed to and provide a link to subscribe or unsubscribe. Is there any way to achieve this using arguments, custom PHP field, etc?

I created an argument that filters the nodes the current user is subscribed to, but it hides all the nodes their not subscribed to, even if "Display All Values" is selected.

I'm using the Notifications module and Views 2.16 on D6.

For a single View of non-subscribed nodes:

Using a contextual filter for NIDs, select provide default value by using PHP code.
Then in the PHP code use an EntityFieldQuery to get a listing of all nodes that are subscribable. Save this array of IDs to a variable.
Then use a 2nd EntityFieldQuery to get an array of all subscribed nodes for the active user.
Then subtract the 2 arrays, these are all nodes able to be subscribed to by the user.
use return $subscribable_nodes; to return the nodes as an array to the View.

Your view would contain a node title, and you could rewrite the node title as a link to the subscription url if you want.


how to implement jquery image gallery in drupal theme tpl.php files? I am new to Drupal 7's theme system. i am creating a custom theme that have image gallery inside it.but i have no idea for implementing jquery image gallery in drupal theme tpl.php files. i searched many tutorials about image gallery in drupal theme. but most of them just show implementation of image gallery using views and gallery related modules. can anybody know tutorials series that show how to add js files in theme tpl.php file from scratch? and what kind of drupal variables are use for gallery purpose.

If you want the bluemasters rotator exactly, you need to copy their javascript and css that apply to the rotator element (image_reel) and install it in your theme. The following instructions would also be relevant for other slideshow scripts with obvious substituions.

First, you need to add the rotator script from bluemasters to your theme. The name of the file is bluemasters.js and is in bluemasters/js/ in the theme folder.

To install it in your theme, you could just add it as a script tag in your page.tpl.php file in your template, ex:

There are much better ways of adding this, using drupal_add_js and page_preprocess functions but this is the easiest way to make sure it is loaded on every page.

Next, you're going to need to isolate the css bluemasters is using to create their slider. From their css file, it looks like all of the css for the front page slider is in one block in the file, starting with the comment 'Front-page slider'

/*
 * Front-page Slider
 */
.main_view { float: left; position: relative; }

...etc.

Grab that and add it to your theme's css file.

If you've got these two files added to your theme correctly, then anywhere the image_reel class exists (with the following structure) on your pages, their code will convert it into a slideshow. The exact structure (from their demo file) is just a list of links like this:

You can add this code in as a block or on a page or in your template directly and it will create the same slider effect.


My new theme doesn't show the slogan My site has a nice slogan that was shown with the previous theme.

Now, after installing the new theme "Nexus" (Live demo here), the slogan appears no longer. What should be done to make it appear again? thx.

Let's call it a bug in Nexus theme.

If you sub-themed Nexus, copy the page.tpl.php from Nexus templates folder into your sub-theme's template folder, then make the following change to the copied file, just after the h1 tag for the title:

// look for this

  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?>

// then add this below it
<?php if ($site_slogan): ?>

    <?php print $site_slogan; ?>

<?php endif; ?>


how do i modify the paypal order details? My client logs into Paypal to review the orders that have been processed and would like to see the actual product name rather than the order number. How do I accomplish this?

There is a patch in the queue that supports sending itemized information to PayPal, but it was never completed / integrated as far as I know. It gets tricky when you itemize, because any rounding errors in taxes, discounts, etc. triggers a failure to accept payment at PayPal.

In order to do this yourself even without the code being part of the module, you'd need to alter the form used to redirect to PayPal or the API request used to process the payment. Either of these would be possible in a custom module using hook_form_alter() or the relevant alter hook from the PayPal module for the payment method you're actually using.


Numbering the content list in drupal (as simple as it sound) - possible via the UI? Went through the conf and the Drupalsite > Content page but couldn't find any where to number the list (or at least to get a nubmer of all contents of all entities and types - including Views, Panels, Webforms, ETC).

Would thank you for showing a simple way for numbering this list \ get a content-total number.

Here is the picture of my natural display of the content page... Thanks, Ben.

Looks like you might be looking for number of nodes by content type (among other things). If that's the case then you may want to consider the Charts module. It comes with a sample view that gives you both a tabular overview and a chart of these numbers.

The (accepted) answer to the question Views and node count for taxonomy terms contains another (views) based example.

The question Count of nodes by type contains some code snippets that may help to write your custom module to calculate these counts.

If you don't want to install/enable the Charts module permanently, you may want to temporarely enable it to (eg) look at the view for the tabular format display, and then create a clone of that view to perfectly fit your needs (and then uninstall the Charts module again). Of course the "Views" module is yet another module. But it's rare to find a site that does not use the views module, so that's maybe an acceptable compromise to consider (you might have Views available already)?


Can't find where to edit content I've recently inherited an Drupal 8 website.  www.berkslibraries.org  At the bottom of the site in the footer there is the word Contact and under it a link to Hours & Locations, email address, and a phone number.  I have searched through Drupal and can't find where that information in stored to change it.  It's not in the content section or in the custom blocks.  I was hoping someone might have some advice on where I can possibly look to change that info.

Thanks,

When you log in as admin. just hover your cursor over the words and you can do a quick edit. You might have tried create content. If you just click content, all content created will populate.


Form API multiple #validate records I have an interesting question.
There is a custom module that defines form -> form validate and form submit

I am not allowed to touch this module, still I want to execute another custom action on submit (OR validate).

I have added
$form['#validate'][]='_custom_validator';  in my hook_form_alter
So the $form array has two functions that validate.
And that seems to work, the problem is I have to "copy-paste" the validation code from the other module (the code inside hook_form_validate).(To prevent any incorrect form validation).
This is considered as a bad design pattern.

Question:
Is there somewhere a property that defines the order of the validations ?

Cheers

You can use array_unshift to make sure your validation is called first:

array_unshift($form['#validate'], '_custom_validator');


How can I use WordPress-like short codes? I am new to Drupal. Previously I was working with WordPress, where you can use short codes for getting plugin functionality for pages.

Is this possible in Drupal as well?

For example in WordPress when editing a blog post I can use this in the editor:

[foobar] // This is a short code.

And here's how it got defined in WordPress:

function foobar_func( $atts ) {
  return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

How to do that in Drupal?

The Shortcode module provides this functionality, it even has this comment:

  Initial work is based on the Wordpress Shortcode API but was reworked for Drupal.

So I think it's the closest thing you're going to find (although the Drupal 7 version is currently only in alpha).

It's not quite the same as the one in Wordpress from the looks of it. It seems you'll need to define a shortcode for each function that you want to run (using hook_shortcode_info()), or else define a more complex shortcode that will allow the adding of arbitrary functions.

There are a few extension modules included with the main module that look pretty easy to understand so I'd have a look through those to see exactly what you need to do to add your own functionality.


hook_validate() returns errors, but the form has lost all the user's submitted values I'm sure there's a standard Drupal way of doing this, but I've tried a couple of the statements that I've found on blogs and stuff, and I can't get a form to restore the values submitted by the users.

For example:

form default value: "enter a long word"
user submits: "foo"
validation sets: "word not long enough"
form displayed on page with value: "enter a long word"
expected value: "foo"

So far, in the hook_nameform_validate function, I've tried setting form_state['rebuild'] and form_state['redirect'] to FALSE (I've seen both listed in blogs as the right answer).
Perhaps unsurprisingly to anyone who knows the correct answer, neither works individually, nor do they both work together.

EDIT as requested, here is some actual code to show what I'm doing (wrong).  You're correct that the question was probably too general to be of value without any actual code on display. This sample is still "abstracted" - there's closer to a dozen fields, but the effect is the same.

In this case, with these functions (and the others, like theme etc...) when a user submits their email address, if the validation returns an error, the form tells them "bad user" then clears the email field (and all others).  Ideally the form should repopulate all fields with any typing they've already done.

function sampleform_nameform($form, &$form_state) {
    $d = sampleform_defaults();
    $form = array(
        '#method'                   => 'post',
        '#prefix'                   => $d['form_prefix'].'
',
        '#suffix'                   => '
'.$d['form_suffix'],
        'your_email'                => array(
            '#value'            => $d['your_email'],
            '#type'             => 'textfield',
            '#field_suffix'         => '*',
            '#required'             => TRUE,
            '#attributes'           => array('class' => array('standardInput'),
                                             'default' => $d['your_email'])
        ),
        'sampleform_submit'         => array(
            '#prefix'               => $d['clear'],
            '#type'                 => 'submit',
            '#value'                => $d['submit'],
            '#attributes'           => array('class' => array('buttonInput', 'submitInput')),
            '#executes_submit_callback' => true
        )
    );
    return $form;
}

function sampleform_nameform_validate($form, &$form_state){
    $d = sampleform_defaults();
    if (!valid_email_address($form_state['input']['your_email'])) {
        form_set_error('your_email', $d['e_email_v']);
    }
}

It's very possible that one of the two answers below has fixed the issue, and I've not had the chance to read them yet, so with a few more minutes, maybe we'l find the answer is already here.

:)

EDIT 2

kiamlaluno has shown us that while I was using #value in my form-builder function, the correct nondestructive setting in creation of a form is #default_value

If I look back to my original reference point, Pro Drupal 7 Development the form API examples in chapter 11 give the instruction to use #value on page 247 (where you build your first form).

They also use MODULENAME_nameform as the hook, while it appears to be more correct to use MODULENAME_form (according to the way drupal works, it's easier to find further documentation if you search for _form rather than nameform).

Anyways,  hopefully this saves someone else some time.  Someone should probably tell Todd Tomlinson and John K VanDyk that they've got an error in their book.

:)

There is nothing particular that needs to be done, to avoid to overwrite the value entered by the user, when a validation handler returns an error.

For example, the following form, is build from the code shown below (system_ip_blocking_form()):

function system_ip_blocking_form($form, $form_state, $default_ip) {
  $form['ip'] = array(
    '#title' => t('IP address'),
    '#type' => 'textfield',
    '#size' => 48,
    '#maxlength' => 40,
    '#default_value' => $default_ip,
    '#description' => t('Enter a valid IP address.'),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
  );
  $form['#submit'][] = 'system_ip_blocking_form_submit';
  $form['#validate'][] = 'system_ip_blocking_form_validate';
  return $form;
}

Its validation handler is the following one (system_ip_blocking_form_validate()):

function system_ip_blocking_form_validate($form, &$form_state) {
  $ip = trim($form_state['values']['ip']);
  if (db_query("SELECT * FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField()) {
    form_set_error('ip', t('This IP address is already blocked.'));
  }
  elseif ($ip == ip_address()) {
    form_set_error('ip', t('You may not block your own IP address.'));
  }
  elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
    form_set_error('ip', t('Enter a valid IP address.'));
  }
}

When I enter a value for which the validation handler returns an error, the value I enter is not modified, as you can see from the following screenshots.

This is what happens on Drupal 6 too. The only case where a field value is cleared is when the form validation handler reports an error for a password form field; in that case the password field doesn't contain the previously entered password, which would be difficult to edit as it is shown as "•••••."

There is nothing that needs to be set; by default Drupal will not change the content of a field when a validation handler reports an error for that field. As far as I know, the value of a field could be changed by its "#after_build" callback, that is invoked after the field is built, and that is described in form_builder() with the following sentence:

  The "#after_build" flag allows any piece of a form to be altered after normal input parsing has been completed.


broken blocks after Drupal 7 Windows to Linux migration I'm in the process of migrating a Drupal 7 site from a development Windows box to a soon to be production Linux box.

The Linux box has all the required dependencies and is running the same version of PHP/mySql/Apache/Tomcat/Solr.

I've copied all of the files over and exported/imported the database.

The first time I went to the page, it loaded fine.  I get my superfish menu and my rotating banner.  However, after I goto a different (any) page, my superfish menu and rotating banner disappear.

I dropped the database and re-imported it, and got the same exact behavior.  First load is fine, subsequent visits the page is broken.

I thought it might be something to do with caching, so I cleared the cache and got the message:

The block Superfish 1 (Superfish) was assigned to the invalid region superfish and has been disabled.
The block View: Rotating Banner was assigned to the invalid region nivoslider and has been disabled.

I tried to export/import the database using the "Backup and Migrate" plugin... no change.

Is there anyway to fix this?  Anyplace I could start looking to see where it's falling apart?

Have you checked your block regions? Sometimes when I migrate a site (though for me it's between servers running different OSs), blocks disappear from the site. However, it's just a matter of them getting thrown out of their regions, and the solution is to just go to Structure -> Blocks and put them back into their appropriate regions.


Custom action to create a new entity based on a fields of an existing entity There are two entity types on my site: 1) an application for participation (entityform) and 2) a participant profile (node). At first user creates an application for participation. And then site administrator must create somehow a new participant profile and fill its fields from an entityform created by user.

How to create such an action "Create participant profile from application"? The action must be accessible to administrator as a button or a menu tab item on a entityform view page.

If I have to do that, I would take these steps to achieve what you want here :

Make a custom module for it.
Add a path by help of hook_menu.
Make a custom function for menu callback & mention the same in there.
Inside function, get current node ID (entityform submission, where admin is there) by something like if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
Then write code to load a entity by ID by help of entity_load & take all the values in custom vars as per requirement for new node(profile).
Save the node of type profile by help of node_save.
Insert a link(CREATE PROFILE) mapped with created path(by above hook_menu) to the node view of entityform submission by help of hook_node_views.

Now when ever your inserted link will be clicked, a profile will be created.

You can restrict the access of created path by implementing hook_permission & give access to admin only.

You are free to do some other stuff as well, like if profile node exist for entityform submission them make link disappear as well. It all depends upon your need & plan :)


Create a reference all available block content In Drupal 7 there is Block Reference field module that can reference pretty much all available blocks, including views' blocks, system blocks, menu blocks etc.

I'm just starting with Drupal 8 and since the Block Reference module doesn't have a version for it, and the built-in Entity Reference doesn't seem to pick up views' blocks, system blocks, I want to create a new custom block type. In this new block type, I want to have a reference field that can reference all available block content.

Is there a way to do it?

Like I said, I'm new to Drupal 8 so not familiar with new rule and features. After a bit digging here is what I found out.

Entity Reference field allows to reference block instances (config) or custom blocks (content).

Before I was set my field to Content > Custom block, now I switch it to Configuration > Block then you have to Place the block that you want to reference to, even if it is in disabled. After that, you can have your Entity Reference field pick that up otherwise it won't show.

You can have a look at here for more detail.


Cache remains stale for custom blocks after editing My Drupal 8 website consists of multiple custom blocks created from the drupal backend user interface.

As I went from dev to production settings and activating Internal Dynamic Page Cache (set to 1 minute), the custom block content doesn't change on the actual site after editing (for both anonymous and authenticated users). If I go back to editing mode, the changes are persisted as expected.

The changes are visible when I clear the caches (i.e. drush cache-rebuild). I don't have any issues with my own blocks that implements the Block plugin and has a max-age set. Nodes works works as expected too.

What could be wrong?

hope this works ...

<?php
abstract class BlockBase extends PluginBase implements BlockPluginInterface {
  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return array(
      'label' => '',
      'module' => $this->pluginDefinition['module'],
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
      ),
    );
  }
}

refer to this link block cache api is removed

The following block cache constants have been replaced with the combination of the cache.max_age and ::getCacheContexts() return values (or bubbled cache contexts) on blocks:

DRUPAL_NO_CACHE (equivalent: cache.max_age = 0)
DRUPAL_CACHE_CUSTOM (equivalent: cache.max_age = 0 + Cache::keyFromQuery())
DRUPAL_CACHE_PER_ROLE (equivalent: cache.max_age >0 + user.roles)
DRUPAL_CACHE_PER_USER (equivalent: cache.max_age >0 + user)
DRUPAL_CACHE_PER_PAGE (equivalent: cache.max_age >0 + url)
DRUPAL_CACHE_GLOBAL (equivalent: cache.max_age >0, no cache contexts)


How do I filter by node ID in views? I am trying to add Node ID in contextual filters but it seems there isn't Node ID anymore.

You must use content ID, which is now the same thing.

That is the one to use as contextual filter, in Drupal 8.


Editing time for pages in google analytics? I've been asked for "development/editing" time for pages analytics to be made available.

Is this possible? If so, how?

Ok - you want to use Google Analytics custom variables for this and a bit of javascript (though will try and make this as Drupaly as possible). For the timer, you can write javascript/jQuery code to start a timer on the window.load() event and then attach it to the submit button on your particular form. Number of examples of javascript timers, I found this example that looked promising.

Key thing to get this data to your google analytics account is to add a google analytics push event (see documentation above) so your code would look something like this (rough psuedo code)

$(document).ready(function() {

   function StartTimer() { some timer function ... }

   function StopTimer() { some timer stop function ... return $time; }

   startTimer();

   $("#id-for-form-submit-button").click(
       $timeValue = StopTimer();
       _gaq.push(['_setCustomVar',
          1, // This custom var is set to slot #1.  Required parameter.
          'Editor Time', // Category Name. Required Parameter
          $timeValue,  // This value of the custom variable.  Required.
          3  // Sets the scope to page-level.  Optional parameter.
      ]);

});

Finally, you need to attach your javascript to your form (the drupaly part). I use this quick code snippet (from switchbackcms) as a good way to avoid losing the javascript if the user reloads the form:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
     $form['some_element']['#after_build'] = array('_load_my_javascript);
   }
}

function _load_my_javascript($element){
    drupal_add_js(
      drupal_get_path('module', 'my_module')
        . '/track_editors.js');
return($element);
}


How to add active-trail class to a links in a view? How to add an active-trail class to all links in a view, which a parents of a current page (according to a result of menu_get_active_trail())?

One solution is to add an invisible PHP-field to a view (let the field identifier will be php).

Set a setup code to

$static = module_exists('crumbs') ? crumbs_get_trail() : menu_get_active_trail();

Set a value code to

$href = 'taxonomy/term/' . $data->tid;
foreach ($static as $item) {
  if ($item['href'] === $href) {
    return 'active-trail';
  }
}

And at last add a custom CSS class to a link field with token [php]


How to replace the date field selects with one text field in Drupal 7 web forms I am using webforms in Drupal 7. Is there a way to set the date field to a single textfield instead of 3 select fields?

Since it seems like the webfrom module doesn't support this functionality yet, if found that the easiest way to do this, was to use a textfield and use form_alter to add the datepicker plugin.

function custom_form_form_alter(&$form, &$form_state, $form_id) {

  if($form_id != 'webform_client_form_2') return;

  // Alter textfield for date to integrate popup calendar
  $form["submitted"]["expected_move_date"] = array(
    '#type' => 'item',
    'finished_after' => array(
      '#type' => 'textfield',
      '#attributes' => array('class' => array('datepicker')),
      '#required' => TRUE,
    )
  );

  $form['#after_build'] = array('custom_form_uidatepicker');

}

function custom_form_uidatepicker($form, $form_state) {
  drupal_add_library('system', 'ui.datepicker');
  drupal_add_js("(function ($) { $('.datepicker').datepicker({
      showOn: 'both',
      buttonImage: 'sites/all/modules/custom/custom_form/images/calendar.png',
      buttonImageOnly: true,
      dateFormat: 'dd/mm/yy',
    });
    $('.datepicker').datepicker( 'option', 'minDate', 'd' );
    })(jQuery);", array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

    return $form;
}


What else must I do to set up a new custom module? I am defining my first custom module and cannot get Drupal to see it.

What I have done:

Created a subdirectory with module name at sites/all/modules/custom/mymodulename. The name is just letters, nno spaces underscores or dashes.
Added two files mymodulename.info & mymodulename.module.
mymodulename.info contains: name = mymodulename and includes a description, package = Other, and core = 7.x.
ran update.php
flushed caches
reloaded admin/modules page
module is not listed???

I suspect that I somehow let Drupal know this is my first attempt and it is just messing with me! How can I appease it?

Check for spelling mistakes, because you seem to have everything you need for it to be listed.


Disable email alerts when modules are out of date How can I disable Drupal's email alerts when modules or core are out of date?

Go to http://mysite.com/admin/reports/updates/settings, and remove all the email addresses from the E-mail addresses to notify when updates are available textarea:

Just to highlight the pertinent of the description on that field:

  If blank, no emails will be sent.


add same class to book and it's child pages I have book node with assigned article nodes as child pages. On certain books I want to be able to use different theming. Using context I can print additional css class on book page according to taxonomy. Is it somehow possible that the class can be passed to all child pages as well? I can not figure out some easy solution. The only way I can think of would be to mark child nodes too. Any ideas? Thank you.

One easy way I can think of if it's only about CSS, you can use body tag classes, it has different classes based on the nodes.


How to add field classes from within template_preprocess_node During template_preprocess_node I would like to be able to dynamically add classes to specific field wrappers.

Is this possible or does template_preprocess_node run after template_preprocess_field? I would much prefer to use template_preprocess_node if possible as the class relies on other fields.

I've tried adding:

$vars['content']['field_name']['classes']
$vars['content']['field_name']['classes_array']

but neither seem to take effect.

Were I to do the same within template_preprocess_field then I apparently would add classes to $classes_array which would automatically flatten into $classes, however these values don't appear to be available, or at least provided, to template_preprocess_node?

EDIT:

After investigation, it seems template_preprocess_node does run first, however it doesn't seem to have access to $classes_array as it appears in template_preprocess_field.

Ok my somewhat dirty solution was to pass a classes array from template_preprocess_node to template_preprocess_field:

function template_preprocess_node(&$vars){
  if(!isset($vars['content']['field_name']['classes_array'])){
    $vars['content']['field_name']['classes_array'] = array();
  }
  $vars['content']['field_name']['classes_array'][] = 'custom-class';
}

function template_preprocess_field(&$vars){
  if(isset($vars['element']['classes_array'])){
    $vars['classes_array'] = array_merge($vars['classes_array'], $vars['element']['classes_array']);
  }
}

If there's a more 'official' way to do this, please feel free to enlighten me and I'll re-award the answer :)


How can get my site out of maintenance mode? I moved my site from one server to another in the same way I moved another site. But it won't get out of maintenance mode.

I can access phpMyAdmin and I can access the server files easily.

I've tried /user and /q=user.

Any suggestions?

There is a few things you can try.

1. Using drush

Go to root of the website and run this drush commands one by one:

drush vset maintenance_mode 0
drush cc all

2. Using database query

Go to phpmyadmin and run this db statement in order to update the "maintenance_mode" property in the variable table to "i:0;":

UPDATE `variable` SET `value` = 'i:0;' WHERE `name` = 'maintenance_mode';

3. Login as admin programatically

Make copy of the index.php file and call it what every want (maintenance.php for example) and at the end of the file replace

menu_execute_active_handler();

with

global $user;
$user = user_load(1);
drupal_session_regenerate();
drupal_goto('user');

go to that file (like [your_website]/maintenance.php), after that just disable maintenance mode and don't forget to remove this file after you finish.

4. Manually set maintenance_mode variable in index.php

Edit index.php file and put

variable_set('maintenance_mode', 0);

just before

menu_execute_active_handler();

5. Configure maintenance mode in settings.php file

At the end of your settings.php file put

$conf['maintenance_mode'] = 0;


tb mega menu is not showing in bootrap theams in drupal7 I am new user of drupal 7.3. I am using bootstrap 3.0 theme in drupal 7.3.

I am using tb mega menu which is not showing. Black color box will be occurred in navigation block.

Please help me to solve this I want solution step by step. I want used in my project please help me.

I have refer you to below links :

LINK1
LINK2
LINK3


How can I make a user-friendly account approval for admins? Right now on my Drupal site I have everything set to send an email to the administrator once an account is created.

The administrator receives a link that says a new account is created, and there's a link to the user's profile in the email.

Is there any way for there to be a little option on the user's profile page that just says 'approve user' (that only the admin can see), or for an admin to get a link submitted to him through the email that he can click to automatically approve a user?

I'd rather admins not have to dig through the backend, look up a user, and then edit the user and approve the account manually.  Is this possible? The most preferable would be the the administrator gets an 'approval link' in the email, so he can just click 'approve' from his email, and assuming he's logged in on the site, it automatically approves the new user account.

There are two modules that you can take a look into

Admin Users

  This module helps to administrate all registered users. You can sort
  out users according to their status (active or blocked), the number of
  published nodes, the number of comments, the last visit or the period
  of registration. You can also change the role of any user, block or
  delete many users with one click just ticking them in the table.

Multi-admin pending approval notifications (MAPAN)

  Problem

  The current behavior in Drupal core when a new user registers
  requesting approval sends mail only to the site's contact address.
  Thus only one person is notified even though there may be several
  administrators/moderators.

  Solution

  This module improves this basic behavior by notifying all users that
  have the 'administer users' permission by default.
  Administrators/moderators get a setting to disable these notifications
  in their user profile form. A link is also appended to each of these
  notifications.


How do I distinguish menu items without children and display different content in panels or views? I have a taxonomy based menu (3 tiers) that displays a specific content type.  Content items are always tagged at the lowest level child (*) so when the menu items are selected a range of content is displayed.

top-level | mid-level1 | child1*
          |            | child2*
          |
          | mid-level2 - child3*
          |
          | child4*

When the parent levels are selected, I would like a summary page for the parent to show. I am using views and panels and getting the lowest level children to show is easily accomplished, but how do I set a filter or context to determine if the view is not at the lowest level?

Panels exposes a context that selects content with a parent (or not) so I can easily identify the top level menu selections, but the bottom children can occur at either level two or three and there is no context for 'has children'.

What can I use as a context to select the parents and which hook to use?

This is an excellent example of a custom Ctools plugin. In this case, our plugin type is "Access". The below is copied from "term_has_parent", and adopted to search for the reverse. It could probably be improved with some more robust error checking.

In Panels, you will get a new "Selection Rule", so that you can distinguish between terms that have children, from those that don't.

<?php
/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Taxonomy: term has child(ren)"),
  'description' => t('Control access if a term has children.'),
  'callback' => 'term_has_child_ctools_access_check',
  'default' => array('negate' => 0),
  'summary' => 'term_has_child_ctools_access_summary',
  'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);

/**
 * Check for access.
 */
function term_has_child_ctools_access_check($conf, $context) {
  $children = db_select('taxonomy_term_hierarchy', 't')
    ->fields('t')
    ->condition('parent', $context->data->tid)
    ->range(0, 1)
    ->execute()
    ->fetchAssoc();

  return count($children) > 1;
}

/**
 * Provide a summary description based upon the checked terms.
 */
function term_has_child_ctools_access_summary($conf, $context) {
  return 'Returns true if the current term has children';
}

If you don't know how to use a custom Ctools plugin, I suggest that is the topic of another question.


Need help with twig test template I'm trying to create a test twig template in drupal 8, I followed "Create custom twig templates for custom module" from their website but it's not working for me for some reason. This is what I have:

Contents of folder test_twig_template:

test_twig_template.info.yml:

name: Test Twig Theme
type: module
description: Module to test if twig theme is working as intended
package: Custom
version: 1.0.0
core: 8.x

test_twig_template.module:

<?php
function test_twig_template_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
    ],
  ];
}

test_twig_template.routing.yml:

test_twig_template.theme:
      path: /twig
      defaults:
        _controller: Drupal\test_twig_template\Controller\TestTwigTemplateController::content
        _title: 'Twig title'
      requirements:
        _permission: 'access content'

Code inside test_twig_template/src/Controller/TestTwigTemplateController.php:

<?php
namespace Drupal\test_twig_template\Controller;
use Drupal\Core\Controller\ControllerBase;

class TestTwigTemplateController extends ControllerBase {
  public function content() {
    return array(
      '#title' => 'Test Twig title',
      '#theme' => 'my_template',
      '#test_var' => $this->t('Test Value'),
    );
  }
}

And finally inside test_twig_template/templates/my-template.html.twig I have:

Test twig template!

test_var: {{ test_var }}

Thing is if I remove this "'#title' => 'Test Twig title'," from my controller nothing gets displayed on my custom page. Otherwise it just displays this title "Test Twig title".
Am I missing a call for twig somewhere or are my hooks_theme() not properly set up?

It looks like you are messing around with your naming.

Since your module is called test_twig_template you must use that name for hooks and namespaces etc.

Fix these things and it should work.

  Rename your hook_theme() from test_twig_theme to test_twig_template_theme.
  Call your route test_twig_template.theme.
  Your controller definition in your route must look like this, _controller: \Drupal\test_twig_template\Controller\TestTwigThemeController::content.
  The namespace in your controller must be namespace Drupal\test_twig_template\Controller;.
  Rename test_twig_template/src/Controller/TestTwigController.php to test_twig_template/src/Controller/TestTwigThemeController.php (the file name must match the class name).

That should be all, since your module is called test_twig_template it's important to use that name in all namespaces for your code to work properly :)

And then as @Hudri mentions your template shall only contain:

Test twig template!

test_var: {{ test_var }}

Head and body tags are provided by a general template in your theme.


False variation title is displayed On my Commerce Kickstart Page, I have each prodcut with 2 different variations.
My problem is that I am unable to change the variation title for the product variations that have been added first on the product itself. It continuously overrides my changes with the original, auto-generated title for a couple of products, but not all of them.
The second variation is always called "DVD - Product name" and works fine.

The first is set up like this:

When I now click on "Update product", it shows the correct values in the overview of the variations:

I now simply say "Save" on my edit product view and save the product. I click edit again and the old value is back as the variation title. But when I open the variation settings, it still shows me my changed title in the textfield:

I already took a look into the database, and the correct value (my changed title) is stored there. This made me think that this is a chaching problem, I played around with cache settings and stuff but that did not change anything.

It may also be noted that this problem does only occur for about 30% of my products, and also only for the first added products.

This happens when you go into a product display and then edit the variations inline from there. To stop this happening go to the manage fields screen for your product display e.g.  "Structure > Content types > Product display > manage fields"

Then click edit on the "Product" field and you should see "Auto generate the product title" tick box. Untick that and it should stop the issue happening going forward


Is it possible to return form, themes, content in an array for my page callback function? For right now I need to return a themed table, a form, & content on one page. In my page callback function how do I properly store and return this variable/array?

I looked at the page below, but the code did not seem to work properly. I can only get the themed table (first in array) to show, but nothing else after it.

Return both a form and content in a menu callback

EDIT:

i tried the code below for my return, but it doesn't work. $header & $rows are both properly declared and holding the right data.

return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_table' => theme('table', array('header' => $header, 'rows' => $rows)),
);

Remember that theme('table'.. returns HTML markup, so you are assigning a HTML string to the my_table key. In the example you linked drupal_get_form was being used which returns a renderable array, so it would have functioned correctly. Since render() doesn't know what to do with an HTML string, you must pass the render function the information before it has been turned into HTML:

return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_table' => array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ),
);


How to hide empty region in Omega It seems that by default all regions are rendered in Omega theme because of the Debug blocks.

Sidebar First

This is a debugging block

Is there a way to have an option to debug blocks and hide empty blocks at the same time?

Go to admin/appearance/settings/your_subtheme_name. Check attached image. You can set rights on who is or isn't allowed to see debugging stuff.

Uncheck debugging options will hide empty blocks...


taxonomy term is not working when i am added any query code is added in blocks our taxonomy term is not working they give two kind of errors:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'term' in 'where clause' when i clicking on taxonomy term
Notice: Trying to get property of non-object in eval()  when i am added code in blocks
Here is my code:

$nid=arg(1);

$tid=db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
INNER JOIN taxonomy_term_data td ON th.tid=td.tid
INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
WHERE td.vid = '6' AND th.parent = '0'  AND book.entity_id = $nid
")->FetchField();

print $tid->Name;
$child=taxonomy_get_children($tid);
 foreach($child as $t)
 {
$link = l($t->name, 'taxonomy/term/' . $t->tid)."<br>";
print $link;
}

I can't see any 'term' in your where clausole, so it's probably because you forgot the single quote around $nid.

oh, when i have query problems, the first thing i do is printing them on screen to see what I'm sending to the db, you wont believe what i managed to write some times, but i blame my keyboard >_>


Drupal 7 Views Multiple Jump Menus in single page not working I have two Jump Menu block (views driven) into single page.

The first Jump Menu block is working fine - Drop Down Content type - Using Ajax

While on Second Jump Menu showing an error of "An Illegal Choice has been detected. Please contact the site administrator." - Drop Down of Taxonomy Term Id

Do any one know how to resolve this issue ?

I did not get any help from community as well for the solution of this. I have to customized the code which resolved my issue. I have to put the form_alter hook for that jump menu form and apply

$form['jump']['#attributes']['onChange'] = 'javascript:location.href = this.value; return false;';

Hope this helps you guys.


Use of hyphen instead of slash in hook_menu For SEO purpose, I need to use hyphens instead of slashes in a URL defined in hook_menu, here's an example :

$items['mypath-%'] = array(
  'page callback' => 'mypath_render',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'access arguments' => array('access_content'),
);

Apparently Drupal doesn't support it natively. Is there a way to make it work ?

Cheers

Although I would never do this just for the sake of SEO personally, I believe the workaround is to use both hook_url_inbound_alter() and hook_url_outbound_alter(). By using these hooks you can change any URL displayed by the site to replace slashes with the hyphen, and then back again when Drupal processes the page after the user has clicked the URL. That way you can still use slashes in your hook_menu(), but it would show as hyphens in your site.

I'm not sure there is any other way.

Oh dear, I just realised the question was for Drupal 6, my apologies.

I think for Drupal 6, using custom_url_rewrite_inbound() and custom_url_rewrite_outbound() could be used instead.


Hide block for specific content types? How can I hide a block on specific content types in Drupal 8? There's the setting for displaying blocks only on specified content types, but not for hiding them. Looks like the PHP filter is out in D8, so not sure how to go about this. I'm sure it's a simple fix.

You can use this module:

Block Visibility Groups

Here you can configure a visibility group which hides blocks for a specific content type.

The visibility groups not only provide more options for block visibility, they are also reusable, that means you can apply the same settings on multiple blocks.

Ctools also provides the functionality to hide blocks for content types, but there was an issue, I don't know if this is resolved.


What modules are used by Open Atrium 2? I am looking for a list of the modules in the standard Open Atrium 2 install, something similar to those posted for Drupal Commons and Acquia Commons like:

https://drupal.org/node/2160755
https://docs.acquia.com/commons/module

Is one available? Where is it?

Thanks!

There's a set of drush make files in the project directory. Those list the various dependencies.


Hooking in to the email verificatin process In Drupal 7 (7.22), we'd like to hook into the email verification process for new users.  Perhaps the one time password node.  We need to do a test on the email address and set a value in a custom user field based on what we find.  This will allow us to give software activation terms to users with email matching certain business partner domains, for example.

Extra credit: we'd also like to enable a particular role for these users.  The first step, though, is to figure out where to hook in our php to do a regex test of $user->mail.

It would make more sense to create a rule to activate on After saving new user account. You could do a Text comparison on Account:mail using your regular expression, and if the condition was TRUE, Assign a role for the  new user. It would be waiting for them when they verified their account.

If your requirements change for the site, it is easier to make an alteration through the UI than it is to track down the code that has to be changed.

The same rule can Set a data value in the custom user field if you wish.

EDIT:

Install and activate the Rules module. Then go to /admin/config/workflow/rules and create a new rule,  calling it, lets say 'Upgrade new user' and set it to react on After saving a new user account.

When the configuration screen comes up Add condition and select Text comparison (wait for the AJAX request to complete) then set the Data selector to account:mail. Under Matching Text, click the Switch to direct input button, enter your regular expression in the  Value box, and at the bottom use Regular expression for the Comparison operation. Then save the condition.

Then add two actions; First add Add user role (wait for the ajax to complete) and you should see account as your data selector. Then choose the role(s) to add and save the action.

Then add an action to Set a data value. In the Data selector, find your field, and click Continue. In the Value box using <?php ... ?> delimiters, enter the code you need to return your activation key.

Save everything and try it out.


Templates as content I currently have a project with the requirement to edit templates for content like content, i.e. we will have a template content type which will be used as template for another content type.

I've looked for projects and best practices on the matter but didn't find anything. Does someone have experiences with a similar setup?

Should I use Twig and inline_template or should I write my own template system with tokens? Other ideas?

Any help is greatly appreciated!

It sounds like what the client really wants is something like the Paragraphs module:

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

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/


List outline of books related to another book by a node reference field I am using the book module with four content types: A, B,C and D.

A is the content type for child pages and the rest are allowed in book outlines.

I also have a node reference field in A that allows users to select nodes of type A related to the one they are creating.

I am trying to use views to display all the nodes that are related to a certain type A node and also display the outline of these related nodes.

E.g. viewing Book A.1 related topics and their outline:

Book A.1

Book A.2

Page A.2.1
Page A.2.2

Book A.3

Page A.3.1
Page B.3.2
Page C.2.2

I have gotten as far as displaying all the related nodes to a certain node but I am not being able to display their outline.

Any help/critics appreciated.

Have you tried views to create the outline.

A simple custom module will also do the trick and then you can use the generated result to show in the block as outline. In my opinion this is the best and fastest possible way to do your job.


Block showing users of a specific role is only showing up for the administrator I have a view/block that is shown to all the users who have a specific role (RoleX, member and administrator), and I set the view to a specific page. Whenever I look at the page as an administrator, I can see the block and everything looks great. When I log in as a user with the role RoleX, as authenticated user, or as anonymous user, and I look at the page, the block doesn't appear. I thought that this only happened if I only checked off the administrator when you go to configure block and then roles yet I left all of the roles unchecked so the block would be visible to all.

Does anyone have any idea how I might go about solving this?

My guess is that there is an access check somewhere that is failing. When logged in as user 1, it's impossible for a standard access check to fail, so this would be why you're seeing the block.

To solve this, try granting ALL permissions to RoleX (make sure you do not do this on a live site) and see if the block appears when you log in as the test user who has RoleX. If the block starts showing up, start disabling permissions a few at a time until you find which one is causing the issue.


Is it possible to have 2 different thumbnail image styles for the same field? I'm importing videos and video thumbnails from a legacy site. A lot of video thumbnail have black boxes at the top and bottom due to the aspect ratio of the videos, for example:

I would like to crop all video thumbnails to remove those bars. I haven't done it yet but assume it's pretty easy to just modify the image style for "thumbnail".

Now, any new videos that will be uploaded (using the video module) or any of the images that use the thumbnail style don't need to be cropped that way. If I would change the image style for "thumbnail" after all videos are imported then I would lose the crop effect, right?

How can I solve this problem?
I'm displaying all video thumbnails using views. Do I need to do a template override where I manually apply a different image style to those "legacy" videos?

You can put more than one filter on a preset, so it is possible, depending on the aspect ratio of the new and the old, that you can add a first filter that will remove the black bands and a second that will change the size.

Otherwise, you might try programmatically making image style change the aspect ratio of all your old images, deleting your old images, then copying the images in your changed image style directory to your root file directory. Image styles doesn't change the name of the file.

If either of those options doesn't work for you, you can create a custom field formatter that looks at the file id and decides which image style preset to use (as you suggested above except don't so this in the theme system as the new formatter would be available to any node view as well as in the views module). See: http://www.computerminds.co.uk/articles/creating-new-field-formatters-drupal-7


How to post correctly fields in views-view-fields.tpl.php? I'm using Drupal 7, and Views 3.

I would like to reproduce my comment template in views-view-fields.tpl.php.

Thus I need to print my fields to be able to arrange them as I wish it.

For each field, I proceed like that : <?php print $view->render_field('field_name', $id);?>, is it the correct/secure way ?

I don't think so, because all the row does not display.

The correct way is:

<?php print $fields["field_name"]->content; ?>

Note: Using views-view-fields.tpl.php will affect all of your views, which you may not want.

To target a specific view you need to use:

views-view-fields--[view-name]--[machine-name].tpl.php


Can't sync site config from git, entities exist of type x For whatever reason I seem unable to find a good resource to explain syncing the actual structure of a site (like blocks and configs).
I'm using git currently and am doing local development using lando. I have just been using the same folder this whole time but recently had to do some things and needed to clone my repo.
I've got the site running but it's back to the "defualt" state and made me install drupal and such.

I have the config/sync folder but cannot use drush cim or sync via the UI.

The configuration cannot be imported because it failed validation for the following reasons:
Entities exist of type Taxonomy term and Vocabulary Blog Categories. These entities need to be deleted before importing.
Entities exist of type Shortcut link and Shortcut set Default. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Webform + Content. These entities need to be deleted before importing.
Entities exist of type Paragraph and Paragraph type Standard Content. These entities need to be deleted before importing.
Entities exist of type Content and Content type Page. These entities need to be deleted before importing.
Entities exist of type Content and Content type Homepage. These entities need to be deleted before importing.
Unable to install the Commerce Store module since it requires the Path alias module.
Unable to install the Commerce Number Pattern module since it requires the Path alias module.
Unable to install the Commerce Order module since it requires the Path alias module.
Unable to install the Commerce Product module since it requires the Path alias module.
Unable to install the Commerce Cart module since it requires the Path alias module.
Unable to install the Commerce Checkout module since it requires the Path alias module.
Unable to uninstall the Path alias module since the Path module is installed.
Unable to uninstall the Path alias module since the Pathauto module is installed.

This is spat out by the UI.
I had tried to do something with the uuid but it obviously didn't work. I'll say that's because, again, I can't seem to find a good explanation of how this actually works.

Two things are happening:

In your active configuration in the database, some module(s) is/are installed, that isn't/aren't installed in the configuration you are trying to import. The problem is that you have content for the thing(s) being uninstalled, so if you were to import the configuration, you'd have ghosts in your database. These ghosts are listed in the errors that begin with 'Entities exist of of type X'.

To resolve this you'll need to either enable the missing item(s) in the configuration you're trying to import, or you'll need to delete the items from the database before you import your configuration.
The configuration you are trying to import has enabled modules, but the codebase for those modules does not exist in the Drupal installation you are trying to import the configuration into. These modules are listed at the end of the errors that begin with 'Unable to install the X module' (ex - you are missing the Path Alias code base).

To resolve this, you'll either need to add the code for the required modules to your codebase.


Drupal way of storing data related to a node I want to store some data that is related to a node and trying to figure out the best way of doing it. For example, I send emails related to a node and I want to save details such as:

To Email address
Cc Email Addresses
Date sent
User
Email type
Other chosen email options etc

In the past I would use Paragraphs to have an unlimited field but this will, over time, grow to have a lot of entries. I'm also using Revisions on the node so I think this will slow everything down when saving the node.
My question is... should I create my own entity for this? One that doesn't have a page like a node does? Or is there a better way of storing the data? I could create a custom table, store it there, and maybe register that with Views but I would like to have the entity API available on the content and maybe add fields in future using the UI. Any ideas?
Is there a module similar to Paragraphs but is not a Entity Reference Revision type? Or is the Drupal way to create a custom entity in a module?

Create a custom content entity with entity_reference fields relating each "email" entity to a node and a user.
The information you're saving is neither part of the node's content nor part of the node's metadata. It is metadata about an email that has been sent. Since the email records aren't related to any particular revision of the node, you want the email records to remain even if the node is reverted to a previous revision. So you shouldn't put the email records in a node field of any kind.
Creating a custom content entity is more useful than creating a custom table, because - as you have pointed out - you can make use of the built-in Entity API, which allows you to add field bundles, but also makes it easy to relate your records to node and user entities, and optionally do cleanup if those users or nodes are deleted. If you generate your custom entity using Drupal Console then it will work out of the box with views.


table component for webform is there any module to add "table component" to webform?
I want to have a button to add a row to that table.it means that the rows count not limited and is added number of  user want.

sorry,my English not good ;)

There's now a table component module for webform, take a look to it.


how to inspect the output array from PHPVideoToolkit::getFFmpegInfo() I got the following error message

PHPVideoToolkit Error: Execute error. Output for file "$DOCROOT/sites/example.com/files/private/videos/original/file.flv" was not found. Please check server write permissions and/or available codecs compiled with FFmpeg. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().

How do I inspect the ouput array from PHPVideoToolkit::getFFmpegInfo()?

Quickest way I can think of:

Install the Devel module.
Go to http://mysite.com/devel/php and run the following code:

$info = PHPVideoToolkit::getFFmpegInfo();
dpm($info);

When you run that code you should be presented with a nicely formatted array in the messages area that you can inspect.

If you get an error that PHPVideoToolkit does not exist then find out what file in your installation declares that class, and make sure it's included using either module_load_include() or PHP's include/require.


Twig template for content in body I want to put some custom information in the content area of book pages (so, after the author info and before the add child page, etc. links). In the node template, the content comes in with both the body content and the following links already merged. I've dug through the core template directories and I can't find the template for just the body content itself. Anyone know what it is? Thanks!

The correct answer is you need to look at how to turn on twig debugging
Please read and understand:
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates
once you have fully read the above and have set it up you will be able to find the correct template and copy the default form  the core to your theme and edit away.


What are the differences between Search API/Views and regular Views? What are the differences between setting up Search API (with the Search Views module) and creating a particular set of results with Search Views against using Views is the normal manor?

The big difference I can see straight away is the Search Facets and being able to easily create the blocks that filter/facet the search results.

This question is pretty vague and probably should be blocked.. but I'll take a stab at it.

Search API views have a bunch of different features.  They allow full text search across multiple fields.  E.g. title and body and possible extra text fields all combined in one search filter.

You can set your search api setting to also deal with stemming (e.g. search for learn and also get learning, learns, and the like.

Search API views also allow you to sort by Relevancy.  E.g., if the search terms are found more times, the relevancy is higher.  You can also set up boosts for different fields.  E.g. if the term is in the title or product fields, it has a score of 10 rather then in the body where it has a score of 0.5.

This allows you more control over what shows up at the top of the search.

Search API views can also be set up to return 'excerpts' from the content with the search terms highlighted.  This can be useful in helping people decide if the content is what they want.

There are a bunch of other things that Search API / Views can do, like synonym setups (e.g. orthopedic is the same as orthopaedic).  Weighting specific nodes higher. Many of them may be at the search engine level (e.g. Solr) or require some extra modules (DB Server).

There is also the possibility of setting up auto completion suggestions as well.


How to modify add to cart form in detail Currently add to cart form can be modified from the "manage form display" of the line item. But this place shows all the attributes as a single entry.

Where is the best place to modify the sorting of attributes, inject other elements to the form between attributes etc?

For example I want to show an image field (from product) just before "add to cart" button. Should I use form_alter or is there a twig file that I can readily use?

I realise this answer may be a little late, but for those that end up here looking for a way to display the product variation fields (price, add to cart buttons, etc) separately, you can do it through the commerce-product.html.twig template using something like this:

<article{{ attributes }}>
  {{ product.title }}
  {{ product.body }}
  {{ product.variation_price }}
  {{ product.variations }} //show add to cart button
</article>