Add node reference to Product field with rules I am working on a rule to create a node based on a commerce product after it is purchased. So far I've been successful in creating the entity and filling in fields from the product fields. I am having trouble updating a field within the product to reference the node created by it's sale. I'm not receiving an error, but the product field is not updating. I've tried multiple configurations. Here's the rule exported:

{ "rules_create_projects_from_sold_instrumentals" : {
"LABEL" : "Create Projects from Sold Instrumentals",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules_conditional", "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : { "instrumental" : "instrumental" } },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "CONDITIONAL" : [
            {
              "IF" : { "entity_has_field" : { "entity" : [ "list-item" ], "field" : "commerce_product" } },
              "DO" : [
                { "CONDITIONAL" : [
                    {
                      "IF" : { "data_is" : {
                          "data" : [ "list-item:commerce-product:type" ],
                          "value" : "instrumental"
                        }
                      },
                      "DO" : [
                        { "entity_create" : {
                            "USING" : {
                              "type" : "node",
                              "param_type" : "recording",
                              "param_title" : [ "list-item:commerce-product:title" ],
                              "param_author" : [ "commerce-order:owner" ]
                            },
                            "PROVIDE" : { "entity_created" : { "pr_created" : "PR Created By Instr Order" } }
                          }
                        },
                        { "data_set" : {
                            "data" : [ "pr-created:field-recording-cover-art" ],
                            "value" : [ "list-item:commerce-product:field-cover-art" ]
                          }
                        },
                        { "data_set" : {
                            "data" : [ "pr-created:field-pr-producer" ],
                            "value" : [ "list-item:commerce-product:field-producer" ]
                          }
                        },
                        { "entity_save" : { "data" : [ "list-item:commerce-product" ], "immediate" : "1" } },
                        { "CONDITIONAL" : [
                            {
                              "IF" : { "entity_has_field" : { "entity" : [ "list-item:commerce-product" ], "field" : "field_project" } },
                              "DO" : [
                                { "list_add" : {
                                    "list" : [ "list-item:commerce-product:field-project" ],
                                    "item" : [ "pr-created" ],
                                    "unique" : "1"
                                  }
                                },
                                { "entity_save" : { "data" : [ "list-item:commerce-product" ], "immediate" : "1" } }
                              ]
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  }
]

Any ideas?

You rule seems to be using the Conditional Rules module ... which does not play well with saving entities like your rule seems to be doing.

You should rework those parts of your Rules Actions to performing equivalent Rules Components. After doing so, you have taken away a possible reason why your rule does not seem to behave as you would expect ... and possibly also solved your issue. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

Debugging is the art of taking away all possible reasons why something doesn't work as you'd expect it to work ...

PS: I'm assuming this question is about D7.


Replacement patterns for form fields I have a drupal commerce form and I'd like it to send me an email with all the data from the form the user filled out every time they submit the form.

Is this possible?

Not sure what a "drupal commerce" form is. There are two major kinds of forms in Drupal Commerce, including the add-to-cart form and the checkout form. Both forms include actions in the Rules module that would let you send an email should one of them get submitted.

Here's a rule that proves the point for add-to-cart (though I would not recommend spamming yourself this way):

{ "rules_spam_yourself" : {
"LABEL" : "Spam Yourself",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
  { "mail" : {
      "to" : [ "site:mail" ],
      "subject" : "Product added!",
      "message" : "\/\/ Product\r\nProduct Added: [commerce-product:title] ([commerce-product:sku])\r\nQuantity: [quantity:value]\r\n\r\n\/\/ Order\r\nOrder ID: [commerce-order:order-id]\r\nOrder Number: [commerce-order:order-number]\r\n\r\nOrder Status: [commerce-order:status-title]\t\r\nOrder State: [commerce-order:state-title]\r\n\r\nCreated: [commerce-order:created]\r\nUpdated: [commerce-order:changed]\r\n\r\n\/\/ Customer\r\nCustomer Email Address: [commerce-order:mail]\r\n\r\n\/\/ Actions\r\nCustomer View: [commerce-order:customer-url]\r\nAdministrative View: [commerce-order:admin-url]\r\n",
      "language" : [ "" ]
        }
      }
    ]
  }
}


Create link to users created content only I have a content type Business, When a user creates a business and then signs into the site, I have a link called "my business" that when the user clicks on i want it to take them to only their created business.

Not sure what to "link" too for this to happen.

You can link to a view, that filters the content type Business and the current user.

This is a similar question for D7, I think both solutions provided there work in D8 the same way:

Filtering on node whose user ID is equal to the current user


hide JSON:API endpoint parameters for a client application The Existence
I 'am using the JSON:API core module to serve a  client (react application)
so that each time I have made a back-office modification I  need to reconstruct the URL parameters  ex :

to send the feature image information
?include=field_featured_image

then I have added a paragraph to my article content type so to include the paragraph:
?include =field_featured_image,field_composants

to display specific element in the created parapgraph and not all fields I have use the field set
?include =field_featured_image,field_composants&fields[paragraph--composant]=video

and so on the modification keep going...

then I need to send the new endpoint to the client (ex: react application)
The problem
the client is not up to date with the new URL so each time I made a modification I need to communicate it to the front team.
What do you think about this solution
THE JSON:API parameters will be like BlackBox for the react application :

REACT sends a request to DRUPAL without sending any parameters  ex:
GET /jsonapi/node/article/55d611ab-5752-469a-bf44-648c8cad2a9f
OR
GET /jsonapi/node/article

on kernel.request Drupal takes the request url and alter it by appending the proper JSON:API parmters  to it ex:
/jsonapi/node/article?include =field_featured_image,field_composants&fields[paragraph--composant]=video

NOTE:

for easy administration The JSON:API parameters will be configurable from BO.
The request handler method can change the parameters according to the requested node bundle or according to collection or single entity request

using HTTP client ex(GuzzleHttp\Client) to request the new constructed JSON:API endpoint
$res = $client->request('GET', '/jsonapi/node/article?include =field_featured_image,field_composants&fields[paragraph--composant]=video');

problem: for each request instead of a single request I Nedd to execute 2 requests.

4.then send a response to the client :
$event->setResponse($response );
note: for a technical reasons I prefer to keep using JSON:API and not creating custom rest endpoints.

Rather than the JSON:API I would go with the REST resource plugins. Here you are basically only writing controller methods and return what you want. That is already part of the Drupal core:
https://www.drupal.org/docs/drupal-apis/restful-web-services-api/restful-web-services-api-overview
Here is a code example (ServicekontoResource.php):
<?php

namespace Drupal\fms_api\Plugin\rest\resource;

use Drupal\fms_api\Exception\ServicekontoApi\NoServiceKontoResponseException;
use Drupal\fms_api\ServicekontoApi;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\servicekonto_integrator\Exception\ServicekontoResponseStorageException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * @RestResource(
 *   id = "servicekonto_resource",
 *   label = @Translation("Servicekonto resource"),
 *   uri_paths = {
 *     "canonical" = "/fms-api/servicekonto-data/{session_hash}"
 *   }
 * )
 */
class ServicekontoResource extends ResourceBase {

  /**
   * @var \Drupal\fms_api\ServicekontoApi
   */
  private $servicekontoApi;

  public function __construct(array $configuration, string $plugin_id, array $plugin_definition, array $serializer_formats, LoggerInterface $logger, ServicekontoApi $servicekontoApi) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->serializerFormats = $serializer_formats;
    $this->logger = $logger;
    $this->servicekontoApi = $servicekontoApi;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('fms_api.servicekonto_api')
    );
  }

  public function get(string $sessionHash) {
    try {
      return new ResourceResponse($this->servicekontoApi->provideData($sessionHash));
    } catch (NoServiceKontoResponseException $exception) {
      $response = new Response('Could not retrieve dataset of service konto response.', 500);
      return $response;
    } catch (ServicekontoResponseStorageException $exception) {
      $response = new Response($exception->getMessage(), 400);
      return $response;
    }
  }

}


Drupal 7 video player for stream I'm using JW Player for playing video files and it's working great.

Is it possible to play video streams with this player?

I already have a rights to stream and link for a TV station. It's in this format: http://XX.XXX.XXX.XXX:9090/stream.flv

How can I set this link for stream?

If you know some alternative player with possibility of live streaming, please let me know.

JWPlayer does streaming.

http://www.longtailvideo.com/jw-player/hls-rtmp-live-streaming

I wasn't able to find a module that did this, but you can add this to your page, using the Full HTML text input:

Loading the player


Excluding specific user role from query I have this query, which fetches all users with the role #7.

$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';

$result = db_query($query, array(':rids' => array(7)));

Some users currently have both roles #7 and #8. I beleive they are all fetched by this query. I would like to exclude users with the role #8.

Can someone help me?

Try

$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids) AND ur.rid NOT IN (:rids2)';

$result = db_query($query, array(':rids' => array(7), ':rids2' => array(8)));

Or if you wanted just the more specific version

$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid = (:rids) AND ur.rid != (:rids2)';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));


How to override the display of a field in a view: is preprocessing possible? I want to override the display of a field in a particular view, so that rather than printing:

Content here

I just want:

Content here

Is this something which is best done in a template (I assume):

views-view-field--view-name--field-tagline.tpl.php

Edit: I've solved this using the above template, and then removing the wrapping elements from the view in via the Views UI. If using preprocessing is more performant, I'd still be interested to know, so please drop a line below if so. Otherwise, this question is solved.

I would suggest implementing the Semantic Views module. This allows you to easily customize the HTML that Views outputs for each level of elements (the entire view, row wrappers and field wrappers) from the UI. It is a bit easier to use and maintain than custom templates and preprocess functions.


Change the way a node is themed based on an argument added to a URL I am currently trying to eliminate my need for the panels module from a site I am working on and don’t have a lot of PHP experience. How would I go about changing the way a node is displayed based on an argument added to a URL? (E.g. http://example.com/node/123/argument.) I already have the node type themed but I need to display the node in a different form based on the argument. Thanks in advanced for your help.

one solution is to use Views. Create views page, for path add node/%/argument, choose Content on Format Show and View mode you want. See Entity view mode module for ability to add more View modes per entity. Add one to Article named "Custom view" for example. Add next code in template.php (change THEME to your maschine theme name).

function THEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . $variables['view_mode'];
}

Then copy node.tpl.php to node--custom-view.tpl.php in current the dir - if your already add new view mode with name "Custom view" and edit node view template as you want.

To have node--Content-Type--View-Mode.tpl.php like node--article--custom-view.tpl.php the above code must be

function THEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];
}

EDIT:

Programmaticaly solution with code in custom module:

function HOOK_menu() {
   $items['node/%/argument'] = array(
    'page callback' => 'node_custom_view',
    'page arguments' => array(1, 2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function node_custom_view($arg1, $arg2) {
  $content = '';

  if (is_numeric($arg1) && $arg2 == 'argument') {
    $node = node_load($arg1, $vid = NULL, $reset = FALSE);
    $content = drupal_render(node_view($node, $view_mode = 'custom_view', $langcode = NULL));
  }

  return $content;
}

"custom_view" is our custom display for node created by Entity view mode module, then we enable this for content type from Manage display


View filtering, Relationship Vs Contextual filter I used contextual filters before and I know they are just like the normal filters but more dynamic, now I have this view "Sidebar Product advert block" that needs to show the product advert ( Similar to product teaser! advert is a view mode ) BUT only if the product is referenced in the field_product_teaser in the article data type. So to be more clear:

Articles have a reference entity (Autocomplete) field_product_teaser.

Products referenced in this field should appear in the sidebar!

So the condition is {{ product.Product-id == article.field_product_teaser }}

I hope that was clear enough, what should I use in this case ?? contextual filters? relationships? I tried using both with no luck!

You should use the contextual filter to identify the article the block is being displayed on.  E.g. content id from URL should work.

Then you should use the relationship option to link the field_product_teaser info to products.  E.g. Content referenced from field ....

Then in the view, you can select the product fields you want to display and use the reference to tell views what you want displayed. E.g. title w/ product reference relationship = product title.


Theming: when I use a smaller device, my main content goes behind my sidebar I am making a sub-theme from the basic theme for Drupal 7. The side bar works fine on all sizes above 480px in length, but on 480px or below, my content goes behind my sidebar and there is a horizontal scrolling bar. I can see the content when I scroll, but I want all the content to fit in the main content area and not in space to the left or extra space to the right. I set my sidebar to the css code of

position: fixed;

I took out the media selection of 480px for the content, and everything seemed to be working. I narrowed it down to a width: 100%. (inside of the media entry of course) After taking this out, everything was good to go.


Custom redirect specific page after edit With my Drupal website ( which is much more custom than drupal ) I've got node referenced in another ( ex. an article in a custom page ).

I want the ability to easily edit the referenced content. To do that I've put a button with the link:

<?php print $base_url; ?>/node/<?php print $article->nid; ?>/edit?destination=<?php print urlencode('node/'.$node->nid); ?>

Sadly Drupal doesn't care about the destination and redirects me to the article node and not the current node it was into.

It is always a good habit to use l() to create links in Drupal. In your case, you can use the below code to create link.

l(t('Title'), 'node/' . $article->nid . '/edit', array('query' => array('destination' => 'node/' . $node->nid)));


Drupal7 provoking ajax error in Views (installed in sub folder) I have installed drupal 7 in a subdirectory of my domain. The subdirectory is masked as explained on the following site: http://kahthong.com/2011/05/how-serve-drupal-sub-directory-web-root-0

Now, this works pretty well EXCEPT when an AJAX query is done by the drupal backend. This will always produce an error. One example is in the Views-UI module: when I try to edit some setting in a view, an error like the follow will pop up:

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: ***mydomain****/en/admin/structure/views/ajax/display/store/page/row_options
StatusText: error
ResponseText:
ReadyState: 0

My guess is that the URL rewriting specified in the .htaccess is not being applied. Therefore my two questions:

Why does the URL rewrite not work for AJAX queries
How can I fix this?

I have found that my problem is distinct: the AJAX request has included the www in front of my domain meanwhile I have set the default without www.

So I had to change in settings.php the base_url FROM 'http://www.mydomain.com' TO 'http://mydomain.com'

Cheers


Get active trails's siblings in menus I'm developing a custom theme using sub-theme just for learning purpose. In custom theme, I have added a custom block in which I need to display main menus' sub items if in_active_trail. I have already tried many times and wasted a lot time but unsuccessful.

Block should display when Level 1 is in_active_trails and it has child(s).
Block should not display when Level 1 in_active_trails but it has no child.
If any Level 2 is current page, display Level 2 and 3 menu items expect level 1.
Same as point 3, if Level 3 is current page then display level 3 and 2 items.

See attached image below for more understanding what I want to do.

Main Menu hierarchy

Here is the solution Menu Block. Install and configure it.

It works for me.


resave all taxonomy terms by vbo I have a site with a large number of taxonomy terms. Now I need to add meta keywords and meta description to all of this terms.
My solution is :

Resave all terms by VBO module.
Create a rules on "before saving taxonomy term".
The created rules execute a PHP code which adds meta keywords and meta description to each of the tags.

In this way when VBO is resaving terms one by one my rules is executed for each of theme and do the trick.

Now the problem is in step one. I have an "execute arbitrary PHP script" operation in VBO for terms. I use this code in it:

taxonomy_term_save($entity);

but I face this error:

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /backup-sar/batch?id=412&op=do StatusText:
  OK ResponseText: Fatal error: Function name must be a string in
  C:\xampp\htdocs\backup-sar\sites\all\modules\views_bulk_operations\actions\script.action.inc(20)
  : eval()'d code on line 1

This one with the same error does not work too:

taxonomy_term_load($entity->tid);
taxonomy_term_save($entity);

Any help would be appreciated. Thanks in advance.

If you're executing the VBO operation while in the Views configuration page, you're likely to run into this error. Save your view and go to the URL for that view and then run the operation.

A 200 return code actually indicates success, but the presence of the AJAX debugging screen interferes with the completion of the operation.

I know because I just ran into a nearly identical issue. :-)


How can I use aggregation in multiple field in view I want to group by multiple field but I don't know how it works.

In my view, I have :

Code A | cmd Date | Quantity | Price A | Total |

And I want to regroup by Code A then regroup by cmd Date.

For each CodeA I have multiple order in the same month and I want to regroup them, then sum quantity and total. Like :

|Code1 | 09/2015 | 15 | 5 | 75€ |
|----------|10/2015 | 10 | 5 | 50€ |
|Code2 | 08/2015 | 11 | 7 | 77€ |
|----------|11/2015 | 10 | 7 | 70€ |

Someone can help me ?

Thanks

First you have to enable fields in your view. Then in your formatting settings you can now use "group by". You can also use more than one grouping field. Hope it will help!


How do I access the array of label values? I can access the value of fields in my template using $view->style_plugin->rendered_fields.

How do I access the array of label values in my template file?

$datas = $view->style_plugin->rendered_fields;
print_r($datas);

// Response
// Array ( [0] => Array ( [field_company_name] => Google [field_registered_address] => USA ) )

The field definitions are in a slightly different place, you can extract all labels with something like this:

$labels = array();
foreach ($view->display['NAME_OF_DISPLAY']->display_options['fields'] as $definition) {
  $labels[] = empty($definition['label']) ? 'No label' : $definition['label'];
}


Do page arguments in hook_menu get sanitized? The title pretty much says it all.

If a callback is defined in a hook_menu, such as

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

    $items["mymodule/foo/%"] = array(
        "page callback" => "mymodule_foo",
        "page arguments" => array(2),
        "access arguments" => array("mymodule permission"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function mymodule_foo ($parameter)
{
    // do stuff
}

When the callback gets called, has $parameter been sanitized, or is this the responsibility of the module?

I always sanitize in the module, but have never seen this stated either way and haven't found where callbacks get called from core.

In D6

menu_execute_active_handler() calls the callback. However it gets it's arguments from menu_get_item(), which uses arg.

I can't see any sanitizing in any of that. So it looks like the answer is no.

In any case extra sanitizing can't hurt.


Accessing field values in node--mycustomtype.tpl.php I have a content type that contains a field called headshot. This is a file field. In my custom node template file, I need to access the value of the headshot's filename property. dpr($content) produces this for the field:

[field_headshot] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [fid] => 53
                                            [display] => 1
                                            [description] =>
                                            [uid] => 10
                                            [filename] => kanderson.jpg
                                            [uri] => public://headshot/kanderson.jpg
                                            [filemime] => image/jpeg
                                            [filesize] => 21669
                                            [status] => 1
                                            [timestamp] => 1337356962
                                            [type] => image
                                            [rdf_mapping] => Array
                                                (
                                                )

                                            [image_dimensions] => Array
                                                (
                                                    [width] => 180
                                                    [height] => 252
                                                )

                                        )

                                )

                        )

I've tried

<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot'][0]['filename']); ?>" alt="<?php print $title; ?>" />

and

<img class="speaker_headshot" src="sites/default/files/styles/large/public/headshot/<?php print render($content['field_headshot']['filename']); ?>" alt="<?php print $title; ?>" />

with no success. How do I access this property?

To get a web-accessible URL for the file you need to use file_create_url() on the field's uri property. You can also make use of theme_image() so you don't have to write the HTML yourself:

$vars = array(
  'path' => file_create_url($content['field_headshot'][LANGUAGE_NONE][0]['uri']),
  'alt' => $title,
  'attributes' => array(
    'class' => array('speaker_headshot')
  )
);

$img = theme('image', $vars);

print $img;

Since this code will clutter up your template file you might want to consider putting in a preprocess function instead, something like:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'headshot') {
    $items = field_get_items('node', $vars['node'], 'field_headshot');
    $image = array_shift($items);

    $image_vars = array(
      'path' => file_create_url($image['uri']),
      'alt' => $vars['title'],
      'attributes' => array(
        'class' => array('speaker_headshot')
      )
    );

    $vars['image'] = theme('image', $image_vars);
  }
}

Then in your template file you can just print $image; to get the HTML output.


In hook_user_presave how to check if account is being activated and account is new? Currently in Drupal 7 I have two conditions in hook_user_presave,
1. Is account is being activated
2. Is account new

function hook_user_presave(&$edit, $account, $category) {
    if (isset($account->is_new) && !empty($account->is_new)) {
        //If account is new then execute my code here
    }

    if ((isset($account->uid)) && (isset($account->status)) && ($account->status == 0) && ($edit['status'] == 1)) {
        //If account is being activated for the first time then execute my code here
    }
}

I want to convert this code to Drupal 8, What should be the conditions?

function hook_user_presave($account) {

    //Condition 1

    //Condition 2
}

Is there any other way to achieve this?
Any help would be appreciated. Thanks.

To check if the user is new:

$account->isNew()

To check if the user is active:

$account->isActive()

See User API isNew or User API isActive for more information.


EntityFieldQuery return nodes with all terms I have form that allows a user to filter a list of results.  The filter is set using checkboxes.  EntityFieldQuery is used to retrieve the results based on taxonomy ids.  The problem is that if multiple checkboxes are selected, it returns all nodes tagged with any of the taxonomy ids, while I want only the nodes that are tagged with ALL of the taxonomy ids.  This includes terms that are from multiple taxonomies.

These are the definition of the field conditions in my EntityFieldQuery:

$query->fieldCondition('field_section', 'value', $sections, 'IN');

$query->fieldCondition('field_features', 'tid', $params['features'], 'IN');

$query->fieldCondition('field_region', 'tid', $params['regions'], 'IN');

Basically, when checking on items in the filter it returns MORE items, when it should go the other way.

Does anyone know how to adjust the EntityFieldQuery so it does what I'd like?

Thanks in advance

You can try:

foreach ($sections as $section) {
  $query->fieldCondition('field_section', 'value', $section);
}


Position Block Below Content but Above Editor I have created a block for a horizontal ad. I positioned it in the Content region and as you know I can display it either above the content or below everything. However, I would like it positioned above the editor (or comments area), not above it all.

I have found this pots but I am using an Omega-based theme and I see under the all/themes/omega/templates folder that there are "region.tpl" files so I assume here is where I add it, not in a node.tpl.php file.

Omega based themes still allow for custom regions and various *.tpl.php files. There is probably a node.tpl.php theme file in the base theme thats inherited by the subtheme your using.

The code doesnt go in the tpl.php file it goes in the preprocess function:

  How to display block in node above comments. What i have tried is:
  create region - regions[above_comments] = Above comments after in
  template.php i have added this to THEME_preprocess_node

You then output the correct block within the specific region of the theme. In the linked page they created a region called Above comments in their theme. They set a block to that region using the Blocks Admin UI and rendered it using block_get_blocks_by_region using the theme preprocess function.


Which Drupal versions are affected by the vulnerabilities in advisory PSA-2016-001? There is an PSA about the 2016-July-13 Security Advisory of several critical updates:

  View online: https://www.drupal.org/node/2764899

  Advisory ID: DRUPAL-PSA-2016-001
  Project: Drupal contributed modules
  Version: 7.x
  Date: 2016-July-12
  Security risk: 22/25 ( Highly Critical)
  AC:None/A:None/CI:All/II:All/E:Theoretical/TD:All 1
  Vulnerability: Arbitrary PHP code execution

  DESCRIPTION

  There will be multiple releases of Drupal contributed modules on
  Wednesday July 13th 2016 16:00 UTC that will fix highly critical
  remote code execution vulnerabilities (risk scores up to 22/25 [2]).
  The Drupal Security Team urges you to reserve time for module updates
  at that time because exploits are expected to be developed within
  hours/days. Release announcements will appear at the standard
  announcement locations. [3]

  Drupal core is not affected. Not all sites will be affected. You
  should review the published advisories on July 13th 2016 to see if any
  modules you use are affected.

The advisory only mentions version 7.x as vulnerable, but I realized that I'm not entirely sure how I can interpret that. My interpretation is that Drupal 8.x should not be affected by these issues. But I'm really not sure about Drupal 6.x.

Drupal 6 is no longer supported. Does that mean that this kind of advisory won't even mention if it is still vulnerable? Or can I interpret this one as only version 7 is affected?

Which versions exactly are potentially affected by this advisory?

The security team is intentionally a bit circumspect with these warnings. They either have to catch us all flat-footed or give potential attackers a heads up that something worth their time is coming. Currently they are siding with the latter method (and as much as I hated seeing that message today I agree with them).

For the most part it will not be clear until they release the news what modules will be covered. There is already speculation in some circles, but there isn't likely anything to be done before the announcement. Clearly from their announcement multiple modules are effected, and likely at least one is something very common.

Depending on the number of sites you support you should block off enough time to do updates for all of them.

These advisories will no longer cover Drupal 6. There is no formal way to know if Drupal 6 is effected (there will probably twitter comments, blog posts, etc about it after the release of the updates). If D6 is effected the only solution may be to take them offline.


How can I link one drupal View field (an image) to a QuickTab? Im trying to link each image field of my view to a quicktab that I created. This is my view

and this is how it looks

As you see I already tried to put the url link and rewrite the stuff, I put content and nothing to the image (the part of the landing), I even tried to put it as an external link, but it never recognize it as a link.

I got it!
What I did:

Create 2 different content types for each image.
Then I did add each one as a field.
Then I played with Filter criteria, adding a taxonomy term previously in my content type.

Then I did rewrite the results of each field (each image) to land to the page that I wanted.
Finally I did create the basic pages inserting in each one the Quicktabs that I needed.

And voilá! that was all :D

Thanks


How do I create a variable to check last time hook_cron() implemented from a custom module was ran? We have a custom module for which we need to run on a daily basis. I am not sure  it is working, as I am unable to store the time correctly.

Does the following code allow me to create a variable, and use it to store the last time cron ran?

function mymodule_cron() {
  if (variable_get('mymodule_last_run', 0) <= strtotime('-1 day')) {
    // Omissis.
    variable_set('mymodule_last_run', time());
  }
}

function mymodule_info($options) {
  $variable['mymodule_last_run'] = array(
    'title' => t('Last Run', array(), $options),
    'type' => 'datetime',
    'default' => t(time(), array(), $options),
  );
}

You are implementing the wrong hook. What you are trying to implement is hook_variable_info(), used from the Variable module. Hook name apart, that hook implementation seems correct.

Instead of using variable_set(), you should use variable_set_value(). The equivalent of variable_get() is variable_get_value().

See the project page for more information about how to use the module API,  Variable API for a list of available functions, and variable.api.php for a list of hooks used from the Variable module.

The code you want to use should be similar to the following one.

function mymodule_cron() {
  if (variable_get_value('mymodule_last_run') <= strtotime('-1 day')) {
    // Omissis.
    variable_set_value('mymodule_last_run', REQUEST_TIME);
  }
}

function mymodule_variable_info($options) {
  $variable['mymodule_last_run'] = array(
    'title' => t('Last Run', array(), $options),
    'type' => 'datetime',
    'default' => 0,
  );
}

Notice that variable_get_value() doesn't need the default value, since it gets it from the hook_variable_info() implementation done from your module. If you need to use a different default, you call the function as variable_get_value('mymodule_last_run', array('default' => REQUEST_TIME).

As for your original code, you don't call t() as t(time(), array(), $options) because:

The first argument of t() must be a literal string, not the value returned from a function
time() returns an integer; even if it would be casted to a string, t() doesn't change an integer in any way, for example returning '1,000' when receiving 1000 as first argument.

If the Variable module is expecting a string (e.g. '19700318T19:00') as default value for a variable of type datetime, you need to use a different function.


Autofill texfields based on select option in dynamic fieldset In my custom form i am dynamically generating multiple fieldsets.Each field set has select option(dropdownlist) and textfield generated dynamically. The value for textfield is dynamically generated based on user selected value from select option.

My problem is that if i select species from fieldset2 then density texfield1 in fieldset1 is overwritten and density textfield2 in fieldset2 is empty which is wrong. Each time the ajax callback return value is overwriting textfield1 in fieldset1(Field#1)

function fuel_design_tool($form, &$form_state) {
$form = array();
$form['#tree'] = TRUE;

if (empty($form_state[FIELDS_NUM])) {
    $form_state[FIELDS_NUM] = 1;
}

for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++) {

    $form['field'][$i] = array(
        '#type' => 'fieldset',
        '#title' => t('Field #@num', array('@num' => $i)),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,

    );

    $form['field'][$i][FORM_FIELD_SPECIES] = array(
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => 'Choose Species',
        '#options' =>  _load_species1(),
        '#default_value' => 0,
        '#ajax' => array(
             'callback' => 'fuel_design_tool_callback',
             'wrapper' => 'fuel_design_tool-wrapper',
             'event' => 'change',
           )

       );

      $profile = isset($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) ? ($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) : NULL;
    $form['field'][$i][FORM_FIELD_DENSITY] = array(
        '#type' => 'textfield',
        '#prefix' => '
',
        '#suffix' => '
',
        '#title' => t('Density'),
        '#value' =>$profile,

    );
    $form['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add More fieldet'),
    '#submit' => array('fuel_design_tool_add_name')
    ),

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

     return $form;
 }

 function fuel_design_tool_add_name($form, &$form_state) {

    $form_state[FIELDS_NUM]++;
    $form_state['rebuild'] = TRUE;
   }

function fuel_design_tool_callback($form, &$form_state)
 {
   for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++)
   {

  $form['values']['field'][$i]['FORM_FIELD_DENSITY'] = $form_state['values']['field'][$i]['FORM_FIELD_SPECIES'];
  return array (
    $form['field'][$i]['FORM_FIELD_DENSITY'],

   );
  }

 }
 }

