How do I use "GROUP BY"? How do I use GROUP BY to display the result by group (email)?
this is my file .php

<?php
/**
 * Created by PhpStorm.
 */
namespace Drupal\gestion_contact\Controller;
use Drupal\Core\Controller\ControllerBase;
class GestionContactController extends ControllerBase
{
    public function admin() {

        $result = db_query("SELECT * FROM {contact}");

            $node = $result->fetchAll();

        return array(
            '#theme' => 'gestion_contact',
            '#nodes'=> $node,

        );
    }
    public function delete($id)
    {

        db_delete('contact')
            ->condition('id_contact', $id)
            ->execute();
        drupal_set_message(t('Your form has been deleted'));

        $result = db_query("SELECT * FROM {contact}");

        $node = $result->fetchAll();
        return array(
            '#theme' => 'gestion_contact',
            '#nodes' => $node,

        );
    }
    public function afficher()
    {

        $result = db_query("SELECT * FROM {contact} WHERE vu = :vu",
            array(':vu' => 'false'));
        $node = $result->fetchAll();
        return array(
            '#theme' => 'nouveaux_contact',
            '#nodes' => $node,
        );
    }
}

Follow an example:

$result = db_query('SELECT tid, count(tid) AS count FROM {taxonomy_term_field_data} WHERE vid <> :vid GROUP BY tid', array(':vid' => 'tags'));

But, from docs...

  Deprecated

  as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a
  database connection injected into your service from the container and
  call query() on it. For example, $injected_database->query($query,
  $args, $options);

More info in db_query.

Edit 1:

Drupal set by default sql_mode with 'only_full_group_by', in your case when you use SELECT *, an database exception is throw, look in your log, you will see something like this:

  Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.table.field' which is not functionally dependent on columns in GROUP BY clause.

So to correct this you must aggregate all fields in your SELECT list. If you only need e-mail list something like this can solve:

db_query('SELECT email FROM {contact} GROUP BY email');


Use Color Field Value in Views Field Template File I have two fields in my view:

field_background_colour and field_heading

The are both being pulled from nodes and displayed in a rotating hero banner. Each node has a different colour and different heading.

The field_background_colour is defined by the color field module and therefore can be any colour they select.

I need to add the value of the background colour in hex (e.g. #000000) to the html output of field_heading.

[field_heading]

I tried using some html and replacement patterns in the rewrite of the field but it seems that gets stripped out by views. It seems to me that I need to use the field's template file to get what I want.

In this use case, I believe inline styles are the way to go. There are methods to write a CSS file in your module or theme, for example, but since users can select, and update at any time, any color code, all situations would be very difficult or messy to manage. Inline styles are not ideal in the grand scope of things, but with multiple users, and multiple hex values reaching the millions, sometimes requirements make our choices for us. And plus, we just want to get it done.

Below assumes the view shows nodes, both fields are on the content type, and the title being styled is the node title, not the views title. This is best achieved setting the view to display content, and utilizing template files for your chosen display mode such as node--content-type--teaser.tpl.php.

node--content-type--rotating-hero.tpl.php:

<section>
  <h1
    title="<?php print render($title); ?>"
    alt="<?php print render($title); ?>"
    <?php if (isset($content['field_background_colour'])) : ?>
      style="color: #<?php print $content['field_background_colour']['#items'][0]['value']; ?>;"
    <?php endif; ?>
  >
    <?php print render($title); ?>
  </h1>
</section>

Here, each .views-row will contain an individual node display, and you can focus your javascript and CSS on those for the slider.

*multiple h1 tags on the same page need to be wrapped in a <section> tag, otherwise, use h2 tags.

*Templates are related to structure and usage. Views templates are for the structure and layout of content aggregation, node templates are the structure of individual entities. Wherever the field (or desired data) resides is the best place to theme template files.

Below assumes you need to style the views title itself...

will need more info about where the color field lives. If user profile, for example, you will need to load the user object to access the field value.

MYMODULE.module:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_name') {
    $view->build_info['title'] = "custom title";
  }
}

template.php:

function MYTHEME_views_pre_render(&$variables) {
  if (&$variables['view']->name == 'view_name') {
    &$variables['view']->build_info['title'] = "custom title";
  }
}


Hide field label with hook_form_alter() In hook_form_alter(), I am trying to disable/hide a field label in a custom form. I know I could use $form['my_field']['#enableLabel'] = FALSE;.

Is there a way without unsetting the title?

Unsetting not really, hide yes : use #title_display and its get accessible to screenreader :

$form['my_field']['#title_display'] = 'invisible';


What do all these problem have in common (can't find the origin)? A series of problems appeared in my install and I need help to narrow them down to a probable cause.

Most problems come in Views

1) All the dropdown menus that group options are gone. Clearing the cache will then display then again for once. Reloading the page again reproduces the issue.

2) Some block views with ajax/exposed filters are broken: instead of reloading themselves they call the home page with the arguments in the url: http://www.mysite.com/?field_tags_tid_i18n_op=or&field_tags_tid_i18n=All&status=All

Again, clearing the cache may solve the issue, but only once

3) Here and there, some glitches such as an geofield map not showing in a form until clearing the cache. And again, clearing the cache is only a one time fix as the issue reproduces next time the page is loaded.

I have tried the following:
- Clear the caches (All cache taken indepently work except CSS and Javascript, Theme and tokn regsitry, and update data)
- Clear the content of cache tables directly in mysql
- Remove all performance otions (aggregate css and javascript, cache,...)

So the problem was the dhtml-menu module with the "Expand on bullet option"


How can I tell Guzzle to safely ignore ssl.certificate_authority in Behat testing? (Development server) On a sandbox install of Drupal running behat under the Behat Drupal Extension, I'm trying to fun the following feature:

@api
  Scenario: Logged in User
    Given I am logged in as a user with the "administrator" role
    And I am on '/user'
    Then I should see the heading "User"

Inital cURL error

I get this error complaining about the SSL certificate.

cURL error 60: Issuer certificate is invalid. (GuzzleHttp\Exception\RequestException)

My first attempt to ignore fails

This makes sense. This is a sandbox on RHEL 7 where I just activated mod_ssl. In order to try to ignore this, I added the ssl.certificate_authority: false to behat.yml. Since that I now see this...

  No method can handle the ssl.certificate_authority config key
  (InvalidArgumentException)

behat.yml set up

 default:
      suites:
        default:
          contexts:
            - FeatureContext
            - Drupal\DrupalExtension\Context\DrupalContext
            - Drupal\DrupalExtension\Context\MinkContext
      extensions:
        Behat\MinkExtension:
          goutte: ~
          sessions:
            my_session:
              goutte:
                guzzle_parameters:
                  ssl.certificate_authority: false
          selenium2: ~
          base_url: http://localhost
        Drupal\DrupalExtension:
          blackbox: ~
          api_driver: 'drupal'
          drush:
            alias: 'local'
          drupal:
            drupal_root: '/var/www/html'

Update
Based on information from the Github issue queue, I have changed my

After reading on https://github.com/Behat/MinkExtension/blob/master/doc/index.rst#drivers, I tried the following in the behat.yml file.

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte:
        guzzle_parameters:
          verify: false
      selenium2: ~
      base_url: http://localhost
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/var/www/html'

It worked.

I needed to find out how to tell Guzzle/cURL to not worry about validating any CERT. Again, I would not do this under a production server, but for the sake of a local development environment, I'd give it a go.


How to show/hide the prefix/suffix of fields in node templates? I previously asked a question about hiding the prefix/suffix in fields template here, now I want to understand how can I programmatically hide the prefix or suffix of numeric fields in nodes templates only?

On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.

So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.

A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:

{{ node.field_example.value }}

But then you lose all formatting options, not only prefix/suffix.


Domain access issue w.r.t viewing a content other than admin user I am using domain access module with sub domains and content creation.

I am able to create content but I am not able to view content which was created by the user, it says You are not authorized to access this page where as admin I am able to create and view content.

In my another local site I tried domain access module and for other roles I am able to crate and view and edit the content. I don't have any issues. Same settings only I have for my another site.

But still it throws me this error You are not authorized to access this page after creating a content and in view section it shows this error.

Is any other module causing this issue?

My answer is based on experience with D6 version of the module but I believe the core is still relevant. As the site administrator (user id 1) you can view all site content unless you disable that option in the domain settings page (Administer >> Site Building >> Domain >> Domain Settings >> Domain module behaviors fieldset >> Enforce rules on administrators:).

With relation to content viewing for other users, it is the default behavior to return HTTP 403 (Not authorized) when a content created specific to one domain without being shared to all affiliates is viewed from a different domain. The option to publish node to one or few of the sites is available in the node creation or edit form.

If you wish to change the default behavior of specific node types, the option to either allow specific node types to be published to all affiliates can be found in Node settings under Domain. When nodes are saved that way domain access table has an entry for such nodes with affiliated domains as domain_site.


Why a module has a package for a 8.x-3.0-beta1+54-dev version? I'm currently in the process of composerizing a quite old project where I ran into some strange module versions, which seem to have been packaged by drupal, ie.
# Information added by Drupal.org packaging script on 2019-03-28
version: '8.x-3.0-beta1+54-dev'
core: '8.x'
project: 'field_group'
datestamp: 1553812385

