texts:
The last couple of days I have been looking into Drupals multisite with content sharing. Got some great information like http://palantir.net/blog/multi-headed-drupal and http://munich2012.drupal.org/program/sessions/multi-headed-drupal

It gives me a good idea of the options I have building a multisite and content sharing setup. As I am quite new to Drupal I am trying to get input on my setup and the architecture that is required to build it. I will briefly explain the architecture and then the options I think will be suited for this.

Basic setup
The basic setup is as follows. There will be 1 global website with an own admin/editor. Next to the global site there will be 10 regional websites with their own regional admins/editors. The regional websites will have content in their own language, but in the CMS there is an option to translate the content to English.

Global website
The global website will be a 1 page website and it displays content (English) from the regional websites. Content that needs to be curated by the global content-editor.

Regional websites
The regional websites are all the same (pages , nodes, content types) except for some different styling and logo's.

Access levels
The global admin can access all the websites, this can be using other logins or preferably an own global account. The regional admins/editors can only access and edit their own site.

From the information I have so far, this will require a combination of Domain Access and Organic groups but I am not sure if this is going to work.
My main concern is combining a global home with the regional websites and push content to the global home. Not only pushing but the the global editor will need to approve content before displaying it on the global home.

Does anyone know if we can build such a setup with Drupal?

Thanks in advance.


texts: Drupal 7 trim user input and other checks to prevent security issues

texts:
What is the recommended way in Drupal to perform trim and other checks before accepting user input to avoid sql injections and other similar security issues?

Thanks.


texts:
In Drupal 7, I have a form where I would like to do the following:

Display a list of options in a simple two column table
Selecting an action from a drop down list fires AJAX and replaces options in the table

I have code written and Drupal only posts values to the AJAX on the first time you pick a select. Does this just not work on form 'item' types? Note, there are also other forms on the page, but the form IDs are unique as are the form fields.

$form['new_date'] = array(
            '#type' => 'select',
            '#title' => 'Delivery Date',
            '#options' => $date,
            '#ajax' => array(
                'callback' => 'delivery_date_weekends',
                'wrapper' => 'dates-ajax',
                'method' => 'replace',
                'effect' => 'fade',
            ),
        );

$form['date_weekend'] = array(
                '#type' => 'item',
                '#prefix' => '
',
                '#suffix' => '
',
                '#markup' => '',
          );

Then in the AJAX callback, data is returned with #markup set to theme('table') of the results. It only works the first time around, I see the POST data in the Firebug console. Pick another drop down option, my table does not update.

Did I do something wrong here?

Edit: seems like the POST is making it, but the response is empty, but should not be.

Edit 2: Ajax Callback:

function delivery_date_weekends($form, $form_state) {

    $query = new EntityFieldQuery();
    $result = $query->entityCondition('entity_type', 'field_collection_item')
        ->propertyCondition('item_id', $form_state['values']['rates'])
        ->fieldCondition('field_delivery_basis', 'value', 'Weekly', '=');

    $startmonth = strtotime(date('m', $form_state['values']['new_date']).'/01/'.date('Y'));
    $endmonth = strtotime('+1 month', $startmonth);

    $query->fieldCondition('field_delivery_date_period', 'value', $startmonth, '>=')
                ->fieldCondition('field_delivery_date_period', 'value', $endmonth, '<=');

    $result = $query->execute();

    if ($result) {
        $headers = array(
            array('data' => 'Weekend', 'class' => 'tableHeader-processed'),
            array('data' => '', 'class' => 'tableHeader-processed'),
        );

        $rates = entity_load('field_collection_item', array_keys($result['field_collection_item']));

        foreach ($rates as $key => $rate) {
            if ($rate->field_delivery_available['und'][0]['value']) {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'delivery link', 'class' => array('fee'))));
            } else {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'Not Available!')));
            }
        }

        $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
    } else {
        $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
    }

    return $form['booking_weekend'];
}

Basically when a month/year is selected, I am querying for dates (inside a field collection).


texts:
I would add a webform in the checkout step of a particular product. I need this feature because sometimes the products that i offer needs more information and sometimes the information that i need are different, so the webform that i should show could be change.

I would show the webform during the checkout, i don't want to have a webform that redirect to checkout (commerce webform module i think)


texts: Fatal error: Call to undefined function db_transaction()

texts:
I am new to drupal. In an attempt to achieve transaction, I get this fatal error. I am using drupal 6.22 and MySQL. db_query() and all the other database related functions are working fine, but db_transaction() alone fails. What am I doing wrong here? Any help is appreciated.

$transaction = db_transaction();

try {
       $result = db_query($query);
}
catch (Exception $e) {
       $transaction->rollback();

}


texts: User profile fields translated but not showing up on user account modification and registration

texts:
I translated my user fields (select list) and they show up fine on:

Exposed Filters
In .po files and and translated
User Display view mode

However, they don't show up translated for users.

Hard to explain...so let me try this way:

A user registers on the site in French, with fr prefixe.

When modifying his account, the drop downs are not shown in French, they are in English. However, even if English selections are selected, the display is indeed translated into French.


texts:
I have this code in my javascript:

(function ($) {
    Drupal.behaviors.myid_print_table_id_link = {
        attach: function (context, settings) {
            $.ajax({
              type: 'POST',
              url: '?q=myid_print/table_pager',
              success: function(data) {
                console.log(data);
              }
            }).done(function(o) {
              console.log(o);
            });
        }
    }
})(jQuery);

This calls a function called myid_print_table_pager declared in my hook menu:

 function myid_print_menu(){

     $items = array();
     $items['myid_print/table_pager'] = array(
         'title' => 'Table Pager',
         'page callback' => 'myid_print_table_pager',
         'type' => MENU_CALLBACK,
     );
     return $items;
  }
 }

Below is my function:

function myid_print_table_pager(){
    drupal_add_js('$(document).ready(function () { alert("Hello!"); });', 'inline');
    watchdog('message', 'I've been here!');
}

I'm pretty sure that the function myid_print_table_pager is invoke because 'I've been here!' is seen in my watchdog table in my database. But why does the alert with the message Hello! has not been invoke?


texts:
function custom_profile_action_info() {
  return array(
    'custom_profile_mail_action' => array(
     'type' => 'system',
     'description' => t('Custom Send Mail'),
     'configurable' => TRUE,
     'permissions' => array('access content'),
     'pass rows' => TRUE,
    ),
  );
}

    function custom_profile_mail_action($object,$context) {
      global $user;
   drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE)
$check =drupal_mail('custom_profile',custom_profile_send_mail','abc@redcom.in', language_default(), array(),NULL, TRUE);
         drupal_set_message('enters the action');

    }

For adding a custom action I have written the above code but I dont get it listed in views bulk operations list in new view of format vbo
What can be the issue?


texts: How to send an email notification when a subcription renewal is due?

texts:
When a subscriber’s monthly subscription is due for renewal, an automatic email should go to that user stating that the renewal is due. There will be two possibilities:

If there is no response to the notification, automatically the CC will be charged as per the current package selected.
The automatic eMail notification will have a link to upgrade to a different package if the subscriber wants to.

How to achieve this?


texts: Alter webform value submitted by webform

texts:
I'm using a Webform, which have 3 fields:

- number of table (enter by user)

- price per table (default webform value)

- total amount to pay (calculation using formula, in webform is hidden field with no default value)

The calculation formula should be:
 total amount to pay = number of table * price per table

What I want to do is add in total amount to pay after calculation and submit to webform.

I'm writing the codes as below but it does not work.

function my_module_validate($form, &$form_state) {
  if ($form_id == 'webform_client_form_7'){
        $form['submitted']['total']['#value'] = $form['submitted']['number_of_tables']['#webform_component']['value'] *  $form['submitted']['price_per_table']['#value'];
    }
}

Am I writing anything wrong?


texts:
I am new at Drupal, so I apologize if I am missing something obvious.

I have a content type that has some fields. This field is text and I want to have a custom "Field Display" for it.

I can do the JavaScript JQuery stuff to have a div expandable with a click, etc, but I don't know how to make that happen.

How do I change the field display for a field so that I can customize its look (with css or some elements or javascript). I don't want to put this stuff in the content of the field, as I don't want the content author to have to put that in every time.

Thanks.


texts: On my client(s) website,  I turned the update module on.  From time to time, they receive an error message on every page about a security update.  They complain about this message, and they don't want to see it, so I turn the module off.  I still want to keep up-to-date with all the security upgrades.  How do I make sure I receive security updates?  Is there a feed,  an email list?


texts: Why don't calls to drupal_set_message() show up after a drupal_goto()?

texts:
My question is similar to How to  redirect the user to a  page and show a message on the admin overlay (using drupal_set_message and drupal_goto), but I'm not doing an overlay -- it's just a straight page.  This issue has been talked around a bit on this site, but I've never seen a real resolution of it.

My situation is:

The user submits a form, through the usual method.
The form has a _submit() handler, which runs: it does some stuff,
sets a drupal_set_message(), and then redirects somewhere via
drupal_goto().
The user properly ends up on the intended page, but the message is
nowhere to be seen.

Any clues on this?  I really can't figure out why this is happening.


texts: Cannot login to my drupal site because of php version 5.6

texts:
I have installed drupal 7.36 and developed my site on localhost in XAMPP. After I logget out I'm not able to log in again even if name and password is correct. I have only one user created - admin. After I attempt to log in I get a message

  You are not authorized to access this page.

I can still log in. I have tried every solution I found on Internet:

Log in with another browsers
Clear all cookies of browser
Clear all caches
Truncate all cache_ tables, truncate sessions and flood tables
Set $cookie_domain = 'localhost' variable in settings.php
Add ini_set('session.cookie_domain', '127.0.0.1') to settings.php
Restart apache server
Create another user programatically and log in as new user
Log in programatically
Vacuum/reindex database in pgAdmin

Nothing worked for me. It's really simple drupal website. What exactly could cause this problem?

I've reinstalled my site (and lost my database data) and enabled again my theme and all the modules. I was able to log in and log out, repeatedly. But then I logged out one more time and closed the browser. After reopening the browser, I was not able to log in again, even with other browsers.


texts: How to send E-mail and SMS notifications when one user outbid another user in drupal 7?

texts:
I am new to auction idea of drupal 7. My client wants an checkbox to be implemented ,where users can select whether they require any e-mail notification /sms or both or none.I want to send e-mail and sms notification to the respective logged in user on the basis of bids placed by them!

I configured the mail and sms notifcation part .Can anyone let me  know how to send notifications when user checks the checkbox in drupal 7 on the basis of bid?


texts: Why do I get a blank page when I create a new node?

texts:
It seems there are some problems with the content submission. When I select filtered HTML or full HTML, it shows a blank page after submitting a new node. I turned on the error messages, but I still get a blank page with no error message. When the input format is plain text, all works fine.

How do I resolve this issue?


texts: How can i write css for content of the dynamic url page like 'http://mysitename/user/23/prayerrequests'. Here 23, assume user id. I want to effect conent div css of this dynamic url's.


texts: BOA installation caching does not refresh

texts:
I have recently migrated an existing site into a fresh BOA platform. The problem I am facing is that the cache for the anonymous users is never cleaned, when new content is added. The anonymous user can only see new content by adding ?nocache=1 at the URL. But otherwise cache is not regenerated neither by drush cc all.

Given that this happens when boost is disabled, I conclude that this is an issue with speed booster. I tried all suggested solutions to reduce the TTL to 30seconds or so, but there is no improvment. New content is not even displayed for the devel.domain.com, which is supposed to have TTL of 1 second. So I don't know what to think.

Adding ?noredis=1 helps only occasionally, most of the times it delivers older content as well.

If the anonymous user submits a comment, caching gets suspended, as it should be according the documentation.

Edit: I also noticed that drupal reports

  1 error has been encountered when purging URLs Array

and nginx gets similar errors

  Blockquote [alert] 52902#0: *65633 stalled cache updating, error:0 while closing request, client: 127.0.0.1, server: 127.0.0.1:8888

I am copying here the headers of a normal request and I would appreciate some directions on how to resolve this issue, which is actually preventing totally all my sites from working. This is a news and forum website, where content needs to be displayed immediately, the latest after a minute or so.

Response Headers

Cache-Control public, max-age=0
Connection close
Content-Encoding gzip
Content-Language el
Content-Type text/html; charset=utf-8
Date Thu, 30 Jan 2014 01:09:38 GMT
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified Thu, 30 Jan 2014 00:58:19 +0000
Server nginx
Transfer-Encoding chunked
Vary Accept-Encoding, Cookie
X-Cookie-Domain .mysite.com
X-Device normal
X-GeoIP-Country-Code DE
X-GeoIP-Country-Name Germany
X-NoCache Cache
X-Server-Name www.mysite.com
X-Speed-Cache EXPIRED
X-Speed-Cache-Key /node/4042

Request Headers

Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Cookie has_js=1; __utma=1.2022174721.1391038387.1391038387.1391038387.1; __utmb=1.49.10.1391038387; __utmc=1; __utmz=1.1391038387.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __unam=f0418e2-143e0596284-fd42fad-47
Host www.mysite.com
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0

Response Headers From Cache

Cache-Control public, max-age=0
Connection close
Content-Encoding gzip
Content-Language el
Content-Type text/html; charset=utf-8
Date Thu, 30 Jan 2014 01:09:38 GMT
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified Thu, 30 Jan 2014 00:58:19 +0000
Server nginx
Transfer-Encoding chunked
Vary Accept-Encoding, Cookie
X-Cookie-Domain .mysite.com
X-Device normal
X-GeoIP-Country-Code DE
X-GeoIP-Country-Name Germany
X-NoCache Cache
X-Server-Name www.mysite.com
X-Speed-Cache EXPIRED
X-Speed-Cache-Key /node/4042


texts: how to put "add friend" link with flag friend with views

texts: Flag Friend Add Friend Link with views. Flag friends shows a link to add friend in my account page but i want to display this link on in a field for a view.


texts: Merging output of Print.module's printpdf with existing PDFs

texts:
Recently, I created an output template for the Print module, such that it dynamically generates a measurement sheet when a certain content type is parsed by its PDF functionality (using dompdf in this case).

Everything works great, but the client's requested file attachment fields for PDFs, such that existing PDFs are added to the end of dompdf's output. For instance, a PDF of a CAD drawing would be attached in Drupal, printpdf/$nid generates the template I've created, and the file locations given from the file upload fields are used to merge the files at those locations with the generated PDF.

dompdf apparently cannot merge PDF documents, so I'm thinking a workaround would be to generate the PDF and save to disk somewhere, run another PDF merger script, then present the merged output to the user.

How would one go about programmatically saving the output of Print.module's PDF generator to somewhere on the server, then running an external class on that saved output?

(Alternately, if you know of a way for dompdf to read PDFs and append them to the document, that'd work even better.)


texts: How can I collapsible the facet search block with checkbox

texts:
I need to create a  collapsible facet search block with check-box. Has anyone done this type of functionality.
I tried the Facet API Collapsible module but this modules provides the link and not the check-box.


texts: Drupal Commerce: Create advanced add to cart form block in views

texts:
With Drupal Commerce product variations, certain values will update without a page refresh based on an attribute selection. For example, changing a color attribute may update the product image.

I want to the display the add to cart form in a views block using the method described in the following video https://drupalcommerce.org/questions/10801/display-add-cart-separate-block . At the same time I would also like to include other product fields in the block, such as price.

I am finding that the block is static and does not update based on an attribute selection. And I have tried enabling Ajax for the block without success.

Is is possible to create a dynamically updating views block to replicate some of the functionality of a commerce product display?


texts: How to access commerce_product field of line-items using Rules to flag the Commerce Product?

texts:
Related to this question: How to mark product if it has already been purchased by current user?

I have a Drupal Commerce shop, where I'm trying to use the Flag module to mark products to inform users if they have already purchased that particular product.

Now I'm trying to create a rule (using Rules) triggered on "Completing the checkout process" to flag all products that were purchased. Problem is I can't gain access to the commerce_product field (product reference field) of the line item, no matter what I do, and because of that I can't find the info I need to flag the products.

Could someone show how to do this in detail, preferably with example(s)?


texts: how to find out if a custom filter handler is in use when in hook_views_query_alter()

texts:
Drupal 7. I have a custom filter handler which needs to amend the views query. As the filter can be added to any view I can't simply check for view name in the hook_views_query_alter()

I know the filtername exists somewhere in the $views parameter to hook_views_query_alter() within its arrays of array of objects I have yet to find an efficient way of checking if the filter is in use.

anyone come up with a solution to similar?


texts:
I have a  content type "Task" with a Date field to define a deadline for tasks. What I'm trying to do is to add an extra css class to the field wrapper to indicate that today is the deadline. I can do it with JQuery, but its stupid...

So i'd like create a function in my custom module which checks the field date, compares it with today date and if it results that today is a deadline (or the deadline already past), adds an extra class to the wrapper.

Will be very appreciate for any help or advice.


texts: How i can use entity_metadata_wrapper for new database entry and update data in Drupal 7

texts:
How i can use entity_metadata_wrapper for database entry and update data in Drupal 7

I am using below code to save entry in database but not finding logic to update existing entry

    $node = new stdClass();
    $node->type = "event";
    $node->uid = $user_id;
    $entity_wrapper = entity_metadata_wrapper('node',$node);
    $entity_wrapper->title->set($row->title);
    $entity_wrapper->body->set($row->description);
    $entity_wrapper->status->set(0);
    $entity_wrapper->promote->set(0);
    $entity_wrapper->comment->set(0);
    $entity_wrapper->field_eventbrite->set($row->eid);
    $entity_wrapper->field_venue->set($row->name);
    $entity_wrapper->field_eventbrite_city->set($row->city);
    $entity_wrapper->field_privacy->set($row->privacy);
    $entity_wrapper->field_repeats->set($row->repeats);
    $entity_wrapper->field_date_period->set(array(
        'value' => str_replace(' ', 'T',$row->start_date),
        'value2' => str_replace(' ', 'T', $row->end_date),
    ));
    $entity_wrapper->field_eventbrite_url->set(array(
        'url' => $row->url,
    ));
    $entity_wrapper->save();

Please help. Please let me know if require more information is needed.Thanks..


texts: Drupal + Solr, boost result based on custom node weight

texts:
I use Drupal 6 with the ApacheSolr search module.

On my website, all visitors can flag any node with a yes/no answer to the question "Did you find what you were looking for?". Based on those answers, I calculate a custom ranking score for each node which is stored in a separate DB table.

Now I would like to include this score when sorting/boosting the search results in Solr, so that those nodes with the best relevancy / score come out on top.

Can it be accomplished with hook_apachesolr_prepare_query()?

All suggestions are welcome :)


texts: Not load JS formatter field used Views Infinite Scroll

texts: I had my module formatter field for Image Slide . After load scroll page that field not run slide , I Debug see not include js slide when load scrolled ! So how to include js or call js field formatter after load scrolled ?


texts:
Rather than creating a new field via the Field API, and as a quick workaround, I've added a simple text field to a content type that I'm now attempting to validate via hook_node_validate(). Unlike previous versions of Drupal, the value for this field is not simply available as $node->field_name or $form['field_name'], but instead as a nested array containing a variety of other information.

My question then is this: what is the 'correct' and therefore most future proof way to retrieve the value for this field?

Am I supposed to be using the likes of field_view_value() or field_view_field(), or is it acceptable to simply reference $node->field_name['und'][0]['value'] for example.


texts: Sorting by "aggregation type: count" is not working

texts:
I am trying to solve this problem: Drupal 7 Most Popular Tags in a list as a block: How? with Views 7.x-3.0-rc1.
The solution is the answer by Dylan Tack.

create a view of terms
add a required relationship to "content using tags"
set use aggregation: yes
add the "term name" field a second time, set one of the to "aggregation type: count"
add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467

It works until I try to sort the list; in that case, I get an error when adding a sort criteria. If I set "aggregation type: count" the sort-criteria changes to "Broken/missing handler" and it is not sorting.
Do you have any idea? Am I doing something wrong?


texts: How to validate and collect errors from CSV import without submission failure

texts:
I have been tasked with creating a tool which accepts a CSV and presents it in a spreadsheet display with additional dialogues to explain and link to errors on the display.

Have investigated / experimented with several approaches using combinations of Views, Feeds, Sheetnode and Field Validation modules. I've found no issues when CSV is precisely formatted.

The problem is that all of the modular / Drupal validation mechanisms will cause the import to fail or disallow values from being added to fields. I'm looking for a mechanism which will accept all data but gather the errors to allow display and guidance to the user on where mistakes lie - so they can fix and resubmit a corrected CSV. I can't find hooks that would facilitate this.

It seems pointless to write a whole bunch of custom code, when there is so much in the way of Drupal validation stuff that could be taken advantage of (if I could only figure out how???)


texts:
Can someone please help me to adjust views filter in Drupal.

I have content type with field collection and it is displayed through Field collection views module.
Also, I have a field collection ID filter to show some specifics FC. In this filter I have enabled "Remember the last selection" and URL argument for that. It works as expected.

For example, I have two nodes "node/12" and "node/24".
If I open node/12 with argument ?item=3, it shows node/12 with field collection #3.
However, after that I go to node/24 (the same content type) and it opens with field collection filter ID 3 (from node/12). However, it displays nothing, since FC #3 was created in node/12.

So it remembers field collection ID from node to node.
But how can I make it remember FC ID only with specific node. I don't need it to transfer FC ID from node to node (from node/12 to node/24, for example).
Every node has to remember its own field collection ID in the filter.


texts: Drupal 8 correspondence to node_access function on Drupal 7

texts:
I feel like asking a silly question, but here it is anyway: I need to test if a given user (in my case, the logged in, current user) has access to a given node for one of the existing operations (view, create, edit or delete).

In Drupal 7 you could test this by using node_access function (https://api.drupal.org/api/drupal/modules!node!node.module/function/node_access/7.x) and it would be as simples as this:

if(node_access('view', $node, $account)) {
  // Perform something
}

Return value would be TRUE or FALSE. How can I achieve the same result on Drupal 8?

I will be running this code from inside a _custom_access check for a specific route I am setting for my custom module.

Thank you!


texts: Cache a block by a custom entity rendered within

texts:
I struggle with getting a custom block cached correctly:

we have a custom entity "Politician"
For that entity we have several routes where we want to render a "politician header" with some basic information about the politician
the politician header is a custom template which is rendered in a custom block
the problem is: when caching is activated the block always shows the politician data from the first politician which was rendered.

Here is the code for the block plugin - to keep it simple I do not copy the method getPoliticianFromUrl() here:

/**
 * Provides a block with the profile header for a politician. We do not render
 * it on the public edit form path
 *
 * @Block(
 *   id = "aw_frontend_politician_header",
 *   admin_label = @Translation("Politician profile header"),
 *   category = "Abgeordnetenwatch"
 * )
 */
class PoliticianProfileHeader extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician == NULL) {
      return [];
    }

    return array(
      '#theme' => 'politician_header',
      '#politician' => $politician,
      '#cache' => [
        'keys' => ['politician', $politician->id()]
      ]
    );
  }

  public function getCacheContexts() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician != NULL) {
      return Cache::mergeContexts(parent::getCacheContexts(), $politician->getCacheContexts());
    }
    return parent::getCacheContexts();
  }

  public function getCacheTags() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician != NULL) {
      return Cache::mergeTags(parent::getCacheTags(), $politician->getCacheTags());
    }
    return parent::getCacheTags();
  }
}