My callback function returns only one value and that by default filled to fiedset#1 textfield.I guess i need to modify my callback function.

I am looking forward for your kind help.

If my question is not clear please let me know. I am finding bit difficult to explain this problem

Give the textfield wrappers unique ids, e.g. fuel_design_tool-wrapper-1 and fuel_design_tool-wrapper-2, and assign accordingly in the FAPI array.


Views exposed filters - how to show "You searched for [exposed filters]" above results? I'd like to summarize the current filters used on the data in the results.

What's the easiest way to do this?

[ ] Cats
[x] Dogs

[Search]

You searched for Dogs

===============================
Lassie        Movie star
Bones         Runner
Hobbes        Show-dog

Thanks!

Use the Exposed Filter Data module. With it you can print the filters used in the view header.


Include email attachment in new content Rule I'm trying to send an attachment within a rule I've set up for new content notification.  I have the requisite modules installed: Mail System, Mime Mail, etc.  I've set the rule up to send HTML mail to users of a role, specified the body content, and the attachment in the following manner...

I've tried various incantations of the attachments value by changing the token.  The file I'm trying to attach is an Excel file attached to an article.  The email notification does get delivered, and, appears to have an icon indicating an attachment.  However, when I open the email, the body text is correct, but, there's no attachment.  From the research I've done, I've found that attachments seem to be an enigma.  Some posts I've read imply that I need to do some coding to get this to work.  Seems like I shouldn't have to.  Can anyone shed some light on how to attach a file correctly?