or
# Information added by Drupal.org packaging script on 2017-03-13
version: '8.x-1.1+1-dev'
core: '8.x'
project: 'login_emailusername'
datestamp: 1489402385

In the case of login_emailusername, it turned out that the code of the project is identical to 8.x-1.1 plus 1 follow-up commit from dev, and so could be brought into the project via composer as:
"drupal/login_emailusername": "1.x-dev#f152ee7"

However, I wonder how these modules were "packaged" in these versions, because they don't seem to exist. Maybe someone has an idea? Might this be complete custom syntax or where they maybe imported via drush:make?

The 8.x-3.0-beta1+54-dev version means the development snapshot is 54 commits ahead of the 8.x-3.0-beta1 version. Similarly, 8.x-1.1+1-dev means the development snapshot is one commit ahead of the 8.x-1.1 version.
Since development snapshots can change much during time, it is probably a way to make better understand how much the development snapshot changed.
Notice that 8.x-3.0-beta1+54-dev is the version reported from the page listing all the installed modules or in the .info file for the module (as you shown, between the lines added by the Drupal.org packaging script).

(The screenshot is for Drupal 7.)

It's not the title you see for a release node in the page showing all the releases (for the Field Group module, in this case), where the release is field_group 8.x-3.x-dev.
To answer your question, it's not a custom syntax. It's the version that the Drupal packaging script adds in the .info file for development snapshot releases, which could then be used in the user interface when showing the installed project version.
The Drupal.org packaging scripts alter the .info file when creating the archive for the project. If the project is copied using Git or Composer, for example, that information is not present, and the version wouldn't appear as 8.x-3.0-beta1+54-dev. (This is also the reason why I took the screenshot from a Drupal 7 instance created on simplytest.me.)


Create personality quiz i'm looking for solution on how to create personality quiz. The Quiz module doesn't have an option to label answers - I need to find the most popular label checked and not the total amount of points.

It could be like this: 2 questions, 3 answers each. Each answer for each question has labels: "label one", "label two" and "label three" and they are randomized. I answer both questions and get "label two=2", which is the most popular label and therefore I am forwarded to node2 with some description.

Is it possible to do this with forms?

The webform module would work for you. It gives you a nice interface to fetch the results so you can do some meaningful post analysis on your results too.


Displaying follow up fields for a content type I have a form that asks the user to answer several yes or no health questions. These questions are radio button widgets and what I've been trying to do is ask the user to fill out a follow up question, a text area which should be invisible until when the user selects the 'Yes' radio button. I have one method which involved some Javascript, but my I'm mostly a backend developer so I'm really struggling.

Anyone know how I can do this?

Drupal 7 introduced the #states property for form elements. It:

  Adds JavaScript to the element to allow it to have different active states.

Here's a short example that applies to your use case:

function MYMODULE_my_form($form, &$form_state) {
  $form['my_radios'] = array(
    '#type' => 'radios',
    '#title' => 'Radios',
    '#options' => array('no' => 'No', 'yes' => 'Yes'),
    '#default_value' => 'no'
  );

  $form['textarea'] = array(
    '#type' => 'textarea',
    '#title' => 'Textarea',
    '#states' => array(
      'visible' => array(
        ':input[name="my_radios"]' => array('value' => 'yes')
      )
    )
  );

  return $form;
}

The above assumes you're building the form yourself; if you're not, you can combine this logic with a hook_form_alter() function. This example assumes you're adding it to a node add/edit form for the Basic Page content type:

function MYMODULE_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['textarea']['#states'] = array(
    'visible' => array(
      ':input[name="name_of_radios_element"]' => array('value' => 'yes')
    )
  );
}

If you're using the second method you'll need to do some digging into the $form array to find out exactly which element you need to target. If you don't already have it I recommend installing the Devel module and using it's excellent dpm() function for your debugging.

There's more information on the various different options for #states on the drupal_process_states() docs page.


Panels not showing default image set in Field settings of content type The image you upload to be as a default image for all pages where you didn't upload custom images for each page, so it would show same one image from the content type settings.

It works in Preview when editing the node and it shows in non-panel pages.

In Panels it doesn't render entire field. But if you upload the custom image then it does show it. But not the default one.

I don't get it why

This is an issue with CTools. Apply the patch from Default value of image field is not shown


Mod Rewrite for Subdomain to point to TLD Is it possible to create a Mod Rewrite rule to point a subdomain to a TLD?
Example; cars.test.com -> Mycarsite.com

Am using the shared cookie, tables (for the users), and Domain access in D7. Now all I need to do is craft a rewrite rule that can point all the requests going to subdomain.tld.com to goto mytld.com.

CLARIFICATION/EDIT: This is specifically a drupal question. I shared the users with test.com & cars.test.com so that I can do a single sign on. So I did the typical adjustments to settings.php and crafted the single db with prefixes per site. The only "out of the box solution" that works with D7 for an SSO solution is sharing the DB and and sharing cookies. I got that part working. Now this is the part that am experimenting with but am not sure its possible. I want all requests that goto cars.test.com appear as if they are coming from mytld.com. I already have mytld.com parked on the host. But when I goto cars.test.com using the mod rerewrite rules from @acouch below, it redirects me test.com. Is this possible?

This should work:

RewriteCond %{HTTP_HOST} ^subdomain\.tld.com [NC]
RewriteRule ^(.*)$ http://mytld.com/$1 [L,R=301]


How do I show a "results count" on my search results page? I'm using Search API along with Facet API to administer a search for my products. I'm also overriding the search with a view. I'm looking for some method of counting the search results and displaying this information. For example, at the top of the search results page I want text to be displayed that reads something like "Showing 1 - 16 of 39,352 Results". I've read somewhere that views is able to do this easily, the problem is that I'm using facets and I don't think the results count from views will work together with applied facets. Can someone give me a solution or at least an idea?

In the view that I'm using to override my search results, I added "Global: Result summary" to the views Header and it seems to be working with the facets. Thanks.


How to validate deletion of custom entity? I'm making decently complex system, where many entities are referencing each other, and I don't want to allow any broken references. That is why I would like to implement validation at entity deletion, but where should I actually put it?

I know hook_form_validate runs on deletion, but it is hard to know if it has been invoked by deleting operation. I guess I can also do proper check in access callback of entity, however it isn't about access but validation, and I think that would be ugly workaround, as those are two different things. What would be a good place to put, a validation mechanism for deletion that would query the database to know if deletion of entity is possible?

There are a few options that may mean you don't have to code anything:

A patch for the entityreference module to add this type of cleanup: https://www.drupal.org/node/1368386
A module to handle cleanup: https://www.drupal.org/project/reference_delete
A sandbox module to handle cleanup: https://www.drupal.org/sandbox/drothstein/1775816

I would go with one of those if possible instead of writing custom code.

Seeing as you do want to run custom code though I would suggest reading up on how those solutions work and implementing something similar, but with your own custom logic.

For example in the issue in that first link they discuss 3 different ways of doing the deletions and some of the pros and cons of certain possible solutions, so I think that information would be useful to you in implementing your own.

Although I don't know your exact requirements I would suggest that doing this at the validation stage is not a good idea because it means it is possible for you to delete referencing entities at validation stage and then something could stop the deletion of the referenced entities after your code runs and you will have deleted the reference when you shouldn't have.

It should be done later than the validation stage.

That patch issue suggests maybe hook_entity_delete(), which I think is a better place for it, however in that issue they also mention possible page timeouts if there are lots of references to delete.

The code in those 2 modules may also be useful to you but I haven't read those.

EDIT: just had a quick look an the reference_delete module also uses the entity delete hook.


Caching - techniques? suggestions? best practices? I have a website that will be using three (3) views slideshows on the landing page/front page. What are the best ways to set this up site to be able to load efficiently?  Should I start with a Pressflow site? Install and enable specific modules to improve performance? Use Boost? Are most of the caching modules and techniques related only to logged in users? Do I have to own my own server to do this well?
I am assuming that because there are so many slideshow instances loading at the same time that this will be a severe performance hit at loading.

In general, I'd recommend using boost if you don't have access to the command line of a server.  Boost creates a static HTML copy of the file inside a cache directory within your Drupal file structure.  It updates cached pages only when content changes.  It is used in conjuntion with the performance enhancement features of Drupal such as CSS and JQuery compression found under /admin/settings/performance.

If you have command line access I'd reccomend APC and memcache/memcached.  This takes a little more effort to set up, but is well worth it IMO.  There are plenty or resources on Drupal.org to help you to set up memcached.

You can also set basic caching on individual views as shown here:

 You'll see the option for caching 7th from the bottom.  There is also a similar option in panels if you use them.

These caching options are designed for end-users really, not specifically logged in users.  Indeed you may want caching disabled for logged in users if they are administrators and/or are making changes to the site.


How to create a "read more" button using AJAX in a module? I'm working on a really simple module in Drupal 8 to get the hang of things. What it does (or rather, what the page I'm asking about in this question does) is grab some data of a bunch of simple article-style entries, and display them.

What I would like to be able to do is to have it only display the first few (say, 5), and then have a "Read more" button, which uses AJAX to display the next 5, lengthening the page so it now shows 10.

Here is the controller as I have it at the moment. The routing.yml file points to MyController::build. For the sake of simplicity, I've left out exactly how it gets things from the database, and some simple processing (in particular, image gets converted from a managed_file in the database into a URL to the image).

class MyController extends ControllerBase {

