texts:
I am trying to use the MailManager class in Drupal 8 to send HTML mail. I got it working, but it isn't parsing the HTML markup. I think something is wrong with the headers of the email.

What I have is a custom module (Custom_forward) that contains a form and that calls Mailmanager::mail() in its submitForm() method, which contains the following code.

        // Email body
        $header = $sender . ' thought you would like to see this page from the website.';
        $personal_message = $form_state->getValues()['message_body'];
        $entity_url_value = 'toString() . '">Go to article';
        $message = $header . '
' . $personal_message . '
' . $entity_url_value;

        // Email
        $langcode = 'en';
        $mailManager = \Drupal::service('plugin.manager.mail');
        $to = $form_state->getValues()['recipient'];

        $params['title'] = 'Forward';
        $params['message'] = $message;
        $result = $mailManager->mail('custom_forward', 'forward', $to, $langcode, $params, NULL, true);

        if ($result['result'] !== true) {
            drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
            \Drupal::logger('mail-log')->error($message);
        }
        else {
            drupal_set_message(t('Your message has been sent.'));
        }

According to Drupal you also need the hook_mail method in mytheme.theme to be able to send message, you can see this method here:

function custom_forward_mail($key, &$message, $params) {
  $message['body'] = [];
  $message['subject'] = [];
  $message['headers'] = array(
    'content-type' => 'text/html',
    'charset' => 'UTF-8',
    'format' => 'flowed',
    'delsp' => 'yes',
    'from' => \Drupal::config('system.site')->get('mail')
  );

  switch ($key) {
    case 'forward':
      $message['subject'] = $params['title'];
      $message['body'][] = '' . $params['message'] . '';
      break;
  }
}

As you can see, I am setting the content type to text/html and that should tell the mail system to parse the content as an HTML, but this is not working for some reasons.

This is a testing email. All the HTML markup is not shown, but also not working.

Bassem thought you would like to see this page from the website. personal message Go to article [1] [1] http://myhost/node/81


texts: Rules triggering rules - how to enforce or disable it

texts: There are many situations in which a rule could trigger another rule.  For example, If I have a rule that reacts to a Node being created, I can trigger that rule with another rule that created a node.  The same should hold true for flagging nodes, but I have seen cases in which it does not.  I have written 'single flag enforcement' rules that are triggered by a node being flagged, which un-flag all nodes flagged by that user, then re-flag only the triggering node.  This rule should trigger itself over and over infinitely, but it does not.   How does Drupal's Rules handle these situation?  Is there a way to force rules to allow or disallow this form of cascading rule triggering (and potentially cause/prevent an infinite loop?)


texts: db_select with groupBy(CAST(column as DATE))

texts:
I am looking to achieve GROUP BY CAST(date_time AS DATE) in a db_select function in Drupal 7 but with no idea how.