Then I render the politician header - again I just put in interesting parts:

function template_preprocess_politician_header(&$variables) {
  /** @var \Drupal\pw_basic\Entity\Politician $politician */
  $politician = $variables['politician'];
  /** @var \Drupal\Core\Render\Renderer $renderer */
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($variables, $politician);
  $variables["#cache"]["contexts"][] = 'user.roles';
  $variables['#cache']['keys'] = ['politician_header', $politician->id()];
}

I thought when I define cache keys this ensures that different versions of the render array are cached. This does not happen - not for the custom politician header template (for which I do not find any cached data in cache_render tanle - is this just cached with Twig caching?) and not for the block.

My idea was to create a custom cache context based on my Politician entity but as far as I understand cache contexts they depend on more global circumstances such as the active theme, the current user and things like that. I hoped the Entity API would generate such a context in a magical way so I tried $politician->getCacheContexts() but nothing.

What do I miss?


texts: How to disable the revision feature completely?

texts:
I've followed discussions here and on d.o about removing unneeded revisions tables.

How would I completely prevent any data from being written to the node_revision and field_revision_* tables?


texts: Order pending but credit card charged drupal commerce

texts: I am using authorize.net gateway and when I have done test runs myself everything is great. But we had our first order today and was only notified when saw authorize.net charge. The credit card charge went through BUT Drupal commerce shows order as PENDING. and no email is sent, what could this be? Is there a final step they are not completing but still after payment? This is strange.


texts: Would disabling these following functions in PHP.INI affect Drupal 7?

texts:
If i disabled the following php functions:

disable_functions = escapeshellarg,escapeshellcmd,exec,ini_alter,parse_ini_file,passthru,pcntl_exec,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,show_source,shell_exec,symlink,system

would this affect drupal 7 in anyway? I am disabling them to increase security on my server. This was mentioned on securing an Invision powerboard forum.


texts: How to access files from a custom block without code

texts: I've created a custom block in D8 via the UI. Is there any way to reference the files path in order to use images in the block without having to create a module?


texts:
I'm building a job directory.

This will allow users to register, create Companies and Jobs associated with those companies.

A Job can be from one of the following types: Full-time, Part-time, Freelance and Internship.

The current Jobs View can be seen here:

It was created using Views, just like in this video and looks like this on the back:

My current problem is anytime a tab is clicked, the user goes to a completely different page, requiring the page to load again.
I don't want the user to go to a different page anytime they select a type of job...

Unsure how to do this using Drupal but I were to do this manually, would use Ajax and PHP so that the data could be retrieved from the DB and the page wouldn't require to load again.

Drupal Legoland builds tabs using Field Group Module. This looked like a good technique and easy to implement, but for my case doesn't really work as I don't have a specific field in the content type Jobs just with the Full-time Jobs Data and not sure how to create it.


texts: How can i enable automatic path creating for all nodes?

texts:
In Drupal 7.12 i use pathauto, cleanurls, transliteration, i18n.

When i edit one node i saw that, "Generate automatic URL alias" in unchecked.
Then i checked other nodes and saw that for all type of nodes it became unchecked.

I'm pretty sure that it was checked until last week.

The last modifications i made:
I updated Pathauto module, installed Transliteration, installed Debug Cron module.

So, how can i re-enable this checkbox in node settings page automatically ?

(Of course i can i that manually, by editing every node, and checking the check-box)

Thank you very much for your help.


texts: Is there a means of setting an alternative or a default for an undefined token?

texts:
I am using the nid in combination with other fields to set the title of a node, but as the nid is only defined after the node creation, the initial title has a blank in the nid's place.

I have to edit it again and clear the title before the title is set correctly. Is there some syntax or method which creates a default for a token if it's value is not yet defined?


texts:
I need a way to create a form with tabbed navigation at the top, "save and next"/"save and back" navigation at the bottom, and saving the data for an individual page using ajax, with the following business rules:

-A user may access and work in any part of the form at any time.

-Individual pages can be saved, even if nothing in the rest of the form is filled out.

-Changes in any page result in a "exit without saving? prompt", implemented as a separate module (but which can detect switching between tabs).

I have attempted to do this using fieldgroups: Root is a horizontal tab group, which has a single child in the form of a multipage group, which has 1 tab item child for each page, which in turn each have 1 multipage child, in which I place the forms. The hirarchy looks like this:

Horizontal Tab Group->Multipage Group->Tab Item->Multipage

This doesn't work; apparently the fieldgroups module doesn't let groups search beyond a single level. If they could search beyond that, this may have worked fine and I could have applied the ajaxified multipage fieldgroups module.

What is the best way to go about accomplishing this in D7?


texts: sending parameters to external url and redirect to that url simultanously

texts:
I saw this link:Webform - Submit values from Drupal 7 from to external url

I have this problem too (sending parameters to external url and redirect to that url simultaneously)!

But I also want to redirect user, who submit the parameters to url, redirect to that url simultaneously!

my Code is:

function Chargingform_nameform() {
    $xml = 'PHP Handbook30000130000This is good book.MySQL Handbook25000250000This is a good book too.';
    // Get sing
    $sign ='ewtnXYRWPSalHhna9hgO+Kc0W9Z8JBUeG1FkcKPvZL5w2s588c0/B9rTki/Ry4vHuNG7uuPcttTAz/3j4e/5GcZ4L40jNyzK7dkQyEalRVOZNe9gdnSXMH7h8Q6OY5vwLENn7S4MGTMZCABRrmj1W9vviykftP4tv0EDtNkUgjU';
    $form['xml'] = array(
        '#title' => t('xml'),
        '#type' =>'hidden',
        '#value'=>$xml,
    );
    $form['sign'] = array(
        '#title' => t('sign'),
        '#type' =>'hidden',
        '#value'=>$sign,
    );
     variable_set('xml_hidden', $xml);
     variable_set('sign_hidden', $sign);
 $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('submit'),
    );
    return $form;
}

function Chargingform_nameform_submit($form, &$form_state) {
$options = array();
     $options = array(
        'method' => 'POST',
        'xml' => $form_state['values']['xml'],
        'sign' => $form_state['values']['sign'],
    );
    $url = 'https//:url';
    $response = drupal_http_request($url, $options);
}