  public function build() {
    $stuff = $this->getStuff();
    return array(
      '#theme' => 'my_theme',
      '#stuff' => $stuff,
      '#attached' => array(
        'library' => array(
          'my_theme/style',
          'my_theme/readmore',
        ),
      ),
    );
  }

  private function getStuff() {
    $stuff = getStuffFromDatabase();
    $result = array();
    foreach($stuff as $key => $item) {
      $tmp = new \stdClass();
      $tmp->id = $item->id;
      $tmp->title = $item->title;
      $tmp->description = $item->description;
      $tmp->image = $item->image;
      $result[] = $tmp;
    }
  }
}

Which then gets sent to a template file:

    {% for item in stuff %}

{{ item.title }}

        {% if item.image is not empty %}

        {% endif %}
        {% if item.description is not empty %}

{{ item.description }}

        {% endif %}

    {% endfor %}

<form method="post" action="" onsubmit="readmore()">
  <button name="read-more" type="submit">Read more</button>
</form>

What I want is a way to change this set up so that at first the controller only sends a few of the entries, but when the button is pushed, it sends the next few, and the template displays the new ones as well as the old.

Thanks

Okay, I think I may have worked out to at least make a start on this problem. I've followed this tutorial, and want to get a small message displaying at the bottom, to at least get a feel for how Ajax works with Drupal 8. I've added

to the bottom of the .html.twig file.

I created a file identical to his ReadMessageCommand.php, except named mine MyMessageCommand.php (and renamed the class inside it accordingly). The function render has myMessage in place of readMessage.

I added a method called myMessageCallback into MyController, which works the same as in that guide, but with my_module_load_message and MyMessageCommand in the appropriate places.

To readmore.js, I added the function from the above guide, but with readMessage replaced by myMessage. I also added the following, just so I can know more easily if the function is at least being called.

console.log(response.subject);
console.log(response.content);

And I added the core/drupal.ajax dependency to the readmore library.

My question is, how do I actually get this function to be called. As far as I can tell, the guide that I've used has no indication of it. How to I get a message to be displayed in the div at the bottom? Once I've figured that out, I feel extending it so that the button acts as a "read more" shouldn't be too much trouble.

That tutorial won't help you. That's for more advanced stuff.

I would not use a form, but a simple link with an ajax response.

But if you want to use a form you need to create a proper Drupal form. Too much to write here to explain that so just take a look here https://www.drupal.org/node/2117411

Your buildForm should be something like

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // The default value for working with non JS should be taken from the route and adding 1.
  $form['page_number'] = array(
    '#type' => 'hidden',
    '#default_value' => 0,
  );
  $form['my_stuff'] = array(
    '#type' => 'value',
    '#value' => [],
  );
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Read more'),
    '#button_type' => 'primary',
    '#ajax' => array(
      'callback' => 'Drupal\example\Controller\MyController::myFormSubmit',
    ),
  );
  return $form;
}

You can call this form in your page with (changing accordingly):

$form = \Drupal::formBuilder()->getForm('Drupal\example\Form\ExampleForm');

You do all the stuff you want in your submitForm, and not in the callback if you want the form to work without JavaScript. If you don't care you can do in the ajax callback. I will assume you do it in the submitForm.

/**
 * {@inheritdoc}
 */
public function submitForm(array $form, FormStateInterface $form_state) {
  $page = $form_state->getValue('page_number');
  $stuff = getStuffFromDatabase($page);
  $result = array();
  foreach($stuff as $key => $item) {
    $tmp = new \stdClass();
    $tmp->id = $item->id;
    $tmp->title = $item->title;
    $tmp->description = $item->description;
    $tmp->image = $item->image;
    $result[] = $tmp;
  }
  $page++;
  // Here for non JS you probably would just redirect to the proper page
  $form_state->setValue('page_number', $page);
  $form_state->setValue('my_stuff', $result);
}

Then in your MyController::myFormSubmit

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AfterCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

public static function myFormSubmit(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $selector = $form_state->getValue('my_stuff');

  // Here you build the render array based on the output you want on the page
  $build = [
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  ];
  // The selector is as if you did this in jQuery
  $response->addCommand(new AfterCommand(
    '.some-selector',
    $build
  ));
  $response->addCommand(new HtmlCommand(
    '.some-selector-that-wraps-the-form',
    $form
  ));
  return $response;
}

That's the gist of it. It should put you on the right track.

If you want to use a simple link. You need your initial function to take that into account and send what you have now for non JS and a response as in the ajax submit callback when it's called through JS.

Note that if you add a class "use-ajax" to a link and write the link as "/some/path/nojs" Drapal.Ajax will change that to "/some/path/ajax" so its easy to know if the called was made through Ajax or not.


Create nodetype with cck fields Any clues or examples how to programmatically create node types with cck fields in Drupal 6? I would like to create a content type with has a cck file field in it. The Example module has an example of creating a node type but it does not utilize existing cck fields.

This blog post explains one way to do this: http://www.openbandlabs.com/blog/2009/06/programmatic-cck-content-type-creation


Select users that do have certain roles and do not have others I need some help with my SQL in that I want to get all users with a certain role that do have another role.

SELECT distinct users.uid, users.name, users.mail
FROM users AS users, users_roles AS ur
WHERE ur.uid = users.uid
AND ur.rid <> 4
AND ur.rid = 13

My SQL is really bad so any help would be appreciated.

According to Drupal db_select API Use this to fetch user id and names that user have roleId 13 and not have roleId 14

$query = db_select('user', 'u');
$query->join('role', 'ur', 'u.uid = ur.uid');
$query->fields('u',array('uid','name'))
 ->condition('ur.rid', 13)
 ->condition('ur.rid', 14,'<>');
 $result = $query->execute()->fetchAll();
dpm($result);


Proper way to add external JavaScript file What is the proper way to add Amazon oneTag code to Drupal 8. Instructions say to add it before the ending body tag.

I think it should be loaded to the /theme.libraries.yml. Here is the code I am trying to add:

Do I need to create a file onelink.js with this code? Then reference it in libraries?

Thanks

It's actually pretty well documented: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#external

MYTHEME.libraries.yml (or MYMODULE.libraries.yml)

amazon-onetag:
  js:
    //z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789: { type: external, attributes: { async: true } }

MYTHEME.theme (or MYMODULE.module)

function MYTHEME/MYMODULE_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'MYTHEME/amazon-onetag';
}

Now we could start to discuss what is "the proper way"?

As Amazon wants it directly before the closing body tag (which is irrelevant in my experience) and as they also put a nice container with an ID around the script (which very likely is irrelevant as well) you could also simply copy the whole snippet into your (custom or sub-)theme's html.html.twig directly before the closing <body> tag.

But that would at the same time take this script a little bit out of Drupal's influence to handle, preprocess and order all scripts according a desired logic. And it can become a little bit more difficult to maintain in the end.


How to install a text filter for plain_text input format The users at my Drupal 7 website discuss a card game in plain_text comments and I'd like to format the hearts and diamonds characters by red color.

Based on the Examples module recommended to me here at "Drupal Answers" site I've added the following code to my custom module sites/default/modules/pref/pref.module:

function pref_block_view($block_name = '') {
       ... this other part of my custom module works well ...
}

function pref_filter_info() {
  $filters['plain_text'] = array(
    'title' => t('Pref filter'),
    'description' => t('Replace the ♠ ♣ ♦ ♥ characters'),
    'process callback' => '_pref_filter_process',
  );
  return $filters;
}

function _pref_filter_process($text, $filter) {
  $text = str_replace('♦', '♦', $text);
  $text = str_replace('♥', '♥', $text);
  return $text;
}

However still nothing is highlighted in comments.

The rest of my custom module works fine (it generates few blocks - for the Flash game and player rating).

How to register my filter for the plain_text please? I suspect that

 $filters['plain_text'] = array( ... );

is a wrong way.

Do it in GUI. http://example.org/admin/config/content/formats/plain_text

Check it in Enabled filters section and then make sure it's the last one in Filter processing order section. If you'll put it before Display any HTML as plain text, your tags will get added and then in the very next step removed.

Also,  tag may be removed by HTML cleaning modules. Modern way is to make it like  and then style it in CSS. Actually, it might be a wise idea to add  as well, and maybe "card" class for both, and respective classes for clubs, spades, hearts and diamonds. That way you will be able to style them differently or even use image substitution, if you wish - all in CSS.

You can provide default CSS in your module. In mymodule.info add line:

stylesheets[all][] = css/cards.css

Create that file in mymodule/css directory and place all styles there. That way they will be there, and themes will be able to override them in their own CSS files.


How to check user by user name is exist in ldap server? I am using LDAP as my source for users. This works fine, and everyone can simply log in using their LDAP info, and it will create a Drupal user for that person.
However, one of our requirements is during user registration how to check this user already in ldap server or not , means is there any API by which i can check this user already in ldap server on user registration.

The LDAP module can handle that for you.


shopping cart is empty when I programmically create order I create a order with below code

      global $user;
     $product_id = 860;
     $price=intval($form_state['values']['field_suggest_your_price']['und'][0]['value']);
     dsm($price);
     dsm($form_state['values']);
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
       $order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
        commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
        $product = commerce_product_load($product_id);
        $product->commerce_price["und"][0]["amount"]=$price;

        $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
//// Save the line item to get its ID.
        commerce_line_item_save($line_item);
//// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
//// Save the order again to update its line item reference field.
commerce_order_save($order);
dsm($order);

//// Redirect to the order's checkout form. Obviously, if this were a
//// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);

but in checkout/orderid  shopping cart is empty, any body know where is my fault?
appreciate any urgency help

Here's an example on how to programmatically create an order and add a product to it, then redirect to checkout.

/**
 * Create new commerce_order with product
 * based on $_GET['pid'] from URL
 */
function MODULE_commerce_order_new(){

  global $user;

  // Sanitize just in case
  $product_id = filter_xss($_GET['pid']);

  // Load product
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }

}


View's path prevents 404 page from showing D7, Views 3. I'm kinda puzzled with how Views path work. I have these paths at my site:

mysite.com/people - a view displaying a list of all people

mysite.com/people/alice - an article about Alice

mysite.com/people/bob - there is no such article at mysite.com

When I go to /people/alice I get my article. And when I go to /people/bob I naturally expect to get a 404 page. But /people view is shown instead, probably seeing the "people" part of the path and thinking I've called /people view with some parameter. As I do not expect /people view to have any parameters and always want it to display a list of all people, how do I tell it not to get into Drupal's process of resolving its paths?

This is not a problem with the Views module; it's how Drupal behaves.

If you look at menu_get_item(), you will notice the following code.

$original_map = arg(NULL, $path);

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

I tried the following code, in a test site.

$original_map = arg(NULL, 'people/bob');

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);

What I got is an array containing the following items:

people/bob
people/%
people

In your case, as there isn't a menu callback for people/bob, and people/%, the query executed from menu_get_item() will find the menu callback for people, the view you have defined.

To avoid people/bob returns the view page, I would create a custom module with the following code.