The function up until now is:

 foreach ($distinct_users as $user){
    $day_record = db_select('mytable', 'p')
      ->condition('p.processed', 0, '=')
      ->condition('p.first_name', $user['first_name'], '=')
      ->condition('p.last_name', $user['last_name'], '=')

and I need to group the results by day which is in Y-m-d H:i:s in my table column.

Please advise.


texts: Insert field value into DB without node_save

texts:
I need to insert +30.000 field values in one of my client site for 1 content type only. I can not use the standard way (node_load, change, node_save) because when I save node this start a series of events and actions.

So, can I insert my values directly to the db table ? Or is there an other way ?

M.


texts: give permission of create new revision to specific roles

texts:
I need to give the permission of "create new revision" to a specific role. but nothing related to this issue appeares in permissions page! I've installed Revisioning module too.
how can I set it?


texts: Call template file, hook_theme() thru theme( hook, $data )

texts:
I am trying to call a template file but without luck.

   /**
     * Implements hook_theme().
     */
    function my_module_theme($existing, $type, $theme, $path) {
      return array(
        'my_module_text' => array(
          'template' => 'my_module_text',
          'variables' => array(
               'myvar' => 'helloworld'
           ),
          'path' => drupal_get_path('module', 'my_module'),
        ),
      );
    }

    /**
     * Preprocessor for theme('my_module_text').
     */
    function my_module_preprocess_my_module_text(&$variables) {
      debug('text preprocessor called');
    }

I have a template file in the module directory named my_module_text.tpl.php.

When I call theme('my_module_text',array('myvar' => 'helloworld')); I get nothing. The template file is not used.

Am I missing anything?


texts: What is the most reliable and fault tolerant way to integrate 3rd-party data structures via a web service in Drupal 7?

texts:
I've seen a number of strategies for integrating remote data structures in Drupal. The strategies have seemed to evolve as certain modules have stabilized and use cases have been tried.

Imagine we have a data structure "Farmers Markets" that is represented by a number of data types (market, market_hours, vender, stall, produce) etc that are exposed via a REST API. The IDs for the external service would need to relate in Drupal, ie when loading a "market" we would want to grab data from the 'market_hours' and 'stall'. What would be the best way to represent that as read-only content in Drupal that is synced on a regular basis?

I'm trying to evaluate this with the following criteria:

Data Structures in Drupal:

Nodes vs Custom Entities

A number of scenarios involving web services I've seen use custom entities. It simplifies the CRUD ops. However, these items would be "content" in that they would be viewed publicly.

Storage (Local vs Remote):

I've seen a couple of examples where services are loaded as remote entities, which this module creates a library for: https://drupal.org/project/wsdata . This sounds most appealing, but haven't seen a lot of use cases. There also examples of custom code: https://drupal.org/sandbox/fago/1493180

Syncing Data:

Feeds vs Migrate vs Guzzle vs 'Web Service Client' vs 'Web Services Data'

There are a number of options. Feeds now supports entities. Migrate seems a lot cleaner than feeds, especially for custom scenarios. I've also seen folks using a guzzle client to grab sync with remote services: http://drupalcode.org/project/ckan.git/blob/refs/heads/ckan_dgu_7.x-1.x:/ckan.drush.inc#l273. I've also noticed the WS Client module https://drupal.org/project/wsclient provides an option that has been created specifically as a rest client. Web Services Data loads directly from a service and caches it locally.

Thanks for any thoughts.


texts: Why won't taxonomy list sort alphabetically?

texts:
Running Drupal 7.28, I've created a taxonomy vocab 'care centers' with a list of terms with care center names 'Atlanta''Boston''Cincinnati' 'Detroit' etc. Problem: Care centers were entered in random order 'Detroit' 'Boston' 'Atlanta' 'Cincinnati', when I click on 'Reset to Alphabetical' they reorder alphabetically, but when I save, they go back to order entered. People self-select their care center from a drop down list populated by the taxonomy, would help if it were displayed alphabetical.

How do I get the list to sort and display alphabetical?


texts: How to display data in blocks of a given size?

texts:
Is Drupal 8, which is shown in the accordion (module views_accordion) the terms of the taxonomy. By default, the module displays the list. I want to display in the blocks of a given size (as the picture)

In the module folder found twig template views-accordion-view.html.twig with the following content:

{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {# A div wrapping the row content is required for the accordion to work #}

      {{ row.content }}

{% endfor %}

How to change it for my task? Or is there another way?


texts: How to implement Facebook style Notifications for Organic Group posts?

texts:
I am using Organic Groups, Drupal Commons. If someone posts in group, then all the members should be notified like in Facebook with the number of notifications. Similar to this screenprint:

How can I achieve that ?

Notes:

By Posts I mean a creating new node of Post content type (default) in Organic Group (and commenting part is not required now).
I have not implemented any rule for this, can you explain how can I achieve this using rules ?


texts: Copy content from Word and use paragraph style names as classes

texts:
Is it possible to copy content from a Microsoft Word document into Drupal and use the name of paragraph styles used in word as class names in the HTML?

I am using:

Drupal 7.34
CKEditor 7.x-1.15+1-dev

If I drag-and-drop content from Word into CKEditor the paragraph styles are used as class names which is good, but unwanted XML comes over from Word too. Example:

Prefixes<o:p></o:p>

A paragraph here with the normal paragraph style to test that class comes along:<o:p></o:p>

•&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; These are my own bullets<o:p></o:p>

•&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; To test if the HTML<o:p></o:p>


texts: Make URL from 1 field available to another field [Drupal 8]

texts:
Drupal 8 Twig question:

I have 2 fields: textfield and a linkfield.

When the linkfield is filled, the text entered in the textfield should become the link.
I cannot edit the node.html.twig for this, I want to do this in the field--textfield.html.twig to include the URL (if it is set).

But I don't know how to make the URL from "field--linkfield.html.twig" available in "field--textfield.html.twig"

(Needed because the link module is still a little bit broken in Drupal 8 (no optional URL possible)).


texts:
I have problems establishing a private files directory (D7.22)

I started at reading this article: http://drupal.org/documentation/modules/file.
I then created a private folder above the Drupal root, and entered its path ../private at admin/config/media/file-system. Despite being warned about the performance implications, I chose the Default download method as Private local files served by Drupal.
Then, in a content type I created a native file field named Attachment, with Upload destination set to Private files. Widget: File.

At this stage I imagined that these settings would cause an uploaded file to go inside the ../private directory. Nope, instead they go into public directory sites/default/files. Was my assumption wrong?

I tried the following debugging changes - but to no avail:

changed ../private to sites/default/files/secure
changed field widget to Media file selector
changed default download method to Public local files served by Drupal

Is it a site ghost? Am I doing anything wrong?
I really see no reason for this not to work. I'm close to filing a bug issue but would appreciate someone confirm that on their installation before I do so.


texts: Get list of nodes by field-collection value

texts:
I am having field_feature as a collection of fields (field-collection) in a content type called 'watches'. Those fields are,

field_water_resistance -> water_resistance(Term Reference)
field_gender -> gender(Term Reference)
field_function -> function(Term Reference)
field_sub_function -> sub_function(Term Reference)

And so on.

I have my query like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'watches','=')
    ->propertyCondition('status', 1);
$query->range($offset, 15);
$query->addTag('joinentity');
$query->addTag('fieldcollection');
$query->addMetaData('termscollection', $filterparams); // $filterparams is array of tids

Now I want to add above field collections in the query with the parameters (array of tids). How can we do that?

I know the EntityFieldQuery with the entity_type as field_collection_item but I don't know the same for entity_type as node.

How can we do that?


texts: Hide node created messages programmatically

texts:
I'm trying to the node created messages for a certain content type, but I can't use Disable Messages because it has a conflict the Commerce Add to Cart Confirmation module.

All the other methods (like the ones here) I've found either hide all status messages, or hide all status messages after a content type is created, which are inappropriate for me since I'm using rules to show a messages after a node is created, but I need to hide the default "__________ has been created" message, and I appreciate any help you can offer me.


texts: How do I prevent Drupal from sending an email to the admin every time a new user is created

texts:
I've inherited maintenance of a drupal 7 site from another group.  Currently, every time a new user account is created the admin is sent an e-mail about it.  The admin wants this disabled.

I've been unable to find what's sending the e-mail.  There's no workflow rule for it, and the Trigger module is disabled.  Admin Notify doesn't have any setting turned on for new users, and visitors do not require admin approval in order to create their accounts.

Some of the research I've done suggests that this is drupal core functionality with no settings attached to it.  If that's the case, how would I go about stopping it?  Any ideas on where else the setting might be for the e-mail?


texts: Proper way to define weight / country wise shipping rates

texts:
I need to configure country wise shipping rates by weight. So each country has different shipping rates for different weights. So I have divided countries in different zones. The countries in each zone have same shipping rates. So what I have done is created several flat rates services like following.

Zone 1 - 0.5KG, Zone 1 - 1.0KG, Zone 1 - 1.5KG, Zone 1 - 1.5KG, Zone 1 - 2.0KG and so on ...
Similarly Set for each Zone
Zone 2 - 0.5KG, Zone 2 - 1.0KG, Zone 2 - 1.5KG, Zone 2 - 1.5KG, Zone 2 - 2.0KG

Defined respective rates for each flat rate service. And configured like following.

Order total weight comparison
Parameter: Order: [commerce_order], Operator: <=, Value: 0.5

AND

Order address component comparison
Parameter: Order: [commerce_order], Address: Address, Address component: Country, Operator: is one of, Value: AL ...

This works for me well, but I have to configure 91 flat rate service and define the conditions manually again and again.

Though at the end I am getting my desired result, I feel there must be a better way to achieve this task, but I am not aware of that.

Please guide me to do it properly.


texts: How to assign define role to group creator in groups created with the Group module?

texts:
I am using the Group  module. Whenever a new group is created, member is added to that group with role none.

I want to assign a role to a group when a user creates a group. How can I do that?


texts:
I'm in the process of upgrading from Drupal 6 to Drupal 7 and the upgrade process terminated due to disk usage error.

I found out that ibdata1 occupies 98% of /var. So I decided to empty this file so I can have the space again and re-run the update.php, but I got bunch of SQL PDO error.

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': SELECT name, value FROM {variable}; Array ( ) in variable_initialize() (line 943 of /var/www/vhosts/drupal/includes/bootstrap.inc).

    mysql> show engines;
    ERROR 2006 (HY000): MySQL server has gone away
    No connection. Trying to reconnect...
    Connection id:    177
    Current database: drupal_drupal

    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    | Engine     | Support | Comment                                                        | Transactions | XA   | Savepoints |
    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    | MyISAM     | DEFAULT | Default engine as of MySQL 3.23 with great performance         | NO           | NO   | NO         |
    | MRG_MYISAM | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
    | BLACKHOLE  | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
    | CSV        | YES     | CSV storage engine                                             | NO           | NO   | NO         |
    | MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
    | FEDERATED  | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
    | ARCHIVE    | YES     | Archive storage engine                                         | NO           | NO   | NO         |
    +------------+---------+----------------------------------------------------------------+--------------+------+------------+
    7 rows in set (0.06 sec)

Do you have any idea?


texts: How to build an install profile progmatically

texts:
I need to create an install profile from an existing site. My question is what to do with the site configurations? The site is pretty complex, so putting them manually in the profile is out of the question.

My current best idea is to create features from the site, and revert them during the install, but it has a big drawback: If I have to modify something on a site that is installed this way, the state of the features will be "overridden", so they need to be ignored or recreated.

I've checked out some possible solutions, but none of them seemed to be perfect.

Ftools can "detach" features, but only for a few types of settings.
Profiler seems to be exactly what I need, but it also lacks of support for most of the settings.
With Features Override I can override the install profile's own features, but is it a good practice? I'm afraid it could cause problems when the complexity increases.
I've heard about Ctools Export Bonus, but only 600 people downloaded it yet. Is it safe to use?

So wich is the best (or the least worst) solution currently, with drupal 7?


texts:
Goal: Have a custom page that shows various elements including links, logos, images and a custom form to help the users reset their passwords (we have a custom reset password interface which sends the user a code so we are over-riding the default reset password interface).
Problem: The submit button is not firing the submitForm function on the reset password form.
Here is my code now:
In my module:
function example_theme($existing, $type, $theme, $path) {
  return array(
    'reset_password' => array(
            'variables' => array(
                'form' => NULL,
                'url'=> '',
                'main_logo_url' => '',
                'foot_logo_url' => '',
            )
        )
  );
}

In my routing:
example.reset_password:
  path: '/reset-password'
  defaults:
    _controller: '\Drupal\example\Controller\ResetPasswordController::resetPassword'
    _title: 'Reset password'
  requirements:
    _permission: 'access content'

In my Controller:
namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;

class ResetPasswordController extends ControllerBase {
  public function resetPassword() {

    //code here that sets the variables in the return array

    $form_state = new FormState();
    $reset_password_form = \Drupal::formBuilder()->getForm('Drupal\example\Form\ResetPasswordForm', $form_state);

    return array(
      '#theme' => 'reset_password',
      '#form' => $reset_password_form,
      '#url' => $url,
      '#main_logo_url' => $main_logo_url,
      '#foot_logo_url' => $foot_logo_url,
    );
  }
}

in my form:
namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ResetPasswordForm extends FormBase {
  public function getFormId() {
    return 'reset_password';
  }

  public function buildForm (array $form, FormStateInterface $form_state) {
    \Drupal::logger('rp-form')->notice('hello from build Form');

    $form['#theme'] = 'reset_password';

    $form['step_one_user_exists'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#attributes' => array(
        'placeholder' => t('Enter here')
      )
    ];

    $form['actions'] = ['#type' => 'actions'];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Send Code'),
    ];

    return $form;
  }

  public function validateForm (array &$form, FormStateInterface $form_state) {
    \Drupal::logger('rp-form')->notice('hello from validate');
  }

  public function submitForm (array &$form, FormStateInterface $form_state) {
   \Drupal::logger('rp-form')->notice('hello from submit');
  }
}

and in my twig template:
// I have other elements on the page here

 {{ form.step_one_user_exists }}

 {{ form.actions.submit }}