How should I solve this issue?


texts: Exclude taxonomy terms from search_excerpt in snippet

texts:
In search-result.tpl.php or in preprocess_search_result function, I want to keep $snippet. It is a great view to display search results.

But Apache Solr results, or Search module results, are displayed with terms that matches the query. These terms are designed to be hidden to anonymous. They can't be displayed in the snippet.

  ex: Marguerite Duras … histoire " avec DURAS. Celle de deux personnes qui se reconnaissent avant de se connaître. Une … "Qui est Marguerite Duras ?" Il avait découvert l'écrivain, il allait rencontrer la …

The term Marguerite Duras is an admin tag. By the way, it is nice that the score relevancy depends on it.

How is created the snippet, or search_excerpt ?  I tried the Taxonomy Hide module, but it doesn't affect search results.


texts:
I have a node view and want to show all terms (which have one image field per term) related to that node (which might be multiple terms), explicitly showing their respective images. How can I do that?

I was assuming that I would choose 'all taxonomy terms' as a field and then would e.g. rewrite the output, showing the terms' image fields. But they don't exist, hence don't show up. I know some workarounds based on theming with overwritten .tpl.php files, but I prefer dynamical solutions... So - does anybody have any suggestions for me?


texts: Why are foreign language registrants redirected to home page after registration?

texts:
When someone registers an account in English (default language) the registrant is redirected to the Login page with a message: "A welcome message with further instructions has been sent to your e-mail address."

So far, so good.

But when a registrant select a foreign language on the registration page (like es for Spanish,) he is redirected to his profile page after submitting his registration.

Anyone knows how to fix this bug so that it behaves like the English registration? Or a workaround?


texts: How to set GET param to current Request?

texts:
I created a service and it works as well.

A piece of my code from "event_subscriber":

public function addRequestAddValue(GetResponseEvent $event) {
  $request = $event->getRequest();
  $request->query->add(['key' => '123']);
}

And than I try get this param on my Controller all Ok:

$key = \Drupal::request()->query->get('key');
dsm($key); // return 123

But if I try get URL I can see only:

$url = \Drupal::request()->getUri();
dsm($url); //return http://localhoct.dv/patn

What I need do to get URI with GET param?

Thanks


texts: I'm trying to get the SKU on the confirmation E-mail when an order is completed (I have custom PHP code handling SKUs) but only the product IDs are output to $commerce_order. I'd like to (need to) work with SKUs. Is it possible?


texts: Commerce Kickstart 2 change admin toolbar logo

texts:
In admin/appearance/settings/commerce_kickstart_admin, in section Logo image settings, there is an option to change default logo of admin. You can upload a new logo. But the new logo doesn't appear in admin toolbar.

In Commerce Kickstart 2 how to change the admin toolbar logo?


texts:
How many page views does drupal.org get each month? and what is the infrastructure used there?.
I found this page about the infrastructure of drupal.org.
It says that it's a relatively accurate list from September 2011.


texts:
My new project involves the requirement of manually setting a time of creation of nodes because they're looking into manually migrating parts of their old website into their new one. The date will mainly be used to sort the nodes, only 2 out of 6 content types will have the date printed in the frontend.

In D8 you can select between a date and timestamp field. Both output options seem to be the same. The only difference I noticed is the HTML output.

The timestamp output looks like this

Mon, 03/18/2019 - 18:00

Date output looks like that

<time datetime="2019-03-18T18:00:17Z" class="datetime">Mon, 03/18/2019 - 18:00</time>

I found a documentation page for D7 on the matter: https://www.drupal.org/node/1455576 but I have the feeling that this information doesn't apply for those two field types in D8.

Which one should I choose for this purpose? And what's the difference in D8 between those two field types?


texts: How to add custom Jquery in drupal module?

texts:
I have created a custom module in drupal 7. The module creates a form for user and store the  form's data into database. The module is working fine. But I want to add a custom jquery for the page. I searched Google and find the result for adding custom JQuery for theme not for modules. I guessed and add the following in my module's  info file

;scripts
scripts[] = js/test.js

Just alert a "hello" word while the module will load. But nothing is happened. Is this possible to add custom Jquery for a module or I am doing wrong? Please help.


texts: Is there a way to show the content of a field taken from the user profile in the comment.tpl.php file?

texts: How does one display a custom field from a user's profile in comment.tpl.php?


texts: Rating for all images in a singular node?

texts: Setting up a private gallery for a photographer, so that their clients may log in, see images specific to a certain photoshoot, and check a box, or click a star to favorite different images. Any ideas of how I would set something like this up? An example of this currently being done would be Adobe's Lightroom.


texts: Problem with "drupal_add_js": Conflicts ShareBar module with IMCE popup

texts:
I have installed ShareBar module (https://www.drupal.org/project/sharebar) at my drupal 7 site. Unfortunately it caused that on IMCE popup (when we can upload images) doesn't appear buttons for files management e.g. upload file.

The code snippet from sharebar.module:

if (variable_get('sharebar_bar_horizontal', TRUE)) {
  $hori = 'TRUE';
}
else {
  $hori = 'FALSE';
}
$width = variable_get('sharebar_bar_width', 1000);
$swidth = variable_get('sharebar_bar_swidth', 75);
$position = variable_get('sharebar_bar_position', 'left');
$leftoffset = variable_get('sharebar_bar_leftoffset', 10);
$rightoffset = variable_get('sharebar_bar_rightoffset', 10);
drupal_add_js(drupal_get_path('module', 'sharebar') . '/js/sharebar.js');
drupal_add_js('jQuery(document).ready(function($) { $(\'.sharebar\').sharebar({horizontal:\'' . $hori . '\',swidth:\'' . $swidth . '\',minwidth:' . $width . ',position:\'' . $position . '\',leftOffset:' . $leftoffset . ',rightOffset:' . $rightoffset . '}); });', 'inline');

I noticed that this issue is due the last line:

drupal_add_js('jQuery(document).ready(function($) { $(\'.sharebar\').sharebar({horizontal:\'' . $hori . '\',swidth:\'' . $swidth . '\',minwidth:' . $width . ',position:\'' . $position . '\',leftOffset:' . $leftoffset . ',rightOffset:' . $rightoffset . '}); });', 'inline');

My guess is that this may be caused by a jQuery libriaries conflict, but I have no idea what can I do more with this line. I have tried:

put this in new file *.js
add line in (function($) { /* ... */ })(jQuery);
install JQuery multi module: https://www.drupal.org/project/jqmulti

Can you assist me? What can I do more?


texts: drupal ubercart membership functionality

texts:
In a drupal site i had defined three packages for a users.
And i want to achive two functionality as :

I want user to be able to purchase only one package at a time, and
Users will be not able to add another package if already a package
exist in the cart or if  he already had bought a package.

Kindly suggest the way of implementing the functionality.


texts: Migrate row data into text formatted long multiple

texts:
I would like to import 3 different row values into a multiple text formatted long field.

This is my migrate (plus) map yml:

  ...
  field_mytext_formmated:
    plugin: get
    source:
    - dataValueA
    - dataValueB
    - dataValueC
  ...

The data is being migrated but the main problem is that the format property is not being filled so the HTML content is not interpreted.
I don't figure out how to set the format to full_html for all fields.

I've seen that for just one field I should use something like:

'body/value': example_matched_field

https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview

But it doesn't seem to work with multiple values.

Thanks!


texts: Difference between drupal_write_record and db_insert

texts:
I want to know what is the difference between drupal_write_record and db_insert
example :
can i translate that drupal_write_record('MyCustomTable', $Myrecord, $primary_key); to an insert query ?

thank you


texts:
I'm creating an action to trigger on a rule when a user is logged in. I have a field of the user that is a term reference.

I would like to redirect to the url field of the chosen term. This is how I get the chosen url:

$tid = $user->field_redirect_field['und'][0]['tid'];
$taxonomy = taxonomy_term_load($tid);
$url = $taxonomy->field_url['und'][0]['safe_value'];

I receive a perfect url like stocklijst/gezocht (this works ok). Now I would like to redirect to that url. I've tried this:

drupal_goto($url);

But it doesn't redirect. It always goes to the front-page...

UPDATE:

This is what I do now:

I have a rule (When user logged in) that triggers a custom action "Redirect to user url". It's a custom action like this:

function redirectonlogin_rules_action_info() {
    $actions = array(
        'redirectonlogin_redirect_login' => array(
            'label' => t('Redirect on login'),
            'group' => t('My custom actions'),
            'parameter' => array(
                // curent user
                'user' => array(
                    'type' => 'user',
                    'label' => t('User'),
                    'description' => t('The current logged in user.'),
                    'save' => FALSE,
                ),
            ),
        ),
    );
    return $actions;
}

function redirectonlogin_redirect_login($user) {
    // REDIRECT TO USER REDIRECT FIELD
    $tid = $user->field_redirect_field['und'][0]['tid'];
    $taxonomy = taxonomy_term_load($tid);
    $url = $taxonomy->field_url['und'][0]['safe_value'];

    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');
    drupal_goto($url);
}

The user can select a url in a select list. These are taxonomy terms... .

This works perfectly. But it takes some time, could there be a cleaner way and faster way of doing this?


texts: Surround specific webform elements with a div

texts:
As the title describes, I am to style a webform and for that i need to surround specific fields in divs in order to give them their CSS properties and I have no idea how I should go about doing that. Also I'd like to do the same to the Submit button.

I've caught the form with hook_form_alter but no idea what to do after.


texts:
I am looking for a solution to show a summary of revision history for all nodes in one place. The out of the box solution is to show a revision history for each node apart. I want to be able to track my content admins' changes in one place (I couldn't find a module that does what I want)
Thanks!


texts: Where to put a personnalized copy of a layout from layout_discovery?

texts:
I want to personnalised core/modules/layout_discovery/layouts/twocol/layout--twocol making a copy of it renamed with a suggested name in the display mode but I don't know where to put it in my subtheme of Bootstrap... I've tried different places, but none worked...