function mymodule_menu() {
  $items['people/%'] = array(
    'page callback' => 'mymodule_people_view',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

function mymodule_people_view($username) {
  $alias = "people/$username";
  $path = drupal_get_normal_path($alias);

  if ($alias == $path) {
    // $alias is not a defined alias; in this case, drupal_get_normal_path()
    // returns the string it gets as argument.
    drupal_not_found();
  }
  else {
    drupal_goto($path);
  }
}

There is a module to resolve this issue (Views 404), which has now a version for Drupal 7.

  Are your views returning a 200 when it should return a 404? Views404 is the answer! This is very helpful for any caching layer and it will help SEO.
  [...]
  Standard Drupal behavior is to pass all arguments through, whether or not they requested. Sometimes this behavior is desired. The views 404 module assumes that by default you do not want arguments passed through. 404s for views can also be accomplished by setting the Global: Null under Arguments.


How to display value in View global text field if another field has specific value In my scenario I'm trying to display a flag (Font Awesome icon) in Views Global Text Field if another field in the same row of a type "Date" has a value of, say, a week from now.
I tried Views Table Highlighter but it has some bugs with filters I'm using, so I thought that using the above approach would be better.

You can use views conditional module.

  Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views


How to create a module as a wrapper for js I do a lot of theming but I don't have much in the way of php skills. So when I use or create a cool piece of javascript, I put it into my theme layer. The problem is, 90% of the time it doesn't belong there, and I really can't share what I've done with others.

So, how can I create a module, basically as a wrapper, for js code? I need to know more about that basic custom module structure and also the php used to insert js and css. Bonus would be basic info about creating blocks, content types and views with the module rather than creating them on the site UI.

If you've done work with themes and template.php, writing a module will be a snap. Review Creating Drupal 7.x modules for the basics, but at a minimum you need a yourmodulename.info and a yourmodulename.module file to get going. Declaring the block
 specifically will start you off on being able to define your blocks. As for including css and js, use the drupal_add_css and drupal_add_js functions respectively.


Drupal's main-menu not displaying I've started my first custom theme and I pulled the main-menu print statement from the default page.tpl but it didn't display. Curiously, if I create a region and add the main menu to that region via the blocks administration it will show up. Why won't this show when hard-coded?

<?php if ($main_menu || $secondary_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>

<?php endif; ?>

If I switch the theme over to Bartik, that uses the exact same print statement, the menu seems to work fine.

I spent countless hours figuring it out as well; the solution was so dumb simple !

Edit your theme's ".info" file and add :

features[] = main_menu
features[] = secondary_menu

Otherwise main_menu and secondary_menu doesn't display at all.

Hope that helps.


Page title set from the title callback doesn't change I created a simple download module to redirect a user when they click the download button to another page. Now I need to change the the page title every time a new download is triggered.

This is my code.

function custom_download_menu() {
  $items['download-code'] = array(
    'title callback' => 'custom_download_page_title',
    'page callback' => 'custom_download_view',
    'access arguments' => array('access content'),
    'access callback' => TRUE,
  );

  return $items;
}

function custom_download_page_title() {
  if (isset($_POST['title'])) {
    $title = "Downloading " . $_POST['title'] . " Code";
  }
  else {
    $title = "Download Code";
  }

  return $title;
}

But most of the time, the title does not change. It seems that it is using the title that is cached before.

I already added the following code so the page will not be cached:

drupal_add_http_header("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
drupal_add_http_header("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
drupal_add_http_header("Cache-Control", "post-check=0, pre-check=0", false);
drupal_add_http_header("Pragma", "no-cache"); // HTTP/1.0
drupal_add_http_header("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

Am I missing something?

Update:

<form id="form1" name="form1" method="post" action="/download-code">
    <input type="hidden" name="title" id="title" value="[node:title]" />
    <input type="hidden" name="download_code" id="download_code" value="[node:field_code_file]" />
    <input type="hidden" name="uri" id="uri" value="[node:url:relative]" />
    <input type="submit" class="downloadButton" value="Download Code">
</form>

You're missing the title arguments key in hook_menu

e.g:

/**
 * Implements hook_menu
 */
function custom_download_menu() {
  $items = array();

  $items['download-code/%'] = array(
    'title callback' => 'custom_download_page_title',
    'title arguments' => array(1),
    'page callback' => 'custom_download_view',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * hook_menu title callback
 */
function custom_download_page_title($file) {
  if (isset($file) {
    $title = "Downloading " . $file . " Code";
  }
  else {
    $title = "Download Code";
  }
  return $title;
}

If the download link is

  download-code/my-file.txt

The page title should then reflect that.


Form select type: setting default based on options' value So I've got this form:

$form['color'] = array(
        '#type' => 'select',
        '#title' => t('Kleur'),
        '#options' => array(
            0 => t('Wit'),
            1 => t('Geel'),
            2 => t('Groen'),
            3 => t('Rood'),
        ),
        '#default_value' => 'Rood',
  );

As expected, this doesn't currently set the default value to 'Rood'. How would I get it so that the default value can be accessed by it's value?

Note that this example shows the string 'Rood', but in practice it would be a variable string that is pulled from the database.

Thanks in advance!

Default value should point to key, not a value.

In your example, default_value should be as in below.

'#default_value' => 3,

Hope below link will help you.

https://www.drupal.org/node/240783#comment-1794710


How and where to create a prefix key for memcache? I am up to here in drupal documentation :

  Start at least one instance of memcached on your server.
  Edit settings.php to make memcache the default cache class, for example:
    $conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
    $conf['cache_default_class'] = 'MemCacheDrupal';
    $conf['memcache_key_prefix'] = 'something_unique';

Why do I need a memcache key prefix if have only one database? Anyway where and how do I set it?

All those settings are added to settings.php

usually sites/default/settings.php

$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'k1';
// Use database for cache_form
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

You only need a memcache key prefix if you're using memcache with more than one site on that server. Adding a short key, e.g $conf['memcache_key_prefix'] = 'k1'; is good practice.


After crash I can't access certain sections nor login to site I'm working on localhost. After saving a view the loading icon kept going for about 15 minutes. I changed over to other admin sections and they were fine, but after coming back to the original view the loading icon was still there. My clever answer was to log out and log back in to see if this fixed it. Oh terrible mistake, now I can't log back in, the page stays loading for a long time until finally returning a blank page. Being logged out I can still view the site's sections EXCEPT the view that crashed, that page just hangs.

I'm on a tight schedule so reinstalling would be my last option. Anyone has experienced this, how can I fix it from 'outside'? I'd appreciate any help, I'm growing desperate.

Thank you.

EDIT [SOLVED]:

Not much of a solution but I ended up restoring the DB with a backup file (luckily I had backed it up early today!) and the site works fine again.  I couldn't post this as an answer because I don't have enough reputation.

My fix was to re-install the database from a backup I did.  Not exactly a solution to the problem but it worked :)


Do I need to optimise images for smaller file sizes? Im adding images to my content through Drupal eg as a CCK field and im normally displaying them through image cache.

I want the images to be compressed for a smaller file size as sometimes the originals can be massive without looking that much sharper. Note, im not talking about resolution here, but the quality of the image.

Do I need to first do this with a graphics program like Photoshop or will Drupal automatically do this for me? If it does it automatically, are the results fairly good or is it still best to do it manually?

Thanks

Drupal does this for you; check your ImageCache settings (look for it under admin/settings), since it basically runs ImageMagick or uses GD in the background to do the image conversions. There is a quality setting that should do what you need.

IIRC, ImageMagick does a good job. The external GD library when called from PHP apparently aren't as reliable, but the built-in GD also does a good job, I think. Ultimately, you have to test this to see if it meets your own standards.


user:role:add for email addresses in Drush 9/10? In Drush 8, you can add a role to an email address like this:
drush user-add-role "power user" --mail=penguin@example.com

In Drush 9, the --mail option no longer exists for user:role:add.
So, if I only have an email address, how can I add a role to the user account?

Maybe there are better ways, but the following should work:
drush user-add-role "power user" $(drush user-information --mail=penguin@example.com --field=name)

You get the user name from the e-mail address using the user-information command.


Keep Alive in .htaccess Any potential issues with enabling keep alive in the .htaccess file for my Drupal 7 websites?
 Header set Connection keep-alive

I can't see any potential issue with using Keep-Alive unless it is not properly configured. e.g

KeepAliveTimeout value is not ideal. For example, if the site is high traffic the value should be higher to make sure there is no frequent tcp connection re-initiated.
MaxKeepAliveRequests should be tweak according to number of assets the server is serving.

It is recommended to use this feature to:

Reduce latency
Reduce the use of server resources such as CPU and memory

For HTTPS you might want to check SPDY.

  SPDY is a protocol developed by Google to increase the speed and
  efficiency of delivering web content. SPDY modifies parts of the
  HyperText Transfer Protocol (HTTP) to improve web performance.


stylesheets-remove in .info.yml file doesn't work I'm following Drupal 8 Theming Fundamentals, Part 1 to create a Drupal 8 theme. They say that default CSS styles are added by modules in the core as shown in the following screenshot.

Those CSS files can be removed from the .info.yml theme file using code similar to the following one.

stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css
  - core/modules/system/css/system.module.css
  - core/modules/system/css/system.theme.css
  - core/modules/views/css/views.module.css

I've done that, but nothing happens (it's says the same). Plus, when I watch to the source of the page, I see the following.

The CSS styles are aggregrated. What is happening here? How can I fix this?

I was also having trouble with this and I found a change record which states:

  "In cases where a Drupal core asset is being removed (for example, a
  CSS file in jQuery UI) the full file path is needed. In cases where
  the file is part of a library that belongs to a module or theme, a
  token can be used. Note that when using the token it needs to be
  quoted because @ is a reserved indicator in YAML."

In my case I was trying to remove the eu_cookie_compliance.css file from the eu_cookie_compliance module. To do this I used the following in mytheme.info.yml:

stylesheets-remove:
  - '@eu_cookie_compliance/css/eu_cookie_compliance.css'

To remove module (even core ones) provided css you could try something like:

'@system/css/system.module.css'

To answer your second question about the aggregation of css files, you can switch off aggregation by visiting /admin/config/development/performance and unchecking "Aggregate and compress CSS files"


Register entity type as a group Is it possible to programmatically register a custom entity type as an Organic Groups group? I know I can add a group field to the entity type using the UI, but I would like to register the entity type as a group in the module code. Users should be able to add such an entity and then these entities should automatically be a group and the checkbox should be hidden from the administration form.

Of course I could 'check' the checkbox and hide it by altering $form and $form_state, but I feel it is a better practice to register it as group in the entity type definition, if possible at all.

To register content type grammatically you can by code and by the module - features. But I do not see a reason why you need to create it problematically.


Require First and Last Name on Comments in Drupal 7 I enabled Comments on a content block in Drupal 7. I would like to have First and Last Name required on the comments. How do I make that happen?

In Drupal 7, Comment fields are managed the same way Node fields are managed.

Go to structure->Content types-> edit link. If comment is enabled for selected content type, It will add a tab for "comment fields" on top besides manage fields tab.

For article content type url will be "admin/structure/types/manage/article/comment/fields" and tab looks like the image attached below.


Access trimmed description in module I have a content type with a Long text and summary field. In the node view display, it is set to to show as Summary or trimmed.

I have a module that gets all the nodes of that content type.

How do I programmatically get the trimmed value of that field? Using var_dump(), I get the following output.

  ["field_description"]=>
  array(1) {
    ["und"]=>
    array(1) {
      [0]=>
      array(5) {
        ["value"]=>
        string(5763) "
Test user DescriptionTest
"
        ["summary"]=>
        string(0) ""
        ["format"]=>
        string(9) "full_html"
        ["safe_value"]=>
        string(5764) "
Test user Description
"
        ["safe_summary"]=>
        string(0) ""
      }
    }

The summary value will only be set if someone has actually filled out the summary textfield when editing the node. You'll need to do the trimming yourself in code. Drupal has functions such as https://api.drupal.org/api/drupal/modules%21field%21modules%21text%21text.module/function/text_summary/7.x or views has https://api.drupal.org/api/views/views.module/function/views_trim_text/7.x-3.x

So you'll need to do a check to see if the summary value exists, if it doesnt use the main text and trim it with the functions or something similar above


Way to see the date roles were assigned? Is there a way to setup a view in drupal 6 that shows me users assigned new roles in the last month and who assigned the role?

I have video products that sell both through the online store and at the front desk of various martial arts schools. Currently the online portion is handled with ubercart granting access to appropriate roles. However tracking the sales from the front desk is messy, using the role watchdog module and filtering the email notifications.

Being able to see all role modifications in the last month would simplify tracking of sales to each school greatly.

You could create a content type User Role, then with Rules module register when a role it's assigned.


Webforms: pages 1,2 of 4 not being displayed I'm developing my first Drupal 8 Webforms application. It had three pages to start with and I had managed to get it to do what I wanted it to. I have also developed a WebformHandler to go with it.

I needed to add an extra page between the old 1st and 2nd page. I created this using the "build" tab and it was created in 4th position in the list of pages, so I dragged it up to 2nd position and did "Save Elements".

But then, when I used the "View" tab to try out the form, the dialogue started at the 3rd page (the old 2nd page). I have now deleted the new 2nd page and appear to have the same old configuration that worked, but using the "View" tab still ignores the first page.

I have flushed all the caches; I have looked in the database for anything obvious (but not found anything); I have looked at the YAML files in the module I created for the Webform; I have even rebooted the server.

I have tried to scan the entire Drupal file tree looking for files that have been modified in the last couple of hours (since the webform last started correctly), but I haven't managed to find anything, except the WebformHandler, but that isn't called before the initial page is shown.

Using a different browser (Safari instead of Chrome) produces the same result, so I guess the problem is on the server and not the client.

Somewhere, something is holding information about my webform: could anyone help me to locate it?

I was looking in the wrong places...

The element editor in Webforms includes an Access tab. For the pages that were not being shown I had removed all the permissions, which included the permissions of ‘Administrator’, the user I was logged in as. So – obviously – those pages were not shown.

Duuhh.


Using Adaptivetheme subtheme how to have fixed width left column? How do I have a fixed width left column and fluid right? At the moment, in my panels config there is only the fluid layouts available  e.g. AT Two column 33/66.

From the AdaptiveTheme documentation:

Sidebar Units and Widths
You can use any combination of units - meaning you can set a percentage width on the page and pixel widths on the sidebars. In some layouts you can only set the width on one sidebar because the second sidebar wraps below the main content and becomes a full width horizontal region - useful in smaller screen displays.

Example screenshot:

If you're using Panels, however, you're going to have to modify the CSS/theme code yourself.  You can either make your own new layout (just look at the code-- AT is pretty well documented) or just override the part that is making the layout fluid.  Note that doing this is almost certainly going to break the "responsiveness" of AT.


Pulling #hashtags and displaying them on site I see that you can you the Activity Stream module to pull feeds from twitter and other social media sites. Well how could I pull a predefined #hashtag from ANY social meida site and present it in a feed on my drupal site.

Example:

Hashtag is #NCAABasketball

From bjones on Twitter:
Saw KU beat UNC's butt. Love #NCAABasketball

From jbean on Google+:
Love #NCAABasketball !

From ktghram on Instagram:

I'm at the game! "picture:" #NCAABasketball

It doesn't have to be like this, but would this be possible with out the user posting or tweeting to my account?

Any suggestions?

This is possible using the dev branches of a few modules put together:

feeds, >= 7.x-2.0-alpha8+56-dev

feeds_oauth, >= 7.x-1.0-beta3+2-dev

feeds_jsonpath_parser, >= 7.x-1.0-beta2+12-dev

I think there are a few other necessary modules you'll need to have installed, like oauth, ctools, feeds_ui.
One of the most important things is that you need to register an app at dev.twitter.com, and get an API key / secret. You put that into the feeds setup (admin/structure/feeds/FEED_NAME/settings/OAuthHTTPFetcher). When you setup your feed, you will want to choose the HTTP OAuth fetcher (oauth2 does not work) as the Fetcher type.

You create a new feed importer.

Additionally, you'll want to create a content type like "tweet" and add the fields you want to parse (like author, date, name, body, location).

Back in the feeds setup, setup your mapping, and create several jsonpath_parser maps to your respective fields. After that, click "settings" under JSONPath parser, to map your json contexts to your fields.

It should be something like this:

Context: $.statuses.*

Title: id_str

body: text

etc, etc, etc

Finally, once this is all setup, you can go to SITEURL.com/import
and input your search string, which will look like this:

https://api.twitter.com/1.1/search/tweets.json?q=%23HASHTAG

Anyway, I hope this is helpful. I realize that my answer could be better organized, but it should give the gist as to how this is done.

For my "tweet" content type, I have the default setup to be NOT published, so that I can moderate what actually shows up on my site.

One more caveat is that non UTF-8 strings (common in foreign languages for example) will error out and break your feed importer (which should run on cron automatically). Ideally you want to sanitize the input before writing it into the database anyway.

Here's the PHP you can put into a quick custom module to sanitize the input of the body field for example. You want to make sure your jsonpath_parser:ID matches the ID you setup in the node-processor settings.

<?php

/**
 * Implements hook_feeds_after_parse().
 */
function feeds_custom_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
//dpm($source); // look at source variables, requires devel
//dpm($result); // look at result variables, requires devel

  foreach ($result->items as $delta => $item) {
    $result->items[$delta]['jsonpath_parser:1'] = utf8_encode($item['jsonpath_parser:1']);
  }
}


entityform association with organic group Is it possible to associate entityform with organic group?
Ive created form and would like it to be accessible by a group specified.

Organic Groups allow to make that possible with content types but I was wondering if this is possible with entityform.

If not - are there any alternatives?

It looks like you and I have two very similar questions going. This is a link to my question, which you (@sly) have a nice answer to, and which also includes my custom module answer: Organic Groups access to Entityforms: is it possible?.


How to assign a role to a user depending on order subtotal using Ubercart? I am using ubercart in drupal 7 . I need to assign a role to user after checkout. For this I created a rule using checkout complete.
But I need to assign a role depend on order subtotal. this option is not meeting me on rule.

If you want to use that "Order subtotal" in a Rules "Condition", you could try to first add a Rules condition Entity has field (related to the field containing that "Order subtotal").

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition, somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

So if you don't have an appropriate "field" for it, then you may be able to get it to work also by using that 'content is of type'.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Pre-populating a CCK field item with values from another field I'm working on a project that has two compound field ("flexifield," or "multifield," if you use CCK3) sections that output content types "rooms" and "levels".

Level is defined first and has a title, a total area and an "above ground" binary value.

Room has a length, width and area, then a level defined by a select box — populated by the first set of fields via the following "allowed value" code:

$result = db_query('SELECT `vid`, `field_level_label_value` FROM `drupal_content_type_meas_areas`;');
while ($item = db_fetch_object($result)) {
$items[$item->vid] = $item->field_level_label_value;
}
return $items;

Alas, while the proper label is available when filling in the fields, when actually viewing the content type, the value of each "level" field is a numerical value, instead of the label defined by the level's "field_level_label" field.

How do I make this field save the field's string value instead of its (I'm guessing) vid?

Thanks!

$result = db_query('SELECT `vid`, `field_level_label_value` FROM `drupal_content_type_meas_areas`;');
while ($item = db_fetch_object($result)) {
$items[] = $item->field_level_label_value;
}
return $items;

I figured it out -- removing the $item->vid bit as $items' array key results in the proper values.

Oh Drupal, so subtle in its frustrations! :D


How to delete children when main entity is deleted? I am looking for the best way to delete children of my main entity when i delete it.
I have 2 entity type :

commandes_entity
commandes_ligne_entity ( entity reference to commandes_entity )

The only way i have found is to create a hook_entity_delete :

Edit :  This is how i delete children :

function boutique_commandes_entity_delete(Drupal\Core\Entity\EntityInterface $entity)
{
  $query = \Drupal::database()->delete('commandes_lignes_entity');
  $query->condition('commandes_id', $entity->get('id')->value);
  $query->execute();
}

Is there another way (maybe better) for delete children ?

You could use rules  to react to an entity being deleted, then add a loop over the reference field and use entity delete for the current list item.

Currently on my phone so apoligies for the compact answer.


How to "freeze" a View at the time of publishing? I have a content type for publishing a node once a week (type A) - on Saturday night/Sunday morning - that needs to show, as an attachment, a list of some other nodes (type B) that go live daily during the week (one node a day)
I have a view that puts together nodes of type B for 6 days of week - Monday through Saturday, so I have a filter on Post Date between 'last Sunday' and 'now' and I limit the number of nodes to 6. Then I use Viewfield to show the view of nodes B on content type A - and it all seems to work, but! (there are always those 'buts', right??) - I want to 'freeze' the View's content at the time of publishing - so if somebody will click on the type A node two weeks from now, the list of the type B nodes should be relevant to the week the type A node was published on - so, I need to somehow filter the type B nodes view using an "external date" parameter
How do I do that?

I thought about the relationship angle and couldn't find one but I have been known to be blind in the past to things in front of me and instead went the hook_views_pre_view() route...

function YOUR_CUSTOM_MODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='last_sunday_and_now') { // or whatever your View is named

    // see what we have to work with...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('
Before: ' . print_r($filters, TRUE) . '
');

    // here on my box it is 'date_filter' so let's change things up

    $filters['date_filter']['default_date'] = // set this to whatever you want instead of "Last Sunday"
    $filters['date_filter']['default_to_date'] = // set this to whatever you want instead of "now"

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $value) {
      $view->display_handler->override_option($option, $value);
    }

    // let's see what we have...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('
After: ' . print_r($filters, TRUE) . '
');

  }

}

It's up to you to define the logic of what to set the dates to, but if this is sitting on a node, you can grab the post date of it via menu_get_object() pretty readily and then use any of the various date and time functions to create the dates.


Errors occured while trying to retrieve tweets I am running drupal 7 and using the following twitter module for twitter feed to display on the front page of a site.

Twitter Pull   7.x-1.0-rc1 Pull Info from Twitter and Create Contextual Insets

Recently, start getting the following error message instead of twitter feed

Errors occured while trying to retrieve tweets. Please check Watchdog log messages.

I don't have watchdog configured nor see any other error log that lead to anywhere. Please note that I am new to drupal. kindly let me know with detail steps how do I resolve this issue.

I see the following on /admin/reports/dblog

 Reports
 Status report
 Get a status report about your site's operation and any detected problems.
 Field list
 Overview of fields on all entity types.

This was working so I am sure the API keys were setup but I don't know where to look to confirm this.

Good idea to enable database logging. I have enabled the database logging now seeing more detail error message:

Non-empty list of tweets returned blank space after applying theme function. Most probably you are passing invalid/unregistered theme key or tpl file corresponding to the theme key does not yet exist. Please fix the problem.

I will check details on sendbox.

If you haven't enabled Database Logging yet, go ahead and do that on the modules page. Then you should see  errors reporting under admin/reports/dblog.

Twitter recently dropped their version 1 support, which is what Twitter Pull runs off of. Now you must use the Twitter and oAuth modules to deal with v1.1. Look at this sandbox for a solution. It branched off from Twitter Pull as an alternative to deal with oAuth tokens.

Updated: Better way to do it

There's recently a new module that came out that makes it a whole lot easier to embed tweets using the embedded widgets. Try Twitter Block instead, and you'll get up and running a lot faster.


add a menu in a field Does anyone know if there is a custom field type that allows you to assign a menu inside of the field? What I would like to do is add a list menu inside of the body field. I know I could do it manually through html but I would rather add it as a menu type.

My suggestion to you is use list as type and select list as widget then in select list value add something like below :

link1|link1
link2|link2
link3|link3

and after node saved it is completely link .


what is the hook when a commerce order is updated? I am searching for a hook name when a commerce order is updated ?

Indeed I have programmed a module that it must perform some operations when a commerce order is modified. for example when order status is changed or when a line item in selected order is changed.

do you know what is the hook name when a commerce order is modified ?

The documentation for commerce_order_status_update() says:

  While there is no explicit Rules event or hook devoted to an order
  status being updated...

It is possible to use hook_commerce_order_presave():

/**
 * Implements hook_commerce_order_presave().
 */
function my_module_commerce_order_presave($order) {
  if ($order->status != $order->original->status) {
    drupal_set_message("The order status changed from {$order->original->status} to {$order->status}");
  }
}

Here's an optional helper function for use elsewhere if you have an $order object, and are curious if its status has changed from what is stored in the database:

/**
 * Given an order object, this returns FALSE if the order status has not
 * changed. If it has changed, it returns an associative array with the
 * following keys: new_order_status, old_order_status
 */
function my_module_order_status_changed($order) {
  $result['new_order_status'] = $order->status;
  $result['old_order_status'] = db_select('commerce_order', 'co')
    ->fields('co', array('status'))
    ->condition('co.order_id', $order->order_id)
    ->execute()
    ->fetchField();
  if ($result['new_order_status'] == $result['old_order_status']) {
    return FALSE;
  }
  return $result;
}


How can I show the flagging field edit form on a node? On a flagged node, instead of showing the flag/unflag link, I want to show the flag edit form.
Here's my setup.
Basic page content type can be flagged with the flag Bookmark.  Bookmark is a per-user flag that has an int list field Rating, which has values from 1 to 5.  On the flag admin page (/admin/structure/flags/manage/bookmark), Link type is set to Field Entry Form.
What happens now:

Go to a basic page that has been flagged.
Click the "Unflag" link for bookmark.
The Field Entry Form pops up and lets me edit the value of Rating or delete the flag.

What I want to happen:

Go to a basic page that has been flagged.
The Field Entry Form is embedded in the page and the user can adjust the rating as he/she likes.

I don't know how to build the form.  By digging through the flag module code, I managed to find the class that generates the form in FieldEntry.php:
/**
 * Class FieldEntry
 *
 * @ActionLinkType(
 *  id = "field_entry",
 *  label = @Translation("Field Entry Form"),
 *  description = "Redirects the user to a field entry form."
 * )
 */
class FieldEntry extends FormEntryTypeBase {

But I don't know how to embed this in a node.
I looked at Inline Entity Form but that only supports Commerce modules and Entity Reference fields out of the box.
I also tried the Twig Tweak module and tried to embed an entity edit form using a view that returns the flagging ID like this:
{{ drupal_entity_form('flagging', id__value) }}

However, this gives me an error:
Twig\Error\RuntimeError: An exception has been thrown during the rendering of a template ("The "flagging" entity type did not specify a "" form class.") in "__string_template__87f4d3d6f14aa36d2fb8ce031f07b73d8b577189b4e5f3c535809f672ffb6af8" at line 1. in Twig\Template->displayWithErrorHandling() (line 469 of /app/vendor/twig/twig/src/Template.php).

I can embed the entity itself with Twig Tweak just fine (but that is not the goal; the goal is to embed the entity edit form):
{{ drupal_entity('flagging', id__value) }}

Here's the code I ended up using:
/**
 * Implements hook_node_view() for MYMODULE.
 */
function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($node->getType() == 'MY_CONTENT_YTPE') {
    if ($display->getComponent('my_flagging_form')) {
      $flag = \Drupal::service('flag')->getFlagById('MY_FLAG');
      $flagging_entity = \Drupal::service('flag')->getFlagging($flag, $node);
      $form = \Drupal::service('entity.manager')
        ->getFormObject('flagging', 'edit')
        ->setEntity($flagging_entity);
      $build['my_flagging_form'] = \Drupal::formBuilder()->getForm($form);
    }
  }
}

/**
 * Implements hook_entity_extra_field_info() for MYMODULE.
 *
 * Https://www.webomelette.com/creating-pseudo-fields-drupal-8
 */
function MYMODULE_entity_extra_field_info() {
  $extra = [];

  $extra['node'][NodeType::load('MY_CONTENT_TYPE')->Id()]['display']['my_flagging_form'] = [
    'label' => t('My flagging edit form'),
    'description' => t('This shows the my flagging edit form.'),
    'weight' => 100,
    'visible' => TRUE,
  ];

  return $extra;
}

For more details, see this question.


Ask user for URL on registration and create feed from the URL on his/her profile page I know i should be using the Feeds module for this but i want to know how will i turn that particular URL into feed automatically when user enters his feed URL.

Basically i want to let users show their github activity feed on their drupal profiles.
URL for it is something like this https://github.com/githubusername.atom
So in a feed, the URL still remains standard and if i just ask them to enter their github username and generate the feed accordingly, that would be really amazing. I know how to do it in php but i don't know drupal moduling. It would be great if anyone could help me with it or give me ideas on how to do it.

Since you already know how to do it in PHP, you could use the Panels module. You can then use a Panel to display the user's profile, and you can add a "Custom" field with your php inside.

You could also do something similar by using the Display Suite module and adding a custom code field.

Of course that would require you put php directly into the UI, which isn't always considered the best approach but can be done. To get the user's username, you'd put a field in their profile asking them the user name. That value would then be stored in the $account object.


Add popup within the ckeditor dialog box? Here is the scenario. I had added a custom plugin in ckeditor. The plugin provide a button on the editor menu and when we click on that button ckeditor dialog box opens up with a text field and and a link attached to it. Now, when I click on the link a form with some list items should pop up using CTOOLS and when I select any items it's value should be placed in the dialog box text field.

I had created the dialog box but now when I try to click on the link it redirects me to another page instead of opens up another pop up block.

I don't know a custom module that can do this, I'll do like this:

Create a new content-type with an  entity reference, a trigger
string and a dialog text area.
In the referenced node, query for any referencing entities from the new content type. Most likely with a preprocess function and preferably in a newly created custom module.
Load referencing entities if found and attach a JS file that will receive the triggers and dialogue values through the settings array.
If all is well then JS file will have triggers in selectors and
dialogues to display.


Output the field as $_rendered in the node page When a CCK field is added, we get the rendered output in the node page as $<field_name>_rendered.
How can we get a variable in the same way when we alter the form and add new field?

To load the data back to the node and render them, you first need to implement a hook_nodeapi load. Here some a short example:

function satya_module_nodeapi(&$node, $op, $teaser, $page) {
  switch ($op) {
    case 'load':
      // retrieve the p1 value from custom_table (it's better to use vid instead of nid to allow revisions.
      $p1 = db_result(db_query('SELECT p1 FROM {custom_table} WHERE vid = %d', $node->vid));
      return array('p1' => $p1);
      break;
  }
}

Then you will have a $p1 variable available in your node.tpl.php.

If you don't know yet the Examples modules, I'll definitely recommends it to have great examples and developer documentation for a lot of hooks.


Disable register email notification I have made a deep research over the web and I also tried a lot of alternative solutions, but I didn't find any solution to disable the email notification for new users.

In my User Settings, I have the option "Visitors can create accounts but administrator approval is required" checked, and the option "Require e-mail verification when a visitor creates an account" not checked.

Do you have any idea?

If you look at the function _user_email_notify(), it checks the variable 'user_mail_' . $op . '_notify' if it should send an email or not. Assuming that you have disabled email confirmation (otherwise, disabling mail notifications would be weird ;)), the $op is 'register_no_approval_required'. So the full variable name is 'user_mail_register_no_approval_required_notify'.

There doesn't seem to be a User Interface for that variable. However, you can set it in your settings.php, adding the following line at the end of settings.php (probably inside sites/default).

$conf['user_mail_register_no_approval_required_notify'] = FALSE;

You can do the same for other mail notifications too; the other possible $op values are listed on the linked page.


Responsive Image Gallery I want to create a responsive Image gallery block. I have used Views Slideshow Liquid Carousel module for this but that is not working properly, It breaks when the screen is too small. I want a carousel like display of images with responsive skin like http://tympanus.net/Development/Elastislide/, I have also tried this plugin but this plugin is not working properly can't find why. So is there any other way or plugin for this.

Trying to use these modules may help you (quotes included are from their project pages):

Responsive Images:

  ... integrates the Responsive Images library created by Filament Group.

  The purpose of this library is to load images in different sizes based upon
  the resolution of the browser loading the page. This allows for mobile-optimized images.

  ... provides a "Responsive Images" image field formatter for which you can select
  both a small (mobile-optimized) image style as well as a large (for normal screens) image style. The image style configuration options are provided by Drupal core.

Responsive images and styles:

  ... solves the problems with images and responsive themes, it allows you to define multiple image style suffixes and their corresponding maximum width.


Independent arguments for View Page and Attachment Setup:

A Views page with an Attachment

Is it possible to have the first argument in the url affect the main page only, and the second argument affect the attachment only?

e.g.
http://url.com/%1/%2

%1 is a cck field in a node.  If %1 == 'acme' the main page displays a list of all nodes where a certain cck field equals 'acme'.  It then ignores the second argument (e.g. %2 can equal anything or nothing without  affecting the page list).

%2 is an nid.  The Views page's attachment displays a single node where the nid the value of the second argument.  (Argument 1 will always be true for this node, so it can be inherited, but it doesn't have to be).