As I said above, the problem is that the submitForm function from the form class is not firing when I click the submit button. The form shows up on the page, you can type in the text field, you can click the button, but then nothing happens.  I have loggers in the buildForm (which logs), and in validateForm and submitForm (which do not log).
I want to use a controller because there are other variables needed on the page that change based on language and other factors, but am open to other methods of doing this (although I'd prefer to keep most of the logic out of the template).
Thanks!


texts: How can I contribute to a contrib module within the context of another active site?

texts:
I am working on a new feature for a contrib module. I have created an issue and followed the new process just put in place for contributing code, as described on Creating issue forks and merge requests.
I would like to contribute to that module within the context of the site that is driving this new feature, but I am unsure of how to achieve it and still be able to test the changes introduced in the issue fork.
How can I achieve it?


texts:
This is the only filter defined:

but the the line breaks are removed and multiple paragraphs are joined into one paragraph.

How can I fix this?


texts:
My goal is to render a warning message to IE 11 users, prompting them to use a modern browser.

I'm a bit of a noob, but from what I understand, it's possible to detect a user's browser using a preprocess function. I found this function online, which looks like it does what I need it to do, but I'm getting a "The website encountered an unexpected error. Please try again later." error when I add it to my THEMENAME.theme file.

function THEMENAME_preprocess(&$variables, $hook){
  if (get_browser_name(htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8')) == 'Internet Explorer'){
       $variables['browserIs'] = 'IE';
   }
   else{
       $variables['browserIs'] = 'OTHERS';
   }
 }

Any ideas on how I can accomplish what I need?


texts: How to know which method is not covered by Unit test?

texts:
I want to finish the Unit test for a contrib module and I want to know if there is a way to know the methods that don't have tests, so this way, I can identify the tests I need to implement.

Is there a way to do this?


texts: Drupal 7 - Internationalization module - some blocks not visibile (i18n)

texts:
After adding the Internationalization module for Drupal 7, I am having some trouble with a particular block not showing up when switching languages.  I set the block to be translatable (and set full html to be translatable) - the block only contains an image and is displayed in the "slideshow" region of the IV Solutions Theme.  The block/image shows up fine when the page is set to English, but when the language is changed, it disappears.

Thanks for any assistance you can give-


texts: Returning a db query for select options in webform

texts:
I am trying to return dynamic select options for a webform component.  I have it working to return node titles, but I need to instead return values from a manually created table in the db that is not drupal related.  How would I alter this function to achieve that?

function _MY_MODULE_get_rate_options() {
    $nodes = array();
    $select = db_query("MY DB QUERY HERE");
    foreach ($select as $node) {
        $nodes[$node->nid] = $node->title;
    }
    return $nodes;
}


texts: Reference (include) php file in content summary

texts:
In my content summary section I will have the same information for each node. I would like to reference an external php file so that down the road if I ever need to change the summary content I don't have to go through each one and manually change it.

I set text format to php code.

In the summary I added:

<?php include("external.php"); ?>

Problem is that I am not seeing the contents of the php file. In fact, I am not seeing any sign of it in my code.

Am I going about this the wrong way?

Edit: I basically want to be able to change some static HTML that needs to belong in the summary field of my nodes if I ever need to without having to go into each node and change it manually. The text will be the same for all my nodes.


texts: Modify how Drupal builds fields on a per form basis

texts:
I want to change the way Drupal builds specific fields on a specific node edit/add form on my site. For example, when I use print drupal_render($form['textarea']); in my node--CONTENTTYPE--form.tpl.php file, I get the default Drupal render of the field widget. I want to modify the HTML markup of the field widget.

There are three ways I can think of that might solve this problem:

Using a forms equivalent of the theme_field() hook. This seems ideal, but after searching for the last few hours, I haven't found anything on this.
Building custom field widgets for every field type I'm using on that node. This is definitely not ideal and I have to believe there's an easy way to do this in Drupal from a theme point of view.
Manually build the HTML markup for the form and field in node--CONTENTTYPE--form.tpl.php with print $form['textarea']['und'][0]['title']; and the like.

Is there a hook in Drupal to do this, or must the code for every field I want to modify be manually generated?


texts:
I'm trying to work on a site that's using Panels to, among other things, create a sidebar navigation menu. It's working well on a page that exists in the menu tree structure:

Primary links

Info Page

One type of info
Another type of info

Updates

One category of updates
Another category of updates

Another page

With some subpages
Of its own

On the Updates the menu (correctly) appears as such:

Info Page
Updates

One category of updates
Another category of updates

Another page

I want to create essentially the same structure, with only a selected part of the menu expanded, but on pages that are not themselves part of the menu structure (i.e. individual updates within the categories of updates). Ideally I'd like to do this based on the path alias or content type or something of that nature, so all updates show a menu with the whole updates category expanded (but not Info or Another)

How do I do this with Panels in 6.x?


texts: How To Add Button To Commerce POS Command Pane?

texts: My module needs to implement a custom payment workflow. I want to add a button to the Commerce POS command pane to perform a task, then modify the order entity according to the result of the task.


texts:
I have a page of content type insert which adds images to my website. It currently just displays images in rows when you click to view the album name pages.

I have installed FlexSlider as I want to use that module to display all images  that are on pages that contain /Album/AlbumName in the URL  as a slideshow automatically. How do I do that in Views?


texts: What's the right way to have a contextual link on controller action?

texts:
I just installed a custom module and created a controller with index function in it. I want to have a contextual link for this. I have following code in index function.

public function index() {
    return [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: hello'),
        '#contextual_links' => [
            'mymodule' => 'mymodule.another_action',
        ],
    ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure Custom Module'
  route_name: 'mymodule.another_action'
  group: 'my_module'

Please suggest the right way.


texts: Translating pages, only the last version remains

texts:
I am setting up my first Drupal site, with Drupal 7, which is multilingual; I thought after surprisingly much work I had set it up correctly.
I can choose a language for each page, and translate pages, but when I translate a page, all translations of that page will have the same text: the last one I entered. So the text of the other language versions is overwritten by the last edited one. Did I do anything wrong? Is there a bug?

You may have a look here.

The login credentials, if you want to test it are: test, test.


texts: I would like to edit the functionality contained in nodereference_autocomplete() so that it will only return a subset of all nodes. What would be the best way to override this default functionality?


texts: How can I add the og to a menu when a new organic group is added?

texts:
I want to create organic groups that represent counties, and have a menu with some states already Set up, so the user can just select the state for the organic group to be listed under.  The title of the organic group will be the name of the county, which should be the same as the link in the menu.

Is there a way that this can be set up when the organic group is being created?

I'm using the latest release of drupal 6, and organic groups 6.x-2.1.

Is there a module that allows you to automatically assign a sub menu for group content without the user being able to change what the menu title is called? I guess that, ideally, I'd like to have an About page that has the same title and menu path for each group.


texts:
I want to theme the Recent Content block with associated thumbnail of each node. After researching for a long time I found the function node_get_recent(). This function selects data from table 'node', but this table doesn't include any url pointing to the url of an image, which means I am not be able to use $node->(url of this thumbnail) to fetch its thumbnail. I happend to find the url of the thumbnail is located in the table 'file_managed', but I still cannot associated it with table 'node' through leftjoin.

I do not know how to do it the right way. I do not want to use Views. Thanks!

When I put the following code into my .module file the title displayed for each node is the same.

function example_contents() {
  $number_of_post = 10;
  $result = db_query("select n.title,n.nid,f.entity_id,fm.fid,fm.uri from {node} n left join {field_data_field_image} f on n.nid=f.entity_id left join {file_managed} fm on f.field_image_fid=fm.fid   limit $number_of_post");
  $items = array();
  foreach ($result as $node) {
    $items[] = l($node -> title,'node/'.$node -> nid);
  }
  return array('#markup' => theme('item_list', array('items' => $items)));
}

$node -> title turned out to be same, however $node -> nid worked. That is to say the list of nodes used the same title but different urls. What was wrong with my code? Secondly, I do not know where to put my $node -> uri into $items[] in order to display the thumbnail.


texts: hook_menu shows in menu but not show page

texts:
I made module, and want to add settings page.

Menu Item appear in settings dashboard, but when try access page it display dashboard with menu items again, thought URL is correct.

return array(
    'admin/store/settings/vsl_spl'=> array(
        'title' => 'SPL Settings',
        'description' => 'SPL Settings Page',
        'page_callback' => 'vsl_spl_page_test',
        'type' => MENU_NORMAL_ITEM,
        "access arguments" => array('access administration pages'),
        'position' => 'left',
        'weight' => 10,
    ),
)

and callback function is just for test yet

function vsl_spl_page_test(){
    return '
Test
';
}

Page opens with status 200 but content is wrong.


texts: How to display a view within a template only if there is something to display

texts:
I'm looking to embed a view within a template file BUT only if there is something being returned within the view.

I'm using this solution that I saw within the Drupal forum:

<?php
 $view = views_get_view_result($name, $display, $args);
 $result = count($view);
?>

      <?php if ($result) : ?>

Related Articles

        <?php print views_embed_view('related_articles', 'related_articles'); ?>
      <?php endif; ?>

So is this the right way to check if that view is returning anything? Or am I missing something there?


texts: The responsive menu (Sidr menu) is not working with anchors

texts:
I'm using the responsive menus, specifically the Sidr menu, the menu is not working when the paths have anchors.  When I do click in a item with anchor the menu is still opened.  The toogle in the menu is not working.

Thanks in advance for your help.


texts: Why would !order-summary token be available/unavailable depending on payment method?

texts:
I'm trying to use a payment gateway module (Icepay for Drupal Commerce), but I noticed that the payment method I choose in checkout influences the availability of order tokens.

I have Commerce Message configured with an email using the !order-summary token (like Commerce Kickstart does). When I choose commerce_payment_example's payment on checkout, the email contains the expected line items and total price provided by !order-summary. When I choose Icepay, this part remains empty in the email.

Could the payment method influence the availability of tokens? Is there something the payment module needs to implement for that, or should I be looking at other causes?


texts: Is performance affected on local server?

texts:
I have my drupal on a server that doesnt have access to internet.

Does this hurt the preformance?

I am getting this error on the status report :

  "HTTP request status  Fails"

If it does, how can I overcome this?

Thanks


texts: How to redirect to a node/add page after clicking on a flag link

texts:
I want to set a flag to link to a node creation page - i.e., when a user clicks on the flag ("Apply for this Job") they should be redirected to a Job Application creation page where they can fill out an application for the job.

So for flag action I selected the "Redirect to URL" action and entered node/add/job-application. But when a user clicks on the flag there's no such redirection, the user is never sent to the node creation page. Am I missing something or just using the wrong method?


texts: en/ language prefix remains after uninstalling internationalization module and dependencies

texts:
I have cloned an existing internationalized Drupal website to create a new website. This new website does not need internationalization and translation. Therefore, I uninstalled all corresponding modules.

Unfortunately, the navigation through pages still use the default language prefix en/. Drupal complains that it does not find pages anymore. Yet, when I remove the prefix manually from the URL, the pages are reachable again.

How can I have Drupal stop using the en/ prefix in URLs?


texts: how to get the region (the menu is rendered in) or block name/ID in hook_preprocess_menu

texts:
I have a menu that want to behave differently based on the region its displayed in.

By default there is no file suggestion that differentiates which twig file to be used for a menu based on the region.  Even if there was I think for the purpose of adding/removing a class it is more convinient to modify a variable in a preprocess function than keeping to versions of a twig template.

here is what I have

function THEMENAME_preprocess_menu(&$vars) {
    $test = "";
    if ($vars['menu_name'] == 'main') {
        if (!isset($vars['attributes']['class'])) {
            $vars['attributes']['class'] = [];
        }
        //test region or block name before merging
        $vars['attributes']['class'] = array_merge($vars['attributes']['class'], ['main-menu-regionA']);
    }
}

I need a way to test the region or the block name to add a specific class to the parent UL element

my 2nd choice would be to explore the hook_theme_suggestions_alter


texts: retrieving values from a database in drupal 7

texts:
I am new to drupal. I am trying to create a function that will retrieve rows from a database and display the results.From the tutorials I have read, I am trying to implement a function I have created but no results are displayed. There's just a whitespace. Where might I be going wrong? Here is my code.

function print_users(){
$query = "SELECT first_name, middle_name, last_name FROM {registered_users}";
$header = array(
array('data' => t('Cell 1'), 'field' => 'first_name', 'sort' => 'ASC'),
array('data' => t('Cell 2'), 'field' => 'middle_name'),
array('data' => t('Cell 3'), 'field' => 'last_name'),
);
$q = db_query($query . tablesort_sql($header));
while ($r = db_fetch_array($q)) {
    $rows[] = $r;
}
print theme('table', $header, $rows);

}

and am calling it as follows via a menu link

 $items['view_users'] = array(
        'title' => "view",
        'description' => 'Viewing service',
        'page callback' => "print_users",
        'access callback' => TRUE,
        'weight' => '2',

);


texts: Views relationship not been added by code

texts:
Im trying to make a abandoned cart notification module, trying to relate my notification table with the commerde_order table by its order_id in views. Right now i have this in my hook_views_data

function commerce_abandoned_cart_notification_views_data(){
    $data = array();

    $data['commerce_abandoned_cart_notification']['table']['group']  = t('Commerce abandoned cart notification');

    $data['commerce_abandoned_cart_notification']['table']['join'] = array(
        'commerce_order' => array(
            'left_field' => 'order_id',
            'field' => 'order_id',
        ),
    );

    $data['commerce_abandoned_cart_notification']['table']['base'] = array(
        'field' => 'id',
        'title' => t('Commerce abandoned cart notification'),
        'help' => t('Commerce abandoned cart notification'),
    );

    $data['commerce_abandoned_cart_notification']['id'] = array(
        'title' => t('Notification ID', array(), array('context' => 'A Commerce abandoned cart notification internal ID')),
        'help' => t('The unique internal identifier of the notification.'),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    $data['commerce_abandoned_cart_notification']['order_id'] = array(
        'title' => t('Order ID', array(), array('context' => 'A Commerce order ID')),
        'help' => t('The unique internal identifier of the order.'),
        'relationship' => array(
            'base' => 'commerce_order',
            'field' => 'order_id',
            'handler' => 'views_handler_relationship',
            'label' => t('Referencing order'),
        ),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    return $data;
}

The problem is that when creating a view i do not see my relationship to commerce orders or viceversa, (the hook works because i can create a view of type commerce_abandoned_cart_notification and add some of its fields). I know there is a commerce_abandoned_cart_notification or commerce_notification module but they seem incomplete and/or abadoned

Should i use hook_views_data_alter to alter commerce_order relatations and add one to my custom table?


texts:
I have a sub theme based off Bootstrap and my current nav bar look like this

My goal is to move the menu (Home ... contact) to appear underneath the slogan when the page is larger than 768px as it is the breakpoint when it turns into a burger button and appears on the right. I was trying to play around with the css and the page.tpl.php, but no results there. This is the first time I've used Bootstrap with Drupal.


texts: How do I relate a text field from a node to a Commerce Order?

texts:
I have a View displaying content 'X'... it has a text field called Order_Number, which may or may not contain a value which would reference the order_number field in a Commerce Order.

I would like to be able to display a field from a Commerce Order if X:order_number matches Commerce:Order Number.

Unfortunately, no Commerce fields are available in the Relation section of Advanced. I assume this is because the field is NOT an Entity Reference, right? Also, this content type already contains lots of nodes so I can't change the field type anyway. And finally, the field X:Order_Number is not an Entity Reference and cannot be because, as I said, this field will often be blank. So it's an outer join.

So, is there a way to custom join (relate?) the X:order_number field to the Commerce Order:order_number field so that if there is a match, the View will display a related field from Commerce Orders?

OR put another way: How do I get fields from Commerce Order to appear as candidates in the Relation list without an Entity Reference field?


texts: Check if theme is enabled programmatically

texts: How can I check to see if a theme is enabled on a drupal installation? I'm looking for something like module_exists() but for themes. I couldn't find anything on the documentation.


texts:
I have created a views for label printing;

1st item in the row is name,

2nd item in the row is address,

3rd row is city,

4th row is state,

5th row is Country.

All of them are fields of type contact.

Now I want two things;

If country is India, then it should not be displayed.
If two records has same Address & city & State & Country they should be aggregated.


texts: Send custom data to endpoint based on checkbox value via webforms POST handler

texts:
Drupal 8.9, webforms 5.x

I'm trying to send some text data to a endpoint on form submission via a POST handler. It's based on the value of a (single) checkbox on a webform. The endpoint only accepts specific text values, so I need to somehow convert the 0/1 to those specific text values - if checked => "Signed up", else => "Not signed up".

I want the equivalent of

"key": [webform:elements:checkbox_machine_name:checked] ? "Signed up" : "Not signed up"

if you could have a ternary in the yaml format...

Is there a way I can do this via webforms?

I'm happy to install more modules, but if possible I'd like to avoid writing any PHP...


texts:
I want to  use Services and Profile 2 together.

Like following json code:

request:

http://localhost/api/user/1

response:

{
  "uid": "3",
  "name": "test1",
  "theme": "",
  "signature": "",
  "signature_format": "filtered_html",
  "created": "1393554511",
  "access": "1393562420",
  "login": "1393562420",
  "status": "1",
  "timezone": "Asia/Chongqing",
  "language": "",
  "picture": null,
  "data": false,
  "roles": {
    "2": "authenticated user"
  },
  "rdf_mapping": {
    "rdftype": [
      "sioc:UserAccount"
    ],
    "name": {
      "predicates": [
        "foaf:name"
      ]
    },
    "homepage": {
      "predicates": [
        "foaf:page"
      ],
      "type": "rel"
    }
  },

  "profile 2 field": "test",
  "profile 2 field2": "test",
  "profile 2 field3": "test",
  "profile 2 field4": "test",
  "profile 2 field5": "test",
  "profile 2 field6": "test"
}

I find some code detail in Services Module :

modules/services/resources/user_resource.inc

/**
 * Get user details.
 *
 * @param $uid
 *   UID of the user to be loaded.
 *
 * @return
 *   A user object.
 *
 * @see user_load()
 */
function _user_resource_retrieve($uid) {
  $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);

  // Everything went right.
  return $account;
}

It seems services invoke user_load() method to get user's default information.

So I think:

Can I implement hook_user_load() to load Profile 2 fields?


texts: How to show image in teaser of any content

texts:
I have created a view which displays the recent blog entries made by users...i have placed this block in sidebar...right now the view is displaying only the recent content with the teaser..however i need the view to display the recent content along with the user picture who posted it and display any image in the teaser if the user has also posted an image in the blog...i.e., if there is an image in the blog then it should be displayed in the view and if not then the teaser should be displayed

thanks


texts: How to override version of drupal-library (JavaScript library) included with composer merge-plugin?

texts:
I'm using Webform with the composer-merge plugin to bring in its libraries:
Relevant parts of my composer.json file:
    "extra": {
         "installer-paths": {
             "public_html/core": ["type:drupal-core"],
             "public_html/libraries/{$name}": ["type:drupal-library"],
             "public_html/modules/contrib/{$name}": ["type:drupal-module"]
         },
         "merge-plugin": {
             "include": [
                 "public_html/modules/contrib/webform/composer.libraries.json"
             ]
         }
     }

I can define my own version of the same library successfully, by using the same code as Webform's composer.libraries.json does but changing the version— successful in that it is recognized:
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "jquery.inputmask": {
            "type": "package",
            "package": {
                "name": "jquery/inputmask",
                "version": "5.0.6-beta.45",
                "type": "drupal-library",
                "extra": {
                    "installer-name": "jquery.inputmask"
                },
                "dist": {
                    "url": "https://github.com/RobinHerbots/jquery.inputmask/archive/5.0.5.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "~1.0"
                }
            }
        }
    },

But unsuccessful in that it does not have priority over the one defined in webform:

Root composer.json requires jquery/inputmask 5.0.6-beta.45, it is satisfiable by jquery/inputmask[5.0.6-beta.45] from package repo (defining 1 package) but jquery/inputmask[5.0.5] from package repo (defining 1 package) has higher repository priority. The packages with higher priority do not match your constraint and are therefore not installable. See https://getcomposer.org/repoprio for details and assistance.

But i don't know how to take priority.


texts: Where does Drupal set the uploaded file name syntax?

texts:
I have a file with a filename which has a double underscore in it. When Drupal saves the file, it shortens it to be only one. ie:

  Snapshot__john_doe_2_opt.jpg

When Drupal saves the file, it removes one of the underscores and names it this:

  Snapshot_john_doe_2_opt.jpg

Where does Drupal do this? I need to account for any changes which Drupal makes to the filename and I need to know what other characters it may remove etc.


texts: How can I add arbitrary placeholder text to form fields?

texts:
I'm converting an existing site (built by someone else) from Drupal 7 to Drupal 8.

The old site uses the Field Placeholder module to add placeholders to form fields. However, there isn't yet a Drupal 8 version of this module.

I came across the Form Placeholder module, which does have a Drupal 8 version – but it won't work for my case. (Most significantly, it only allows you to use the field label as the placeholder – you can't enter an arbitrary placeholder that's different from the label.)

Is there another option I can consider?

(I'm aware that I could hack something together with jQuery. For various reasons, I'd prefer not to do that.)


texts: How to use _user_mail_notify with a defined language

texts:
as the title say, I would like to know how to use _user_mail_notify with a specified language.

According to the documentation the third parameter should be the one that override user_preferred_language() but when I specify it the language used is always the one returned by language_default().

My code is pretty simple:

_user_mail_notify($op, $account, $mail_lang);

Where:

$op is 'register_admin_created' as the account is created programmatically.
$account is the return value of user_save
$mail_lang is an object selected from the array returned by language_list('enabled') (as I understood it should be).

I don't know if I'm using it wrong or there is a bug in the function, anyone used it with a custom language and can help me understand?

Thanks you.


texts: How do I set the HTML5 date "min" attribute?

texts:
I have a date field set up on a node in Drupal 8 using the default date time field formatter. I would like the date picker pop-up to start with a specific date I have defined in a config variable.

How can I do this? I have tried the code suggested on How to add select years and months select Drupal 8.1 date picker? but it doesn't do anything for me.

I have also looked for a way to pass datepicker options to the field element (looks like you could do that in Drupal 7 date module), but couldn't find a way to do that either.


texts: Stop Youtube when changing between tabs (Quicktabs)

texts:
I am trying to stop a Youtube video when I change between tabs using QuickTabs but the video is still running, even in the iPad, I can even play the both videos, in this case Trailer and Full Movie at same time.

By the way, I am using the vanilla Youtube iFrame.


texts: Letting users remove webform submissions they've made earlier

texts:
I have a website where people can sign up for events. The client now wants the users be able to delete their submission for the event, by entering their email address, displaying a list of events they're attending, and choose which event they want to remove themselves from.

Is there any module that adds this functionality, or is it something that can be done out of the box?


texts: Multiple records entry using spreadsheet

texts:
I have a simple Content type "Contact List" with following fields:

Contact Person
Designation
Company
Email Address
Contact No

I want to create a spreadsheet-like interface for my users to past their multiple contacts on the webpage and get their entries recorded into the content type. I don't require full spread-sheet features like of "Sheetnode (http://drupal.org/project/sheetnode)", but would definitely require that the entered records are fully compliant with the content type validations (e.g. email addresses).


texts:
Configuring Google Analytics Module, I mistakenly kept the example code during the first 2 configurations of the module: UA-673320-6.

Then I finally out the correct code:UA-30183564-3.

From looking at my website's page source, it appears all 3 configurations are in the header as javascript snippets?

I am not sure how to get Google Analytics setup so that it is linked to my website?

<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-673320-6']);
_gaq.push(['_setDomainName', '.XXXXX.com']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-673320-6']);
    _gaq.push(['_setDomainName', '.XXXXX.com']);
    _gaq.push(['_trackPageview']);

    (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async    = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +     '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript" src="http://XXXXX.com/sites/all/modules/umi_docs_migrate/js/sphinx.js?m17g0h"></script>
<script type="text/javascript" src="http://XXXXX.com/sites/XXXXX.com/files    /js/js_IDBX5SzkJ9gGNq7x-qOE_2DZsexqguTJQGMKvi4w-Uw.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];_gaq.push(["_setAccount",    "UA-30183564-3"]);_gaq.push(["_setDomainName", ".XXXXX.com"]);var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30183564-3']);
_gaq.push(['_trackPageview']);_gaq.push(["_trackPageview"]);(function() {var ga =     document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src =    ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-  analytics.com/ga.js";var s = document.getElementsByTagName("script")        [0];s.parentNode.insertBefore(ga, s);})();
//--><!]]>
</script>


texts: Second managed_file upload field fails with "An unrecoverable error occurred"

texts:
I have a form with two (ajax enabled) upload fields.

Submitting a file to the first one works, then submitting a file to the 2nd does not, giving

  An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (20 MB) that this server supports.

(the "likely exceeded" bit is wrong in this instance)

Looking at the code and the network requests it looks like the first is POSTed to a URL including the form build ID, and includes the same build ID in the POST body data. The second is posted to the same URL, however the result of uploading the first is that the form's hidden build id has changed -this is why the code in file.module rejects it and issues this error.

Thing is, I believe this has been working until recently (perhaps a recent upgrade of Drupal 7?) as I'm only getting these reports now but the code has been unchanged for at least a year.

Any suggestions?

(Drupal 7.69)


texts: How to change search_api_server options via CLI

texts:
I'm using drupalvm to create my local dev environment, and am writing scripts to automate importing an existing site's db and changing other settings so that it's more like our actual server-hosted sites.

Drupalvm creates a Solr server at /solr/collection1 and uses HTTP, whereas the existing site looks for a Solr server at /solr/live and uses HTTPS. When the db is imported, the local site is looking in the wrong place for the Solr server.

I'd like to check the feasibility of adding another .sh script that changes the db entry for search_api_server so that it uses http and /solr/collection1.

I tried using a sql command to update/set the new value for search_api_server 'options', and it does successfully change the scheme to HTTP but doesn't change the path. Also, when I load the site's search api server admin page, the options seem to be completely empty at first and you have to edit and save them again for it to stick.

P.s. I am also currently testing changing drupalvm's default Solr server so that it uses /solr/live and https, but having some issues with the https part.


texts:
I have a content type: "artist_news" which has an entity reference to "field_artists". So that when you create a news story you attach it to an artist.

the url for this might look like this: /artists/picasso/news/my-news-item

I am trying to create a view block, to appear on the page "/artists/picasso/news/" that shows all news "artist_news" items that reference any given artist (e.g. picasso)

I cannot figure out how to exactly structure it. I suspect I need to use contextual filters but the exact settings of contextual filters is escaping me.

Thank you in advance for your help.


texts: What is the template file for node add/edit page?

texts:
I need to add extra CSS styles for a set of fields in the node add page for the jobs content type, but I don't know what template file should I use. I enabled Twig debugging, and I tried the following options.

page--node--add--jobs.html.twig, but it shows all regions
hook_theme(), but the custom template is not getting applied

My code for hook_theme() is the following.

 function custom_module_theme() {
  //  dpm("node:".drupal_get_path('module', 'comp_jobs'));
  return [
    'node-jobs-form' => [
      'render element' => 'form',
      'template' => 'jobs',
      'path' => drupal_get_path('module', 'comp_jobs') . '/templates',
    ],
  ];
}

What template file should I use, and how do I tell Drupal to use that?


texts: How to hide a custom user field in user profile?

texts:
In Drupal 7, what is the best way to prevent any non-administrative user from changing a custom user profile field?

Use case: I've created a user field called "Customer ID" that I do not want the user (any of my actual customers) to change. The field exists for my own reference and for programmatic usage in other modules. I don't mind the user seeing Customer ID, but they should not be able to edit it.

Should I override the page template for the user profile page? If so, how is the template changed to make a field read-only or invisible?

Thank you very much for your help!

Chris


texts:
I have a Comodo certificate for my site to serve content using HTTPS.

I would like to add the Comodo TrustLogo (https://trustlogo.com/) so that it appears on every content page. The problem is that the JavaScript comprises of two parts that must be placed in specific locations according to Comodo:

a) One piece must be loaded just before the HTML HEAD closing tag.

The generic code Comodo wants me to include is:

b) The second piece must be included just before the HTML BODY closing tag.

The JavaScript is this - anonymised for site-specific content:

Positive SSL Wildcard

Since Bartik and other themes do not meddle with the HTML page stuff (only with the actual content) I looked into messing with the file

  core/modules/system/templates/html.html.twig

and add some content there, but stuff does not appear - it seems ignored as it doesn't even appear in the HTML source...

Please help!

Thanks,
Michel


texts: How to display the variation of a custom display in Twig

texts:
In my type of product variation, I have 4 different display :

Default
Panier (Cart)
Teaser
Teaser relation

I have created a template for product type and want to display the "Photo" field of the "Teaser" display of the product variation type.

Here is what I put in my template:

{{ product.variation_field_produit_image }}

The problem is that it displays the "Photo" field of the "Default" display.

How to get the "Photo" field of the "Teaser" display?


texts: How can I rename uploaded files programatically? (auto-rename image files)

texts:
I am aware that the File Paths module allows administrators to use tokens to set patterns for renaming files, but as of writing (Jan 2015) there are more than 100 bugs in the queue and no updates to the dev version in almost one year.  (I also installed it and it and was unable to get it working.) So, I want to do this programmatically.

My goal is to rename all new user-uploaded image files on my Drupal 7 site to this pattern: [uid of logged in user][timestamp].extension.

Being able to rename them with the UID is very important because these files are often downloaded and exchanged (sent back and forth via email, without reference to Drupal), and we need an easy way to identify which user originally uploaded the file after it has been downloaded from the site.

I am using the Transliteration module. For inspiration, I also took a look at the File Entity Paths module, but it didn't provide me any insight.  I further consulted this article on file-naming best practices from Acquia but it provides no suggestions for doing this programmatically.


texts: Can a coupon be programmatically added to an order using the add to cart subscriber?

texts:
I'm attempting to add a coupon to an order when an item is added to the cart.  I've added an event subscriber for commerce_cart.entity.add. Within the subscriber, I use $to_apply->getPromotion()->apply($event->getCart());.

This does end up in Promotion::apply() and does call $offer->apply(), but the coupon doesn't seem to actually get applied.  I've tried to see if, once we arrive at /checkout/{order_id}, the promotions/coupons are reset. AFAICT, they are not.

I have confirmed that I can manually apply the coupon once on /checkout/{order_id}.

What am I missing?


texts: How to update custom paragaph which is added to User Profile?

texts:
I have a requirement to create/update a paragraph which is added as a custom field in USER profile. After surfing here, i got how to update a paragraph which is connected to node. But I am not able figure out for User profile. Any help will be appreciated. I used below code for saving the paragraph, but how it will linked to $user->save(); ?

$paragraph = Paragraph::create([
      'type' => 'mmodule_paragraph',
      'field_employee_id' => 'Field value',
      'field_location' => 'Field value',
      'field_name' => 'Field value',
      'field_segment' => 'Field value',
    ]);
    $paragraph->save();


texts:
I have a config page in my module were you can upload a file and change a few other settings.  It works fine IF you do upload a new file when you click save however if you don't upload a file and just try to change a setting I get this error:

Argument 1 passed to file_save() must be an instance of stdClass, boolean   given, called

The message references an error in the following piece of code:

function background_audio_form_submit($form, $form_state) {

  // The file is automatically uploaded and saved in the default
  // validation process so you just need to load the file object at this  point,
  // mark that you want to keep it, and save it again.
  // The file ID is contained in the $form_state['values'] array
  $file = file_load($form_state['values']['background_audio_file']);
  file_save($file); <-- THIS IS WERE THE ERROR OCCOURS

  variable_set('background_audio_upload_path', $file->filename);
  variable_set('background_audio_height', $form_state['values']['background_audio_height']);
  variable_set('background_audio_width', $form_state['values']['background_audio_width']);
}

Can I do something like if $file is changed then execute it if it is NOT changed ignore it?    If so how would I do that?


texts: Translate the frontend part of the site only

texts:
I am working at a project that needs a biilingual translation (content + interface). I've installed the following modules:

Locale + Content translation (core modules)
Internationalization Module (i18n)
Variable Module (required by Internationalization) – it deals with meta tags
Admin Menu

I can't find a way to:

To provide interface translation for front-end only. Admin should be in English

Note: I assume this can be done by deactivating the language block on admin side) but how can this be done without duplicating the theme (the same theme for admin but with the block language disable).

How can this tasks could be accomplished?


texts:
I am developing a website with Domain Access. Each domain has the same structure but different content. I would like to show online users. When I activate who's online block from block list in admin, it will display all online users. But, I want to display the 'online user' for a particular domain.

I use Domain Strict module so users login only their assigned domain.

How can I show 'online user' of a particular domain using Who's online block.


texts: How can I remove the default value _none in a select list?

texts:
Created a content type and added a field "list(text)".
Under field settings marked the field as required.( Please make a note of an option for default value where the value is set to None by default).
Started creating content and given all the mandatory fields and left the value of the select-list field to default like 'select a default value' and try to submit the content.
The form gets submitted without HTML5 validation(i.e it is not showing a popup that the field is required to the user while filling the form.) but server side validation is in place so one can observe form error after submitting the form that field list is required.

Noticed the reason behind the HTML5 validation not working is the value for the option is a string '_none'.

How to remove the default value "_none" from select-list.


texts: How to check the stock count of an ubercart node

texts:
I'm using a using a custom function to display child nodes of a taxonomy term while displaying the term page. Here is the function

function theme_name_child_terms($vid = 1) {
  if(arg(0) == 'taxonomy' && arg(1) == 'term') {
    $children = taxonomy_get_children(arg(2), $vid);
      if(!$children) {
        $custom_parent = taxonomy_get_parents(arg(2));
          $parent_tree = array();
          foreach ($custom_parent as $custom_child => $key) {
            $parent_tree = taxonomy_get_tree($vid, $key->tid);
          }
          $children = $parent_tree;
      }

    $output = '
';
    // Avoid unnecessary "Invalid foreach" errors showing up in the log:
    if (!empty($children)) {
        // If not empty, run the foreach loop:
        foreach ($children as $term) {
            // Then check to see if any nodes exist for that term id:
            $number_of_nodes = taxonomy_term_count_nodes($term->tid);
            // If there ARE nodes...
            if ($number_of_nodes > 0) {
              // ... then add them to the output:
              $output .= '
';
              $output .= l($term->name . ' (' . $number_of_nodes . ')', 'taxonomy/term/' . $term->tid);
              $output .= '
';
              }
        }
    }
    $output .= '
';

    return $output;
  }
}

This is the output: screen shot. You can can see that it's showing terms and node counts in brackets for items that are not in the 'jewellery' catalogue anymore as they are sold.

The problem I have is that the nodes i'm dealing with are products in an ubercart catalogue - - all items are unique as it's an antique trading site. The function above still counts 'sold' items as nodes associated with the term - a sold item is of course still tagged with a taxonomy term  .  - so, some terms are leading to blank pages, because I filter out nodes that are sold, from the taxonomy view.

Can another step be added to the function that checks each node associated with a term if it is a has stock level of 1 or above?

I've found the following function in uc_stock.module:

/**
 * Get the stock level of a particular product SKU.
 *
 * @param $sku
 *   The Ubercart product SKU of the stock level to return.
 * @return:
 *   The SKU's stock level, or FALSE if not active.
 */
function uc_stock_level($sku) {
  $stock = db_fetch_object(db_query("SELECT active, stock FROM {uc_product_stock} WHERE sku = '%s'", $sku));

  if ($stock && $stock->active) {
    return $stock->stock;
  }

  return FALSE;
}

I just can't figure out where or how to call this function in the original function. It needs to be passed the product 'sku', but i'm not sure how to give it that parameter.
I guess it should be something like:

$stock = uc_stock_level($sku);
  if ($stock > 0) {
    ...
  }

Any help much appreciated.


texts:
Is there any way to make a custom page.html.twig template in Drupal 8?

By default, Drupal generates some suggestions, but I'm looking for something like page--node--content-type.html.twig.


texts:
I need to have price field which will display a price field. This field is a number with the dollar sign (i.e. $200). In my view, this price field will be used for sorting also.

I have installed and enabled the currency module and the currency API.

Via structure > content type > manage fields > I tried to add a new field. But the list of field types do not have the 'currency option'. So I am not sure how I should add the currency field with a dollar sign.

My question: How can I add a field to a content type which will accept a price value in the format of a currency?


texts: Why some twig templates have no file name suggestions

texts:
I have enabled twig debug. The following source snippet shows that there are some templates has no any suggestions such as views-view.html.twig:

Latest Articles

The question is: why those templates has no suggestions like others? Is there any way to have suggestions for them or even any way to replace them with another templates files for specified place such as, hypothesis name of course,  node--article--teaser--view-views


texts:
I want to allow all authenticated users to upload files, but I want them to be approved first before they're publically viewable.  I'm currently using a single image field for the uploads, that can have unlimited values.

I'm not sure what is a good way of going about this.  Let's say, the user uploads 4 images, which are all shortly after approved.  Then, later, they upload one more image... I still want the first four to be publically viewable, but I don't want the fifth one to be until it's approved.

Also, I am kind of concerned about the fact that the files would be downloadable immediately, as soon as they are uploaded via sites/default/files.  Is this a big deal?  Concerned about copyright violations and such.


texts: Adding nodes to term instead of terms to nodes

texts:
Is there a way to easily add nodes to terms? In other other words, let's say I have a taxonomy called top 5 sellers and I have a collection of nodes that represent books.

Currently it's hard to manage something like that because I have to search and find each book, and then assign the taxonomy term to it. I'm looking for a way to do it 'the other way around' where I have a gui that lets me choose a taxonomy and then choose nodes to add and subtract to it.

I hope that is clear. Any ideas?


texts: Why my first tab is missing for local menu tasks defined by hook_menu()?

texts:
I am learning how to use hook_menu(). I am at a point where I have a question and not figure it out. I have a local task button inline with View and Edit and I want 4 sub-local_task buttons. See chart below.

View | Edit | **Outcomes** |

*Outcomes Viewer* | Add New User | Add Bulk Ghost | Registration Report

However, the first button(Outcomes Viewer) is missing and I cannot figure out how to get it to show up. Below is the menu code within the function. The Outcomes Viewer is a view. I am mixing this with some custom code and views as well.
(*Drupal 7, Views 3)

$items['node/%node/ecg-outcomes'] = array(
    'title' => 'Outcomes',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 50,
  );
  $items['node/%node/ecg-outcomes/'] = array(
    'title' => 'Outcomes Viewer',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add Bulk Ghost',
    'page callback' => 'entity_ghost_participant_report',
    'page arguments' => array(1),
    'access callback' => 'entity_ghost_participant_access_report_tab',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'entity_ghost_participant.reports.inc',
    'weight' => 11,
  );
  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 14,
  );


texts: Submit donation form as product with instant checkout?

texts:
Wondering what's the best way to go about using Commerce 2 to present a single page donation form to the user with an instant buy/donate button? I.e. no add to checkout then going through the checkout procedure.

User should be able to enter any donation amount into the form, along with their contact details etc.


texts: How to change permissions to a role when a content is set as published

texts:
I have been working with Drupal 8 and need help: I have a News content type, and an Editor role type. This Editor role can view/edit/delete his own content. I want that Editor roles can't edit/delete their own content when this content is published by Admin roles.

I have been searched and I found Permissions by fields, Permissions by terms, Groups and Custom Publish options modules, but I can't make this works.

Maybe this can be done with php, but I don't know how.

Please, any help?


texts: Get result view with formatter programmattically

texts:
Example a view with show fields:

I want retrive array result like this:

[
  [title,
   date_start
   data_end
   ...
  ]
]


texts: How to set a default controller if no other routes match

texts: I my project I would like to have a default route or controller that handles any request that does not match any available route. For example on requesting /abcd it now returns 404 as there is route defined for the path /abcd. I want any such request to be handle by a default controller that consider 'abcd' or any other string for that matter as a parameter. How can I implement that. If I define a route for path /{param} wouldn't that override other active routes


texts: drupal_render not working in views-exposed-form.tpl.php?

texts:
I put this in the template:

<?php print drupal_render($form['title']); ?>
<?php print drupal_render_children($form); ?>

Neither renders anything. If I dsm($form) the variable looks correctly populated.

Any ideas?


texts:
In Field UI RouteSubscriber we have this route:

$route = new Route(
  "$path/fields/{field_config}/delete",
  array('_entity_form' => 'field_config.delete') + $defaults,
  array('_entity_access' => 'field_config.delete'),
  $options
);

{field_config} is converted to an entity because "_entity_form" has attached a paramconverter to it. How would I go about adding that to a _controller?

$route = new Route(
  "$path/fields/{field_config}/delete/some-path",
  array('_controller' => '\Drupal\my_module\Controller\SomeClass::someFunction') + $defaults,
  array('_entity_access' => 'field_config.delete'),
  $options
);


texts: Form Ajax not working when rendered from Ajax callback

texts:
I am trying to load a Drupal form through an AJAX callback when the user selects an option from a select list. The code used to generate this form as follows:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['dashboard_list'] = array(
    '#title' => t('Select Dashboard:'),
    '#type' => 'select',
    '#ajax' => array(
        'callback' => 'Drupal\dashboard\Controller\DashboardController::OnPanelSwitch',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => array(
            'type' => 'throbber',
            'message' => NULL,
            ),
        ),

   );
return $form;
}

Inside of OnPanelSwitch(), which is called when the user selects an option from the list. I am using the renderer service to get the form's HTML and then inserting the form into a div.

 public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');
$AddChartFormHTML =\Drupal::service('renderer')->render($AddChartForm);

    $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartFormHTML));

    return $ajax_response;

}

This HTML is then inserted into a DIV in the page. The form being loaded via AJAX is built in the following manner and contains a single select list:

public function buildForm(array $form, FormStateInterface $form_state) {
   $form['query_type'] = array(
      '#title' => t('Query Type'),
      '#title_display' => 'invisible',
      '#type' => 'select',
      '#options' => array(t('Chart'), t('Table')),
      '#prefix' => '
 '
',
      '#ajax' => array(
          'callback' => 'Drupal\dashboard\Controller\DashboardController::OnQueryFieldChange',
          'effect' => 'fade',
          'event' => 'change',
          'progress' => array(
              'type' => NULL,
              'message' => NULL,
              ),
          ),

  );
return $form
}

The OnQueryFieldChange() callback is not being called when this form is being loaded via the initial AJAX call. If I load this form without AJAX through the twig template everything works correctly. So it seems to be an issue of the form being loaded via AJAX.

From my research it seems like I might have todo something with Drupal Behaviors to enable AJAX for this form? Any guidance would be really helpful.


texts: Can I write two cron( hook_cron() ) in one module

texts:
I have a custom module abc_xyz and i want to write two seperate cron for this module.

below is the code which i am trying but it is creating only one cron ,
with name abc_xyz_cron. it is not creating for zzz_yyy_cron

file name : abc_xyz.module

abc_xyz_cron(){

}

zzz_yyy_cron(){

}


texts: I am building a multi-step form.  For one of the steps, I have some required fields.  When the user goes back, I'm skipping the validation, but it gets hung up on my required fields.  Is there a way to disable or ignore my required fields so my user can go back a step?


texts:
I'm trying to update drupal core on a large multisite version of drupal. He only wants core updating for a security update. However, I can't see any instructions out there on just updating core without updating all the modules, unless you have drush installed. (I tried updating all of them anyway on my dev box and the update failed because of duplicate entries in the nodewords table).

He doesn't have drush and I don't have the ability to add it. Is it possible without drush?

Thanks
Alex


texts:
I'm using Drush and the migrate tools to migrate a Drupal 7 site to Drupal 8. The site uses field_collections which do not migrate. The field_collections page indicates it is probably being deprecated and recommends moving to paragraphs.

I have searched, but all of the custom migrations I have found so far have been flat fielded. I need to figure out a way to convert field_collections to paragraphs, or field_collections to custom entities.

I am generally comfortable with PHP and OOP, but building the entities and/or migrations in a new module have me confused.

How would I proceed to build a migration for a content type that included one or more field_collections, so that the field_collection data would be available in Drupal 8?


texts: Show latest content date from group content type

texts:
I've a group type vendor with following groups:

V1
V2
V3

Each group is associated with content type notes as shown below:
Notes (Content Type) with nodes associated with groups:
N1 (Group: V1)
N2 (Group: V1)
N3 (Group: V2)
N4 (Group: V2)
N5 (Group: V3)

So the relationship between them goes like this.

Vendor (Group Type)

Group V1
Group V2
Group V3

N1
N3
N5

N2
N4
None

Where N* are nodes of content type Notes
I want to create a view where following data should be displayed:
V1
    Latest content update date
V2
    Latest content update date

But I do not want all the contents update date listed. When I use grid layout I can group the content as per associated group but the output contains all the last updated date for all contents. I want to limit the output only to last 2-3 contents.
Example:
Views -> Grid Layout -> Group by group title -> Number of columns per row -> 2
Output:
V1

N1 last update date     N2 last update date

V2

N3 last update date     N4 last update date

Expected output:
V1

N1 last update date

V2

N3 last update date


texts: Can I get integers from a dynamic query using fetchAllKeyed?

texts:
So basically I want an array of integers from a query using fetchAllKeyed for the results.   The field is an tinyint in the db so I would expect an indexed array of integers but I am getting an indexed array of strings.

Here is the database call:

$query = $this->connection
  ->select('database_name', 'db')
  ->fields('db', ['first_index', 'value'])
  ->condition('db.value', 0, '<>')
  ->condition('second_index', $array, 'IN')
  ->execute();

$indexed_array_of_ints = $query->fetchAllKeyed();

I've tried to find other mentions of this issue and I haven't so maybe I'm just doing it wrong, I don't know.

I know that I can convert the values after the call, but I'm looking to make this operation as fast as possible so any help here would be greatly appreciated.


texts: Modules Page: Keep Package Sections collapsed

texts: As I'm working over and over with modules, I'm constantly having to scroll past all of the Core modules and such. I can collapse module packages, but when I reload the page they are all expanded again. Is there any way to make drupal remember which module packages to remain collapsed?


texts: How to add a custom field to personal campaign page - Civicrm

texts:
I'm using Drupal 7 and Civicrm 4.4.1 and I enabled the Personal Campaign Pages so individuals can create campaigns.  It comes with the standard default fields such as Title, Goal Amount, Welcome, and Your Message.  I would like to add another field to that form which I can then access through views to display in a table.

The field I'd like to add is called sponsor, so I could then show the sponsor when listing a view of all Personal Campaign pages.  I've tried creating a custom field dataset and applying it to the Contribution type that I'm using, but I didn't have any success.

Any ideas on how to create a custom field for these pages?


texts: I'm using filefield module, and it has permitted extension field. Is it possible to disallow certain extensions (e.g. exe, zip, rar) instead of adding permissions for ones that are ok?


texts: Tag to show Related Content Type and Term

texts:
I have Content A and Content B
Both share the same taxonomy tags i.e interests i.e football, sport, tennis

When someone clicks on tag
i,e term "sport"

I want it to show
All Content A with "sport" Terms tags

Not All Content A and B with Sport Terms tags

How can I do this please?

Many Thanks for your help


texts:
I have a bunch of sites running both on Drupal 6 and Drupal 7 on my server. Every site has its own folder (ie. I don't use multisites feature). I created a small script to run drush pm-update on every site.

All of this is working okay, but I noticed something strange. Often when I run, either manually or via the script above mentioned, the drush pm-update finds a update for a version of a module or core in one site, but not for others.

I tried to clear drush cache but it showed no result.

Have anyone seen this behavior and has a hint of what it is? I'm curious about it :-)

Update: Now I think it's related to this issue https://drupal.org/node/952394


texts:
Is there a simple drush site-install script for Drupal 8? I've gotten very used to running the following script to install Drupal.

drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://username:password@localhost/sitename -y;


texts: How do I use the Commerce Coupon module?

texts:
Does anyone know how to use the Commerce Coupon module?

I created a coupon discount (%) type with Product_reference field; then, I created one coupon of that type, and selected the products to wich it should apply. This seems not to work.


texts: How to add Parent and Child to a Views 3 table format using Groupping Field?

texts:
Working with views and a taxonomy list is a popular subject at DA. Many of the examples I've found refer to making a jump list of taxonomy terms and parent terms similar to what you may see with a nested vocabulary on your site's core taxonomy page [1] (following the list terms link on any given vocabulary). My Views view goal is just as simple and I'm nearly there except for two important requirements.
My Views view is a catalog of node content titles and truncated descriptions categorized by a two level vocabulary. (Think of finding something at a hardware store). The goal is a single page without a sorting requirement (think of it as a very small hardware store, so I skipped the answers suggesting wild card sorting in the URL). I'm nearly there using the table format where I've used the setting Groupping Field Nr. 1: Content: My_Taxo to organize the node content. This creates a separate table for each group and a caption element for each category.
The first missing requirement is the parent term.
The instructions for a simple vocab list say to add the Relationship, Term parent. This adds several new items to Fields: add list page. Unfortunately, none in this list are distinguished as parent term, which means I can't easily add a parent taxonomy term field, add a child term field, go back into Table: Settings set Groupping Field Nr.1 to be the parent and Nr.2 to child and be done with it. (9_9)

Content: All taxonomy terms
Taxonomy term: Name
Taxonomy term: Rendered Taxonomy term
Taxonomy term: Term description
Taxonomy term: Term edit link
Taxonomy term: Term ID
Taxonomy term: Weight
Taxonomy vocabulary: Description
Taxonomy vocabulary: Machine name
Taxonomy vocabulary: Name
Taxonomy vocabulary: Vocabulary ID

The second missing requirement, which may only be correctly answered by the first problem, is the captioned tables do not sort in the same order as the weights set on the taxonomy page list. To try to set this requirement I added, Sort criteria: (menu_category) Taxonomy term: Weight (asc)


texts:
I am using HybridAuth as my login module and I want that user have to register with email and password. How can I do that ?

In the current process, user gets mail only and then sets the password instead of doing it on the registration form.

Thanks for the help


texts: features for same content type but different structure collide in multi site

texts:
I have a multi site and one content type has different fields in it than the same content type in a different site.

When I make a feature for this content type, they conflict with each other even though I have not enabled one of them in the other multi site.

Is it possible to have different features that don't conflict within a multi site if content type is the same but with different fields?


texts:
I want to query node titles by multiple word fragments and sort it by relevance.

Currently I have this but it does not sort:

$words = explode(' ', $text);

$db_or = db_or();

foreach($words as $word) {
   $db_or->condition('title', '%' . db_like($word) . '%', 'LIKE');
}

$result = db_select('node', 'n')
   ->fields('n', array('nid', 'title'))
   ->condition($db_or)
    ->execute();

I tried the following and it throws an exception:

$sql = "SELECT nid, title, MATCH (title) AGAINST " .
      "(':text' IN NATURAL LANGUAGE MODE) AS score " .
      "FROM node WHERE MATCH (title) AGAINST " .
      "(':text1' IN NATURAL LANGUAGE MODE)";

$result = db_query($sql, array(':text' => $text, ':text1' => $text))
   ->execute();


texts:
I have a view that is a page and I'd like to be able to add a a field to this page.

My other pages are content type pages and they have the option to assign a top hero banner content type to them. How can I assign a hero banner content type to a view page?


texts: Get current node's count (rank/order?) from node.tpl in a View which renders a list of nodes

texts:
I have a view that lists multiple article nodes.
Now for each rendered node, I want to be able to know its rank/order from the list of displayed nodes.

Here's a visual representation:

[view]
    [node.tpl] $count=1 [/node.tpl]
    [node.tpl] $count=2 [/node.tpl]
    [node.tpl] $count=3 [/node.tpl]
    [node.tpl] $count=4 [/node.tpl]
    ...
[/view]

For the first rendered node, I will be able to access a variable called $count whose value is set to 1 because it's the first and so on.

Btw, I'm using Rendered entity so I'm using node.tpl not views/rows templates


texts: views and contextual filters with entity reference field

texts:
how do you use contextual filters to a views block when you want to use a reference field from the content type displaying the view?

here's the simple scenario

artist content type has some basic fields
song content type has a reference field referencing which artist
event content type has a reference field referencing which artist is headlining
view has a block with fields

on each Artist content page, it's working and i have a block of songs for that artist in the sidebar. i used views provide default entity and basic validation (but does not work for below)

on each Event content page, i want a block of songs for that artist in the sidebar. Essentially i want the reference field in the event to match up with the artist's songs.

since we don't have access to the path, i've been playing around with contextual filters on the reference field (and reverse of it) to no avail.

Ok thanks to @Jimajamma I seem to have figured it out, it's actually quite simple.

In order to get the argument into the Song view, you add a 'contextual filter' and select the Song's artist reference field. Then under 'When the filter value is NOT available' choose 'provide default value' and PHP Code. In that PHP code you want to return the value of the Event's artist reference field like so

$node=menu_get_object();
return $node->field_event_artistref['und'][0]['target_id'];

then under 'When the filter value IS available or a default is provided', choose 'Specify validation criteria' and basic validation

In a nutshell, this is simply taking the argument of the artist the Song references and comparing it to the default value you provided which is the current node's artist reference field. also as @Jimajamma said, best practice would be to use a switch statement on the node->type to be able to use the songs by %artist block on several different types of content like artist nodes.


texts: What is significance of confirmation page before deleting a node?

texts: I want to know what exactly usage of node confirm delete page except to avoid miss configuration.


texts: Add FILTER CRITERIA in Views Programmatically

texts:
I want to add/modify a filter criteria programmatically.

For example, for a view, I added an "Email Address" filter whose value is needed to change dynamically, it is needed to set to the current logged in user's email id.

How to achieve that? Please see attached image for more details. Please help.


texts: Is there a way to see what parts are not in a feature?

texts:
I am working on a site where I have content types with fields coming from several different feature modules. I've added organic groups with groups on most of those content types, and also added some content types and fields.

Now I need to package things up, update the features modules, and make new ones. I am going over things looking for overridden features, and adding fields that are missing. While I can see what is overridden, it can be easy to overlook new fields that I need to add, especially when I have to cross-reference different modules.

Is there a way I can see what featureable parts are not in a feature? Since I'm dealing with several different features, I can't just look at one 'recreate' page and see what I need to add. I would like to see a master list of what part is in what feature and what is still in the database.


texts: Can I run drush command from composer with custom script

texts: I have a nested root Drupal 8 site.  I would like to create an import and deploy script that runs multiple drush commands.  Is this possible via custom script?


texts: Drupal jquery behaviors & views - Ajax multiple times / wrong arguments - triggerHandler('RefreshView')

texts:
I am having some problems using ajax to trigger an views update (D7).

Basically there is a map (leafletMap) and when it is moved/changed/zoomed, a function gets a list of node ids and triggers a views ajax refresh.
Those node ids are passed into a contextual filter, so only matching packages in that view are displayed below the map.

The problem with the ajax is it often fires multiple ajax requests. When I inspect the extra requests one or two will have the correct arguments, but one will have the old arguments and then the view will refresh with the wrong nodes.

I've tried using return false and binding what I can to this or context. As you can see I've tried unbind()ing the
 but nothing seems to help. Often the first set of ajax calls append the wrong view, but then the next one works. And so on. To be honest I'm a bit out of my depth.

Basically I need there to be one ajax call with the correct arguments, or at least multiple ajax calls that use the correct arguments.

Any hints, ideas or suggestions would be most welcome. Many thanks.

TLDR; The below code triggers an ajax refresh of a view. This view has a contextual filter. It is triggering multiple ajax requests, some of which retain the old ajax arguments & therefore refresh incorrectly. Thanks!

Drupal.behaviors.packageFilter = {
    attach: function (context, settings) {

      if (typeof window.leafletMap === 'undefined' || window.leafletMap.length == 0) {
        return;
      }
      this.leafletMap = window.leafletMap[0];
      this.leafletMap.$map.once(function () {
        this.leafletMap.map.on('moveend', this.refreshView.bind(this));
        return false;
      }.bind(this));
      // Reset arguments back to default when not filtering map.
      $.each(Drupal.settings.views.ajaxViews, function (key, value) {

        if (value.view_name === 'packages') {
          Drupal.settings.views.ajaxViews[key].view_args = '';
        }

      });
      $('.views-exposed-form-packages-search', context).attr('action', '/packages.json');
    },

    refreshView: function (context, settings) {

      Drupal.attachBehaviors('ViewsAjaxView');

      // This gets markers from the map and converts them to node ids
      var visibleMarkers = this.leafletMap.getVisibleMarkers();
      var totalMarkers = this.leafletMap.markers.length;

      // Do not run if map isn't filtered.
      if (visibleMarkers.length < totalMarkers) {

        var visibleMarkers = this.leafletMap.getVisibleMarkers();

        var nids = '';
        $.each(visibleMarkers, function (i, v) {
          nids += v.node.nid + '+';
        });
        nids = nids.slice(0, -1);

        // nids is an array of node ids for the view to return

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name === 'packages') {
            // this should add the node ids as an views ajax argument
            // to a contextual filter
            Drupal.settings.views.ajaxViews[key].view_args = nids;
          }

        });

        var throbber = '

&nbsp;

';
        $('.views-submit-button').append(throbber);

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name == 'packages' && value.view_args == nids) {
            $('.view-id-packages').triggerHandler('RefreshView');
          }

        });

        $('.view-id-packages').unbind();

      }
    }
  }