Any help will be appreciated.

Drupal 8.4.3.


texts: how to resend email to new created user with wrong email

texts:
I created a new user, after several hours the email sent by the system was undelivered because the email was not correct.

After changing the email with the correct email, how can I resend the email? I could not find this.


texts: How can I create a menu link that shows only to authenticated users?

texts:
How can I create an user account menu link that shows up only to registered/authenticated users in Drupal 8? I do not want anonymous users to see it.

For example, I want to have "add node" menu link.

( When anonymous users come to drupal sites they just see "login" on user account menu . When register users come to drupal sites they see "my account" and "logout" . I want show anonymous just "login" and for register users "my account","add node" and " logout .  )


texts: How to debug Batch API more efficiently?

texts:
I've some issues with Feeds importing (I don't want to focus on particular case) and I'd like to find the way of able to debug Batch API processing more efficiently. Given the fact of complexity of Feeds module (a plethora of classes), I can't easily implement one-time processing in a short time.

Here are the methods which I'm aware so far:

using dd() from Devel and tail -f drupal_debug.txt (minus: not time efficient)
using watchdog() like watchdog('foo', '<pre>'. print_r($foo, TRUE). '</pre>'); then drush watchdog-show --tail --full to monitor in real-time
using XDebug and its xdebug.auto_trace (minus: non-interactive excess of trace logs)

but they're not helpful in particular case and at the same time I'd like to learn something new.

Ideally I'm looking for some easy way to convert Batch API into standard non-AJAX processing, so I can do old-school var_dump($var); exit; and refreshing the page by sending the same POST requests over and over again, unless there are some more efficient ways. I'm also considering temporary core hacks to achieve that.

Any ideas?


texts: Is it correct that a node and it's translations have the same node id?

texts: I just translated a node and I saw that both nodes have the same node id. Since I cant find anything about it: is this correct?


texts: Finding out what file was called immediately before error

texts:
I'm getting the following errors in dblog whenever I look at a page:

Notice: Undefined offset: 0 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).

Notice: Undefined offset: 1 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).

I know it's not Menu that's causing the issue, but rather, some module is passing permissions incorrectly via hook_menu.

I remember reading a long time ago that one way to find out which module is causing core to emit notices, is to drop a function right before the line in question. Alas, I cannot find that page at all.

Any thoughts?


texts: How to find node that a file is attached to

texts:
There is a file that I want to find the node it is attached to, or at least the user that submitted it.

I was able to create a view that finds the file itself but when I a field for node id, it displays nothing.


texts: Allowing more file types to upload and get file value

texts:
I'm making a custom form and I want it to be able to upload .pem files. All things I find in google don't work. I already added it into the 2 arrays of file.mimetypes.inc:

1000 => 'certificate/pem',
'pem' => 1000,

But I don't know where to edit the other info to make it possible to upload it. A lot of sites say you have to edit in in content-type but this is a form which is in a module.

I got this as $form item.

$form['public_file'] = array(
'#type' => 'file',
'#title' => t('iOS Certificate File'),
'#description' => t('Upload your iOS certificate file here.'),
'#weight' => 35,
);

And this in the submission handler.

$file = file_save_upload('public_file', array(), 'public://');
if ($file) {
drupal_set_message(t('Thank you for uploading private file. You can download it from @url',
        array('@url' => file_create_url($file->uri))));
}

I want to place message1 in front of public_file in $form. How can I call this in the submit function?


texts: How to assign permissions for a newly created bundle programmatically?

texts:
I am making a CRM management application based on Drupal. It will be used by a number of different organisations so I want it to be configurable. I have made a custom entity type called Person, along with some default Person bundles, e.g. Volunteer and Staff. Organisations can also add their own Person bundles. For example, an organisation giving legal advice might want to add a Lawyer bundle.

I am using the permissions_callback system to dynamically create permissions. This works, insofar as when a new bundle is created, the permissions relating to that bundle are created too.

The type of user who will create these bundles will not be an overall Administrator but will have a slightly cut-down role of Site Administrator.

When a Site Administrator creates a new bundle I want them to automatically be granted permissions to view, add, edit and delete entities of the new type (e.g. if they create a Lawyer bundle I want them to immediately be able to add new lawyers).

I tried using a hook_entity_insert to grant the permissions to the role as soon as the config entity (bundle) was created. But this does not work. Debugging has shown me the reason it does not work is that the permissions do not yet exist at the point when the bundle is inserted.

I have thought of one way to solve this which would be to do it all inside the hook: create the permissions, and then grant them to the role. But I can't find any way to create permissions programmatically except by using permission_callbacks.

Any ideas?


texts: Can a drupal admin user get FTP rights to a godaddy server

texts:
I have a Drupal 7.28 site running on a godaddy server.  I just recently copied it from my local box to godaddy's.  I can't use the function "add module by using URL" method now.  I see the message that I must have FTP rights.  I do have FTP rights when logged in to godaddy through their interface, but wondering if a drupal admin user can be given FTP rights and then be able to add modules, etc through URL's at the "Add module" page?  How does everyone deal with this?  Do you just manually FTP modules to the server and then go back to drupal's interface and enable?  Or do you use Drush to install modules remotely?  Just wondering how everyone deals with this...  Is it best practice to not make a site live until all modules are installed locally and then move the site to a remote server?

Thanks for the help.

Dave N


texts: Commerce Product with diffrent prices for different shops

texts:
Working with Drupal 7 on a comparison site where a product is sold at different price rates at different physical shops. Now there about 300 of these shops. Going by Commerce default setup, I would have to create 300 product types or products and also create 300 product display nodes, which will be insane.