Is this possible?

I also tried by using a combination of an argument for the page and exposed filter for the attachment I could create a url like:

http://url.com/cck_field_value_to_match?nid=123

…but that still produced no results for the attachment.

…but that still prod

Personally, if you just want some content from the node at the top of a view, I'd override the Views template.

Then, in that template just use the following code to get the content:

<?php if (is_numeric(arg(2)) : ?>
  <?php $node = node_load(arg(2)); ?>
  <?php print $node->content; ?>
<?php endif; ?>

I'm pretty sure you can get attachments to inherit arguments, but they can't be used independently; all arguments will always affect the parent view.

If you have to use a view, you can always do as above, create a template, then create a 'new' view; then, embed that view inside the other using:

<?php print views_embed_view('viewname', 'displayname', arg(2); ?>

This will manually pass the third argument into the embedded view.


autocomplete taxonomy field depend on another taxonomy field There is a content type Animal in which two taxonomy field are used  say Animal Type and Breeds . Breeds taxonomy is autocomplete taxonomy field . so What i want Breeds taxonomy field  depend on Animal type taxonomy field. i.e, when cats are select from animal type field then breeds taxonomy show only cats type breeds .How can this acheive ?

I hope this is a drupal site on development state.

If it is possible to you, I recommend you to create just one taxonomy vocabulary, where Animal type are parent terms of Breeds terms as a tree:

Cat

Curl
Bengal

Dog

Afghan
Akita

Then you can use Simple Hierarchical Select or Hierarchical Select, where you can allow users to select a parent term first and then childs.

Hope this help, if you need help with views filters or things like that I can help you :)


Only Publish a node in certain languages In D8 I have a node with several translations - not all translations will be ready to publish at the same time.
If I unpublish one translation it unpublishes all transaltions and default translation. Is this a bug or do I have an incorrect setting somewhere?

First of all lets make sure you have set up Drupal correctly:

Do you have activated the core Content translation module
Do you have activated the core Language module
Do you have set up at least 2 or more languages (of course you have)
Do you have set up detection and selection correctly (I think you have)
Do you have set up content types correctly to allow multiple languages (sure otherwise it won't work)
Now when you start to list your nodes in content/admin overview you should be able to select translate each node
If you choose this and you translate it you should see the button below saying translate and publish which can be switched to translate and unpublish this selection
if you choose the second your translation will not be published automatically. Violá

Hope it helps ...


How do I make a clickable dropdown menu How do I make a clickable dropdown menu?  I'm making a dropdown menu that allows the user to click the item they want.  I would like then like that page appear automatically, or at least allow the person to click on the item and taken to the new page.

There are several modules that can accomplish this, eg Superfish and Nice Menus.

If you want to roll your own, the basic steps are

Edit you menu items (admin/structure/menu/manage/menu-foo-menu) so that they are always expanded.  This will result in all menu items always being available, instead of only available in the active/sibling hierarchy.
Write some CSS and JS to get the menu behavior that you want.  With the way the nested menus are built in Drupal, you should be able to achieve a CSS only solution.  You can either do this with a custom module, or add it to your theme.

The CSS and JS involved with this is beyond the scope of this site, but there are lots of resources on the net to help you out.


Find out what entity type an entity is? How can I find out what entity type an entity is, when all I know is the entity ID?

Or is there a way I could list all the entity types on my website (or even via database)?

You can't.

Different entities use the same ID.

E.g. you can have a user with ID 42, and a node with ID 42, and a taxonomy term with ID 42. So just knowing the ID is 42 is not enough to know what type of entity the ID belongs to.

This is why entity_load takes both the entity type and the ID as arguments.

To list all entities use entity_get_info().


How do I modify email headers when using Rules to send mail? I'm using the Drupal 7 Rules module to trigger and send emails on specific events, but need to modify the email headers before the message is sent.

What would be the appropriate way to add 'reply-to' headers (as used in RFC 5322) to specific outgoing emails that are sent using the Drupal 7 Rules module?

The following works when using drupal_mail() but I do not see how to apply this hook when using Rules.

function hook_mail($key, &$message, $params) {
    switch ($key) {
        case 'key_name_here':
            $message['Reply-to'] = $params['mail'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];
            $message['headers']['Reply-To'] = $params['mail'];
            break;
    }
}
// One note to the above script, lines 4 and 7 seem redundant and likely need work.

You can still use hook_mail, you just need to identify the key for the rule or rules you want to override. The key is set in the rules_action_mail() function $key = 'rules_action_mail_' . $name . '_' . $element->elementId(); where name is the rule name and element id is the numeric id for the rule. You need to make sure your custom module has a higher weight that the rules module in the system table of your database.


How might I have Webforms save files to private file system or as a database blob? In Drupal 7, I have the file system configured as

In the code for the Webforms' file component located at sites/all/modules/webform/components/file.inc, it appears that one could easily change it so that Webform file uploads are moved to the private file system by changing 'scheme' => 'public' to 'scheme' => 'private'. But I also know the pitfalls of hacking (changing) anything that could easily be overwritten with drush upc.

 /**
 * Implements _webform_defaults_component().
 */
function _webform_defaults_file() {
  return array(
    'name' => '',
    'form_key' => NULL,
    'required' => 0,
    'pid' => 0,
    'weight' => 0,
    'extra' => array(
      'filtering' => array(
        'types' => array('gif', 'jpg', 'png'),
        'addextensions' => '',
        'size' => '2 MB',
      ),
      'scheme' => 'public',
      'directory' => '',
      'progress_indicator' => 'throbber',
      'title_display' => 0,
      'description' => '',
      'attributes' => array(),
      'private' => FALSE,
      'analysis' => FALSE,
    ),
  );
}

Given that all file uploads are stored referenced in the file_managed table

mysql> describe file_managed;
+-----------+---------------------+------+-----+---------+----------------+
| Field     | Type                | Null | Key | Default | Extra          |
+-----------+---------------------+------+-----+---------+----------------+
| fid       | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |
| uid       | int(10) unsigned    | NO   | MUL | 0       |                |
| filename  | varchar(255)        | NO   |     |         |                |
| uri       | varchar(255)        | NO   | UNI |         |                |
| filemime  | varchar(255)        | NO   |     |         |                |
| filesize  | bigint(20) unsigned | NO   |     | 0       |                |
| status    | tinyint(4)          | NO   | MUL | 0       |                |
| timestamp | int(10) unsigned    | NO   | MUL | 0       |                |
+-----------+---------------------+------+-----+---------+----------------+

Is it feasible to do a post operation to a file upload that manually moves a file from public:// to private:// and updates the database entry? Would hook_file_presave or hook_file_insert be good tools to accomplish this?

Update

Based on the suggestion of using hook_webform_component_info_alter(), I implemented the following

/**
 * Implements hook_webform_component_info_alter().
 */
function  MYMOD_webform_component_info_alter(&$components) {
   $components['file']['extra']['scheme'] = 'private';
   dsm($components['file']);
}

/**
 * Implements hook_file_insert().
 */
function MYMOD_file_insert($file) {
  dsm($file);
}

After the output of the DSM() shows the component array seems to be altered but the DSM from hook_file_insert() still shows that the file was deposited into the public area:

Did a little digging into Webform. There is a setting for this in webform I believe. There was an issue posted in the webform issues but it has been resolved. Saving file submission to private directory

OP already solved but for future onlookers: There are instructions I believe on how to accomplish this in the comments of the issue referenced above, also make sure Webform is up-to-date.


Radio buttons triggering an AJAX callback to load form elements are pre-selected after navigating back to form in browser My form looks like this:

  $form['field_1'] = array(
    '#title' => t('Field 1'),
    '#type' => 'radios',
    '#required' => TRUE,
    '#multiple' => FALSE,
    '#ajax' => array(
      'callback' => '_myform_ajax_field_2',
      'wrapper' => 'field-2-wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['field_2_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#weight' => 2,
  );

  if (isset($form_state['values']['field_1']) && $form_state['values']['field_1'] > 0) {
    $form['field_2_wrapper']['field_2'] = array(
      '#title' => t('Field 2'),
      '#type' => 'radios',
      '#required' => TRUE,
      '#multiple' => FALSE,
    );
  }

The problem occurs when I submit the form successfully and move to the next page, and then navigate back to this form using browser back button and the field_1 radio button is remembered by the browser. This means that the radio is already selected however in this instance form_state['values'] is empty so field_2 does not display. From here the only way to get field_2 to load via AJAX is to un/re-select the desired option in field_1.

I've tried the following solutions which failed:

Adding a JS file to $form[#attached]['js'] to deselect any radio buttons on load, however this also gets loaded in AJAX calls. I'm not aware of a method to prevent this JS from running as a result of a traditional page load, but not on AJAX.
I've tried setting a #default_value on field_1 however this has no effect.

Since writing this question, I've discovered a solution which I'm really not happy with:

I am checking for and adding a unique class name to the page body to check whether I've already deselected radios. If it's already there, then don't try again. This works, it just feels a bit dirty, so I'm hoping there's a more Drupally way to solve this?

OK after a bit of searching I found this: http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors

Specifically it mentions Drupal 7 integrates the Jquery Once plugin into Drupal 7 core.

Therefore I can modify my Drupal.behaviours.attach to the following:

  Drupal.behaviors.uncheckRadioButtons = {
    attach : function(context, settings) {
      $('body').once('deselect_radios', function (){
        $('input[type="radio"]:checked').attr('checked', false);
      });
    }
  };


Hide/Remove core simpleTests in Drupal 7 I would like to remove the core tests that show up when I activate the Testing (simpletest) module. I have created my own tests for custom modules and I would like those to be the only testing options available to the user. How can I do this?

You can implement hook_simpletest_alter, e.g.

function hook_simpletest_alter(&$groups) {
  // An alternative session handler module would not want to run the original
  // Session HTTPS handling test because it checks the sessions table in the
  // database.
  unset($groups['Session']['testHttpsSession']);
}


How to get the values from a formatted field in inc file I have a description field with a CK editor enabled. And when I get the data from it as node->get('fieldname')->getString() it outputs the content as below.

The contents that I have entered in the Ck editor
, basic_html

I can resolve this in the twig file by getting this as {{fieldname| raw}}. But I need to get this in a php file. How do I get the value without that , basic html part?

How do I get the value without that , basic html part?

$node->field_name->value; should do the trick.

  I can resolve this in the twig file by getting this as {{fieldname|raw}}.

Using | raw filter in twig is bad security practice, see How do I get the raw field value in a twig template? for a safe solution.


can't log in to my off-line drupal site I deleted the navigation-log-in pane.

I logged out, and when needed to log back in, wrote: "mysite/user" and the message I keep getting is as follows:

"
Not Found

The requested URL /pancher/user/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
"

I've had some cases where clean url-s aren't working in offline mode. You should be able to log in using '?q=user' instead.


How can I increase the 128 character limit of a menu path? I know there are patches to core, but they were never backported to Drupal 6 from what I can tell.

Increasing path length to 255 chars
Menu path length is limited by the UI to 128 characters

How can this be overridden in a theme?

You should be able to fix this by using hook_form_alter() and override the default maxlength for the input field, and then change the field in the db to varchar(255) if it isn't already.

Another option would be to use a token value for the path and change the value on output using theme_menu_item().

Perhaps the best option after all would be the Custom Tokens module. I haven't tried it so I can't say if it works.

The downside with tokens is that you would have to make one token per URL, or possibly use a part of the URL if it's generally the same.