If anyone else is struggling with this problem (and, I did find quite a few that were), I've found a work around.  First, it appears like this may be a known bug.  Given that, I found the work around at #25 worked for me.  In my case, I had to tweak the attachments value in the rule to look like this...

[node:field-file-attachments:file:path]

Note: no preceding path was required.  With the above, I now get attachments in emails that are generated via a rule.


How do I add a Site Information variable and make it multilingual? So I've used form alter to add in a site information variable (which auto-saves because it's a system_settings_form), but I can't seem to get it to show up as multilingual.

Here is my form alter to add the field:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function omm_form_system_site_information_settings_alter ( &$form, &$form_state ) {
    // Add field in Site Information area of admin configuration.
    $form['site_information']['site_pretitle'] = array(
        '#type' => 'textfield',
        '#title' => t('Site Pre-Title'),
        '#description' => t('This will appear above the website name on all pages.'),
        '#default_value' => variable_get('site_pretitle', ''),
        '#weight' => '0',
    );
}

Edit: I've solved this already, but need 8 hours to post the solution because I'm new.

So I managed to solve this after searching through Drupal's code and the Variable module. Turns out if you add a call to hook_variable_info, it will add it into the multilingual variables list, and then if you check that off, it makes it translatable like the rest of the Site Information.

/**
 * Implements hook_variable_info().
 */