Since the product name, image, (and other attribute is going to be the same, I thought to create a single product display content type that has a price field and create a single product type with all the default fields except price. So with the content type, several product display nodes can be created that then references the single product type. Great right? But the price field in the product type is locked (you cannot delete it).

What other more civilized process is available to achieve my goal, as I need the Add to cart button on each product so as to be able to add to cart and compare the prices onwards.

I have seen a similar question (Drupal Commerce: How to handle billions of product combinations?) go unanswered, hopefully commerce has matured these past three years. Thank you.


texts: Autocreating new node based on non-existing node reference

texts: Are there pre-existing modules compatible with drupal 7 that let me autocreate a new node when I enter a value into an autocomplete node reference field that doesn't exist? Sort of like with taxonomy, but with node references instead. The new content is based on what's on the form only there's no need for a separate page to show up to fill in more details. I was wondering if there's something that does this, I'm aware that I could just create a simple module with a hook on node_insert to do this but I was wondering if I could leverage something that already exists.


texts: Explicitly passing argument to local action for access check

texts:
I'm using the group module, and in a custom module I'm trying to create a local task that will bring you directly to the create page for a particular group content type. My goal is to skip the create page where you select the content type.

I've defined a local task:

entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
  defaults:
    plugin_id: group_node:service
  appears_on:
    - 'view.group_services.page_1'

It doesn't complain about passing the $group for the access check, which I'm assuming is being successfully passed due to query magic. Where it breaks down is on $plugin_id on the access check with the error.

  RuntimeException: Callable "Drupal\group\Access\GroupContentCreateEntityAccessCheck::access" requires a value for the "$plugin_id" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

As an example, the route I'm trying to provide would end up being:

/group/{group}/content/create/{plugin_id}

aka

/group/1/content/create/group_node%3Aservice

What am I missing here?


texts: What is the correct way to document the schema for a YAML file?

texts: As a module developer, I'd like to convert some of my Drupal 7 info hooks to YAML discoveries in Drupal 8, but it's not clear to me how to document the schema of a YAML file for consumers. For a hook, of course, I would define hook_whatever() in mymodule.api.php. What do I do for *.whatever.yml? What is core doing?


texts: How to filter a View by Year and Month with Summaries for each one

texts:
or How to remove the exception parameter of a View's contextual filter

Hi,

In Drupal 7 I have a View with two contextual filters (date field):

/view-url/YEAR/MONTH

When YEAR is the first argument and if there is none I make a Summary of the view, so the result can be something like:

* 2017
* 2016
* 2015

And MONTH is the second parameter, that if it's not present, the view also makes a Summary:

* January
* February
* ...

I think that I'm stuck replicating the same View in Drupal 8, because the first Summary has a default parameter "all" wich is the exception of the second parameter.

Is there a way to remove that default exception parameter from the url of the first summary? (I'm getting view-url/YEAR/all for each year of the list as its url).
Can I expose YEAR and MONTH so people can easily navigate trough the view?

Also if there is a better way to built that kind of view (like better performance) I'll apreciate the advice.


texts:
I want to upgrade my site from Drupal 6 to the latest version of Drupal 7. Currently I have version Drupal 6.21 for my site and there are other releases available 6.22 - 6.29 so I need to upgrade first to 6.29 or I can directly upgrade to Drupal 6.37 which is the latest version in Drupal 6? Also after having latest Drupal 6 version can I then upgrade directly to 7.41 or I need to do it in steps like 1-4?

Is it necessary to update core and modules first to the latest version of Drupal 6, before upgrading to Drupal 7, or can I directly upgrade to Drupal 7? I read a few articles on this, but I didn't get it.


texts:
If I form alter a form, I see the form_id as MY_FORM_ID; I see this in the $form_id parameter to hook_form_alter as well as in the $form_state->build_info['form_id']. In the rendered output of the form, however, I see the id attribute has something like MY-FORM-ID--2, with a --INT modifier. If I output the same form twice on a page, while logged in the modifier is changed with each render (e.g. MY-FORM-ID--2 and MY-FORM-ID--4), however the modifier is not changed when viewing as anon. This creates an instance where two elements have the same id attribute which is no good! :(

Where does core add the modifier?
How can I add a modifier?


texts:
I have a multilingual site and the content list view can be accessed like this:
htttp://www.website.com/{country_code}/{language_code}/admin/content
There are only two administration page languages: English and Japanese, and the
toolbar is displayed only in these 2 languages regardless the language_code.
However, the content list menus are displayed in according to the language_code.
For example, in case of French (fr) it looks like this:

What I want to do is to display content list menus only in the administration page language.
So I want that the language_code in the path to be ignored and I have the menus
shown only in English or Japanese.
Could you please advise some approaches to solve the issue?


texts: Drupal 7 Custom Content form_alter validation

texts:
Hi I was wondering if anyone could give me some advice on this.
Basically what I have is a custom content type created by the content creator GUI, I am writing a custom module to alter the appearance and values of the content form.

like so:

function sswap_content_validation_form_alter(&$form, $form_state, $form_id)
{
if (isset($form['type']) && isset($form['#node']))
{

if ($form_id == 'advertise_node_form')
{

  // Unset the options we don't want user to see.
  unset($form['menu']);
  unset($form['comment_settings']);
  unset($form['revision_information']);
  unset($form['author']);
  unset($form['options']);
  unset($form['path']);

  $form['#after_build'][] = '_surplus_cck_form_alter';

  // we need to tell the form to follow a validation function
  $form['#validate'][] = '_surplus_cck_validation';
  $form['#submit'][] = '_surplus_cck_submit';
    }
  }
}

This all works fine and I am able to alter values in the form_alter section as expected, however once I get to the _surplus_cck_validation custom function I am unable to change values, basically what I am doing is checking if a value is X if not I'll replace it with something more suitable after some processing. At this point I can't even change X to a static string though.

To alter my form content I am using:

$form['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

These lines do actually work in the form_alter part as mentioned. I should also note the function for surplus_cck_validation is being called I have experimented with a few echos and notices, and the $form and &$form_state are being passed to it also.

Any help on this would be greatly appreciated I've spent the last few hours trying different things and digging down into the form structure with dsm and debug, but can't seem to find what I need.


texts: drupal 7 add element after the username input text element on login form

texts:
I would like to add the domain name of my company in a simple  element right after the username login text input element. Something like this:

I already tried the instructions defined in https://drupal.org/node/350634 and this only affects the text field label or anything around the login form, but not the input fields themselves (unless I'm misunderstanding the directions). This method doesn't seem to affect how I can add an html element after the username text field but before the password text field.

I'm not certain how I should attempt this? Any direction would be wonderful.

BTW - I tried LoginToboggan to simply allow my users to use either their username or their email address, but that solution only partially works. We have LDAP integration, so for the first time the user attempts to log into our Drupal site they must use just their username (without the @companydomain.com) to allow the LDAP authentication to go through. I did not see a way to configure LoginToboggan to force the username through to the LDAP authentication.

Thanks


texts: Why I'm having fatal error when adding PHP code to my text format?

texts:
So I set the text format to "PHP code" and add the following code:

<?php
function f($x) { return $x; }
?>

When I hit Preview, the page dies with Fatal error: Cannot redeclare f(). I have tried this on two separate Drupal 7 sites, one more or less brand new, with the same result.

Is there a step I'm missing to use D7's PHP filter?


texts: Commerce 2 how to set to live paypal signature API Credentials

texts:
I have set up a sandbox account and I can take TEST payments without issue but there is nowhere for the live account details.

If I set the app you can create to live it gives different account API settings but no signature.

It seems Paypal has changed the layout and the PayPal module in D8 commerce 2 and has no help docs as of yet for this just help documents for the old D7 version.


texts: Is there a plain-text equivalent to the 'html' suffix for [webform_submission:values]?

texts:
I've written a Drupal 8 webform handler plugin that sends webform submission data to another server via REST. I'm trying to send all the populated fields of the form to the third-party server so that it can be viewed in the "message" field of their UI. I've tried using the [webform_submission:values] token with the 'html' suffix, but it comes out as a unrendered block of html code. Is there a token suffix that will format the webform values as plain text with new line characters after each value?
Here's an example of the JSON I'm sending to the 3rd party server:
{
   "u_user": "[webform_submission:values:user:raw]",
   "u_service": "Foo Service",
   "assignment_group": "Bar Assignment Group",
   "u_service_provider": "Baz",
   "short_description": "[webform_submission:values:subject:raw]",
   "comments": "[webform_submission:values:html]"
}

I need to implement this across nine different forms, some of which have conditional logic, so hard-coding every field into every handler is impractical.
Also is there a resource on the web that lists all the suffixes and prefixes for tokens?


texts: Why is hook_update not fully taken into account?

texts:
I have a custom content entity created with
public static function baseFieldDefinitions(EntityTypeInterface $entity_type).
I just added a field to that entity with
- adding a new $fields['courriel'] = BaseFieldDefinition::create('email')
- creating hook.install file with

function association_update_8101()
{
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

Running update.php has indeed added the field to the corresponding database table and I can access it with my code (for example, I store in that field a copy of user->mail.
But when I use CRUD forms for my Entity (i.e. canonical, add-form, edit-form or collection), I don't see the new field.
What did I miss?

[Edit] my hook.install is now:

function association_update_8101()
{
  $storage_definition = BaseFieldDefinition::create('email')
    ->setLabel(t('Courriel'))
    ->setDescription(t('The email address of the Personne entity.'))
    ->setDefaultValue('')
    ->setReadOnly(TRUE);
  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('courriel', 'association_personne', 'association_personne', $storage_definition);
}

I managed to run again update.php with success (at least with no errors): the table has now the new column (Courriel) but I still don't have my CRUD forms showing 'Courriel'.
Is there anything else I need to add to hook_update_8101 to have that done?


texts: Get multiple field id when using paragraphs

texts:
I created a paragraph (machine name date) with 2 fields (date_1 and date_2). When adding this paragraph (Entity Reference field_date) to my content type Agenda I choose the 'Allowed number of values: unlimited' option.

I create a node for content type Agenda with multiple fields of the field_date field.

Now I'm changing the output of the fields of the paragraphs in a paragraph--date.html.twig template. But I want to know/track in this template if there is a multiple field and for example if it is the first or the last value.

How is this possible?


texts: Drupal way to create a dynamic url as a content type field

texts:
What would be the Drupal way to create a dynamic URL field on a content type.

Say I have a content type called 'dogs' and so I use that to catalog all the dogs I like on my site. Now I have created a view that lists in two columns 1) all the dogs that I like and 2) a link to search them on google. There are 100s so I would like to make a dynamic url field because I don't want to type in each google search to each record for the dog content type. So:

Title | Search Link

Maltese, http://google.com/#q=Maltese

Beagle, http://google.com/#q=Beagle

etc...

What's the best way to encode the field such that it says:

1) Get the title for this node (Maltese),
2) Append it to the string "http://google.com/#q="
3) Make this my field_dog_search_url

Is this something that can be done in the admin panel or is it better to use a hook. I'd rather use a hook than download and install yet another module just for this one instance, though I'm interested to know if there is a good module that handles this scenario.


texts: How to search by hierarchical taxonomy in views?

texts:
I have a view with a Global: Combine fields filter with some fields, one of theese fields is a hiererchical select field of a taxonomy terms. But it doesn't work.

How can I set a search box to search by text in a hiererchical select field (and other fields)?


texts:
I'm building a module that gets the value of a custom field based on a timestamp that a user clicked on it in the past.

To not make it too specific and complex I simplified my question so other users can use this as well.

Basically I'm selecting from the pop_links_stats ( has the timestamp ), node, node_revision, and field_revision_field_custom tables:

$query2 = db_select('pop_links_stats', 'p');
$query2->join('node', 'n', 'n.nid = p.nid');
$query2->join('node_revision', 'nr', 'nr.nid = n.nid');
$query2->join('field_revision_field_custom', 'f', 'nr.vid = f.revision_id');

I already have the $nid so I set the condition to that $nid

$query2->condition('n.nid', $node->nid);

grouping by so it will only select one 'click' per day, per node, per ip ( added the following for the completeness. I need this but it is somewhat unrelated to my question so ignore the groupBy if this is not causing any problems. )

$query2->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('n.nid')->groupBy('p.hostname');

selecting the fields I need ( for now just the revision id) :

$query2->fields('nr', array('vid'));

So my guess is to join the node_revision table and selecting the max vid where nr.timestamp <= p.timestamp and n.nid = nr.nid
OR 'selecting' the max nr.timestamp where nr.timestamp <= p.timestamp

But I'm having trouble implementing that in the drupal DB API

EDIT:

Here's a query I've used in mySQL which gives me the result I want:

SELECT p.cid, FROM_UNIXTIME(p.timestamp), FROM_UNIXTIME(nrev.timestamp), n.nid, nrev.vid FROM pop_links_stats p
JOIN node n ON n.nid = p.nid
JOIN node_revision nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )
GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), p.nid, p.hostname

So what I'm looking for is how to make the join in:

JOIN node_revision nrev ON nrev.vid = (SELECT max(vid) FROM node_revision nr WHERE nr.nid = p.nid AND nr.timestamp <= p.timestamp )


texts: hook_form_alter with Ajax works for texts fields on first go, but only with images on second go.. I'm sure it's a simple fix

