Is there a way to display current "event" or "show" in date/calendar modules? I'm building a radio station page with Drupal 7, and I would like to display in a block the current show on air, but I can't find a way to do it. I have installed the Views, Calendar and Date modules, a show content type with the starting date (and hour) and the ending date (and hour too). How show the query and filtering be done in views to display only one show and the one that is currently at the same time as the system time?

Basically, you want to tell views to display nodes with starDate <= *NOW* AND endData >= *NOW*. i.e. if now is 11:50, a program from 11 - 12 should be displayed.
This could be done fairly easy via views, following are two screenshots of the two filters you're gonna add to the view:

Hope this helps.


JavaScript loading but not being applied in Drupal 8 theme I'm using this javascript to create a 'zaccordion' on my Drupal 8 site. However, it's not working. My 'slideshow' just appears as a bulleted list of images.

Here's what I've got so far:

A block on my page with the following content:

image

image

I've also got the required javascript files from the download link (above) in themename/js. I've also got my own instantiation of the zaccordion in another js file in that same folder and it targets #slideshow like so:

(function ($) {
  $(document).ready(function() {
    $("#slideshow").zAccordion({
      settings here
    });
  });
})(jQuery);

Then, in my libraries.yml file I have this:

zaccordion:
  header: true
  version: 1.x
  js:
    js/jquery.zaccordion.min.js: { }
    js/jquery.zaccordion.js: { }
    js/zaccordionUsage.js: { }
  dependencies:
    - core/jquery

I put that in the 'header' because it wasn't working in the footer. I can confirm the files are being pulled into the page because I see links to the scripts in the  of the html.

Finally, I have the javascript library being placed into the page with this call near the top of page--front.html.twig:

{{ attach_library('themename/zaccordion') }}

Are all these settings correct?

I have this same slideshow functionality working easily on a Jekyll site I created so I assume it's something to do with the way my block is trying to reference the javascript files or something.

Note: yes, I have JavaScript aggregation unchecked (Performance > Aggregate Javascript)

The dumbest of all possible mistakes was the answer. I had a <div> wrapping my insertion of the page block, like so:

{% if page.slideshow %}
{{ attach_library('themename/zaccordion') }}
    <div class="col-xs-12" id="slideshow">
        {{ page.slideshow }}
    </div>
{% endif %}