function omm_variable_info($options) {
  // Site configuration, site information
  $variables['site_pretitle'] = array(
    'type' => 'text',
    'title' => t('Site Pre-Title', array(), $options),
    'default' => '',
    'description' => t("This will appear above the website name on all pages.", array(), $options),
    'group' => 'site_information',
  );

  return $variables;
}

After adding this, go to admin/config/regional/i18n/variable and click on the Site information group.  Click the checkmark beside your variable (site_pretitle for mine), and hit Save configuration. Once that's done, return to the Site Information area (admin/config/system/site-information) and you should see it appear and say This is a multilingual variable. in bold.


Access the label for a form element via hook_form_alter I have a form with id equal to webform_client_form_3.  I have a particular field that I'm altering by applying a class to it like so:

$form['submitted']['estimated_annual_distribution_of_effort']['sensor_technology']['#attributes']['class'][] = 'span1';

This all works great.  However, I also need to add a class on to the label for that particular element as well.  Looking through the $form array, I haven't been able to find anything that gives access to the labels.  Am I just missing something or are the labels not part of the $form array?

The attributes for labels are hard-coded into the theme_form_element_label() function. You can override it at the theme/module level but you'll have to do so for all labels in the system as the variables passed to the theme function do not contain the form context.

The easiest thing to do would be to add a predictable class to each label in every form (based on the name of the form element that the label is for), and then use a CSS selector based on a combination of your form ID and the label class to target it.

Unfortunately there's a fair bit of code you'll need to copy over, and only one small change you'll need to make, but I can't think of another way to do it:

function MYTHEME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // NEW CODE HERE
  $label_class = 'label-for-' . $element['#id'];
  $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' ' . $label_class : $label_class;

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

Once you put that code in your theme's template.php file and clear the cache, you'll be able to target the label with CSS like so:

form#webform_client_form_3 label.label-for-edit-field-name


How do I reset a user's name using Drush in Drupal 7? To change a password I would use:

drush user-password USERNAME --password="SOMEPASSWORD"

Is there a similar way to change a user's name using Drush from the command line?

There isn't a built in Drush command, but you can use Drush's sql-query command (or sqlq shorthand) to update the user's name:

drush sql-query "update users set name='SOMENEWNAME' where uid=####"

Where #### is the user's uid and users is the user table.


How to change end date automatically after changing start date? I would like to be able to automatically change the value of the end date to be the same as the start date after changing the start date.

Ex: right after changing the start date to 12-12-12, the end date would be the same.

Here's what I did so far:

Added the following code in a custom module (form_modif) :

$form['#attached']['js'][] = drupal_get_path('module', 'form_modif') . '/custom_alter.js';

Witch seems fine, I can see that the script is added in the code source of the page

The JS file's code is :

(function ($) {
  Drupal.behaviors.form_modif = {
    attach: function(context, settings) {
      $('.field_date_1').change(function(){
        $field_date1 = $(.FIELD_DATE_2').val();
        $('.field_date_2').val($field_date1);
      });
    }
  };
});(jQuery);

And that's where my problem seems to be, I'm not very good in JS, could someone help me with that?

Here's the HTML code of thoses fields if that can help:

Start date field:

<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-date-und-0-value-datepicker-popup-0" name="field_date[und][0][value][date]" value="31/01/2014" size="20" maxlength="30">

End date field:

<input class="date-clear form-text hasDatepicker date-popup-init" type="text" id="edit-field-date-und-0-value2-datepicker-popup-0" name="field_date[und][0][value2][date]" value="31/01/2014" size="20" maxlength="30">

I did it the way pretty much mentioned in question with some corrections.

My code with javascript file is

// Change the end date value to same as that of start date.
Drupal.behaviors.form_modif = {
  attach: function (context, settings) {
        $('input#edit-field-event-date-und-0-value-datepicker-popup-0').change(function(){
        var field_date1 = $('input#edit-field-event-date-und-0-value-datepicker-popup-0').val();
        $('input#edit-field-event-date-und-0-value2-datepicker-popup-0').val(field_date1);
    });
  }
};

}(jQuery));


Within my themes page.tpl.php file it has a reference to a lot of variables like $head and $local_styles. What file are they stored in? Within my themes page.tpl.php file it has a reference to a lot of variables like $head and $local_styles.
What file are this variables stored at so that I can looked at what each of these variables represent?
John

The values are not stored at all. Instead they are generated dynamically at run time and feed into the template. The list of variables is just there so you will know which variables exactly are available in any particular template.

If you want to examine their content, you can add

drupal_set_message(print_r($variable, TRUE));

to the template, and simply load the page. If you install the Devel module, you can get much easier to read output like this:

dpm($variable);

I frequently use dpm in my everyday work when debugging or building new code.


Is there a nicer way of getting my nodes language and text direction? My site is almost entirely in English, but with individual pages in different languages. There's one extra page per language other than English, as a single page "this is a summary of the sites information in your language" sort of deal.

I've used the Drupal "language" module to set up some languages and give some nodes a language other than English. I don't really want anything more complicated than this. Specifically I don't want:

To translate the entire site to any other language.
To allow users to pick their language.
To translate anything other than node (single page) content. Menus,
site slogan, etc, will always be in English.

When viewing the pages for those nodes, I want to set some CSS classes and in some cases the text direction (rtl for Arabic / Urdu / Hebrew) based on the nodes language.

For some reason, the global $language variable is always set to English, regardless of the node language.

I can get the nodes language from $node->language and work out my CSS classes and text direction with the following code in my page.tpl.php:

<?php
    $node_lang = 'en';
    if (isset($node) && isset($node->language)) {
        $node_lang = $node->language;
        $rtl = ($node_lang == 'ar' || $node_lang == 'ur' || $node_lang == 'he');
    }
    $en = ($node_lang == 'en' || $node_lang == 'und');