texts:
Edit: I managed to add the image file to [#file] so then the file was in the form but with no preview. My workaround then was to use jQuery .ajaxComplete to check for form elements with .file-size and no .image-preview, and then click the upload button.

The jQuery:

    if ($('.entitytype-interactive_content_wizard-form').length > 0) {
        $(document).ajaxComplete(function(event, response, settings) {
            $('.entitytype-interactive_content_wizard-form .image-widget').
                    each(function() {
                        if ($(this).find('.file-size').length > 0 &&
                                $(this).find('.image-preview').length == 0) {
                            var clickbtn = $(this).find("[type=submit]");
                            clickbtn.mousedown();
                        }
                    });
        });
    }

Question:

I've added an "update" submit button to each row in a field collection.

$form['field_fc_wiz_word']['und'][$delta]['submit'] = array(
                        '#type' => 'submit',
                        '#value' => t('Update'),
                        '#weight' => 2,
                        '#ajax' => array(
                            'wrapper' => 'words-form-update-' . $delta,
                            'callback' => 'custom_h5p_wizard_callback',
                            'clear' => TRUE,
                            'effect' => 'fade'
                            ),
                        );

In that callback, I set various values but the image is causing issues. I've removed the fields that work and put in a hard-coded value that works on the second refresh.

function custom_h5p_wizard_callback($form, &$form_state) {
    $delta = $form_state['clicked_button']['#parents'][2];
    $form['field_fc_wiz_word']['und'][$delta]['field_wiz_image']['und'][0]['#default_value'] = 17984;
    return $form['field_fc_wiz_word']['und'][$delta];
}

I've tested all combinations of trying to set that image field but it won't work on the first update.

The other text fields are fine but adding the fid doesn't do anything for me. If I click the submit button twice, all is well.

What am I doing wrong? Thanks.


texts:
how can we create a select list in webform containing the list of node titles of specific content type.

I have a product content type through which I have added several product nodes. Now I want to create an inquiry form which should allow the visitors to select the *products from the select list about which they want to send inquiry.

*the products in the select list will be the product node titles.


texts: Set exposed filter date programmatically

texts:
I would like to programmatically set an exposed filter for a field date (field_date) in a view.

Date has to be > of a specific date or between to dates.

I tried this, but it does not work. It ignores the filter.

$view = views_get_view('myview');
$view->set_display("default");
$view->get_exposed_input();

$exposed_filters["field_date_value_op "] = "between";

$exposed_filters["field_date_value"]["value"]["day"] = "";
$exposed_filters["field_date_value"]["value"]["month"] = "";
$exposed_filters["field_date_value"]["value"]["year"] = "";

$exposed_filters["field_date_value"]["min"]["day"] = 1;
$exposed_filters["field_date_value"]["min"]["month"] = 1;
$exposed_filters["field_date_value"]["min"]["year"] = 2014;

$exposed_filters["field_date_value"]["max"]["day"] = 1;
$exposed_filters["field_date_value"]["max"]["month"] = 12;
$exposed_filters["field_date_value"]["max"]["year"] = 2015;

$view->set_exposed_input($exposed_filters);
$view->execute();

Any idea? Thank you in advance.


texts:
I need not one, but three different webforms for my content type. So far I've seen that the webform module allows for only one webform per node. Any suggestions?

EDIT:

To clarify why I can't use the easy solution using blocks - I need to have each instance of the webform prepopulated with the node title (the node the webform is attached to) and I also need it to open in a lightbox. For making that work with one webform I used this solution, however, adding more webforms to the mix makes it more complicated.


texts:
This seems like it should be simple, but I can't figure out how to get Page Manager and Pathauto to play nice together.

I'm trying to use Page Manager/Panels for a set of pages of a specific node type.  If I use the built-in (System) "node-view" page, the URLs work fine...

/content/nice-clean-node-title

But if I try to create my own Pages, I'm forced to use the node id as an argument?

/content/1

When you get to the arguments for a URL, there is no option to use node title.

My question is... how do I create variants within Page Manager that deliver node content in different ways based on a (clean) URL...

/content/some-node-title/overview

/content/some-node-title/detail

/content/some-node-title/specs

etc.

Am I missing something?  Or is this really difficult to achieve with Drupal?


texts: block_admin_display_form_submit not getting called

texts:
I am having trouble saving my block regions(admin/structure/blocks).

Problem:
I am doing my thing on block admin page, saving blocks, moving them around and what not. but the changes i make are not being saved.

What i found: after some debugging efforts, i figure out that the function *block_admin_display_form_submit* is not called when the block form submits.

the site i am having problem is on a lamp server somewhere. i have another copy of this site on my local machine, which has no problem saving block regions.

any idea on how to fix this? thank you.


texts: Webform - Submit values from Drupal 7 from to external url

texts:
I am a self-proclaimed newbie to creating forms in Drupal.  I have a form hosted on a Drupal 7 website (using the webform module) and need to submit the form values to an external url. I've been researching this for awhile now and wrote a custom module that uses the webform module to submit externally using hook_form_alter and custom submit handler/function (code pasted below).

I've been using the following pages as guides, but I haven't been able to get the form to work:
https://drupal.org/node/1357136
Using drupal_http_post() to submit to external site: What am I doing wrong?

Can someone let me know if I'm on the right track?  Any guidance would be helpful!

<?php
function webform_extra_form_alter(&$form, &$form_state, $form_id)
{
   //only want form with nid 1171 to submit externally
   //Note that "webform_client_form_1171" means modify the Webform form for the node with NID "1171". Adjust to match whichever webform node's form you're modifying
   if($form_id == 'webform_client_form_1171')
       {
            $form['#action'] = url('https://[url path to external site]');
            $form['#attributes'] = array('enctype' => "application/x-www-form-urlencoded");
            $form['#submit'][] = 'webform_extra_submit';
       }
}

// Adds a submit handler/function for the app signup form (Webform ID #1171)

function webform_extra_submit($form, &$form_state)
{
     // Changes can be made to the Webform node settings by modifying this variable
    //$form['#node']->webform;

    // Insert values into other database table using same input IDs as external db
    $option['query'] = array(
        $firstName => $form_state['values']['firstName'],
        $lastName => $form_state['values']['lastName'],
        $email => $form_state['values']['email'],
        $name => $form_state['values']['name'],
        $phone => $form_state['values']['phone'],
    );
    $url = url('https://[url path to external site]', $option);
    $form_state['redirect'] = $url;
   //$form['#action'] = url('https:[url path to external site]');
   //$url = 'https://[url path to external site]';
   //$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
   //$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));
}
?>


texts: How can I paginate the Views page itself where all views are listed?

texts: At the url admin/structure/views how can I paginate this list of results?


texts: jQuery ui embedded calendar on a drupal 7 form

texts:
I have a drupal 7 custom form written in PHP where the user can add periods of time to define his/her availability. Created periods of time are showed in a tableselect list with a button to delete them one by one. Now I want to delete this table and show the periods on a jQuery ui embedded calendar instead. How can I do that?

Given the fact drupal 7 form api has no calendar type I guess one solution would be to write a custom block in PHP where I could print the calendar. Then I could show/hide this new block when needed with Context module new rule. Do you think this solutions is good or there is a better approach?

Any suggestions would be appreaciated! Thanks!


texts: How to update one select element via Ajax when using node_add

texts:
I have just created a new content type called pieza_musical. What I just want to do is update one select element via Ajax depending on another select choice, a dependant select.

I'm altering the form_node_add using hook_form_alter to inject the #ajax element and replace in the wrapper the previous select rendered by default in the content type.

Everything is working except when it comes to save. I think, due I'm replacing the select via $ajax['method'] = replace, maybe some token is missing and the content type can't be saved.

It show these error messages:

  An illegal choice has been detected. Please contact the site administrator.
  Género: illegal value.

This is my simple code:

function seven_form_pieza_musical_node_form_alter(&$form, &$form_state, $form_id) {
  $generos = taxonomy_get_tree(2,0,1);
  $values_generos = array();
  foreach ($generos as $genero) {
    $values_generos[$genero->tid] = $genero->name;
  }

  $form['field_genero']['und']['#options'] = $values_generos;
  // adds ajax
  $form['field_genero']['und']['#ajax'] =  array(
     'event' => 'change',
     'wrapper' => 'edit-field-subgenero-und',
     'callback' => 'subgenero_ajax_callback',
  );
}

function subgenero_ajax_callback($form, &$form_state) {
  $generoId = $form_state['values']['field_genero']['und'][0]['value'];

  $cat = taxonomy_term_load($generoId);
  $vid = $cat->vid;

  $generos = taxonomy_get_tree($vid,$generoId,1);

  $options = array();
  foreach ($generos as $genero) {
    $options[$genero->tid] = $genero->name;
  }
  $form['field_subgenero_ajax'] = array(
    '#type' => 'select',
    '#id' => 'edit-field-subgenero-und',
    '#required' => TRUE,
    '#name' => 'field_subgenero[und]',
    '#options' => $options,
  );
  return $form['field_subgenero_ajax'];
}

Is it possible to make this is a content type?
Should I create a new entity just for this little purpose?
Should I create a custom field?


texts: Grouping fields with field group doesn't work on display of Drupal Commerce product in product variation

texts:
I've got a content type for a product and fields for variation. I'm writing about fields in that variation. I have created new group containing some fields using field groups.
Let's say:

[Field group]
 1. Foo
 2. Bar

The group setup is done properly on content type/field display in product variation tab. I'm using drupal commerce, I have tried updating CRON, flushing cache, drinking beer, resaving content. It didn't help. Anyone has any idea?


texts: Getting current node ID for use in VBO operation

texts:
I have a view of nodes and I'm using VBO and rules to apply taxonomy terms to the nodes. What I want to do is:

Get the current node's ID (that is, the node with the view block in it).
Get the value of a term reference field from that node.
Apply that value to the term reference field of my VBO selected nodes.

But I'm having problems making menu_get_object work, or any other method of getting the current node's information.

I'm using the "Execute custom PHP" rules action. Here's what my code looks like:

$tagID = 'initialized';

$nodeVBO = $node;  // Storing the $node object sent from VBO

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
  $nodeID = $nid;
  gets_tag_tid($nodeID);
}

function gets_tag_tid(&$nodeID) {
  global $tagID;
  $node = node_load($nid = $nodeID);
  // Get tag tid from node nid
  foreach ($node->field_tags[$node->language] as $item) {
    global $tagID;
    $tagID = $item['tid'];
  }
}

$nodeVBO->field_tags['und'][0]['tid'] = $tagID;

node_save($nodeVBO);

Sorry for the awkward code, it's adapted from another part of my module.

I get nothing out of the "if" or the gets_tag_tid functions. I have tried echoing the values and reforming the script various ways.

I have never written an operation or an action before so I'm not sure what I can and can't do. I think the problem might be that when VBO performs the operation it changes the URL to /batch?op=start or something like that.