I thought if I put the attach_library line there it would load it 'closer' to the actual code needing it (don't try to understand what I was thinking). At any rate, I noticed that I have an id="slideshow" here as well. So I had TWO id="slideshow" - one on this <div> and another on the <ul> in the block...that was causing the slideshow not to work. So I just changed the id of this <div> to something else and it worked.


Creating nodes with Views Bulk Operations This seems like it would be a common application but not sure if it is doable.  I have a view (d7, views3) that is displaying fields in views bulk operation format from a content type (call it general).  For each row the user selects, I want to create a node of a separate content type (call it userspecific) made up of the user id and some of the fields from the general content type.  Is this something that is possible using VBO ??

This can be done using views bulk operations. But you may have to implement hook_actions_info in a custom module to create an action and the use that action in the views bulk operation.

Following code illustrates the process.

function custom_test_action_info(){
  return array(
    'custom_test_create_new_node' => array(
      'type' => 'node',
      'label' => t('Create New Page'),
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
    );
}

function custom_test_create_new_node($node, $context = array()){
  global $user;
  $page_node = new stdClass();
  $page_node->type = 'page';
  $page_node->status = 1;
  $page_node->title = $node->title;
  $page_node->field_body[LANGUAGE_NONE][0]['value'] = $node->field_body[LANGUAGE_NONE][0]['value'];
  $page_node->uid = $user->uid;
  node_save($page_node);
}

After saving this code flush the drupal cache and the views bulk operations form will have the action available.

After saving the view you will get the operation available in the views bulk operation page.

select a node and then execute the operation and you will have a new basic page created.

i am attaching an export of the view which i created you can import this view in your system and give a try to understand the workflow.

Export code of the view:

$view = new view();
$view->name = 'test_vbo_node_creation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test VBO node creation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test VBO node creation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::custom_test_create_new_node' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 1,
    'label' => 'Create a new node',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-vbo-node-creation';


How to display the username instead of the UID? I created a view to display content in a table. I want to show the author of the last comment.
So I added the field "Comment Statistics: Uid of the last comment", but I wish to have the username in place of the UID.

How to do this ?

You'll need to add a relationship to users in your view and then you should be able to access something like the username.


Problem with equal height of columns in Display Suite I`ve got Fluid two column stacked layout in Display Suite. There is responsive picture in the first column, the second column contain some rendered fields. Below that columns is long text. My problem is with right column. I need to make the height of that column equal to height of the picture on left side. How to achieve that? Is there possibility to add some scrollbar in the right column? Anybody had the similiar situation? Some simple solution without coding or only small snippet ;) Maybe I need to add some view in the right column

Create your own layout for display suite and use CSS.

Add the folder 'ds_layouts' to you theme folder root.
Under that folder ad another folder: two_col_fluid_stacked_fixed_height

Ie Must look like this: YOURTHEMEFOLDER -> ds_layouts -> two_col_fluid_stacked_fixed_height

Add the following files to two_col_fluid_stacked_fixed_height folder:

two_col_fluid_stacked_fixed_height.inc

<?php
function ds_two_col_fluid_stacked_fixed_height() {
    return array(
        'label' => t('two col stacked fluid fixed height'),
        'regions' => array(
            'header' => t('Header'),
            'left' => t('Left'),
            'right' => t('Right'),
            'footer' => t('Footer'),
        ),
        'css' => TRUE,
    );
}

two-col-fluid-stacked-fixed-height.tpl.php

<<?php print $layout_wrapper; print $layout_attributes; ?> class="<?php print $classes;?> ds-2col-stacked-fluid-fixed-height clearfix">
  <!-- Needed to activate contextual links -->
  <?php if (isset($title_suffix['contextual_links'])): ?>
    <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

    <<?php print $header_wrapper; ?> class="group-header<?php print $header_classes; ?>">
      <?php print $header; ?>
    </<?php print $header_wrapper; ?>>

    <div class="center-wrapper">

    <<?php print $left_wrapper; ?> class="group-left<?php print $left_classes; ?>">
      <?php print $left; ?>
    </<?php print $left_wrapper; ?>>

    <<?php print $right_wrapper; ?> class="group-right<?php print $right_classes; ?>">
      <?php print $right; ?>
    </<?php print $right_wrapper; ?>>
    </div>

    <<?php print $footer_wrapper; ?> class="group-footer<?php print $footer_classes; ?>">
      <?php print $footer; ?>
    </<?php print $footer_wrapper; ?>>

</<?php print $layout_wrapper ?>>

<!-- Needed to activate display suite support on forms -->
<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

two_col_fluid_stacked_fixed_height.css

.ds-2col-stacked-fluid-fixed-height > .group-header {
}

.ds-2col-stacked-fluid-fixed-height .center-wrapper > .group-left {
    float: left; /* LTR */
    width: 50%;
}

.ds-2col-stacked-fluid-fixed-height .center-wrapper > .group-right {
    width: 50%;
    height:99999px;
    position:absolute;
    right:0;
}

.ds-2col-stacked-fluid-fixed-height .center-wrapper {
    overflow:hidden;
    position:relative;
}

.ds-2col-stacked-fluid-fixed-height.group-one-column > .group-left,
.ds-2col-stacked-fluid-fixed-height.group-one-column > .group-right {
    width: 100%;
    float: none;
}

.ds-2col-stacked-fluid-fixed-height > .group-footer {
    clear: both;
}

/*delete this*/
.group-left {
    background:yellow;
}
.group-right {
    background:red;
}

Clear you cache and use this layout in display suite. Tweak CSS to your liking.


AHAH callback is not working I have a form element in d8 as follows :

$form['cluster_dropdown'] = array(
    '#type' => 'select',
    '#title' => 'Cluster',
    '#options' => $cluster_options,
    '#default_value' => $cluster_selection,
    '#ahah' => array(
      'path' => 'module_name/admin5/callback',
      'wrapper' => 'dependent-dropdown-wrapper',
      // 'event' => 'change', // default value: does not need to be set explicitly.
    ),
    '#attributes' => array('class' => 'cluster-dropdown'),
  );

But in this case ahah callback is not working , is there gasf/admin5/callback want to replace with routing path as am using this in d6? any idea ?

Neither #ahah nor path are used in Drupal 8. Instead of the first, Drupal 8 uses #ajax; instead of the second, it uses url which must be a \Drupal\Core\Url to which to submit the Ajax request.

Finally, callback is a PHP callback, which generally is a full qualified (using a PSR-4 namespace) method name.

Reference

Ajax API
PSR-4 namespaces and autoloading in Drupal 8


Create commerce product through web services I want to create products using commerce services resource module. At this moment, I can create a product calling the resource .../product with POST, but It seems that It only creates a product variations, because If I navigate to "manage products" option, I can't see the new product but if I call a GET over resource .../product I can see the new one.
Then, I'd tried to create a product using .../node resource, but I always get an error:

"field_product][und][form][commerce_price][und][0][amount": "Price field is required"

I don't know what is the right JSON structure to create a node with its product variations.
Could some one put here an example of the right JSON structure for creating node products?
Thanks.

I've found the error. Firstable, my drupal commerce installation hasn't product_display content type. I have to add it manually. I don't know why, but It's missing after clean installation. Secondly, the right JSON structure for commerce price section is:

"field_product":{ "und" :
            {  "form": {
                   "commerce_price": {
                        "und": [ {
                           "amount": "1234.34",
                           "currency_code": "EUR",
                           "data": { "components": [] }
                            } ]
                      },
                   "sku":"eeaafe3231aa"
          }

After this change, I can create products display and I can see it on product manage page. Hope It could be useful for other who has the same problem.


What payment gateway should be used for invoice payment? My Drupal commerce site supports multiple payment gateways. One of the payment types should be paying by invoice. That means if you select invoice payment type during checkout process you don't have to enter any "real" payment info (credit card data or something), but at end site should send you invoice (pdf document) with instructions how to pay your order.
I've installed Invoice module: https://www.drupal.org/project/commerce_invoice
And if I understood well I should use actions and rules to send email after checkout is complete. Is that true?
But what puzzles me most is that this module doesn't provide invoice payment gateway. So I don't know how to achieve that when user is selecting payment method "Pay by invoice" method appears? Should I use some dummy (test) payment gateway or? What payment gateway should be used for invoice payment?
An update:
What Rules event should I use to detect that checkout process is finished, so I can send invoice.
Also, what action should I select to send email that contains invoice (with link to PDF document or PDF document attached)?

Yes - just create a new (custom, standard) payment method named Invoice, and user's then can select that.
On the payment method edit form you can add more details, and even could limit the availability of the method.
Rules are not actively supported as in D7: https://www.drupal.org/node/1535554
But I do not see a need using rules with your use-case.
You need to configure your invoice type to send emails, there should be a checkbox: Email the customer a confirmation when an invoice is generated - see https://www.drupal.org/project/commerce_invoice/issues/3089861
The invoice is attached by default and you can remove the attachment with hook_mail_alter, it's using the id invoice_confirmation. See https://git.drupalcode.org/project/commerce_invoice/-/blob/8.x-2.x/src/Mail/InvoiceConfirmationMail.php (UPDATE: The invoice types seem to create invoices for all payment methods and is not (yet) configurable to limit them)
See also the commerce-invoice-confirmation.html.twig to change the email.
Not attaching the PDF makes the emails smaller, and maybe passes more SPAM filters .. But users need to take action and press a link .. I would discuss that with the customer or maybe try both and gain experience with them. (Like what method is really paid more, and which one is faster)
UPDATE:
If you only want to send the invoice for one payment method you need to alter the commerce receipt email (id: order_receipt) and attach the invoice there. You'll find the order entity in the body's theme render array (first entry using #theme commerce_order_receipt)


Is there a D7 module that allows you to create a content type to be displayed as a system message? Is there a D7 module that allows you to create a content type to displayed as a system message?

Something like http://drupal.org/project/user_alert but gets displayed in the system messages.

It would be a lot of overhead for this one function but Rules can trigger arbitrary system messages with Token support. Here is a screencast by Node One which can give you an overview and he does the system message example in a couple of the videos. I think that if you need extended interaction with users Rules can be very helpful.


How do import and save term lineage using feeds and Hierarchical select? I have to import a number of nodes that only has the lowest term in the csv

e.g. Washington

However, in the taxonomy hierarchy it has United States > Washington

I am using the Hierarchical select module for saving the term lineage however when I use feeds it tries to import the child term as the parent term and doesn't actually select anything.

How do I use feeds and Hierarchical select to import just the child term but save the entire lineage?

The closest I can come to is https://www.drupal.org/node/1319278 however the csv mush contain the lineage, whereas in this case we only have the lowest possible child term.

I did some more research and testing decided to use the Term Set Lineage module so that it is set on import, then just changed to use the Hierarchical select module.


Is there a maximum amount of data that a Drupal database can safely store? Is there a maximum amount of data that a Drupal, let's say MySQL, database can safely store? If it gets too big will problems start to occur?

The short answer is no. There is not reasonable way you can store "too much data".

If you read the Limitations entry on wikipedia about MySQL, you'll see that "maximum amount of data" doesn't come into the picture.

More specifically, MySQLs documentation says

  The effective maximum table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.

Depending on what you do with the data, however, you can get performance problems if you store a lot of data, but that's not a Drupal specific problem.


Unresolved dependency updating the module I'm updating the Views module on a Drupal 7 site, and I'm receiving this message when I update the database.

How do I resolve this dependency issue when I need to update the Views module first?

Just download a newer version of views and replace in your project.

https://www.drupal.org/project/views/releases

If you're using composer just require a newer version.

Then, you should be able to install your drupal.

Best regards
:)


How to send 2 mails simultaneously with drupal_mail() I want to send my order to my email, and also to my client's email.

I am sending an order placed on my website using this code:

function MYMODULE_form_submit($form, &$form_state) {
  order_mail_send($form_state['values']);
}

This is the order_mail_send() code:

function order_mail_send($form_values) {
  $module = 'shop';
  $key = 'key';
  $to = $form_values['email'];

  $language = language_default();
  $params = array();
  $from = NULL;
  $send = FALSE;
  $message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  $message2 = drupal_mail($module, $key, $from, $language, $params, $from, $send);

  $subject = 'Order Status';

  $message['subject'] = $subject;
  $message['body'] = array();

  $message['body'][] = "
Your order: ".$form_values['first']." ".$form_values['last']."
";

  // …

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);
  $message2 = $system->format($message2);

  // Send e-mail.
  $message['result'] = $system->mail($message);
  $message['result2'] = $system->mail($message2);

  if ($message['result'] && $message['result2'] == TRUE) {
    drupal_set_message(t('Your order has been sent. Thank you!'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }
}

Now it sends the first email ($message = $system->format($message); but not the second one. How can I make it work?
How can I empy the cart values after sending the emails? The cart empties when I close the browser, but I want to delete it after sending as well.

You can use CC to send a copy to admin/yourself

$message['headers']['CC'] = "foo@gmail.com"


Taxonomy menu - link to first node associated with term? I have a taxonomy menu block using the vocabulary 'Projects' that links to the terms: 'Bridges', 'Buildings' and 'Boats'.

Currently, each menu item links to a page that lists teasers of all the nodes associated with the menu term. For example, I click on 'Buildings' and it goes to a page with teasers of all nodes associated with 'Buildings'.

How could I have the menu term link to the latest node associated with that term directly? To continue the example, I click on 'Buildings' and it takes me to the latest 'Buildings' node.

The list of teasers is unnecessary as I will be employing elements of the teasers in an aside on each node directly.

I figured it out; here's the solution in case anyone else needs this functionality.

Forget the Taxonomy Menu module. We'll build the functionality with a view.

Make a taxonomy term view (under Show when creating a view).
Under Advanced, add this Relationship: Taxonomy Term - Representative Node.
You can leave all the settings the same, but I suggest checking 'Require this
relationship' so empty terms will not get linked
Also Under Advanced, change Use aggregation to Yes
Add a filter for Taxonomy Vocabulary (with whatever vocab you want)
Add a Content:Path field, exclude it from display and check 'Use absolute link'
Add a Taxonomy Term:Name field and check Output this field as a link. For the Link Path use the Path Replacement Pattern from the Path field we just added (usually [path]).


How to generate an XML feed? I am creating an XML feed (domain.com/content_type/feed).

I looked into RSS Publishing and have turned it off, but do see where I can generate an XML feed: Home » Administration » Configuration » Web services

Is this the correct way?

You can do it using the Views Data Export module (Most popular)

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT
  XML

Example:

Alternatively, you can also do it using the Views Datasource module

  Views Datasource is a set of plugins for Drupal Views for rendering
  content in a number of shareable, reusable formats based on XML, JSON
  and XHTML. These formats allow content in a Drupal site to be easily
  used as data sources for Semantic Web clients and web mash-ups. Views
  Datasource plugins output content from node lists created in the
  Drupal Views interface in a variety of formats - XML data documents
  using schemas like OPML and Atom, RDF data documents using a
  vocabulary like FOAF, JSON data documents in a format like Exhibit
  JSON, and XHTML data documents using a microformat like hCard.


Some CSS and JS is not loading for anonymous users I recently started working on an existing D7 site, which has its own custom theme. With this theme only, some CSS and JS files are not loaded at all for anonymous users. Logged in users dont have that problem. When I switch the theme to Garland for example, the CSS and JS files are loaded correctly for anonymous users.

The CSS or JS files are either coming from core, or from some contrib modules.

Where should I start looking?

First of all you should find where the CSS or JS is being added, this being Drupal, there are tons of ways that this could happen.

if they're added using drupal_add_js and drupal_add_css (which they should be) you have to make sure that possible template differences beetween roles and permissions both print out the $styles and $scripts variables.

If the theme follows D7 standards there should be an html.tpl.php file somewhere (most likely the root) in the theme, that would be the best place to start looking. If that does not exist, try page.tpl.php.

Post your findings and it'll be easier for us to help you.


Should I use all these template files or will theme hooks do the job? Since templates are slower than theme hooks, I'm wondering if I might be able to use them for my application. Here's what I'm trying to do:

Right now I have about 10 content types on my site and I've created a separate template file for each because I want each to have a <div> with a specific 'id' so I can target those pages with CSS. I also give each a separate template file so I can determine on a case by if they should have a secondary sidebar or not.

Those are the only reasons I'm using all these template files.

Two Part Question:

Can what I'm trying to do be reasonably accomplished with theme hooks, and if so, how?

The module that defines a template defines if it is a template or a theme functions, that's not something you have any influence over.

And yes, theme functions are faster, but they're also deprecated and will be removed completely in Drupal 9 (Because twig is far easier to write than PHP). With render caching and so on, the performance difference is no longer as relevant as it used to be.

The performance difference is between having a template or not. There's anyway a template, just not a custom one, and the only performance difference then is the additioal complexity that your template adds and what you are doing sounds trivial.

There might be reason to do what you're doing differently, you could use preprocess, but you'd need to at least share your templates/code (you should always do this when asking questiosn) so you can get a specific code example. But not because of performance, a more valid reason would be code/template management, it will be more work to make further changes if you have 10 different templates or just one.


URL Alias does not work in Menu-Blocks with i18n (pathauto also installed) I'm currently facing a problem with Internationalization and the main menu block on my page.

So when I created the page about-anna and navigating to /de/about-anna - it works great also with /node/27 it works. Thats ok.

But the menu-item is instead of /de/about-anna just /node/27

So I continued testing, added the english-translation and setabout-anna as path alias again. But the problem still exists.

I also looked up the internet and Drupal Answers and I found some good answers... but didn't fix my problem...

I was still testing and found another bug, that when your browser is in german, you can't switch to english.

So in Configuration > Languages > Detection and Selection (admin/config/regional/language/configure) I unchecked "Browser" from the list.

Now the menu-block uses path aliases too and you can switch languages on the site.


How to programmatically handle files (CSV import) I'm trying to make a simple form to upload a txt/csv file, in order to parse it and update some values in database. Here's my code. Unfortunately, at the moment using the form nothing happens (no folder creation, no file upload...) Here's the code. What can be wrong here? Thank you

function vts_departs_conf_form() {
  $form = array();

  $form['browser'] = array(
    '#type' => 'fieldset',
    '#title' => t('Send file'),
    '#collapsible' => TRUE,
    '#description' => t("Send foo file."),
  );

  $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));

  $form['browser']['file_upload'] = array(
    '#type' => 'file',
    '#title' => t('CSV File'),
    '#size' => 40,
    '#description' => t('Select the CSV file to be imported. ') . $file_size,
  );

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

  $form['#attributes']['enctype'] = "multipart/form-data";

  return $form;
}

function vts_departs_conf_form_validate($form, &$form_state) {
  // attempt to save the uploaded file
  $filepath = 'public://depconfs';
  file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
  $file = file_save_upload('file_upload', array('file_validate_extensions' => array('CSV TXT')), $filepath, FILE_EXISTS_REPLACE);

  // check file uploaded OK
  if (!$file) {
    form_set_error('file_upload', t('A file must be uploaded or selected from FTP updates.'));
  }
  else {
    // set files to form_state, to process when form is submitted
    $form_state['values']['file_upload'] = $file;
  }
}

function vts_departs_conf_form_submit($form, &$form_state) {
  //Prepare file parsing
  $line_max = variable_get('user_import_line_max', 1000);
  ini_set('auto_detect_line_endings', true);
  $filepath = $form_state['values']['file_upload']->filepath;
  $handle = @fopen($filepath, "r");

  while ($row = fgetcsv($handle, $line_max, ',')) {
    // do stuff
  }
}

EDIT :

As a first step, @bdurbin corrected my naming mistakes.

Reading file_save_upload() API description, I realised that my basic validation checks are already performed, so I removed them.

So final is quite lighter :

function vts_departs_conf_form_validate($form, &$form_state) {

  $filepath = 'public://depconf/';
  $validators = array('file_validate_extensions' => array('csv txt'));
  $file = file_save_upload('file_upload', $validators , $filepath, FILE_EXISTS_REPLACE);
  //push file object to submit step
  $form_state['values']['file_upload'] = $file;

}

Drupal's naming convention for the automagic association of validation and submit handlers for a given form is:

name_of_form() (builder)
name_of_form_validate() (validation handler)
name_of_form_submit() (submit handler)

In your case, if you wanted to name your form vts_departs_conf_form(), you'd want to either rename your validation handler to vts_departs_conf_form_validate() and your submit handler to vts_departs_conf_form_submit(), or use the #validate and #submit form attributes to associate functions that don't follow the naming conventions.

In your example, changing the builder name to vts_departs_conf() made the form work as expected.


Add translation only for a particular content type I don't have much experience in Drupal and I am trying to create multilingual content for a particular content type. I want to switch the language inside the content instead of changing the whole site language. I have used the i18n module to do this but the whole site gets changing. For example I am using right to left languages like Arabic, Farsi etc. I am using views to list the items for this content type.

It's by design...

Drupal Content translation using modules like i18n and locale works for complete site... For example if you are using Arabic language and if you add a arabic translation for a particular node, if you are viewing arabic version of node complete site changes from right to left..

As a work around..If you just want to add translations i would suggest use modules like Entity reference and node clone to connect english version with other versions and use select box to choose language.. You need to add links to redirect user to other versions based on above reference logic.. Keep in mind by implementing above you will loose Drupal powerful Multilingual feature..


Drupal 8's last minor release = Drupal 9? I have read about the planned release date of Drupal 9 is scheduled to be on June 3rd, 2020. I read this documentation about how to prepare a Drupal 8 site for Drupal 9:

Prepare a Drupal 8 site for Drupal 9

In the document it says:

"1. Keep Drupal core up to date. Drupal 8's last minor release will become Drupal 9."

Does it mean that when we update the Drupal 8 core to the last minor release of Drupal 8, it will automatically convert our site to use Drupal 9 and we don't have to radically change, migrate or redevelop our sites again in Drupal 9?

In summary, is Drupal 8 core's last minor release = Drupal 9?

Yes, upgrading from Drupal 8 to 9 is scheduled to be an incremental update from the last minor version of Drupal 8.

It seems the main thing to consider is to remove any usage of deprecated functions to ensure a smooth upgrade.

  Contributed project developers, as well as those maintaining custom integrations, should follow the deprecations when possible and use the latest APIs available. This means that when Drupal 9 is released they will have to make fewer changes to be compatible

https://www.drupal.org/core/deprecation


why system/connect web services return nothing in drupal 7? I have Drupal 7 with web services activated, but the system/connect resource returns a 404 Controller Not Found response. I was trying the user resource, and it works correctly. I tried using the following URL in my browser window, which does a HTTP GET:

https://localhost/drupal/x_login/system/connect

where x_login is the endpoint.

The services module allows a resource to define the following "things":

Operations: provide 5 different verbs

retrieve: Make a GET request based on the resource name and an identifier i.e. GET /endpoint/user/ID
index: Make a GET request based on the resource name to get a list of resources i.e. GET /endpoint/user
update: Make a PUT request to a resource name and an identifier i.e. PUT /endpoint/user/ID
create: Make an idempotent POST request to a resource name to create a new resource i.e. POST /endpoint/user
delete: Make a DELETE request to remove a resource by identifier i.e. DELETE /endpoint/user/ID

Actions: Allows to make a custom POST request to a resource. This is used for login, logout, etc... These are never GET.
Targeted Actions: Allows to make a custom POST request to a resource + identifier. This is used for making hierarchical resources.
Relationships: Allows to make a custom GET request to a resource + identifier. This is used for make hierarchical requests for things like group membership.

The system/connect resource is defined as an "action" above. This means that you must make a POST request instead of a GET request. And it may require a CSRF Token.

POST /login_x/system/connect HTTP/1.1
Content-type: application/json
Accept: application/json
X-CSRF-Token: 'TOKEN'


Giving permissions to a node to multiple accounts without creating a new role I've built a site where all of the content is essentially private. All the relevant content types are Unpublished and my users (role=Owner) only have permissions to view/edit/delete their own Content. This is working just fine.

However, requirements have changed and I'm trying to figure out what to do. The new requirement is that an Owner can give permission to another user (role=OwnerAssistant) to view/edit/delete their data. I'll refer to the group of users that all administer the same dataset as an OwnerGroup.

It will not be feasible to create a Role for each of these groups because each new customer would need a separate role and we're hopefully going to have 50,000+ customers.

How can I control the permissions on a node so that a specific list of users can view/edit/delete that content? I'm ok with maintaining my own DB table that tracks the mapping of OwnerAssistants to Owners so that I have a way of determine if an OwnerAssistant is allowed to access content created by the Owner. However, I don't know how to let drupal know that uids 234, 894, and 1029 have x,y,z permissions to node 24590.

I will likely be integrating this with the Field Permissions module because I want to hide certain fields from OwnerAssistants.

Any help is appreciated!

How about using Entity Reference to designate non-owner users that may edit the node?

You could make your own module with a function to handle permission checks, i.e. "return TRUE if user is referenced on node".

Then use other hooks (hook_form_alter() for instance) to show/hide edit buttons and override edit privileges on nodes.

You can secure it by making the entity reference field only accessible by the content owner.


How to add region just above title for omega theme? How to add region just above title for omega theme? I try to add a region just above title. But no sccessful.

In case you're using Omega 4 you need to include your regions in two files, instead of only the .info file.

You also need to include them in your layout.inc file, which is located in the theme's folder at:

  layouts/yourlayout/yourlayout.layout.inc

and then print them at the desired spot in your HTML markup in your layout.tpl.php file, which is in the same folder.

Hope this helps.


Number translation with 118n module I have developed a multi-lingual site with i18n module (7.x-1.13) and everything works as expected.My Drupal version is 7.34.

Recently, my client have asked not to translate the number. The website works in English and Arabic.

To be more specific, when Arabic is chosen, we do not want the numbers to be displayed in Arabic, instead we need to display the same in English. Now, each numbers are translated to Arabic when the language is chosen as Arabic, even the user input.

The default language is Arabic and I haven't installed any modules for translation of numbers.

Any help would be much appreciated.

You can use PersianTools modules,
Features

This module is going to cover some basic features required for Persian
websites.
Fix possible misplaced chars in mixed Persian and English texts
Find a way to fix Calendar.
Convert English numbers to Persian numbers.
Fix sort issues for persian characters.

One of its features is Convert English numbers to Persian numbers. ( indeed Persian number is Arabic digits ).
Install this module and go to its settings and just active convert digits.
Also you can convert all Latin digits to Arabic with some Js code.
Try something like this (put it in custom JS file and load in each page_
String.prototype.toIndiaDigits= function(){
  var id= ['list of arabic digits'];
 return this.replace(/[0-9]/g, function(w){
  return id[+w]
 });
}
var content= $('body').html();
$('body').html(content.toIndiaDigits());

See this articles about how change Latin digits to Arabic
https://stackoverflow.com/questions/1675786/convert-from-english-digits-to-arabic-ones-in-html-page
https://stackoverflow.com/questions/21415121/convert-english-digits-to-arabic-digits-in-html-documents
http://jsfiddle.net/McxL5/


Drupal 7 default core search functionality I am using drupal 7, i am in need of showing the default search functionlity, which shows the searched term content type and how many times the searched keyword occurred in the content type.

The entered keyword will be searched with site wide search and the results will show what are the content type nodes having the keyword and how many times the keyword occurred for the content type. Please help me to solve this problem.

display suite offers counts and highlighting,
plus you can edit the search-result-display via UI.
to get the contenttype there, you'll need to add a custom field,
or install search api and use views.


Drupal 6 custom theme development using Zen starter kit I am trying to develop a custom drupal 6 theme with zen starter kit. I installed and configured Zen starter theme kit. My objective is to develop a liquid layout theme from this starter kit. Anybody please tell me how to give layout widths for particular elements and if you have any useful tutorials, please share it.

For setting up a Zen sub-theme check here. And there is a good podcast there ;-)


Adding validation to existing forms using #element_validate Problem

I'm using #element_validate to validate an input on a custom form which creates a node. I'm using element_validate_integer_positive as the function to validate. It works perfectly.

It partly works when I try to hook the same code into the existing node edit form. The form still breaks and displays the correct message but it also throws two errors due to missing values. How can I remove these errors?

So far

Here's the form code from my custom module. This works as expected.

$form['field_total_vacation'] = array(
  '#type' => 'textfield',
  '#title' => t('Total Vacation'),
  '#size' => 5,
  '#element_validate' => array('element_validate_integer_positive'),
);

Here's my hook into the node edit form:

function viewspagehack_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'job_advert_node_form') {

    $form['field_total_vacation']['#weight']             = 19;
    $form['field_total_vacation']['#element_validate']   = array('element_validate_integer_positive');
    }
  }

If I enter a non-positive integer into field_total_vacation on the node edit form, it still breaks and throws the correct message: "Total Vacation must be a positive integer" but it also throws:

Notice: Undefined index: #value in element_validate_integer_positive() (line 4190 of C:\XAMPP\htdocs\drupal\includes\form.inc).
Notice: Undefined index: #title in element_validate_integer_positive() (line 4192 of C:\XAMPP\htdocs\drupal\includes\form.inc).

This is because element_validate_integer_positive() takes $element as it's first input and the function then calls:

$element['#value']
$element['#title']

But this error doesn't throw on my custom form which also doesn't take an input. What's going on?

EDIT

I moved #element_validate to here, this means it now has access to #title:

$form['field_total_vacation']['und']['0']['#element_validate']   = array('element_validate_integer_positive');

This removes the title error but leaves the value error. I can't understand why this function takes #value from $element.

function element_validate_integer_positive($element, &$form_state) {
   $value = $element['#value'];

None of the form elements have #value, #value only seems to appear in $form_state. But yet it works in my custom form and not on the node edit.

the method that work is this

function MYMODULE_form_NODE_FORMID_alter(&$form, &$form_state) {
  dpm($form);
  $form['body'][LANGUAGE_NONE][0][['#element_validate'][] = 'MYMODULE_validate_breads_node_form_alter';
}

/**
 * Implements callback function().
 * Specific alteration for views exposed forms
 */
function MYMODULE_validate_NODE_FORMID_alter($element, &$form, &$form_state) {
  if (empty($element['#value'])) {
    form_error($element, t('Text'));
  }
}


Change Log in or register to post comments for content type We are using the comments for a particular content type to post reviews for that content type. I have searched the web but can't find a proper solution how to change the text

"Log in or Register to post comments" to something like "Log in or Register to add Review"

only for this one content type. Any suggestions how this can be done, also happy if I can figure out how to hide this for this content type.

I don't believe I can alter comment_links() via template file or custom module (in drupal 7)

Thanks

Go through this link will give you a nice work around

https://www.drupal.org/node/170065

Then, you need to change code: Find your modules/comment/comment.module file, open it in a text-editor (like wordpad or the like), and search for the text you don't want to see on pages. You need to comment out (or delete) a bit of code, something like:
//

 if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

The added 'return' is just for case, to ensure nothing to show - I didn't test this.

You can either edit the original file (which is quick but unclean, and requires you to redo the change after every unpgrade), or override that function in your theme properly by placing its copy into your template.php file (whole function!), renaming it to "phptemplate_[name]", and changing as needed. I think (not tested!) that it should look like this (added to 'template.php' in your theme's folder / create the file if not existing yet, with

function phptemplate_comment_post_forbidden($nid) {
  global $user;
  if ($user->uid) {
    return t("you can't post comments");
  }
  else {
    // we cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages
    if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
      $destination = "destination=". drupal_urlencode("comment/reply/$nid#comment_form");
    }
    else {
      $destination = "destination=". drupal_urlencode("node/$nid#comment_form");
    }

//    if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

  }
}

But still, you'll probably need to check on every upgrade, whether this copied code is in sync with core's possible new changes.


Is it possible to use the "Save & Edit" module with Rules? I've created some rules to send notifications when changes some fields and  it works as I expected  when the user click on Save button.

After I enabled Save & Edit module but I receive notifications both if I click on Save and Save & Edit .

I want receive a notifications only when click on Save .

Is possible? Or is there another approach to achieve the same result?

Thank you in advance.

Just a simple concept:
I could imagine using the Rules Forms module with the following Form API conditions:

Form ID: form_id == YOUR_CONTENT_TYPE_node_form
Clicked button: $form_state['clicked_button']['#id'] !== 'edit-save-edit'


Display a promo image at last in every slideshow created for a node I am using Views Slideshow module to display multiple images uploaded in my article content type.
Every node landing page will have a slideshow displayed with its images (slideshow works fine).
All what I need is one common(Promo)Image to display as the last image/slide in every slideshow.

Is this possible with "Views Slideshow" and "Views" ? Do I need to create a separate tpl file for this?

Create a Promo article and add the promo image as the field in this article.

Note the this article will be just a placeholder for us and will not be presented anywhere. So may you could un-publish as well.

Do a dpm to find out the fid or any related that you need to know about this particular image field. Then make changes to the view in post_execute.

   function modulename_views_post_execute(&$view) {
      // wait for the right view
      if($view->name == "name_of_the_view") {
        // create the object you want to insert in the result
        // dpm($view->result); to check how the objects are built.
        $temp = new stdClass;
        $promo_image->fid = 13;

        // replace the old result array
        $view->result[] = $promo_image;
      }
    }

Based on the answer : Insert row into a view


How to make a menu link on a subdomain use the main domain as base_url I have a site example.com with a subdomain sub.example.com.
In my apache config both domain and subdomain point to the same directory, containing the Drupal installation. That is as far as i went to set up a the subdomain.

The issue is, the main menu on sub.example.com uses the same menu and template as the main site. The links link to sub.example.com/node/1 instead of example.com/node/1, effectively creating a clone of the whole site on the subdomain.

How do i show the same menu, but have the links all link back to example.com/node/1

It will depend on your theme, but typically the menu array (e.g. $mail_menu in page.tpl.php) can be altered such that each menu item have the array element 'absolute' set to TRUE so that l() will generate the link with an absolute path.

For example, in a MYTHEME_preprocess_page() function:

/**
 * Override or variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  foreach ($vars['main_menu'] as $id => $menu_item) {
    $vars['main_menu'][$id]['absolute'] = TRUE;
  }
}

As long as $base_url is set to http://example.com, it should render the menu links to your original domain.


Problems rendering drupal 7 user registration form with ajax in BootStrap 3 Modal I have a subtheme based on bootstrap 3 and am trying to load user registration form(user_register_form) on front--page.tpl.php, I am adding #ajax to the submit button using form_alter

     $form["actions"]["submit"] = array(
        '#type' => 'submit',
        '#ajax' => array(
            'wrapper' => "user-register-form", "effect" => "fade",
            'effect' => 'fade',
            'callback' => 'my_form_submit_handler',
            'method' => 'replace',
        ),
        '#value' => t("Sign-up"),
        '#id' => 'user_register_form'
    );

I am rendering the form in two places on the same page (a) in a div which is a regular div
and (b) in a bootstrap modal div as mentioned here http://getbootstrap.com/javascript/#modals

     <?php
            if (user_is_anonymous()) {
                $form = drupal_get_form('user_register_form');
                 print drupal_render($form);
            }
     ?>

in case (a) the ajaxified form works very well, however in case (b) the form is no longer ajaxified , the submit button does not have the "ajax-processed" class attached.

I intend to open all my application forms using bootstrap modal and ajax however i am not able to do this as of now.
I want to know the right way to load any ajax form in bootstrap modal dialog
I know this is a fairly common problem with modal dialogs and drupal forms, but i am yet to understand what the reason behind this behaviour, any help or direction will be highly appreciated.

There is one more similar question that is unanswered here
Drupal load form with ajax callback in Bootstrap modal

By rendering the user registration form twice, duplicate form id's were being created. After recreating the second form with a different ID, things are good.


Make insert module add uploaded images to media library automatically I'm trying to get adding images to work smoothly (more like how wordpress handles it)
I have added WYSIWYG+CKeditor, Insert, Media, Resize Filter (which I can't yet get working).

Right now the main issue is I can insert things from the media library that are already there. But when I'm at the bottom of a post adding an image, I want all added images to go to the media library (especially to make cleaning up unused/replaced images easier for the content editor).

Is there a simple way to set up this behaviour?

Instead of using the Insert module, use the Media module's WYSIWYG integration. This adds a button to the WYSIWYG toolbar which allows you to choose an item from the Media library. You can also upload a new media item which adds it to the library and selects it to be inserted into the WYSIWYG editor. The link above explains how to set it up. Make sure you follow all the steps. You have to enabled this functionality in both the WYSIWYG profile and the text format to get it working properly.

Also, check out this great video on Media for some more information.


Adding a bulk discount to ubercart without adding a new module I have multiple sites using the same ubercart module. One of the sites has a new discount that I need to add. If you buy 25 or more you get a 25% discount, if you buy 100 or more you get a 35% discount for example. I don't want to add a new module to ubercart as I don't want to mess with everything that's already working. Plus it's just this one discount on one specific item.

In going through the ubercart documentation, it looks like there are several hooks that may be useful. hook_add_to_cart, hook_line_item_alter and hook_order which are defined here. Am I travelling down the right path or is there another better way or already laid out example that would make piling through this a bit simpler?

After digging through various hooks and trying different things, this is what ended up working for me, which was actually pretty simple in the end.:

function hook_cart_item($op, &$item) {
    if ($op == 'load') {
        if ($item->nid == xxx && $item->model == 'xxxxxxxxxx') {
            if ($item->qty >= 100) {
                $item->price = round($item->price * .65,2);
            } else if ($item->qty >= 25) {
                $item->price = round($item->price * .75,2);
            }
        }
    }
}


Adding a flag to Menu Content Link to display as a non-link I have been struggling/failing for the last day to try find a way that I can add a flag/marker to the Drupal menu links that I can examine within the menu TWIG template to modify the link such that it becomes plain text instead of a menu link.

I am not using any menu modules, standard Drupal Menu with CSS to provide the drop down functionality and styling.

What I need is to be able to output a menu item as shown in the screen shot, specifically the 'Sell your property' & 'Essential Services' items which are unlinked headers.

Initially I attempted to use the contributed module menu item extras
 (https://www.drupal.org/project/menu_item_extras) which works fine from a menu management plugin point of view but then they change the markup way too much and it actually breaks the drop down functionality, so I cannot use it.

I then tried a second module which seemed simpler, i.e. Menu link content fields (https://www.drupal.org/project/menu_link_content_fields).

This module has some strange behaviour in that it makes the menu links fieldable. I can add a new field but after adding a field, it does not appear under the Manage Fields tab, and in the twig template the new field is un-available in the menu item object (Examined through xDebug)

Also, trying to remove this invisible field at a later stage seems difficult.

Question: How can I easily add some sort of marker to a menu item link  to allow me to modify the template output for said link. Or is the re a module that will allow then insertion of HTML markup/plain text instead of a link (Megamenu doesnt seem to allow this)

Also, I cannot seem to find the hook which deals specifically with a sites menu, i.e. the hook that is executed for each menu link. Does one even exist?

I'd like to avoid a hack whereby I put in a unique string into the text of the link and then examine this in the menu twig templates to see if that string exists to know if I need to modify it.

The module Special menu items allows you this, even some control over the HTML output.

This is now in Drupal core (although Docs need some updating):

  This features is in core for >=8.2.0. Create menu without link by entering route: <nolink>.

That is, you enter into Link:

route:<nolink>

and select:

Show as expanded

if you need it for drop-downs.


How to print You have new private message, You have no new messages I'm using Privatemsg module and I want to print simple "You have new message" and "You have no new messages" for given user how to do that?

The module automatically does that when a user logs in who has the message waiting.  It DOES NOT print you have no new messages - because that is redundant.  It did it that way when we use it on our site - Drupal 6 - have not enabled and used it however yet on Drupal 7


How do I call a controller method from a twig template and passing arguments to it? I know I can pass variables to templates using render arrays.

$theme = 'block-AcademicDisplay';

return array(
  '#theme' => $theme,
  '#content' => $content,
  '#url' => urlencode($url),
);

How can I pass variables and call controller methods from that template? On that template, when clicking on some buttons or links, I would like to call a controller method and pass it 2 parameters.

Passing arguments in route parameters

I think the missing part is the route that you have defined for the controller. You have to use this to generate the url:

$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);

This example is for the node controller and passes the argument nid=1. The parameter names are defined in the route definition.

Passing arguments in query parameters

I've seen in one of your other posts that you want to use query parameters. This is an example for the user login:

$url = Url::fromRoute('user.login', [], ['query' => ['destination' => 'http://example.com']]);

For this to work you don't need to define a query parameter in the route. Simply inject the request as function argument (the request is always available to a controller, it's not necessary to define it in the route) and get the query parameter:

use Symfony\Component\HttpFoundation\Request;

  public function myController(Request $request) {

    $destination = $request->query->get('destination');

  }


How to add catchpa to entityform form IDs for my entity forms is not listed in the catchpa general settings.
Can anyone explain how I add the catchpa?

Hope this will help  you,

In Drupal 7 if you are using Captcha module, you can achieve it by the following steps

Let say you want to add Captcha to Article node form

Get the node form for which you want to add the Captcha, you an achieve it by using

    //Implements hook_form_alter() for node_form().
    function hook_form_alter(&$form, &$form_state, $form_id) {
        //use drupal_set_message to print the form ID
        drupal_set_message("<pre>" . print_r($form_id,1) . "</pre>");
    }

After printing the node article form

Get form id alternative (For developers) : Go on the page where your form is displayed.
Next, use developer tools of your browser to show DOM structure.
The form_id is displayed like the orange box on screenshot (Chrome example):

After enabling the Captcha module go to admin/config/people/captcha and add the node article form id and save the configuration.

Go to node article form and you can see the captcha(for non admin)

Note:

Configure the captcha setting as per your requirement.


How to update custom content type fields value in bulk? Is their any way to provide the bulk edit in the custom content type fields values by csv or in bulk.?

Without a lot of detail about your problem I suggest you research these modules:

Views Bulk Operations (VBO)
Views Bulk Edit
Feeds
documentation for the Feeds module for Drupal 8

VBO works through Views: you create a list of the nodes you want to edit. VBO provides a field through which you can select nodes (checkbox) and then you can perform operations on them.

Feeds can update existing nodes from a CSV file (create new nodes too). They're a bit trickier to configure, mapping must be tested thoroughly and you need to make sure the entries are unique, but once you have them set up correctly you can use them over and over again.


Direct photo and name to Profile page Update#2

Actual user name is superuser but with kint, its still reading the admin id and displayname. This also happens to the URL, its reading the admin's profile link profile/1

I tried to dig into {{ content }} but cannot find tag with value superuser.

Update:

I noticed that in my twig template, {{ content.user_id }} would link into user's profile page(user/1), so the main question I think is what is the correct profile id of user in twig. I tried using content.profile_id but doesn't work.

I have this simple site that a user can post a simple content in the site. I also have a custom Profile type enabled from Profile module. I noticed that when I click on the photo, it is directed to the profile page profile/1(which is my expected result) but when the author name is clicked, it is directed into the user's profile page user/1. How can I change the author's name link to be directed into profile pageprofile/1?

You can use the example from Twig Functions:

{# Link to user entity page. #}
{{ 'View user profile'|t }}

and modify the route to point the link to the profile page:

{# Link to user profile page. #}
{{ 'View user profile'|t }}


Moving nodes from dev to production (a simple use case) I want to use the backup_migrate module to move some nodes from dev to production (production is still off-line). But the node is split over so many tables...and I also added custom fields (image field) to the node. How do I use backup_migrate module to move the tables? How do I know which tables to move? Should I just move the entire db? then what would be the point of using features to export my configuration? Thank you.

From my experience, I use Node Export to export some nodes and import in other Drupal site (same versions). To export/import a node, the respective Content type must have been created with his respective fields.

Also, this page Comparison of Content and User Import and Export Modules have information about some import/export modules alternatives (also I suggest see comments). Could be suitable for your needs.

I hope information be useful.


What is the difference between profile and content profile module? There is a core module called Profile which adds the profile fields; there is also a contributed module called Content Profile that does the same thing (up to my knowledge.)

May anyone clear me the difference between these two modules?
In which case should we go for the Profile module, and in which case for Content Profile module?

Assuming you're in Drupal 6, Content Profile allows you to set up a node type that will act as user profiles.  this is more extensible than the core profile module, which essentially just adds basic fields.

Also, because Content Profile profiles are nodes, you get more flexibility with what fields you can have on a user profile.  Any core or contrib field will be usable with Content Profile ( e.g. image field, file field, node reference), whereas the core profile module has limited options.  You can also use Content Profiles with Views more efficiently.

In short:

Content Profile creates user profiles as nodes, with all the benefits that entails (Views being the big one for me).

Core profile module adds a basic profile to the user that has less customisation/options.

Check out this video for some more help with Content Profile.


Get data from remote REST API (read only) We use a remote service (not Drupal) to publish press releases and to show those releases in a remote newsroom.

This remote service offers an API so we should be able to fetch and show the newsroom on our Drupal site. To use the API a custom token must be present in the request header and the method used must be GET:

Notified-Custom-Token: [TOKEN]

This is what I have done so far in a custom module named notified_api. [custom token] is replaced by a unique token genererated for our newsroom and [id] is replaced by our newsroom ID:

function notified_api_preprocess_page(&$variables) {
  // Fetch newsroom from Notified API with custom token
  $headers =  array('Authorization'=>'Notified-Custom-Token [token]', 'Content-Type'=>'application/json' );
  $url = "https://api.newsroom.notified.com/api/newsrooms/[id]";

  $options=array('headers'=>$headers, 'method'=>'GET');

  $result=drupal_http_request($url, $options);

  dpm($result);
}

Partial result from the dpm:

... (Object) stdClass
url (String, 53 characters ) https://api.newsroom.notified.com/api/newsrooms...
status (String, 5 characters ) Done.
code (Integer) 401
chunk_size (Integer) 32768
data (String, 0 characters )
request (String, 438 characters ) GET /api/newsrooms/345345 HTTP/1.0 Authorizatio...
GET /api/newsrooms/345345 HTTP/1.0
Authorization: Notified-Custom-Token 9832502938403876504329820348ewieitrje...
Content-Type: application/json
User-Agent: Drupal (+http://drupal.org/)
Connection: close
Host: api.newsroom.notified.com

options (Array, 20 elements)
headers (Array, 5 elements)
Authorization (String, 258 characters ) Notified-Custom-Token 9832502938403876504329820348ewieitrje...
Content-Type (String, 16 characters ) application/json
User-Agent (String, 28 characters ) Drupal (+http://drupal.org/)
Connection (String, 5 characters ) close
Host (String, 25 characters ) api.newsroom.notified.com
method (String, 3 characters ) GET

What I get is a 401 message: unauthorized. Can anyone see what I am doing wrong?

In case anyone else have the same problem. By replacing the name "Authorization" like this:

  $headers =  array('Notified-Custom-Token'=>'my-unique-token', 'Content-Type'=>'text/json' );

... it worked and I got a success response with code 200. My mistake was to believe that Authorization was a mandatory name in the name/value pair.


Referencing parent entity I've just started with Drupal and I'm trying to create the following URL structure with PathAuto and Entity Reference:

Category A -> Category B -> Category C

Resulting in

category_a/category_b/category_c

For display purposes, I have to define the entity reference on the parent entity. IE:

On Category A, define an entity reference to nodes of Category B.

However, in PathAuto it appears that I can only reference child entities, not parent entities.

I have referenced this article (Path alias tokens and node references) which describes the solution if the entity reference is defined on the child, not the parent.

Is there any way to achieve the above?

Entity Reference 7.x-1.1
PathAuto 7.x-1.2
Entity Tokens 7.x-1.5

I came across this post when facing the same situation so I am posting the solution I found in case someone else needs it.

The only way I found to solve this was declaring a custom token using hooks. This post was really helpful: https://drupal.stackexchange.com/a/78498

Once both hooks are implemented, you will only need to manually load the parent to get the data you need, whether it is the parent URL or the parent title. After that, just use the token you just created and voilá!

Hope it helps!


How to merge these results? I wonder why these results don't merge. This is the result of searching by postcode.
As you can see it returns 2 times the same shop with another deal. I need it to return the shop once with both deals on it. Thanks in advance! Pictures below:

Found two modules that might help with your issue:

Views Merge Rows - provides a way to combine rows with the same content in the specified fields.

OR

Views Fields Combine - Similar to the one above, but hasn't been updated since 2012.

Experiment and see which one works best. You may need to use Rewrite Option too.


How to delete a content type field without deleting the whole view? I was trying to delete a field from a content type . But it's deleting all the views which have that field in it.

I have some pages inside that view. I even checked in all the pages that this field is present , but not found.

Any idea to delete a field without deleting the whole view ??

As per the following issue registered on Drupal.org, that is what  happening with D8 views hence you are observing that phenomenon. While in drupal 7 the view  gets automatically updated. You  can find the registered issue with drupal 8 core on  drupal.org at following link.

When deleting a content type field, users do not realize the related View also is deleted

That issue is in review phase, hence probably significant work would have been done on that issue. You need to refer that.

If you read the entire discussion there, currently they are working on the idea of Comment #59. suggested by @dawehner which is stated/pasted below,

  Here is alternative approach:

  Don't delete existing views
  Disable existing views and tell people which ones got disabled
  Then the user can go back to this view, fix missing fields and call it a day


How to recreate the user_picture field? On Drupal 8 there is by default a user_picture field for the user's photo. When I started my site several months ago, I deleted this field because I did not use it.

Today I need this field, so I created an image type field.

MY PROBLEM : I installed some modules that use the user's photo, but it can not be found because the user_picture is the default

If I create a user_picture field it automatically adds field_ in front of the machine name.

Is it possible to restore the default field with the correct machine name ?

Instead of importing configuration as suggested previously, you could as an alternative, programmatically re-create the field. Here is some code that does that.

<?php

use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

// Create the user profile field and instance.
FieldStorageConfig::create([
  'entity_type' => 'user',
  'field_name' => 'user_picture',
  'type' => 'image',
  'translatable' => '0',
])->save();
FieldConfig::create([
  'label' => 'User Picture',
  'description' => '',
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'bundle' => 'user',
  'required' => 0,
])->save();

Assuming the code above is placed in a file called recreateUserPicture.php that is stored in your docroot, you can run the following Drush command:

drush scr recreateUserPicture.php

Best of luck!

N.B.: An alternative answer (since the importing of configuration from the standard profile has a problem with having the field being available in Views UI).


Text input onchange event I'm working on a custom field that will store a string.  The text will have a custom formatter applied to it that will manipulate the structure of the string (adding dashes in the right places).  I have a javascript that will apply those changes in the field's input textbox when creating a new content type with the custom field, but I can't figure out how to fire the javascript when the user enters the text.  Can it be done and if so can anyone point me in the right direction?

You probably want to use Drupal behaviors which is a wrapper of sorts for JQuery. With JQuery you can make it so that everytime your textfield gets edited your Javascript code gets executed. Behaviors/JQuery is a big subject and will take time if you're not familiar. You can start here

The Drupal JavaScript API

JQuery tutorials


Running feeds in order I just ran into a situation where I need to run three imports, one after another using the same file providing successful import. Does anyone know how to do this? I looked briefly at Feeds rules but I don't think that will work unless I'm missing something?

Thanks

I would recommend using a small custom module to add your own queue:

http://api.drupal.org/api/drupal/modules!system!system.queue.inc/group/queue/7

Then use your callback to run each item through feeds.


Filter node indexes by current domain I'm building a D7 site using domain access. What I need now is to make a nodes list for each domain. The list would make use of the Facet API. And the list would only display the nodes on that specific domain.

I used to think adding a NODE INDEX view page, with "avaliable on current domain" filter would do the trick. But then I found there is no "avaliable on current domain" when views is selecting Node Indexes from the database !

What sould be done to restrict the results to current domain?

FYI, the site is using database search, not apache solr

For showing nodes of particular domain on a particular domain, you dont need avaliable on current domain. First you have to see, if you are able to see the list of nodes on a particular node without applying the filter on a normal view.

If you cant see the content, then you will have to change some settings by going to link.

admin/structure/domain/settings

Under Advanced Settings, in Search Settings, check Search content for the current domain only

Under Domain Specific Settings >> Domain Settings Behaviour >> Use the active domain


Convert query to D7 for db_query_range How do I convert the query below properly to 7x?

$query = db_query('SELECT latitude, longitude FROM {zipcodes} WHERE city = UPPER("%s") LIMIT 1', $search_term);

$query = db_query('SELECT latitude, longitude FROM {zipcodes} WHERE zip = "%s" LIMIT 1', $search_term);

The Coder module advised that I change it to db_query_range so I tried the code below.

$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, array(':city' => $search_term);

$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.zip = :zip', 0, 1, array(':zip' => $search_term);

As far as I can tell your code is fine except for a small syntax error; you're missing a closing parenthesis on the end of the statement. It should be:

$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, array(':city' =>$search_term));

It's often handy to split the arguments out into a separate array so this sort of thing is easily avoidable:

$args = array(':city' => $search_term);
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, $args);


Edit tabs and configure gears are missing on all content types in my drupal 7 website How can I get my edit tabs and configure gears to appear? I switched themes and they appeared, but they just seem to not be working in the theme that I am now using.

Any ideas?

Thanks!

page.tpl.php needs $title_prefix too. Add  before the main  (and the suffix after if you need to)


Add user's role as a class to all user links My goal is to attach a users role as a class to their user name anywhere it is displayed so I can color the link based on role.

I can get roles of every displayed user link using MYTHEME_username_alter:

function MYTHEME_username_alter(&$name, $account) {
  $user = user_load($account->uid);
  // I can get the roles of each user link through $user
}

Is this the most efficient way to get the role for each user link?
What is the best way to go about adding the role as a class to every user link?
Am I way off track and overlooking an easier way to complete my goal?

I don't think you can do it with username_alter. You can only modify the user name string in there. Its probably better to use preprocess. In your theme template.php. Do something like this:

function YOUR_THEME_NAME_preprocess_username(&$variables) {
  // Username is linked, use the link_attributes to inject the class or any other attribute
  if (isset($variables['link_path'])) {
    $variables['link_attributes']['class'][] = 'SOME_CLASS';
  }
  // Username is NOT linked, maybe do something else or nothing
  else {
    $variables['attributes_array']['class'][] = 'SOME_CLASS';
  }
}


How can I pass multiple values to drupal_view()? I'm on Drupal 8 and I have a view with multiple argument (list of node ID) but I can't embed this on my node.twig.html.

That's my code:

{% set myArray = [] %}
{% for item in content.field_articles_lies['#items'] %}
    {% set myArray = myArray|merge([item.entity.nid.value]) %}
{% endfor %}

{{ drupal_view('articles_lies','default', myArray()) }}

if I do that: {{ drupal_view('articles_lies','default', myArray.0) }}
it's ok but obviously only for one.

How can I pass an argument with multiple values to a view rendered via drupal_view() in a template?

You can't pass an array. You have to implode the array to a string first. And use '+' as glue for OR and ',' as glue for AND. Like '1+2+3' or '1,2,3'. And maybe you also have to enable Allow multiple values in your view (in the very bottom of the contextual filter screen).

I have try that and it works but I'm not sure it's very clear:

{% set arguments = '' %}
{% set i = 0 %}
{% for item in content.field_articles_lies['#items'] %}
    {% if i == 0 %}
        {% set arguments = item.entity.nid.value %}
    {% else %}
        {% set arguments = arguments ~ "+" ~ item.entity.nid.value %}
    {% endif %}
    {% set i = i + 1 %}
{% endfor %}

{{ drupal_view('articles_lies', 'default', arguments) }}


How to save the input values in an unfinished node form Drupal 6:

Is there a way to save the values in a node form, so that if the user leaves the page before the form is completed, they can access that form at a later time and have the values that they input still in their respective form fields?

Can you use node_api to somehow save the node as "unpublished" once the user gets to a certain point in the form? How would it work if required fields aren't yet filled in at the time of the pre-save?

You could save the values in the users session ($_SESSION) and clear the value(s) when the form is submitted. You would have to use AJAX to update the values whenever a field is changed, as you can't do it when the user decides the leave the page.


How to group all custom modules under one menu using hook_menu? I just started learning drupal 7 module development. I wanted to group all my custom modules under one category (say custom). I know how to manually do that using "admin/structure/menu/manage/management". But is it possible to create a new group and put all my module menus under that group using hook_menu ?

For Example :

  function hook_menu() {
  $items['admin/settings/custom/module-name'] = array(
  //other code here
  );
}

The above code doesn't create the "custom" menu item instead it creates "module-name" menu. I want to put "module-name" under "custom" ?

Thanks to kalabro for the answer. For those who are new to module development and need the same functionality, I've posted the code below :

  function hook_menu() {
  $items['admin/settings/custom'] = array();
  $items['admin/settings/custom/module-name'] = array(
  //other code here
  );
}

You can use the "$items['admin/settings/custom'] = array();" in a separate module also.

Note :
Be sure to flush the cache. Sometimes you might need to disable and then enable the modules again for this to work...


How to get hook_install() to run all hook_update_N()? How can i get hook_install() to run all updates that I have for my module? I have in it mymod.install file.

I have tried

function mymod_install() {
  mymod_update_6001();
}

but it does not seem to do anything. If I have an mymod_update_6002() would I still call 6001(), just call 6002() or call both in the order 6001(), 6002().

I thought it would be common sense to run all the updates when you installed a module by default.

You shouldn't get your install hook to run updates. When a module is installed for the first time no updates should be necessary.

Updates are used when the module already is installed (the database or variables have been created). In that case, you don't want to reinstall the module as it will wipe all data, instead you create update_N hooks. Drupal will detect which updates are needed and those will be run going to update.php. In Drupal 6 it will auto select which updates to do, but you can change it, while this is not possible in Drupal 7.

Drupal detects which updates are needed by saving the number of the last run update. This can be changes in the database, which will allow to rerun updates in Drupal 7. Rerunning updates is usually a bad idea and will most often cause errors and can in some cases mess up your data.

Always remember to backup your database before running updates.


How to output the label of a field in a template? I am overriding the node template for a custom content type, say node-custom.tpl.php.
The content type have some fields that I want to show in columns like this :

|Label1|Data1|
|Label2|Data2|
|Label3|Data3|
|Label4|Data4|

If I use render($content['field_custom_data']) both the data and the label are drawn.
I know how to hide the label from the render using the content type display configuration but I need a solution for the label.
The site is multilanguage if that matters.

This code will print all labels .

     $entity_type = 'node';
     $bundle_name = 'CUSTOM'; //machine name of your content type

  foreach ($node as $key => $value) {

        $field_name = $key;

        $info = field_info_instance($entity_type, $field_name, $bundle_name);

        $label = $info['label'];

        print $label;
        print "<br>";
   }

You can modify it according to your need.


How to avoid Rules adding blanks to eMail Id subscribed via Simplenews? The following rule works fine, only it adds always a blank before and after the emailaddress in the database table . And that gives an error when sending the newsletter.

{ "rules_webform_block_to_simplenews" : {
    "LABEL" : "Webform Block to simplenews",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules", "simplenews_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "webform-client-form-113",
          "selected_webform" : { "value" : { "webform-client-form-113" : "webform-client-form-113" } }
        }
      }
    ],
    "DO" : [
      { "simplenews_rules_action_subscribe" : { "mail" : "[data:e_mail-value]", "tid" : "211", "confirmation" : "2" } }
    ]
  }
}

You didn't mention in your question what the data type is for that e_mail component. But you may want to experiment a bit to see if your problem is resolved by using token [data:e_mail-value-raw] instead of [data:e_mail-value].

Here is a quote from the description (in the Rules UI) about such "raw" values:

  The raw value of the selected component, e.g. "email-value-raw". However this is not cleaned up by check_plain(). This is raw user input so take care if you use this somewhere else.

If the above doesn't help, I'd also check if adding (some or all of) these Rules Actions would help (before your existing rules Action):

Add a variable, eg email_id
Set a data value for that email_id, to assign it the value [data:e_mail-value]
Convert data type of that email_id field (which you then use in your existing Rules Action).


Drush crashes after "command dispatch complete" I have a custom drush script.
This script loads, changes and saves ~10000 drupal commerce products.

After that I get the message

Command dispatch complete [1140.43 sec, 663.25 МБ]                                                                                [notice]
 Timer                Cum (sec)  Count  Avg (msec)
 page                 1140.368   1      1140367.61
 drupal_http_request  67.66      1032   65.562
Peak memory usage was 784.48 МБ [1140.43 sec, 663.24 МБ]

And AFTER that script hangs and consumes more and more memory.
Finally, after long time, script reaches 1.5 G memory limit and dies.

PHP Fatal error:  Allowed memory size of 1610612736 bytes exhausted (tried to allocate 80 bytes) in /var/www/vhosts/mysite.ru/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc on line 302

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 80 bytes) in /var/www/vhosts/mysite.ru/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc on line 302

All products which were processed by the script are sucessfully changed.

The question: why drush script hangs when dispatch is complete and what it makes for such a long time when all products are processed?
Is it sort of a post-processing?

Denis

Drush is running out of memory.

In the case of re/indexing search data via Search API, the item in that issue queue for this is Better memory usage on indexing.

To work around these sorts of issues, you can increase the amount of memory used by Drush, without touching the memory limit used by your Web server.  See Configuring php.ini for details.

In my case, in my drush.ini, I increased it from:

memory_limit = 256M

to:

memory_limit = 512M

...and it solved my Search API (re)indexing problem.


How to display events in chronological order? I am new in Drupal and I want to display events in chronological order by start date of the event.

My current setup is that the latest added event is showing.

Here is a screenprint of the View I created so far:

Any suggestions?

Your screenprint and your generated SQL statement shows that your current view is FIRST sorted by node_created_order. Though from your question it seems that you want it to be sorted by "start date of the event".

So just delete the first field in your list of SORT CRITERIA and see what happens next ...


How to apply js and css to ajax loaded content? When content get loaded through ajax, neither theme.css or js get applied. Below is code snippet,

controller

    $twig = \Drupal::service('twig');
        $twigFilePath = drupal_get_path('module', 'mythemename') . '/templates/test.html.twig';
        $template =  $twig->loadTemplate($twigFilePath);
      $markup = $template->render(array('gainerList' => $gainerList, 'loseList' => $looserList));

        $build = array(
            '#type' => 'markup',
            '#markup' => $markup,
            '#attached' => array(
                'css' => array(
                    drupal_get_path('themes', 'mythemename') . '/css/theme.css'
                )
            )
        );
        return new Response(render($build));

Is there any issue with above code?

Also below testing code does not hide the second .

 $build = array(
            '#type' => 'markup',
            '#markup' => '
Demo text content

Demo text content
',
        );
        return new Response(render($build));

Js file code snippet:

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.company = {
    attach: function(context, settings) {
        $.ajax({
                url: "get-top-performing-fund",
                type: 'GET',
                success:function(data, error){
                    console.log(data);
                    $('#topPerforming').html();
                    $('#topPerforming').html(data);
                }
        });
    }
}
})(jQuery, Drupal);

Is there any issue with above code?

Yes, you're using the D7 approach. In D8 it is different. You need to create a libraries.yml file where you will define your CSS and JS files.

See:

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

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

Once you have a library you can attach it like this:

  '#attached' => array(
    'library' => array(
      'your_theme/library_name',
    ),


Creating a rule for changing user role when related profile is filed I have created 2 profiles with using profile2 for users lets name them A and B. All users will have role authenticated when they subscribe and will have to fill profile A.
Then after completing subscription they can become "Pro" user by filling profile B fields. Now I want to change the user role when he fills this profile to "Pro".
I was thinking about doing this with rules but couldn't make it up until now.
What is the best way to do this?

This is doable with Rules:

Create rule that reacts on two events: 'After updating an existing profile' and 'After saving a new profile' - both are necessary because at some point, users might not have the profile created yet.
Add conditions to see if all fields are filled in (use "Data comparison", "Data value is empty" or "Text comparison" conditions and their negations based on what type of fields you have)
If all the conditions are met, give the role to the user with action "Add user role".

Btw. you do not have to worry if the user already has this role, it will not cause any unwanted behaviour if it is assigned several times.


How do you add information text to a Drupal 7 form? I have this:

$form['rate_the_room']['room_rating'] = array(
  '#type' => 'radios',
  '#title' => 'How would you rate the room you stayed in?',
  '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5),
  '#default_value' => isset($values['room_rating']) ? $values['room_rating'] : NULL,
);

$form['next'] = array(
  '#type' => 'submit',
  '#value' => t('Next')
);
return $form;

This will produce a radio button block where you can select the rating for a room and then a submit button right after it. I want to be able to add a block of text inbetween these two elements. That block should be:

Hello

Is this possible or would I have to somehow make it part of the actual fields?

To add plain text to forms, you use #markup- see the Form API.

$form['rate_the_room']['hello'] = array(
  '#markup' => '
Hello
',
);


How to change wrong English sentences in contributed module? Sometimes we find grammatically wrong English sentences or spelling mistakes in some contributed modules. While doing translations, we can translate the way we want.

But how to change these kind of sentences or words, also if the client wants to change it in English? As we know, we can't do changes even in contributed modules.

So, do we need to write custom module or use String Overrides module or contact the maintainer/contributor?
Which is the best way to do it?

Another approach is to use GIT for such contributed modules to actually change such sentences or words. E.g. with the master branch corresponding to the official version of such module, and a branch containing all the changes.

In doing so, it is straight forward to also create a PATCH each time such changes are needed, which you can then also attach to an issue in the issue queue to report about such changes. Bonus: you're contributing to Drupal! ... Which should also show up in your D.O profile ... By creating such "issue" (in the module's issue queue, the module maintainers will get notified automatically (unless they turned of such notifications for their modules). So that's "a" way to contact the maintainer/contributor. Refer to comment #1 in issue # 2327917 for a contributed patch containing only a 1 character typo correction (remove an "s" that was not appropriate), and which I committed afterwards.

If you're not able or willing to create such patch, then at least "report" about it in the issue queue, even if it is only some small issue (in the format of a few lines or text about the typo to be corected). Such issues should get picked up soon by the module maintainers (who will transform that in a patch, etc).

And next time the module gets updated, you use GIT to also update the master branch of that module in your own site. After doing so, you then also use GIT to re-apply all relevant changes that are needed for the new version again. For patches that got accepted in the official version of the module, you won't need to reapply their changes anymore of course.

With this approach, you've reduced your issue to something like maintaining a custom version of a module, and at the same time you're contributing to a permanent solution to reduce the need for such changes in the future.


How do I set up default.settings.php to use it for development, testing and production sites? I use dev, tst and prd environments for my Drupal 7 site set up.
I use git for version control.

I would like to eliminate one manual step I need to do when moving site from dev to tst and from tst to prd.

Now I have to update settings.php separately for dev, tst and prd sites.

I would like to set up default.settings.php file so all the settings for dev, tst and prd are stored in one default.settings.php and. after copying to settings.php, Drupal will pick right settings depending on the environment.

I am looking for something like the pseudo code below:

common.settings

if environment = dev then
   ...
   dev.settings
   ...
else if environment = tst then
   ...
   tst.settings
   ...
else if environment = prd then
   ...
   prd.settings
   ...
end if

Do you know how to do this for Drupal 7, exactly?

Don't use the same settings file like you are suggesting with your pseudocode. Instead, use three different settings files in three different folders, each folder corresponding to the domain name of each of your instances.

As a minimum, generally each environment is going to use a separate database host. Other settings that can differ from environment to environment can include the Apache Solr host, memcached settings, temporary folder and files folder, to name a few. You can place all of those there. When you migrate your database from PROD to TEST to DEV, it will automatically pick up the settings you specified.

Imagine that my site is called myfoobarsite.com. This is how my settings structure would look like:

/htdocs
../sites
..../default
....../default.settings.php
..../dev.myfoobarsite.com (DEV)
....../settings.php
..../qa.myfoobarsite.com (TEST)
....../settings.php
..../myfoobarsite.com (PROD)
....../settings.php

I also generally have two local instances of the site, one with the latest database snapshot from PROD and another where I keep all my changes. This is very useful when working with Features, and it allows you to test your features against the production database (locally) before committing. Here's the modified structure:

/htdocs
../sites
..../default
..../dev.myfoobarsite.com (DEV)
..../qa.myfoobarsite.com (TEST)
..../myfoobarsite.com (PROD)
..../mfbs.local (LOCAL ONE)
....../settings.php
..../mfbs2.local (LOCAL TWO)
....../settings.php

As for your local instances remember to make the appropriate entries in the /etc/hosts file and to modify your Apache host settings.

Just in case, I also placed a snippet from the settings.php for guidance:

<?php
$databases['default']['default'] = array(
    'database' => 'myfoobarsite',
    'username' => 'foo',
    'password' => 'bar',
    'host' => '127.0.0.1',
    'port' => '3306',
    'driver' => 'mysql',
    'prefix' => '',
);

/**
 * Apache Solr settings.
 * Use the acquia_identifier/acquia_key when hosting w/ Acquia.
 * Specify only the apachesolr_path key for your local instance
 * or instances that do not use Acquia.
 */
//$conf["acquia_identifier"] = "ABCD-12345";
//$conf["acquia_key"] = "1234f05ab12345dc1234a1234bbc1c12";
$conf["apachesolr_path"] = "http://localhost:8983/solr";

/**
 * Filesystem settings (MAC OS X, LOCAL)
 */
$conf["file_public_path"] = "sites/default/files";
$conf["file_temporary_path"] = "/Users/amateurbarista/tmp";
$conf["file_private_path"] = "/Users/amateurbarista/Sites/tfk/private";

Finally, if you're hosting with Acquia, you'll need to go to http://myfoobarsite.com/admin/config/system/acquia-agent and click on "clear keys" every time you migrate the database. That will cause Drupal to drop the keys that came w/ the imported database and pick up the ones specified in the settings file.