?>
<div id="content"
    class="primaryContent <?php if($rtl){print "rtl";}?>"
    <?php if ($rtl) { print "dir='rtl'"; } ?>
    <?php if (!$en) { print "lang='$node_lang' xml:lang='$node_lang'"; } ?> >
...content...
</div>

Is there a simpler or "more recommended" way of doing the above? Doing my own detection of rtl / ltr feels fairly brittle.

If $node is the variable containing the node object, you can use code similar to the following one:

$languages = language_list();
if (isset($languages[$node->language])) {
  $rtl = $languages[$node->language]->direction == LANGUAGE_RTL;
  // $direction = $languages[$node->language]->direction ? 'rtl' : 'ltr';
}

If you need to use the string "rtl" or "ltr" basing on the direction associated with the language, then you can use $direction, instead of $rtl.


Create new content node upon user creation with populated fields from user profile fields d7 why is it that ordinary tokens appear in fields where use is made of the "token field" and "field default token" modules?

I created a rule which creates a node with the username in the user creation form. I need to have fields in this new node to be populated by custom fields in the user creation form using tokens.

ordinary tokens work fine, tokens from custom fields either turn out as blank for the "field default token" module or as the token name in "token field" module.

Am I missing something?

More Information as requested in the comments:

I have custom fields on the standard user profile. When a user account is created, a content node is created, using the "rules" module. That node's name is pulled off the user profile using the "token" module, the token being for one of the custom fields. This works 100%. Now I want to do the same for two fields in the new content node, i.e. pulling content from the user profile's custom node's and placing them into the content node. This can be done with "field default token" or "token field". For some reason only standard drupal tokens work, tokens for custom fields don't, as described.

This seems to have to do with porting data from a content node field to a user node field. I solved this by creating the User and then creating the node with data pulled from the user node fields.


Override a file from the parent theme Adding in the child theme a CSS file with the same name as the parent theme CSS file overrides the parent file. It doesn't seem to work JavaScript files.

How can I override a JavaScript file loaded from the parent theme?

You can use hook_js_alter to replace your JS file (from parent theme) with the one in your child theme.
function child_theme_name_doc_js_alter(&$javascript) {
  $javascript['themes/parent_theme_name/js/parent_theme_name_navigation.js']['data'] = drupal_get_path('theme', 'child_theme_name') . '/js/child_theme_name_navigation.js';
}


How to add link to create relationship in a view In my project, I have user relationship module installed. I created a view of online users. I then tried to include a link to enable users "add friends or create relationship" in the view by adding the following code

 global $user;
  $opt = '';
  $requestee_id = $row->uid;
  $requester_id = $user->uid;
  if (user_is_logged_in()) {
    if ($requestee_id != $requester_id) {
      //for friend request button
      $relationships = user_relationships_load(array('between' => array($requester_id, $requestee_id)));
      if (empty($relationships)) {
        $opt = l(t('Add Friend') , "relationship/$requestee_id/request/1", array('html' => TRUE, 'absolute' => TRUE, 'query' => array('destination' => 'user/' . $requestee_id), 'attributes' => array('class' => array('ur-link add-friend-btn user_relationships_popup_link'))));
      }
      else {
        foreach ($relationships as $relationship) {
          if ($relationship->approved == 1 && user_relationships_ui_check_access('view', NULL, $relationship)) {
            $opt = t('Friends');
          }
        }
      }
    }
  }
  print $opt;

When I try to create a relationship, i am informed that "this user does not exist". Please what could I be doing wrong.

P.S: I have 2 relationships on my site.
Thanks in anticipation.

I found out this could be done without writing custom code.

In the view:

I added a field, User:uid.
I unchecked "create a label" and "link this field to its user"
Using Rewrite results, i checked Rewrite the output of this field and input "Add as friend".
I checked the "Output this field as a link" and then added the path www.example.com/relationship/[uid]request/1?destination=user/[uid]

That solved the issue.


When does hook_node_access() get invoked for $op == "create"? When does hook_node_access get invoked for $op == "create" ?  In other words, at what portion of the node creation process is this permission checked?  I am not seeing anything in the API does about this.

I have a situation where I need to restrict a subset of users to only be allowed to create/edit content with a particular taxonomy term based on their user profile.  I have the $op == "update" and node form logic all worked out, and am not sure what I need to do about $op == "update"

Thanks.

It gets called from _node_add_access(), which is the access callback for the node/add path (see node_menu()):

foreach ($types as $type) {
  if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
    return TRUE;
  }
}

node_access() has this line in it:

$access = module_invoke_all('node_access', $node, $op, $account);

Which is when hook_node_access() is actually invoked.

To answer your question, it's called before the node add form is ever displayed to a user; obviously if it returns FALSE then access is denied to the form.


How to change content type Title? I am creating a Student portal in my project.

I am adding student by using content type.

That i gave title as "ADD STUDENT" as a Content name, but it shows "Create ADD STUDENT".

Help me to show the tile as "ADD STUDENT"

Here the [Key Personnel] Comes as [Create Key Personnel], i just want it as [Key Personnel]

You could use hook_preprocess_page() in a module:

function MYMODULE_preprocess_page(&$variables) {
  if (arg(1) == 'add' && arg(2) == 'add-student') {
    $types = node_type_get_types();
    $name = $types['add_student']->name;
    drupal_set_title("Add $name");
  }
}

I'd suggest setting your content type's display name to "Student" rather than "Add Student." You should just need to put the machine name of your content type in place of 'add-student' and 'add_student'


Custom fields per page I need to create a site that is editable for the client. The site is pretty basic: home, about, contact, etc. On each page there are different blocks of text. Like on my homepage, I have different sections like a basic text, "3 reasons" boxes, etc.

I have a content type "pages" with the title and the basic text, which is fine. But how do I create the 3 boxes? Do I create a custom content type for them too? If so, how do I add them on the front page with the text as well?

I heard a bit about the Views module. Would it be useful in my case?

If you are using D6, you need to install the cck module to add custom fields to nodes.

But, if you are using D7, cck has been migrated into drupal core. You can easily create custom fields for each content type at the path admin/structure/types/manage/{content-type-name}/fields. For your page content type, go to admin/structure/types/manage/page/fields.

I think your case is not concerned with the views module. You can generally check what is views here.

AFAIK, there is no module to create different custom fields per node. We can only create custom fields per content type.
If you are sure you have static numbers of page ( such as page, about, etc. ) and if you will not allow your client to add a new page content, it is possible to create and display different fields upon NID.
You will need to write hook_preprocess_field in your theme template.php and hook_form_alter in your custom module to show/hide different field upon NID.
Here are some example code snippet.

In your theme template.php,

function yourtheme_preprocess_field(&$vars){
    $element = $vars['element'];
    // let's say nid=1 is for your home page
    if($element['#object']->nid == 1){
        // hide custom fields for the other node 2
        if( in_array($element['#field_name'], array('field_1_for_nid_2', 'field_2_for_nid_2')) ){
            $vars['classes_array'][] = 'invisible'; // make display:none in theme css file for the class .invisible
        }
    }
    // let's say nid=2 is for your about page
    elseif($element['#object']->nid == 2){ // do same things for nid=2
        // hide custom fields for the other node 1
        if( in_array($element['#field_name'], array('field_1_for_nid_1', 'field_2_for_nid_1')) ){
            $vars['classes_array'][] = 'invisible'; // make display:none in theme css file for the class .invisible
        }
    }
    // and so on.
}

In your custom module yourmodule.module,

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

    if($form_id == 'page_node_form'){ // for the content type 'page'
        $nid = arg(1);
        if($nid == 1){ // when your client edit the page "home", let's say it is nid=1
            // hide custom fields for the other node 2
            $form['field_1_for_nid_2']['#required'] = FALSE;
            $form['field_1_for_nid_2']['#type'] = 'hidden';

            $form['field_2_for_nid_2']['#required'] = FALSE;
            $form['field_2_for_nid_2']['#type'] = 'hidden';
        }
        elseif($nid == 2){ // when your client edit the page "about", let's say it is nid=2
            // hide custom fields for the other node 1
            $form['field_1_for_nid_1']['#required'] = FALSE;
            $form['field_1_for_nid_1']['#type'] = 'hidden';

            $form['field_2_for_nid_1']['#required'] = FALSE;
            $form['field_2_for_nid_1']['#type'] = 'hidden';
        }
        // and so on
    }

}

If you don't know about how to write custom module, here is a good start point.
If you don't want custom coding, the best way is to create different content types with different fields for your pages.


How to add attributes to menu and menu items on the block level in THEME_preprocess_block()? With THEME_menu_tree() we can change the markup of the <ul> element and with THEME_menu_link() we can add css classes to the items of it easely. But what if we have an IF IS IN THIS BLOCK condition to incept?

Not THEME_menu_tree nor THEME_menu_link() know in which block the menues are, they alter, because both will alter all menus known by system.

Two ways came in mind, but both were dead ends: 1) pass a variable from THEME_preprocess_block() to THEME_menu_tree() and THEME_menu_link() -> No, makes no sense. Still, they don't know what to do with it nor can they follow the foreach() of THEME_preprocess_block(), because they have no conditions for blocks. 2) Finding a higher entry level to pass the condition over and alter the menu attributes and its item attributes from there.

Well. Good point. But where would that be? Printing out the $variables inside THEME_preprocess_block() was like counting drops in the ocean. Can someone please enlighten me if I am right with the second thought and with where to look at?