Can anyone point out what I'm doing wrong or show me a better way?

Thank you

EDIT: I have tried reducing the code to the following:

$VBOnode = $node;
$nid = 'initialized';

$node = menu_get_object();
$nid = $node->nid;

$VBOnode->body['und'][0]['value'] = $nid;

node_save($VBOnode);

I was trying to print the nid to see if it was even being retrieved. Nothing is printed in the body field though (not even 'initialized'). To me this indicates that the script is calling menu_get_object(), getting nothing back because the current page is a batch page, thus $node (and subsequently $nid) are set to null values.

Does anyone know of a way to make the VBO operation execute on the node page without switching to the batch page and redirecting back? Or any other alternative solution that I could try? Thank you


texts: When to use a module vs. writing own code?

texts:
At the risk of asking a "too open ended question" I'm giving it a try:

I'm running into more and more situations where I have to decide to either use a module that does a lot more than what I need or just writing my own code or template mod.

For example, the password policy has features that I need, but also has a lot that I don't. The 47kb zip file size tells me that it's a lot of code for my small problem. I implemented my own password policy with less than 20 lines of code in a hook.

I'm trying to limit the total amount of modules installed to a max of around 100. However, since signups don't happen that frequently this module probably won't affect the overall site performance.

Does anyone have specific recommendations on when to use a module vs. writing own code? Especially when better runtime performance and reduced overall complexity are the main goals.


texts:
The drag and drop screws up my theme when viewing it on a mobile device. Since this feature isn't necessary for my site can i completely remove these options to my users? I want to remove all drag and drop functionality.

Im using corolla Corolla 7.x-3.0-rc1.

This can be duplicated by viewing my site and dragging the window to be the smallest width. The drag and drop table does not adjust its width.


texts: cannot get custom Omega stylesheets to load responsively

texts:
I have an HTML5 Omega 3 subtheme. I'm using the responsive grids, and Omega's (Alpha's) -wide -normal etc. css files are working.

But I can't get mine to. I have read the handbook and the wiki to no avail.

In mytheme/css I have

global.css
mytheme-alpha-default-normal.css
mytheme-alpha-default-wide.css

In my mytheme.info file I have

css[global.css][name] = my global stuff
css[global.css][description] = blah
css[global.css.less][options][weight] = 10

css[mytheme-alpha-default-normal.css][name] = my normal stuff
css[mytheme-alpha-default-normal.css][description] = blah
css[mytheme-alpha-default-normal.css][options][weight] = 10

css[mytheme-alpha-default-wide.css.less][name] = my wide stuff
css[mytheme-alpha-default-wide.css.less][description] = blah
css[mytheme-alpha-default-wide.css.less][options][weight] = 10

And I've enabled these in the Omega settings for the theme.

What happens is that all these stylesheets are loaded like the global one -- without any media query conditions at all, just like they were all global styles.

I've tried un-checking them. This just removes them. I've tried removing them from the .info file; this just removes them entirely too.

Can anyone help?


texts: Access submitted form data in custom callback before hook_mail_alter()

texts:
I wan't to alter contact form recipient according to what user chose in one of the dropdown fields of my Contact form.

I implemented hook_form_FORM_ID_alter() in order to add custom submit callback like this

 $form['actions']['submit']['#submit'][] = 'my_custom_callback';

to get submitted data.

I thought I could use State API in my_custom_callback() to store received data temporally and use it's value in hook_mail_alter() but it looks like hook_mail_alter() is called before my custom callback.

This is what the order of callbacks looks like:

Default Submit callback of Contact form;
hook_mail_alter();
my_custom_callback.

I wander if there is any way to change this order to this:

my_custom_callback;
Default Submit callback of Contact form;
hook_mail_alter().


texts:
I'm creating my menu using view along with Bootstrap to create a mega menu style navigation.
I'm having a problem with the nav showing expanded at times when you come to the site and or refresh. not all the time but more than I'd like.
I am using: _menu_link like such:
function MYTHEME_menu_link(array $vars) {
  if ( $vars['element']['#theme'] == 'menu_link__user_menu' ) {
    $vars['element']['#attributes']['class'][] = '';
  }
  elseif ( $vars['element']['#theme'] == 'menu_link__main_menu' ) {
    $vars['element']['#attributes']['class'][] = 'dropdown mm-menu-fw';
    $vars['element']['#localized_options']['attributes']['class'][] = 'url-link';
  }
  return theme_menu_link($vars);
}

This gives me the following HTML markup.

    MY LINK


texts: Get translated field value with fallback

texts:
How can I get the translated value of a field in Drupal 8 and if no translation is given, fallback to the default node language?
I tried this: https://drupal.stackexchange.com/a/145747/9586, but when no translation for a field if added, it just returns NULL.

Here is what I tried:

    $node = Node::load(2);
dsm(\Drupal::entityManager()->getTranslationFromContext($node)->field_my_awesome_field->value);


texts:
I'm working on a module in Drupal 7. I've added a hook_menu implementation:

$items['admin/config/content/mymodule'] = [
  'title'            => 'MyModule',
  'description'      => 'Configure MyModule settings.',
  'page callback'    => 'mymodule_get_form',
  'page arguments'   => ['mymodule_admin_settings'],
  'file'             => 'mymodule.admin.inc',
  'access arguments' => ['administer mymodule'],
  'menu_name'        => 'mymodule',
];

...and a configure line to mymodule.info:

configure = admin/config/content/mymodule

A Configure link for MyModule now appears the admin/modules page, but how can I also have the module listed on the admin/config page? Or is the admin/config page reserved for only core modules?


texts: Adding a temporary column to a db_select query

texts:
I'd like to add a temporary column with a fixed value to a database query. Eg a column called 'type' with a value of 'thing' for every result. I have tried using the addExpression and addField functions to do this but I'm not getting the right result.

Is this possible using db_select? I've tried the following:

$query = db_select('people', 'p')
   ->fields('p', array('id', 'date'));
$query->addField(':val AS type', array(':val'=>'thing'));

However this is executing the following query:

SELECT p.id AS id, p.date AS date
FROM
people p

I suppose I'm trying to get drupal to do:

SELECT p.id AS id, p.date AS date, 'thing' as type
FROM
people p


texts: Upgrading a site from Drupal 6 to 7 using Drush

texts:
I am attempting to upgrade one of my sites from Drupal 6 to Drupal 7. I have downloaded and made Drush executable. I've also install the Drush site-upgrade command. The problem I'm having is understanding the steps or the process of aliases. I really need someone to explain it to me in layman's terms as I am just learning all of this. I've tried several different configurations and still can't seem to get it to work. So after some digging around within Drush I have also noticed when I do the drush st command I get this (posted below)

PHP configuration     :  /home/user/drush/php.ini /home/user/drush/php.ini
 Drush version         :  5.9
 Drush configuration   :
 Drush alias files     :  /home/user/.drush/cm.aliases.drushrc.php

Which I'm thinking is wrong, I shouldn't have 2 php.ini files show up for my PHP configuration should I?
I should mention I have a multi domain site.
I'm guessing I need to fix this first before I figure out the aliases issue, but I have posted what I put in the .drush folder as my cm.aliaes.drushrc.php file

$aliases['test'] = array(
  'root' => '/public_html/folder-of-domain-to-update',
  'uri' => 'localhost',
);

If I go to the /home folder and run the command drush sa, I get:

@cm
@cm.test
@none

If I go to the /home/user/public_html/folder-of-domain-to-update and run the command drush sa, I get:

@cm
@cm.test
@none
@self
default

When I run the command drush sup at the /home/user/public_html/folder-of-domain-to-update level I get this:

  No target argument specified. To perform the site upgrade, define an alias record for the target site.

If someone could give me some direction or help I would greatly appreciate it.


texts: drupal module defines front page using hook_menu...What does it need to return?

texts:
I am using hook menu to define the front page (/front) and I found out if I return '' it renders the theme with all the blocks.

If I return content, is that what gets rendered into the Main Content block? What is the purpose of returning data from this function?

function dc_mad_marchness_menu()
{
    $items['front'] = array(
        'title' => 'Home',
        'page callback' => 'dc_mad_marchness_front',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function dc_mad_marchness_front()
{
    return '';
}


texts:
I want a two-column page layout to display my products which I create with 'drupal commerce'.
The layout is basically the picture and similar articles on the left. Description on the right.

Now, I can manage the display of the product in two column with 'display suite' and then create a node view that is just a dummy page which really all it does is having one big field with the reference of the product.

I almost have what I want now because I have the picture on the left and the description on the right. How do I put the similar products block (I suppose it could be a block, right?) under the picture on the left?

It seems very dirty to add it as a field into the product. But I can’t add it to the column from the view node since I have no granular access on the single columns or fields.

What do?


texts: Is there any API to get corresponding field in a custom content type?

texts:
I have drupal 7 and created a custom "content type" with several fields. just imagine i have:

title field
subtitle field

I need to search the data. I want to search titles and when i found my certain title I want to get corresponding subtitle (in the same row of that title)! I know I can do it by going to directly to my database and do it by db_query(and i have to know the structure of my database as well). but is there any API in this regard?
i need to get them inside my custom module


texts: Create an expiration date field that auto expires

texts:
We are currently migrating a Drupal 6 site to Drupal 8. We have a view that shows a table of files uploaded through the file depot. One of the columns on the table was an Expiration Date. In Drupal 6 we had a module called Auto Expire to set a date for a node to expire which we used to create a field on the view showing the number of days until the link to the file expired.

We created a Node view with multiple fields as the column headings (Date Created, Expiration Date, Staff Member, File Name). For the expiration field, we used Auto Expire to create an Expiration Date field set to 7 days after the creation date. After the 7 days, the node (file depot page) and it's attachments would get deleted.

How do I recreate this functionality (whether programmatically or otherwise) in Drupal 8, since Auto Expire is not updated for Drupal 8?

I am currently looking into the Scheduler module as there is a version for Drupal 8.