texts: Show form errors before opening AJAX modal

texts:
I have a form that adds a product to the cart.

The form uses AJAX to open a modal when the form is submitted.

I want to show form errors (if any) before the modal opens and avoid opening it if there are errors.

Here's my form submit element:

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax' => [
    'callback' => '::submitAjaxForm'
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

My submitAjaxForm:

public function submitAjaxForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand(
    $this->t('Product added to cart!'),
    [
      '#theme' => 'some_theme',
    ]
  ));

  return $response;
}

And my submitForm:

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Add product to cart.
}

I have tried by adding this code to the AjaxSubmit but it only shows the error messages once the page has been reloaded.

if ($form_state::hasAnyErrors()) {
  foreach ($form_state->getErrors() as $error) {
    $this->messenger()->addError($error);

    $message = [
      '#theme' => 'status_messages',
      '#message_list' => $this->messenger()->messagesByType(MessengerInterface::TYPE_ERROR),
    ];

    $messages = $this->renderer->render($message);

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#result-message', $messages));
    $form_state->setRebuild(TRUE);

    return $response;
  }
}

How can I show the errors without having to reload the page?


texts: How can I filter the apachesolr_autocomplete results on a custom search block

texts:
We recently set up solr search and have been happy with it. I started using the custom_search module to set up pre-filtered search results, and while my solr search pages work well, the autocomplete search suggestions return ideas from the full site.

Is there any way to filter them based on content type?


texts: What is the Drupal 7 bookmarking module (a la delicious.com) that is equivalent to userlink in Drupal 6?

texts: I am using the Web Links in Drupal 6, and I would like to use its equivalent in Drupal 7. It doesn't appear to be a clear direction, according to Comparison of Links Page modules.


texts: Blog monthly archive block - list of posts grouped by year then month

texts:
See the implementation on this guy's blog: http://deglos.com/blog

YEAR
-- Month
-- Month
YEAR
-- Month
-- Month

Anyone know how this was accomplished?


texts: How to test if honeypot is working on a form?

texts:
I have applied the Honeypot module to my site and set it to protect all forms on the site.

The problem is I am unsure of how to test it to know that it is working as expected.

Can anyone tell me how to do this?