There are actually functions available for specific menus too:

  Targeted overrides (suggestions) available for theme_menu_link() and
  theme_menu_tree()

  In addition to other changes to menu rendering, a Drupal 7
  theme can implement a THEMENAME_menu_tree__MENU_NAME() and/or
  THEMENAME_menu_link__MENU_NAME() function to override
  theme_menu_tree()/theme_menu_link() for a specific menu. For example,
  THEMENAME_menu_link__management() would override theme_menu_link() for
  links within the "Management" menu. This is similar to how
  "node--article.tpl.php" overrides "node.tpl.php".

Source: https://drupal.org/node/254940#theme-suggestions-for-menus


Cache clearing takes too long: What can I do to improve it? Everytime I clear all the caches, the process takes too long. This is from the log to a prod site I am currently working with.

  368829 | [someuser] | dbname | Query | 3376 | updating | DELETE FROM cache_page WHERE expire != 0 AND expire <= 1370891317

As you can see, it was executing for 3376 seconds. I am wondering if this is a known issue, or it is simply because there is just too much in that table.

Also, is there anything I can do to improve this?

I have a pure MySQL approach to clearing the cache_page table quickly.

use dbname
ALTER TABLE cache_page RENAME cache_pageoff;
CREATE TABLE cache_pagenew LIKE cache_pageoff;
INSERT INTO cache_pagenew
    SELECT * FROM cache_pageoff
    WHERE expire > 1370891317
;
ALTER TABLE cache_pagenew RENAME cache_page;
TRUNCATE TABLE cache_pageoff;
DROP TABLE cache_pageoff;

This script will do the following:

take the cache_page offline
create a new cache_page
load the new cache_page with the most current data
put the new cache_page back online
remove the old cache_page

Give it a Try !!!

BTW the reason the process is taking long has to do with the range of the delete and the storage engine is use.

If your cache_page tables is using the MyISAM storage engine, the DELETE query would be traversing almost the entire table and deleting each row.
If your cache_page tables is using the InnoDB storage engine, this is orders or magnitude worse that MyISAM. Why? All the rows you are deleting are stored in the Undo Logs within ibdata1.

When the DELETE query has completed successfully, all the Undo Logs for the cache_page table are purged.
If the DELETE query is interrupted by a rollback operation, all the Undo Logs are used to restore the cache_page table in its original state. If cache_page is InnoDB, I strongly recommend not interrupting the DELETE  query. Let it goes its full course.


FAPI text_format field doesn't render In D7 I'm creating a form for a custom module.  I would like one of the form fields to provide a wysiwyg editor (these work and render properly elsewhere around the site).  In my custom form though, the text_format field doesn't render.  If I change the type to 'textarea' it shows up, but as text_format, it's just non-existent in the rendered output.

My code is like this:

function mymodule_menu() {
  $items = array();
  $items['admin/mymodule'] = array(
    'title' => 'My Module Form',
    'page callback' => 'mymodule_form',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_form($form_state) {
  $form = array(
    'field1' => array(
        '#type' => 'textfield',
        '#title' => t('Field 1'),
        '$required' => true,
    ),
    'field2' => array(
        '#type' => 'text_format',
        '#title' => 'Filed 2',
        '#default_value' => "",
        '#format' => 'filtered_html',
    ),
  );
  return $form;
}

Can anyone spot a problem with this?  What else should I be looking for to understand why the field doesn't render when the type is 'text_format'?

Well I finally figured this one out.  Hopefully this helps someone else out there:

function mymodule_menu() {
  $items = array();
  $items['admin/mymodule'] = array(
    'title' => 'My Module Form',
    'page callback' => 'mymodule_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_callback() {
  $form = drupal_get_form('mymodule_form');
  return $form;
}

function mymodule_form($form_state) {
  $form = array(
    'field1' => array(
      '#type' => 'textfield',
      '#title' => t('Field 1'),
      '#required' => true,
    ),
    'field2' => array(
      '#type' => 'text_format',
      '#title' => 'Filed 2',
      '#default_value' => "",
      '#format' => 'filtered_html',
    ),
  );
  return $form;
}

For whatever reason, having the menu callback not point directly to the form builder function, but instead at an intermediary function that calls drupal_get_form() caused the text_format type to work properly.


pdf.js unable to locate libraries in Drupal 7 I followed the installation instructions that was located in both the module that you download from the modules section in Drupal as well as also downloaded the precompiled pdf.js and pdfworker.js files from the PDF.JS information page hosted by drupal.

However despite my efforts I am unable to get the modules page of Drupal to see the librarie for pdf.js

I have tried to alter the pdf.module by change the build/pdf.js lines of code to libraries/pdf.js/build/pdf.js as suggested in IRC chat but this didn't do the trick as well.

I was last looking at the simlink solution offered but noticed that there was a additional folder of external?  And not sure since that post was 2 years old and wondered if it was still a valid solution.  See reference -> https://drupal.stackexchange.com/questions/65768/pdf-js-installation-in-drupal-7

Running a windows environment with drupal 7

Not sure what else to do suggestions would be grand.

Step1: Download from here: https://github.com/mozilla/pdf.js

Step2: Download Windows installer: http://nodejs.org/download

Step3: Download & Install: https://www.drupal.org/project/pdf

Step4: Add the install folder of nodejs, to your PATH variable, so you can call 'node' command from command line

Step5: Through command line, goto /sites/all/libraries/pdf.js. Type 'node make generic'

Note: Make sure that in your library folder you have the pdf.js folder named exactly to "pdf.js". Then inside of that extract the pdf.js files. It should look like this.


webform add more module does not show add more button I would like public to be able to add records by person name and city.

I enabled the module https://www.drupal.org/project/webform_addmore

I created a webform.

I added a fieldset "Records".

I added 2 text fields: Name, city. I placed the fields under the fieldset.

Edit the fieldset > selected the checkbox "Add More fieldset"

Save

When I go to the webform page as public user, I can see the webform with the fieldset and fields. I do not see the Addmore button. How can I display the addmore buttons to webform fieldset?

It seems the module has no good support and does not work properly with latest versions of webform I think both 3 and 4 versions

Here is the issue that describes the problem you are having and I am posting this as a solution as there is numerous workarounds there that might give you a solution and some patches to try but none were tested by me.

If admins say this is not fit for an answer I will erase.


Node access user reference Main Modules:

Node access user reference
Node access node reference
Flags
Rules

I'm trying to give access to a user that clicks on a Join Project flag link.

I have a User Reference Field attached to a node call Project.  I'm wanting to tell Rules to add that user to the Node Access User Reference field, AKA "Join the group"

There is as well:
http://drupal.org/project/nodeaccess_autoreference module
which is working in similar way. But I'm not sure if this solves your problem.


no acces to /admin urls after site migration to local wamp server After migration of my site , any url starting with /admin generate a wamp server 'reinitialization error'.
The migration has been done with drush-dump/archive-restore and is working fine when imported in a VM

what could be the cause and how can i debug it ?

Doing a

   drush pm-update

solved the problem.

Any fine explanation why?


Subscription and Node action I am using Drupal 7. And i am quite new.

I want to develop a system in website where an Event is declared by the Administrator. (Event is a custom event type - or i can use any existing one if needed).  The event has a field (variable number of) subscribers to it.

If a user want to subscribe to event he/she can fill in a web form. Alternatively Subscription can be done by having a button (if such a thing is possible on node).

The problem is, usually such triggers help send an email post this. However, i want that once such an event happens, i want to modify the target node and append the current user_reference in the list of subscribers in the node.

So basically, when a user subscribes the page, the system modifies the node to append the name of such a user in the subscriber's list.

Is such a thing possible? If so, how?

Short answers -

Drupal 6: Use Signup

Drupal 7: Use Entity Registrations

Both of these modules do pretty much exactly what you want on both counts.


How to programmatically duplicate a node reference field during rendering? I am working on a node type which contains node references to other types. I want to programmatically duplicate a few node reference fields based on a set of conditions during rendering of the node. I have not been able to figure that out.

You have total control over the layout of nodes within your theme via the node.tpl.php file and its variants and overrides. Check out a lot of information about node.tpl.php here and template files in general here.

By creating a specific template, you can customize it to your purposes along these lines:

function YOURTHEME_preprocess_node(&$vars) {

  if ( /* whatever condition you have that returns true for printing */ ) {
    $vars['template_files'][]='node-printing';
  }

  // any other node preprocessing goes here

}

Then, you put a node-printing.tpl.php file in your theme directory next to the default node.tpl.php for your theme, and in there, customize it as you like.

The key variables to be looking at are $content and $node. If you goto admin/content/node-type/NODE_TYPE/display on your system you can see how $content is built and customized,  while the latter is it as an object containing all of its fields that you can rework and so forth.

Putting a drupal_set_message('<pre>' . print_r($node, TRUE) . '</pre>'); at the top of your new template file will show you what you have to work with.

And, as always, just remember to clear caches after creating this new template so that the theme registry picks it up, but now you should be able put anything anywhere you want in your node display.


Not able to execute Drush commands I am trying to setup a Drupal 8 Environment on Virtual Machine (Ubuntu) and when I am trying to clear cache, I've got the error:

drupal8@drupal8-VirtualBox:/var/www/drupal-8.0-alpha5$ drush cc all
Command cache-clear needs a higher bootstrap level to run - you will [error]
need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'cc all' could not be executed.                    [error]
A Drupal installation directory could not be found                   [error]
drupal8@drupal8-VirtualBox

I have installed Drush, but getting this error. Can anybody help me with this?

There are a few possible reasons for the issue you're facing, as further detailed below ...

Drush commands need to be issued from within the correct subfolder

A "possible" reason might be because Drush commands must be issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site), and then retry your Drush comand.

Use the Drush version that supports your Drupal version

It could well be an issue with the version of Drush that you are using. Check if it is an option to downgrade to a lower version of Drush? FYI: Drush 7.x does support D8 also ...

Note: in one of the comments in the question, the OPer wrote "Drush version is 4.5". Haven't double checked it yet, but that appears to be an extremely old version of Drush. I wouldn't be surprised if that version doesn't support D8 "yet". And since the D8 folder structure changed quite a bit, that would also explain the error like "A Drupal installation directory could not be found" ... More research (and clarifications from OPer) are seems appropriate here ... (I might update my answer here later on with some relevant pointers about "which version of Drush supports which version of Drupal".


How can I import a specific type block? I have created some blocks of a specific type, in Drupal 8, and I want to import them into the cloned instance.

There is no core import feature available. How can I achieve the task?

They don't get imported by the configuration synchronization; if you try, you will get the error

  This block is broken or missing. You may be missing content or you might need to enable the original module.

and no listing in custom block library.

As per my further research I found that there is a module named Content Synchronization which works well with the same issue. As in Drupal 8 blocks as served as content now and block types as entity types.


Grandchild nodes (of a nested taxonomy term) on node page Every time I think I understand relationships… Got desperate and cannot make work following context:

A node has a reference (field_a) to a term 1A of vocabulary A. That term 1A itself has a reference (field_b) to another term 1B of vocabulary B.

vocabulary A > vocabulary B

TERM 1A > TERM 1B

TERM 2A > TERM 2B

TERM 3A > TERM 1B

TERM 4A > TERM 2B

NODE 1 > TERM 1A (> TERM 1B)

NODE 2 > TERM 2A (> TERM 2B)

NODE 3 > TERM 3A (> TERM 1B)

NODE 4 > TERM 4A (> TERM 2B)

On the node page I would like to have a block that shows all nodes that have the same (term) grandchild relationship to 1B (respectively 2B or any term of vocabulary B).

Or schematically (adding other cases)

BLOCK on NODE 1 PAGE shows related NODE 1 and 3

BLOCK on NODE 2 PAGE shows related NODE 2 and 4

BLOCK on NODE 3 PAGE shows related NODE 1 and 3

BLOCK on NODE 4 PAGE shows related NODE 2 and 4

Could someone please give my a hint?

You can start with Content Views that show all nodes tagged with term from Vocabulary A, then add relationships to Taxonomy information, including the reference between terms from vocabularies A and B, and the one introducing content tagged with those terms.

Create a new Views of type Content showing Fields, add a Block Display to the View, change its name to something meaningful you can recognize later on Blocks page
Add a Filter to limit to your desired Content types
Add a new Relationship Taxonomy term referenced from field_a and Require this relationship

This one merely introduces more information about the Vocabulary A term that the current node is referencing.
Add a new Relationship Taxonomy term referenced from field_b, make it use the first Relationship and Require this relationship

This one introduces information about the term from Vocabulary B that is referenced by the term that node is tagged with.
Add a new Relationship Taxonomy term using field_b, make it use the second Relationship and Require this relationship

This one goes reverse, back from Vocabulary B to terms from Vocabulary A that reference specific term from B
Add a new Relationship Content using field_a, make it use the third Relationship and Require this relationship

This one introduces nodes that are tagged with terms from A that also reference term from B that is referenced by term from A that the current node is tagged with.
Add a new Contextual filter ID from Content Category and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
[your relevant CTs]

This one just gives Views information about the current node.
Edit the Content: Title Field you already have and make it use the fourth relationship (it will actually be the only one available). Now the Title won't be showing the Title of the current node, but the Title of the node that is related to the current node through A > B > A "relation path".

You should now see a list of nodes related to the current node through the "grandparent" term.


Multi Domain Robots.txt I have multiple sites running on a single code base in Drupal 8. Is there any possible way to add different robots.txt file for each site?

If you are under apache, you can use mod_rewrite to deliver others robots.txt :

  RewriteCond %{HTTP_HOST} ^domain1.com$
  RewriteRule ^robots.txt$ robots.domain1.com.txt [L]
  RewriteCond %{HTTP_HOST} ^domain2.com$
  RewriteRule ^robots.txt$ robots.domain2.com.txt [L]

Note you may also generate your robots.txt in some controller for each site depends on config and fallback to default if not defined.


Error: Cannot redeclare class becuase of entity self reference I've got 2 problems here.

I have an entity that references itself in field definition (see below).

Problem No.1. I've got a fatal error
PHP Fatal error:  Cannot redeclare class Drupal\mymodule\MyEntity when trying to install the module.

Problem No.2 I now get it every time even when I remove the referencing field and do drush cr unless I wrap the class definition in !class_exists().

I swear this is the only file defining the class.

Is there a way to clean this out of wherever drupal has stored it?

And how do I declare this type of self-reference?

<?php

namespace Drupal\mymodule;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * @ContentEntityType(
 *     id = "myentity",
 *     label = "My Entity",
 *     base_table = "myentity"
 * )
 */
class MyEntity extends ContentEntityBase
{
    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        $fields = [];

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setReadOnly(true);

        $fields['myentity_id'] = BaseFieldDefinition::create('entity_reference')
            ->setTargetEntityTypeId('myentity');

        $fields['name'] = BaseFieldDefinition::create('string');

        return $fields;
    }
}

Ok so the problem was in the namespace:

namespace Drupal\mymodule;

From my observation (can't find this in the Entity API documentation entities are supposed to be placed in the src/Entity (which I did) which imposes the Entity namespace. So fixing the namespace solved my issue.

namespace Drupal\mymodule\Entity;

What a stupid way to spend a half of a day. Looks like I'm too used to class loaders that will simply not find the class if you place it in the wrong directory.


Load scripts in the head AND bottom of the page? I need to load head.js in my head and application.js at the bottom of my page. The following seems to stop all my scripts being loaded! Is there a syntax error? Im confused as I used the documentation from here:

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}

  js-header:
    header: true
    js:
      /ui/head.js: {preprocess: false, minified: false, weight: '-100'}

  js-footer:
    js:
      /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

UPDATE - It appears to me that header: true is used to move either all or none of the scripts to the head. Can someone confirm if this is right?

If this is the case, how can I load scripts in both the head and the bottom of the page?

You have to add additional libraries: https://ffwagency.com/blog/managing-css-and-javascript-files-drupal-8-libraries

So in my theme.info.yaml

libraries:
  - THEME-NAME/global
  - THEME-NAME/custom

In my theme.libraries.yaml file:

global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}
  js:
    /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

custom:
  version: 1.x
  header: true
  js:
    /ui/head.js: {}


How do I programmatically populate a field if another one is empty? I have a CSV feed running and it currently works perfectly. The client now wants to populate a certain field with a sub-string of another field if the first field is empty, on import. I can't see a way to do that with the normal feeds field mapping or tamper.

How can I achieve this?

Create a custom module, in mymodule.module use hook_node_update

function mymodule_node_update($node) {

  if (!isset($node->field_example[LANGUAGE_NONE][0]['value'])) {
  // If field example is not set (is empty), then...

     $new_value = // ...do some stuff to compute a new value for the field.
     $node->field_example2[LANGUAGE_NONE][0]['value'] = $new_value;
     field_attach_update('node', $node);

  }

}


How do I add tags to Advanced Forum posts I would like to add the type of tags this stackexchange forum has, so users can tag their posts and the tags appear at bottom of all posts. How do I do that?

1. If you want to create the Tag in the new topic content, you can follow as suggested by the @lixu (This method will add the tag below the body content, but you can also shift its position up-down by going at manage-field). But this method will not show the tags on the advanced forum topic list.

2. If you want to create the tag at the list of topics page, like stake-exchange but not completely like that, You need to go to views. Advanced forum provides 5 views, Go to Structures->Views->Advanced Forum topic list->Edit, to the field add new field Content: tags.
You can rearrange the position of it by rearranging option(Check second image). I have added to the last as shown in the image. What this will do, it will add one more column of Tags in the topic list page, besides the last-post column(check third image). You can shift the column of tag wherever you want, by shifting the tag filed in views.


integer field select list with min and max value I would like to have integer field that ranges from 0 to lets say 100000 with "select list" widget. It doesn't have to have keys i just don't want to type 10000 numbers in field settings of "List integer" field. If I select integer field type it offers min and max but there is no option to have "select list" widget. Am I missing something obvious?

It may not be the best way to do this, but it might work for you... you can set up the field as a list and leave it empty, then use a PHP script to populate it, EXAMPLE being your field name:

for ($i=0; $i<100000; $i++) {
      // Get the field info
      $info = field_info_field('field_EXAMPLE');
      // Get a reference to the values
      $values = &$info['settings']['allowed_values'];
      // Manipulate the values in some way, e.g.
      $values[$i] =  $i;
      // Save the field
      field_update_field($info);
}

Then you should be able to see the value listed under your field's values (under admin/structure/content/types/YOURAPGETYPE/fields). You can also use this in the future if you need to add more values, just remove/modify the for loop. I can't take credit for this code, I found it here on SE but just can't remember where.


Storing ajax callback variables in PrivateTempStore I have an issue with changing / obtaining variables in form element's ajax callback function. (Sorry for typos, I just placed a pieces of whole code).

I have form with input field, where user can select how many pieces of each product he want

$form['wrapper_amount']['value'] = [
        '#type' => 'number',
        '#prefix' => '
',
        '#suffix' => 'pcs
',
        '#name' => "amount--product-1",
        '#ajax' => [
            'callback' => '::calculatePricePerUnit',
            'event' => 'change',
            'disable-refocus' => TRUE,
            'progress' => [
                'type' => 'fade',
                'message' => NULL,
            ],
        ],
    ];

after choosing a number I calculate price using AJAX callback function and using

public function calculatePricePerUnit(array &$form, FormStateInterface $form_state)
{
    // ... price calculation for specific product
    // $new_price = (amount * price_per_unit);

    $total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
    $response = new AjaxResponse();
    $response->addCommand(
        new InvokeCommand(
            '#total-price',
            'html', [$form_state->get('total_price_with_vat') . ' €']
        )
    );
}

The problem is that when used add amount to second product the $form_state->get('total_price_with_vat') is 0 again. It means that I cant store $total_price variable in $form_state, because it's not persistent (I've already read this somewhere, that I can't store variables to $form_state in AJAX callback function). So I tried to store it to $form_state->setStorage($my_values) but it didn't work either.

Please note that all AjaxResponse commands are working and I only need to find best approach how to store data, not how to re-render form's elements.

My next step is to store data in PrivateTempStore, but question is, if it's good approach?
I don't need data on any other Wizard page, neither in Controller or any further step. I just need to calculate $total_price and some other data that I need to use multiple times in AJAX callback function, and at the end use webform API to send webform submission results via email.

PrivateTempStore is not the right fit for this. You want to store the value in the $form_state, but you do not store it in the AJAX callback, you store it in the submit handler, then set the form to rebuild (which will persist the values in the storage. You can set a custom #submit handler on your ajax submit button that is only called when that button is clicked:

$form['wrapper_amount']['value'] = [
  '#type' => 'number',
  '#prefix' => '
',
  '#suffix' => 'pcs
',
  // note - #name is commented out, as you should never
  // need to change it in Drupal, and doing so will have
  // unexpected consequences.
  // '#name' => "amount--product-1",
  '#ajax' => [
    'callback' => '::calculatePricePerUnit',
    'event' => 'change',
    'disable-refocus' => TRUE,
    'progress' => [
      'type' => 'fade',
      'message' => NULL,
    ],
  ],
  '#submit' => ['::customSubmit'],
];

Then your custom submit will look like this:

public function customSubmit(array &$form, FormStateInterface $form_state) {
  $total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
  $form_state->set('total_price', total_price);
  $form_state->setRebuild(TRUE);
}

After playing around with this a little, I can see that a submit button is required to be able to call a submit handler where rebuildForm() can be recalled. If you set the #ajax on a non-submit button, ajax is called, but rebuildForm() is not able to be called.

As such, I'd say the hack for this is to create an #ajax submit button as I've shown above, but hide it. Then add some custom JS on the number field, that on blur triggers a click of the hidden submit button.


Is this possible to copy Views fields declarations to another view? Use case:

We have a page with a lot of complicated Views generating a lot of queries.
There is a way to do it in more efficient way but this needs a lot of changes in Views or even creating different views, similar in displays field declarations.

Is there any way to copy fields declarations between those views?

Try export view and look in export's code


Get view via php based on page number and 1 argument (uid) I have a view that it has an contextual filter based on "uid".
Now I need to get it via PHP and I can use views_embed_view(). But I need to get only page FOO or page BAR and views_embed_view() accepts only "arguments/contextual filter".

Which is the correct way to call views FOO, for display BAR, using argument "uid = X" and get only "page = Z"

Thanks.

M.

You can specify a page inside a view with views_embed_view().

Fisrt argument will be the view's name

Second will be the page you want to display (Defaults to default)

And then as many contextual filters you want/have

So it will look something like this views_embed_view('view_mahcine_name', 'page_3', uid);


How to load and render a webform with Ajax I'm new on Drupal 8, and I want to make a custom module to load any webform of (webform module) on other pages of the website.

The idea is to load the webform when the page load. All webform has configured with ajax submission.

I don't know how I can do that. I someone can help me. I'm on Drupal 8

I've create a custom module with a custom path in routing.yml:

path: '/webform-data/{webformid}'

In my controller I've created a public function to retrieve the webform by id.

I want for example create a link, like:

Click

When I click on the link, the webform load in a wrapper, but when I submit the webform, I have a redirection to the path of webform and I don't want the redirection. I just want the inline confirm message without reloading the page.

I have this in my controller :

// Controller
namespace Drupal\ajax_webform\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Ajax\AjaxResponse;
use \Symfony\Component\HttpFoundation\Response;

class AjaxWebformController extends ControllerBase {

    public function getWebform($webformid) {

        $build['webform'] = [
            '#type' => 'webform',
            '#webform' => $webformid
        ];

        $renderer = \Drupal::service('renderer');
        $rendered = $renderer->renderRoot($build);

        $response = new Response();
        $response->setContent($rendered);
        return $response;
    }

}

You might want to look into the Ajax links API.
Sadly, there is an issue with the Webform module and BigPipe that needs to be fixed.


How to create an "All" link in a taxonomy menu (block)? I have a taxonomy vocabulary and terms as follow:

Food:
  -Meat
  -Veggies
  -Fruit
  -Dairy

I want to create a menu of taxonomy terms that look like this:

-All
-Meat
-Veggies
-Fruit
-Dairy

... when you are on the "Food" page.

I have tried the Taxonomy Menu and Taxonomy Menu Block modules, but none give me the option to have an "All" link. That's a bit daft innit?

How can you show the user posts/nodes of all terms?

Any other solutions?

My opinion:

You can create a new term called all and add it to all your related nodes.

Or,
You may use Views to create a page to show all nodes, and add that to your menu.


On AJAX-Enabled Views the "Add to Cart" button does not work properly On AJAX enabled Views with exposed filters or pagers the "Add to Cart" button and "add to wishlist" does not work properly.

After an AJAX call, the add-to-cart form action changes to views/ajax, so if i press the button, only a JSON output will be displayed.

Yes, it is. This module will be usefull for you:Commerce Ajax Cart


How to apply Simple Regex Filter to forum signature? I'd like Simple Regex Filter to be applied to Signatures for Forums to close the loophole for human post spammers on my drupal 7 forum. How to achieve it?

It's impossible without your own coding. Currently this module works only on nodes and comments, and this is hardcoded. Given that it is:

  Development status: Maintenance fixes only

you can't hope maintainers will add functionality; they already told they will not.

If you are using Signatures for Forums for Drupal 7, you can try with modules working generically on Entities. As far as I remember Rules could be used for something like that. For Drupal 6, I'm not prepared to even speculate.


Is it acceptable solution to set session.gc_maxlifetime in hook_init()? We need to set session.gc_maxlifetime separately on the site and mobile (app).
Is any best practices here?

UPD. My final solution looks as follows:

$args = arg();
$is_mob_rest_api = FALSE;
if (!empty($args)) {
  $is_mob_rest_api = $args[0] == 'api' && $args[1] == 'v1';
}
$session__gc_maxlifetime = $is_mob_rest_api ? 31536000 : 1440;
ini_set('session.gc_maxlifetime', $session__gc_maxlifetime);

if you set it always and for all, you should do it in settings.php

ini_set('session.gc_maxlifetime',  36000);


How to change Drupal module load sorting(weight) order I need to understand how can we change module weight.

Do we really change that value for custom module.
What are the default values?
If we change weight value what will be effect on Drupal bootstrap process?

You can do this by using Modules Weight module.

  This module provide admin interface for users/people has the access to
  modules page to reorder the module weights as they want.


How to check if result from cache_get() is expired? cache_get always returns an object and I'm a bit confused by its values. There's probably a short generic function that can handle this for once and for all.

$cache = cache_get('key');
if ($cache) {
  // doesn't work, cache_get always returns an object
}

if (!$cache || ($cache->created < time() - $cache->expire)) {
  // cache is expired? I'm not sure
}

Just checking for the data member doesn't cut it.

I had seen the issue reported on d.o (in 2009) but that doesn't really help me fix it on any live site. So I'm looking for a function that will still make cache work for me without resorting to storing the cache myself in the database.

TL;DR Don't, unless you have to. Drupal has long history of optimization and even if it sometimes serves you outdated cache, it's not without a cause. It's to prevent overhead of constant cache wipes. If your application is time-critical for some reasons, read below.

As you can see in the code that does the actual work:

function getMultiple(&$cids) {
  try {
    // Garbage collection necessary when enforcing a minimum cache lifetime.
    $this->garbageCollection($this->bin);

    // When serving cached pages, the overhead of using db_select() was found
    // to add around 30% overhead to the request. Since $this->bin is a
    // variable, this means the call to db_query() here uses a concatenated
    // string. This is highly discouraged under any other circumstances, and
    // is used here only due to the performance overhead we would incur
    // otherwise. When serving an uncached page, the overhead of using
    // db_select() is a much smaller proportion of the request.
    $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
    $cache = array();
    foreach ($result as $item) {
      $item = $this->prepareItem($item);
      if ($item) {
        $cache[$item->cid] = $item;
      }
    }
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
  }
  catch (Exception $e) {
    // If the database is never going to be available, cache requests should
    // return FALSE in order to allow exception handling to occur.
    return array();
  }
}

There is no test built in1, and no limit that makes Core return only unexpired nodes.

The way I prefer if I can, is to delete/hide table rows on database level, for example by creating a proxy view that never returns outdated records in the first place, but usually this is inconvenient. Don't try unless you know what you're doing.
The Drupal-only way would be to add comparison in PHP, like that:

if (isset($cache->data) and time() < $cache->expire) {

If your cache is relatively long, you can, and for performance reasons probably should omit testing their expire date on each call and leave it to Drupal's core. It will allow minimum cache lifetime to work with your data, for example. That's how core is doing it.1

1 There are some tests in prepareItem method, but for performance reasons they do not guarantee that outdated cache items will not be returned - see actual code for details.