Populate a Chosen select list from a view We have a request from a client to create an interface where they select nodes in a Chosen box. We have the Chosen module on the site and have successfully implemented features with it.

In this case, they want to have an admin interface where they choose which nodes populate a javascript image slider. I thought to simply make them a custom view where they can check a checkbox field to indicate whether to include the node or not. However, because they want the Chosen functionality, I need to populate a select box with the values from a view.

How can I create a select box that's populated by values from a view I've already defined? I've done some searching and found the Entity Reference View Widget module, but that doesn't seem to do what I am looking for.

Edit I'm not so concerned about the Chosen functionality, I can handle that. What I really want to know is how to get the values from a view to populate a select box, either with a widget, or defining a select box in an form array.

You can programmatically invoke a view to retrieve data and process it as needed:

  // Example select form array
  $form['my_selectbox'] = array(
    '#title' => t('My Select Label'),
    '#type' => 'select',
    '#description' => t('My select label.'),
    '#options' => array(),
  );

  $view = views_get_view("my_view_machine_name");

  //use "default" for default display
  $view->set_display("my_view_display_machine_name");

  // @TODO: Alter any other view properties
  // (e.g. exposed_input, offset, etc.) as needed

  // Pre execute & execute view query
  $view->pre_execute();
  $view->execute();

  // $view->result contains an array of row objects inside the view.
  // the properties will vary based on your view
  foreach ($view->result as $row) {
    $form['my_selectbox']['#options'][$row->nid] = $row->node_title;
  }


Infinite scroll is firing multiple times I have looked for other answers on the same topic but still cannot find a solution why the event is firing more times in my code:

  (function($, Drupal, drupalSettings) {
    Drupal.behaviors.news = {
        'attach': function(context) {

            $(".loader").hide();
            var loadIndex = 0;
            var isLoading = false;

            $(window).scroll(function(){
                if (!isLoading) {
                    var footerHight = $(document).height() - $(window).height() - $("#myFooter").height();
                    if($(window).scrollTop() > footerHight){

                        isLoading = true;
                        loadIndex = loadIndex + 1;

                        $(".loader").show();
                        $.ajax({
                            method: "GET",
                            url: '/load-news?startIndex=' + loadIndex,
                            success: function (result) {
                                console.log("More loaded");
                                setTimeout(function(){
                                    $(".loader").hide();
                                    onSuccess(result);
                                    isLoading = false;
                                }, 1000);

                            }
                        });
                    }
                }
            })
        }
    };

    var onSuccess = function(data) {
        console.log('SUCCESS');
        $(".news-list-wrapper").append(data);
    };

})(jQuery, Drupal, drupalSettings);

When using Drupal.behaviors you need to use .once('behaviorName')

$(window).scroll(function(){

needs to be:

$(window, context).once('news').scroll(function(){


Drupal Coding D7 - Taxonomy - How do I establish the hierarchy and associated fields for taxonomy terms? Reviewing the code in Taxonomy.module I determined the array to define a taxonomy terms as:

 'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
      'uri callback' => 'taxonomy_term_uri',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
        'label' => 'name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
          'custom settings' => FALSE,

Assigning the correct info in the array and calling taxonomy_save_term($term); creates the term, but I have not unearthed the method or array fields necessary to define the hierarchy and attach data fields.

Are there additional array key/values to identify the parent/children and fields?

Are the fields attached to a term in a separate operation after the term is created?

What array keys are required to create the term?

Here is an example:

// create the Foo vocabulary
$vocabulary = new stdClass();
$vocabulary->name = "Foo Name";
$vocabulary->machine_name = "foo_vocab";
$vocabulary->description = "Foo Description";
taxonomy_vocabulary_save($vocabulary);
// annoyingly taxonomy_vocabulary_save doesn't return any information about the vocabulary
$voc_vid = db_query("SELECT v.vid FROM {taxonomy_vocabulary} v WHERE v.machine_name = 'foo_vocab'")->fetchField();
$terms = array(
  'bar',
  'bat',
);
foreach ($terms as $term_name) {
  $term = new stdClass();
  $term->vid = $voc_vid;
  $term->name = $term_name;
  taxonomy_term_save($term);
}


How to get drupal to remove /drupal/ from all the links on the website I first ran the install.php when drupal was reachable as example.org/drupal/, then later I changed the Apache configuration to make it into a virtual host.  Now that I can reach the site at example.org, the problem is, all links available on that page still have /drupal/ in them, and result in 404.

I have tried uncommenting "RewriteBase /" in the .htaccess file, and restarting Apache.  Nothing changed.  There is nothing of use in the settings.php file for the site.

There are a lot of web pages that seem to solve this, but they are either for older versions of Drupal or just don't work.

I can force the correct URL's down Drupal's throat with an additional rule in the Apache configuration to rewrite the URL without the /drupal/ link, but come on, there must be a less hackish way to fix this.

Also of note, I'm trying this out on Arch Linux, so some file paths might be different.  But this is a configuration issue, not a file path issue.

EDIT: for clarity, what I want is all links to show as example.org/blah without the /drupal/ being automatically inserted.

The entry in the .htaccess file you should uncomment is the /drupal one:

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /drupal


what are some considerations to help me decide whether I should configure through the UI, when to configure programmatically I restarted a site I was developing realizing that I didn't have a systematic approach to design, namely, I was implementing changes through both the UI/database and module code and hooks without thinking about why I was doing so.

My question is:  what considerations should I take into account when deciding whether to make configuration changes through the UI or by coding a module?

Of course this only matters for things that you can do through both UI and module development like hook_menu, views, etc.   Here is my list so far:

Reason for UI:

Ease of integration: (e.g creating a new content type through a module is a pain compared through the UI)
Specific-config: if you don't plan on installing this configuration on multiple sites, UI should be sufficient.

Reason for module:

Versioning:  code can be versioned, when stored in the database it's not
Portability: if you plan on installing this functionality on multiple sites, then a module is pretty much a must.

Unknown:

Speed (database v.s. module code)?
I also find that if you need to use an .install file for something you don't plan on being portable, it seems pointless to add this to module code if it can be done through the UI. Is this right?
Other?

I'm very new to drupal development, but I'm just trying to make the right design choices. Any information you can provide would be helpful.

Thanks!

You should make configuration changes in code as much as possible, in particular it helps with

Ease of deployment
Consistency across deployment environments
Consistency across developer team environments
Configuration changes are tracked in version control.
The required configuration for the application is in the code base.

If you haven't already, checkout the Features module for a good approach to exporting and synchronizing configuration between environments.

For example, you can build a Feature module for your

Views
Panels
Content Types
Fields
etc..

and synchronize the changes in code by rebuilding the relevant feature module on dev, deploying it and reverting the feature module on the deployed environment.


In Drupal 7, moving the comment form above the comments Before anyone suggest the Comment Form Above Comments, I have already tried that it did not work.

Honestly there seems to be amazingly little documentation on this issue, given that comment form above the comments is so standard on many sites now a days I would figure there would be a simple button to click to make this happen.

This leads me to believe that either there is a simple solution that I am completely missing or there is no way to do this and I am doomed.  Me I am hoping for the first one.

I have a blog site... I read about altering the core code of the comments module, but I have also heard that it is bad practice to alter the core code.  So if there is another solution out there available to drupal 7 I would appreciate it.

I think you should copy modules/comment/comment-wrapper.tpl.php to your theme and change it there. The file is pretty much self explanatory. Hope it's helpful.


How to add a field to be displayed alongside the title? I'm trying to create a preprocess function to add one of my fields to be displayed alongside the title of my specific content type. So, instead of my title just saying Book Name, it'll say Book Name - 2018. Basically, the year would come from a field in the content type called field_year.

I have the following in my .theme file which doesn't seem to work but I really don't know where to go from here as I've not dabbled with preprocesses too much:

function THEME_preprocess_node__books(&$variables) {
  $node = $variables['node'];
  $variables['fields']['title'] = ($node->getTitle() + $variables['content']['field_year']['0']['#context']['value']);
}

Let me know what I'm doing wrong and what's the best way to go about this.

Your question may lead to different opinion-based answers. Some might say: Display Suite. Others might say: do it in templates. And you could also: hide this certain field to then preprocess it back as suffix of the title (hook_preprocess_page_title).

All of them are no ideal solutions, IMHO. Display Suite is too heavy. Templates get too fiddly too fast (and I don't like how they can make the Field UI needless). Same for the preprocess function. Although if I would be forced to choose one of the named options I'd rather take the preprocess approach.

What I'd recommend instead is to solve your problem the other way around: Make the title a field, a pseudo field to be precise, that can be placed like any other field in the "Manage display" settings of any content type. Then you simply can drag this title field next to your other field and style them with some basic CSS to be displayed inline.

If you are interested in making the title a pseudo field to solve your problem just implement the code snippets I documented in my other answer on that topic: https://drupal.stackexchange.com/a/263740/15055

Still, if doing it that way you need to edit node.html.twig to remove the default (hard-coded) title output from it, to prevent getting printed twice when viewing this node not as page. Your node title now will be printed like any other field. And of course you also may need to prevent the title block from being printed on your node pages. This can be done per content type in the block settings if I remember it right.


Custom form calls different form in modal, submit/ajax callback of second form not called I created 2 forms:
dms_gift_voucher/src/Form/GiftVoucherForm.php
  ...

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    ....

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'confirmGiftVoucher'],
        'event' => 'click',
      ],
    ];

    // Dialog box dependency
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    return $form;
  }

  ...

  /**
   * Callback for opening the modal form.
   */
  public function confirmGiftVoucher(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Get the modal form using the form builder.
    $modal_form = $this->formBuilder->getForm('Drupal\dms_gift_voucher\Form\GiftVoucherConfirmForm', $form_state->getValues());

    // Add an AJAX command to open a modal dialog with the form as the content.
    $dialog_options = [
      'width' => 'calc(100% - 20px)',
      'dialogClass' => 'modal--gift-voucher-confirm',
    ];
    $response->addCommand(new OpenModalDialogCommand($this->t('Test'), $modal_form, $dialog_options));

    return $response;
  }

dms_gift_voucher/src/Form/GiftVoucherConfirmForm.php
  ...

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $values = []) {
    ...

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Confirm'),
      '#weight' => 100,
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // Library
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    return $form;
  }

  ...

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Never called!
  }

  /**
   * {@inheritdoc}
   */
  public function submitModalFormAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    // Never called!
    return $response;
  }

The first form works correct, the submit is called, the ajax callback renders the modal with the 2nd form.
But when i submit the 2nd form, nothing happens, no submit, no ajax callback called from the 2nd form.
How can i fix this? Any suggestions.
(Every example of drupal modal forms start with a link trigger with routing, but i find it strange why this approach doesn't work).
EDIT: As suggested in the comments, routing info:
dms_gift_voucher.routing.yml
dms_gift_voucher.gift_voucher_form:
  path: '/dms_gift_voucher/form/gift_voucher'
  defaults:
    _form: '\Drupal\dms_gift_voucher\Form\GiftVoucherForm'
    _title: 'GiftVoucherForm'
  requirements:
    _access: 'TRUE'

dms_gift_voucher.gift_voucher_cofirm_form:
  path: '/dms_gift_voucher/form/gift_voucher_cofirm_form'
  defaults:
    _form: '\Drupal\dms_gift_voucher\Form\GiftVoucherConfirmForm'
    _title: 'GiftVoucherConfirmForm'
  requirements:
    _access: 'TRUE'

Since you're programmatically setting a modal with
$response->addCommand(new OpenModalDialogCommand($this->t('Test'), $modal_form, $dialog_options));

For the form that is in the modal, Drupal needs to know what URL it should post the AJAX to and be told that its an AJAX request because this only gets set automatically when the url key doesn't have a value.
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'event' => 'click',
    'url' = \Drupal\Core\Url::fromRoute('dms_gift_voucher.gift_voucher_cofirm_form'),
    'options' => [
      'query' => [
        FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ],
  ];

Side note: The above isn't needed with the HTML way of opening dialog boxes, had you done:
<a class="use-ajax"
   data-dialog-options="{&quot;width&quot;:600}"
   data-dialog-type="modal"
   href="/dms_gift_voucher/form/gift_voucher_cofirm_form">
   Should load Test webform in a Modal
</a>

because it has the URL of the form and knows its an AJAX request from the class name.


Confusion as to the meaning of `cid` in webform.module I'm working on a custom module that will return a single question at a time from an existing webform. For example, from the path mymodule/(webform_nid)/(question).

This is my first encounter with cid.

From the documentation on webform_components_form(), it appears that cid represents a component id. (Elsewhere in the Drupal API documentation and on forums, I have seen it referred to as comment id).

Quickly analyzing some test data, it appears that, as a child element of a webform nid, I can reliably use it to sequentially retrieve single questions from a given webform nid.

Am I correct that cids are unique and sequential per nid? I assume the implementation of cid was done to maintain variable name convention.

Or is a cid a unique value assigned to each 'component' across the entire site, as its implementation as comment id would suggest (because you can load an existing comment without loading its node, it would need to be a globally-unique value like nid)?

A quick look at the webform_component table in the database, the description for that field is: "The identifier for this component within this node, starts at 0 for each node."

In my test, however, the first component has a cid of 1.  AND - keep in mind that if you delete a component, the next cid is incremental - so you can't assume 1 - 6 or whatever.


Thickbox module not loading all images I just started using the ThickBox module to to create a simple gallery.  However, only some of the photos will load.  A couple will work, than one will just give the loading line and freeze on it.  I have the image module working fine and image caching as well.  Any idea what might be going on?  Thank you.

Thickbox -- nothing to do with Drupal -- is no longer supported. I highly recomend using Colorbox. (On Drupal)

(edit) The problem doesn't have anything to do with a modal image viewer. I inspected the code to find the URL of each image and they don't work. Chances are that the images are not being uploaded complete because of an upload limit or they are too large for image cache to successfully manipulate.

In php.ini make sure that:

max_execution_time to around 120 and
realpath_cache_size to 512K, 1M or even 2M.
max_input_time to around 120.
post_max_size = 12M to 16M (or large enough for your images)
upload_max_filesize = 12M to 16M (or large enough for your images)

In the content type widget configuration make sure that Upload Max size is set accordingly.


Why JQuery 2.x was removed since jquery_update-7.x-3.0-alpha2? I noticed Version 2.1 of JQuery was removed from JQuery Update module since 7.x-3.0-alpha2.
Is there any particular reason for that I should be aware of?

Version 2.1 has not been removed; its files are still present in the 7.x-3.x-dev development snapshot.
What eventually was done is updating the version 2.1 files to version 2.1.4, since they don't keep multiple 2.1.x versions (e.g. 2.1.0, 2.1.1., 2.1.3).


Youtube media thumbnail size I want to control the thumbnail image size for my media entities of type video.

The thumbnail image size being fetched by the media module from Youtube has 480 x 360px.

I want to use the 1280x720 images. Is there a way for me to control this?

Drupal core issue regarding this problem:  https://www.drupal.org/project/drupal/issues/3042423

After patching, I would implement the new hook_oembed_resource_data_alter:

function MY_MODULE_oembed_resource_data_alter(array &$data, $url) {
  if (strpos($url, 'youtube.com/oembed') !== FALSE) {
    $thumbnailUrl = str_replace('hqdefault', 'maxresdefault', $data['thumbnail_url']);
    $data['thumbnail_url'] = $thumbnailUrl;
  }
}

Then I would also run an update hook to update the existing thumbnails:

function MY_MODULE_update_N(&$sandbox) {
  /** @var \Drupal\media\MediaStorage $mediaStorage */
  $mediaStorage = \Drupal::entityTypeManager()->getStorage('media');
  if (!isset($sandbox['progress'])) {
    $result = $mediaStorage->getQuery()->condition('bundle', 'video');
    $mediaItems = $result->execute();
    $max = count($mediaItems) - 1;
    $sandbox['progress'] = 0;
    $sandbox['mediaItems'] = array_values($mediaItems);
    $sandbox['max'] = $max;
  }
  $progress = $sandbox['progress'];
  /** @var \Drupal\media\MediaInterface $media */
  $media = $mediaStorage->load($sandbox['mediaItems'][$progress]);
  if (!$media->get('thumbnail')->isEmpty()) {
    $media->get('thumbnail')->delete();
  }
  $media->updateQueuedThumbnail();
  $media->save();
  $sandbox['progress']++;
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
}


Drush scripting fails on call to drush_pm_enable() I'm trying to script the automatic download and install of a set of modules for a Drupal 7 site.

At this point, I have Drupal and all desired modules downloading using a drush make profile, and installation of the site by calling drush_invoke_process on site-install.

I'm trying to get the downloaded modules activated after the installation of the site.  I have tried a number of things, the latest of which is:

(code here...)
drush_bootstrap(DRUSH_BOOTSTRAP_DRUPAL_FULL);
drush_set_context('PM_ENABLE_MODULES',array('ctools', 'views', 'views_ui'));
drush_pm_enable();
(code here...)

Every attempt to enable the downloaded modules results in the following error:

  PHP Fatal error:  Call to undefined function drush_module_enable() in
  /Users/lhridley/sp/Drupal/tools/drush/commands/pm/pm.drush.inc on line
  904

Any ideas?

The Drupal and Drush bootstrap processes are fairly complicated things; it is best no to try to figure out how to call them yourself.  If you want to bootstrap and call arbitrary PHP code, you can do so using Drush via drush @mysite ev 'php code here'.

As for calling Drush code directly, you should use drush_invoke_process, just as you are for the site-install command.  So, instead of drush_pm_enable(), instead use drush_invoke_process("@self", "pm-enable", array('ctools', 'views', 'views_ui')).

However, if you are running site-install on an installation profile, you should not need to call pm-enable, as the installation profile should take care of that for you.  If you're not sure how to build an installation profile, you can have Drush generate one for you.  You'll need to use the prototype generate-profile command, which can be found at http://drupal.org/node/1368242.  It does not work for D6 sites yet, but works fine for D7, so should be good for your purposes. Take a look at the list of modules generated in your profilename.info file; these will be enabled for you during site-install.


Drupal 8: How to put a comma in addressfield display? I'm using the address module with Drupal 8.x. I want a comma in the each line of the below address. Currently addresses display like:

John Peter
1181 Broadway
New York
SW1A 1AA
United Kingdom

I want it to display like:
John Peter,
1181 Broadway,
New York,
SW1A 1AA,
United Kingdom.

It appears you would need to write a custom address-plain.html.twig file and add it to the templates folder either in a module or in your theme.

Code:

  {% if given_name or family_name %}
    {{ given_name }} {{ family_name }},

  {% endif %}
  {% if organization %}
    {{ organization }},

  {% endif %}
  {% if address_line1 %}
    {{ address_line1 }},

  {% endif %}
  {% if address_line2 %}
    {{ address_line2 }},

  {% endif %}
  {% if dependent_locality.code %}
    {{ dependent_locality.code }},

  {% endif %}
  {% if locality.code or postal_code or administrative_area.code %}
    {{ locality.code }} {{ postal_code }} {{ administrative_area.code }},

  {% endif %}
  {{ country.name }}.


Can view HTML and PHP I wrote but install.php returns error I installed Drupal8 for the first time to try things out. I used nginx and mySQL on FreeBSD with php-fpm for fastcgi. I have the nginx root set to /usr/local/www/drupal8 cause that's where the install.php file is. If I put a HTML file in there, I can view it with localhost/index.html. If I write a little info.php file, it runs and shows the expected phpinfo() data but if I try to do localhost/install.php, the address bar changes to localhost/core/install.php and nginx returns a 502 Bad Gateway and the nginx error log shows this:

  Call to undefined function Doctrine\Common\Annotations\token_get_all()
  in
  /usr/local/www/drupal8/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php
  on line 56" while reading response header from upstream, client:
  127.0.0.1, server: localhost, request: "GET /core/install.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm.sock:", host:
  "localhost"

I see this error in a few Google searches but the solutions are related to special programs or programmer errors. I followed directions on setting up php.ini and copied settings.php. I don't know what to do or where to look to fix this.

I installed Drupal8 from FreeBSD ports. I don't normally use PHP for anything so PHP version 5.6.30 is what is on my computer so either that is what Drupal used or that's what the port installed. I don't know why PHP7 was not installed instead.

In FreeBSD, the tokenizer extension is not automatically installed so I added php56-tokenizer and now Drupal8 works.


Services 3: Setting taxonomy terms on node creation/update For a custom node type, I have defined a field that is to hold an unlimited number of values from a taxonomy vocabulary that I defined.

This is what it looks like:

[field_taxonomy] => Array
  ( [und] => Array
      [0] => Array
        ( [tid] => 13 )
      [1] => Array
        ( [tid] => 14 )
      [2] => Array
        ( [tid] => 15 )
  )

This is the JSON I pass to the server during node creation (as per [1]):

'field_taxonomy':
  { '11':
    { 'tid': '11'} }

This format is accepted (i.e. no 406, which I get if I try to mirror the above structure), but when I look at the node on the server, the field does not contain any terms.

What does my request have to look like so I can succesfully set taxonomy terms on a node?

[1] What will be the post parameter when specifying vocabulary term?

Your request should use the following:

"field_taxonomy":{ "und": { "values": "14" }  }


Website 'drupy' cannot be found At our place it was decided to move away from PHP/Drupal (for bad or good) to a Python based solution (Django). One thing we seriously consider is to do a gradual transition and for that I wanted to look at drupy that I have read about some time ago.

But the website www.drupy.com is some advertisement site now and googling drupy got me a lot of videos on youtube. Did this project get renamed? Where can I find information?

Is there some generic transition guide for gradual transition from Drupal?

The project used to be on www.drupy.net (not .com), but that is an advertisement now as well.

The project was unfortunately discontinued (I like Drupal, but it is hard to move away from if you have to, and sometimes that is the better solution). The remainder can be downloaded from GitHub.


Autocomplete Field in View Exposed Filter I have created an index Using the Search Api. and integrate with View. And in filter criteria
i have indexed vocabulary. then i want to expose that filter criteria with auto complete field
instead of select list.

I think you are looking for the taxonomy autocomplete in exposed filter.

 Please find the settings


Error trying to connect to database when installing new site on localhost Has anyone come across this problem?  Once I get drupal all ready to install on my localhost I go to the URL and start going through the installation process and when it comes to my database it fails.

So I import the site into Acquia Dev Desktop, create the database, and then go to the URL, select the type of installation and then when I come to the database information page it fails.

Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2).

I can't find any helpful documentation on this issue.
Can anyone help?

Thanks!!

Thanks for the responses everyone.  I ended up getting so frustrated I uninstalled Aquia Dev Desktop and then re-installed a newer version of it.  It seems to have solved the problem because I haven't run into this issue since.


Architecture Guidance: Many off-the-shelf templated sites I typically work on larger custom projects, but have found I have a lot of requests for projects at a lower price-point. I think I can serve this audience by creating a core Drupal installation profile, supplementing it with features, and installing one of a dozen or so custom themes I'll make.

I'd like this process to be as plug-and-play as possible. Right now I have an installation profile so all I need to do is 'git clone' the repo for that and then 'drush make' and 'drush install' to get up an running really quickly. This profile does some really basic things (sets admin theme, sets a development theme, installs an 'image gallery' feature which includes a content type and a taxonomy, etc).

So far I'm stumped on how I should develop things like layout (panels, display suite, theme templates?) and default content (devel generate?) during installation. Should I develop a base theme (I use a custom inuitCSS framework) and write sub-themes for it?

Has anyone else put anything else similar together? Do you have suggestions?

This has become a pretty complex endeavor and I'm wondering if it would be better to just build a site for each theme, zip it up and export the database.

I've made an infrastructure close to what you're describing, where we launch sites in 24h after a customer orders it.

Basically the architecture is:

Aegir on a VPS. This allows us to spin up websites, service them, migrate them and sometimes clone them without messing on the server.
An aegir platform with an install profile for our use case
A generic zen subtheme for our use case with a bundle of front-end code
Sweaver CSS for the layout customization of the specific site
A basic features module that is installed by the install profile and multiple optional feature modules with extra views and content types, layouts managed by contexts, that administrators toggle using Feature Sets.
Some additional optional contrib-space modules for things like node access customization

I try to avoid Panels as much as possible because of how much complication it adds. If you absolutely want your users to create fancy layouts, that may be a good choice, but at low price points the users have little tolerance for complicated usage. You might just be creating a lot of failure demand on yourself.

If you're going to just zip up sites, at least give Aegir and site cloning a chance first. You're going to save yourself a lot of work.


A view where a user doesn't have a certain content type I am trying to create a view where a user doest have a certain content type.

Say for instance I have content types A, B and C and I only want to return results to show users who don’t have content type A but could have B or C.

I have created a view for (users) and linked it to the content authored. I have played about a bit but haven’t managed to find the correct filters. Can anyone help??

Many thanks

David

I am pretty sure what you need to do is set in the access permissions of the view to be permission: Publish Content


How to change the user registration form markup I want to change the markup on the user registration form that reads

  Spaces are allowed; punctuation is not allowed except for periods,
  hyphens, apostrophes, and underscores.

and

  A valid e-mail address. All e-mails from the system will be sent to
  this address. The e-mail address is not made public and will only be
  used if you wish to receive a new password or wish to receive certain
  news or notifications by e-mail.

to something more friendly.

I don't think String Overrides works with the registration form so I guess I need a custom module - hook_form_alter perhaps?

You can do that by implementing hook_form_alter() in your custom module:

For ex:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    //dpm($form);
    $form['account']['name']['#description'] = t('Your Custom Text');
  }
}

To add Markup you should look into theme_form_element.


hook_form_alter #attributes and #disabled I'm using Drupal 7 and Advanced forum.

The users when will create a new topic will be able to select the forum container and forums, but if they select a container, an error will be showed. I want to avoid this by altering that taxonomy options with adding an #attribute or #disabled to specific forum container.

As I inspect the elements, this is the option that I want to change:

$form['taxonomy_forums']['und']['#options'][334];

First of all I've tried to test by adding a class for that option like this:

$form['taxonomy_forums']['und']['#options'][334]['#attributes'] = array('class' => array('test-class'));

but that didn't worked, it simply erases the title of that option.

With #disabled it didn't work too.

From https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes

I can see a good example, but also a note:

  Note: If you are altering an existing form via hook_form_alter() or a
  similar means, be careful with this property! You will probably want
  to add to the existing array rather than writing over it, so don't
  follow this usage example exactly.

It's kind a confusing, so how can I add an #attribute or #disabled to option with hook_form_alter?

EDIT: This is a part from my code:

<?php
function custom_alter_form_alter (&$form, &$form_state, $form_id) {
   switch ($form_id) {

        case 'forum_node_form';

        $form['taxonomy_forums']['und']['#process'][] = 'custom_alter_process_checkboxes';
        krumo ($form);
        break;
    }

}

function custom_alter_process_checkboxes($element) {
  $element[334]['#attributes']['class'][] = 'test-class';
  $element[334]['#disabled'] = TRUE;
  return $element;
  krumo ($element);
}

Checkboxes are converted to their individual form elements in form_process_checkboxes (), so you'll need a process function:

// In the form alter...
$form['taxonomy_forums']['und']['#process'][] = 'MYMODULE_process_checkboxes';

function MYMODULE_process_checkboxes($element) {
  $element[334]['#attributes']['class'][] = 'test-class';
  $element[334]['#disabled'] = TRUE;
  return $element;
}


Features 8.x-3.7 not writable on Window's Ubuntu 8x-3.7 features, most stable version, but I am having trouble writing to custom module on the UI. My structure is as follow:

 -modules/
    contrib/
       features/
    custom/
       news_blogs/
          config/
             install/
                [code]

when i edit my view, i go to /admin/config/development/features I see that the feature state is  edit. I click the checkbox and click write.

I get error:
Package News/Blogs not written to modules/custom/news_blogs. Error: Failed to create directory /mnt/c/mywebsite/modules/custom/news_blogs/config/install.. and then inside install code is deleted and empty.

I check my logs:
Warning: chmod(): Operation not permitted in Drupal\Core\File\FileSystem->mkdir() (line 226 of /mnt/c/mywebsite/core/lib/Drupal/Core/File/FileSystem.php) #0...

I checked my permissons and it is 777 and my usr is the owner for the directory.
I am unsure what else to check or test to figure out what can be going wrong. Any help is thanked!

It looks like you are using something like a virtual machine (Vagrant?) with a shared windows file system.  The problem is that Windows permissions don't map well to Linux ones.  That is why the chmod error is happening.

You may need to get your webserver running under the same user you share the file system under, e.g. the vagrant user.

Personally, I have never gotten a stable way to have Features write to a windows share. There always seemed to be a gotcha in the ones that worked.  I've just excepted that I had to download the feature archive, unpack it, and copy it to the site on the Windows side.

But your situation may be different.


How can I add a class to a block with code (development) For theming reasons I'd like to add a specific class at the "block" level to some of the blocks I'm generating with a custom module. I know there is a module block class, but I would rather like to do it directly in code (there is no need to change is afterwards).

I also know of hook_block_view_alter, but that does not seem to allow adding or editing classes.

Is it possible to add a class with to a block from within my module code? I'm using Drupal 7.

Simply, you could use a preprocess function.

function YOURTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] ==  'ID-YOUR-BLOCK') {
    $vars['attributes_array']['class'][] = 'YOUR-CLASS';
  }
}


Drupal 7 - Trying to get term reference node, from html.tpl I am trying to access the value of a term reference (field_test), from a node, in html.tpl.

First I need to load a specific node, check if the term reference of this node is the same as another value that i have already in the page.

Is someone knows how to access that term reference, with ne $node object?

I have get already the $node, but i cannot access the "field_test" which is inside the $node.

Thanks

emb

Ok, so you'll want to test for a node, then check for the field and then print it to your template. This should work for you:

<?php

if(arg(0)=='node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));
        if(isset($node->field_test['und'][0]['value'])) {
            print $node->field_test['und'][0]['value'];
        }
}

?>

That's code for Drupal 7


What do I add to template.php so I can render regions in a page created in hook_menu()? I need to recreate a lot of pages after removing Panels from a site.

In order to print regions in node tpls, I added this to theme_preprocess_node. That's fine but it doesn't work for custom pages.

// Get a list of all the regions for this theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {

    // Get the content for each region and add it to the $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }

I tried adding that to theme_preprocess_page but it doesn't do anything.

Here is my module. The divs print fine but the regions don't get printed.

function custom_pages_menu() {

    $items['classes-admin/%'] = array(
        'title' => t('Classes'),
        'page callback' => 'page_sidebars',
        'access arguments' => array('edit field_diary_date'),
    );
    return $items;
}

function page_sidebars() {
    $page_return = "";
    $page_return .= '

';
    $page_return .=                     render($region['sidebar_left']); // or $page
    $page_return .=             '

';
    $page_return .=                     render($region['sidebar_right']); // or $page
    $page_return .=                 '

';

    return $page_return;
}

This seems like a pretty common thing to do but google isn't giving me anything to work with. I don't want to add them to page.tpl because it's a very complex site and I only want it this way, if possible. Any help appreciated.

Well, replace this line

render($region['sidebar_left']);

with

render(block_get_blocks_by_region('sidebar_left'));

and replace this line

render($region['sidebar_right']);

with

render(block_get_blocks_by_region('sidebar_right'));

hope it will work for your case :)


Is it possible to pass classes to twig include template Drupal 9 bootstrap barrio sub-theme.
I would like to use a generic template to build some "card" bootstrap display. This template is called by multiple other templates like this :
{% include '@my_theme/views/views-view-unformatted--card-template.html.twig %}
At begining, I started with this template :
{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row col',
    ]
  %}

    {{ row.content }}

{% endfor %}

But now I see that I must dynamically pass the classes to the template to allow different layouts ("row-cols-1 row-cols-md-2 row-cols-lg-3" or only "row-cols-1 row-cols-md-2" for example).
I saw that we can use the include twig statement with the "with" keyword, so I tried to implement the following :
real template :
{%
  set classes = [
    "card-view",
    "row",
    "row-cols-1",
    "row-cols-md-2",
  ]
%}
{% include '@my_theme/views/views-view-unformatted--card-template.html.twig' with {'card_view_classes': classes} %}

and the generic template :
{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row col',
    ]
  %}

    {{ row.content }}

{% endfor %}

But it don't work. No classes are added.
Maybe someone can point me how to achieve this build ? Or maybe it's not possible to do it like this ?
Thanks in advance for any answer.

Yes @Clive, it's correct. I can simply declare a variable called "card_classes" and it is passed to the sub-template. During my tests I targeted an incorrect base template. It was my problem :-/
In the included template :
{% if card_classes is not defined %}
  {% set card_classes = [
    'card-view',
    'row',
    'row-cols-1',
    'row-cols-md-2',
    'row-cols-lg-3',
    ]
  %}
{% endif %}

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
<div{{ attributes.addClass(card_classes)}}>
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row col',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}
</div>

By checking if card_classes variable is defined or not, I can set default classes in the included template itself, or override the default classes in the base template.
And now in base templates :
{# use default classes #}
{{ include('@my_theme/views/views-view-unformatted--card-template.html.twig') }}

or to override
{# override default classes by another set of classes #}
{%
  set card_classes = [
    'card-view',
    'row',
    'row-cols-1',
    'row-cols-md-2'
  ]
%}

{{ include('@my_theme/views/views-view-unformatted--card-template.html.twig') }}


How to add new form field dynamically on selected change using ajax I'm trying to make dynamic form in my module:
I have one field of type select containing some options, and when selecting one option a new field should be added dynamically to the form which in turn will contain another list of options.
here what I try to do but nothing seems to work correctly

public function buildForm(array $form, FormStateInterface $form_state) {
    $this->controller = new Place_AdsController();
    $terms = $this->controller->content();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $terms,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => 'Drupal\Place_Ads\Form\Place_AdsForm::level1SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    return $form;
}
public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    if ($form_state->getValue('level1') != false) {
        $form['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );
        $form_state->setRebuild(TRUE);
    }

    return $ajax_response;
}

Build form elements in buildForm() only, not in ajax callback. The ajax callback is only for preparing the ajax response. When the ajax callback is called, buildForm() has already run with the updated $form.

Your ajax response is empty. You didn't add any ajax command to it. See ajax examples how you can do this.

But in your case you don't need any code in ajax callback. It would be enough to simply return the changed part of $form in a div container.

For this put an empty container in buildForm() and move the select form element from the ajax callback to buildForm() and put it in the container, if the condition in $form_state is met:

$form['ajax_wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'ajax-wrapper'],
];

if ($form_state->getValue('level1') != false) {
        $form['ajax_wrapper']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => $terms,
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
        );

And the ajax callback:

public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['ajax_wrapper'];

change #ajax to:

'#ajax' => [
  'callback' => '::ajaxCallback',
  'wrapper' => 'ajax-wrapper',
],


Easychart with views cache I have installed easy chart plugin with Drupal 7 website.

My pages are generated with views using nodehierarchy and quick tabs plugin.
To speed up page load, I have enabled views cache.

I noticed easy chart displays while page loads for the first time after cache is cleared. But as soon page speeds up(cached) charts are not displaying.

We have APC cache installed on our website.

Can anyone help with?

Thanks!!!

Found a solution the other way.

Created views for chart separately and inserted into my existing view through "Global view" Field.
It increased page load time a bit so for cached page from 2-3 seconds to 3-4 seconds but that is better than 30 seconds(sometimes even more based on content) without cache


Superfish Menu links disappear on iOS (only if they have dropdown menus) I've got a superfish menu as the main menu on my site. Two of the links in the menu have sub-links and are presented as a drop-down, hover menu. This works great on desktop browsers. On iOS, however, the main link disappears if that menu item has a drop down. It's only gone in the default state though, if I tap on the spot where it should be, the link shows up again and the drop-down menu appears as it should. If I tap the other link which has a drop down menu, the first drop down will disappear and so will the main link. For example, if the normal menu looks like this..

FOO BAR BAZ BAT

and BAR has a drop down menu, then the menu will look like this on iOS:

FOO <empty space> BAZ BAT

but if I tap on that empty space, then BAR will show up and so will the drop-down menu.

I've checked the CSS and don't see any differences in the styles.

I'm sorry I can't give you a link to the site to see where this is happening. I'm under an NDA and the site isn't public yet.

EDIT: I discovered that the css sets .sf-menu li to have position: relative. When I disable this rule in the inspector, then BAR appears in the spot where it should be. However, when I do this, the drop-down menus no longer have the correct context for their positioning. So, I need this rule so the drop-downs work properly, but something about that rule is causing those elements to jump out of position.

So, two questions:

1) Do you know why this is happening and do you know of a fix?

2) or, do you know of a way to make them non-drop downs when iOS is detected? The dropdowns are not crucial to my site navigation.

Enough tinkering and I found a solution. I'm not sure WHY it works, but it does.

During my experiments, I wondered if the z-index was the problem and if it was getting covered by something, so I cranked the z-index up to 10000 but that still didn't solve it.

I eventually discovered the position: relative thing I mentioned above. So I opened up the Computed Style box and toggled the position: relative rule on and off, on and off, which would break it, fix it, break it, fix it. Then I looked in the Computed values to see if anything else changed. Sure enough, the z-index changed. When it was in the working state the computed z-index was auto, so I created a css rule to explicitly set z-index to auto for those elements and viola... it's working.

Hopefully this will be helpful to someone else.


How do I add classes to main menu ul and li in Drupal 8 I want to generate the html elements and their classes to fit my styling of the main menu.

I'm confused by all the near-possibilities offered in the api documentation and by looking at core themes etc. and still can't quite see what I have to do, or where I have to do it.
I would be very grateful for clear pointers to:

which php functions I have to write;
which variables I need to add / update;
in which files the functions will go.

Presumably, in MYTHEME.theme I will need a preprocess function of some sort to add to the attributes and item.attributes variables that links.html.twig uses to print the menu ul and the menu item li's.

[Update]
So far I have discovered one way to place classes on the Main Menu's ul but ideally I would like to add a class to each submenu's ul indicating the depth of the sub-menu.
And I cannot locate any documentation or examples from which I can understand the generation / modifying of the main menu's individual link items.

This function goes into the file  MYTHEME.theme.

function MYTHEME_preprocess_page(&$variables) {

  // Pass the main menu and secondary menu to the template as render arrays.
  if (!empty($variables['main_menu'])) {
    $variables['main_menu']['#attributes']['id'] = 'main-menu-links';
    $variables['main_menu']['#attributes']['class'] = array('links', 'clearfix', 'MYNEW_class');
  }

}

Override the twig file for the main menu by saving menu--main.html.twig to your theme. Copy the original menu.html.twig from /core/modules/system/templates/menu.html.twig or /core/themes/classy/templates/navigation/menu.html.twig if your theme extends from Classy.

You can then modify the Twig macro used to generate the menu output. To get a class on the ul's to indicate level, you could do this:

{% if menu_level == 0 %}
  <ul{{ attributes.addClass('menu', 'menu-level--' ~ menu_level) }}>
{% else %}
  <ul class="menu {{ 'menu-level--' ~ menu_level }}">
{% endif %}

You could do similar manipulations to the li's:

<li{{ item.attributes }}>

Just tack on .addClass('class-name') to attributes like so:

<li{{ item.attributes.addClass('class-name') }}>

If you're a HTML/class name snob like myself you can also remove classes like so:
{{ item.attributes.removeClass('menu-item') }}

Which I did on the line above the li in the for loop.


Get customer shipping information entered in checkout page, from shipping page Following inline documentation on example shipping module api, I have an implementation of hook_commerce_shipping_services_info(), in which I set callback function for 'rate', 'details_form' etc.

I'm trying to calculate the rate based on the zip code entered by the customer, but the callback for 'rate' only takes two arguments, which are $shipping_services and $order. I dpm both objects, but didn't see any shipping information, entered on the previous page (checkout). The field [commerce_customer_shipping] has
Array
  (
   [und] => Array
     (
       [0] => Array
       (
         [profile_id] => 2
       )
     )
 )

How do I get the values for the individual fields, such as address, city, and zip code?

See the replacement patterns and give like as below, for example,
[commerce-order:commerce-customer-shipping:field-name-line]. Use "-", not "_".


How to handle if Drupal site goes down, show a static fallback page instead? One of my sites went down with the following mysql server down message:

How can I show a basic static page when something fatal like this happens? Are there any modules that do this already? What are some other solutions if a site goes out. I tried cloudflare, but they don't already detect the site going down and still show a fatal message. It would be good if users were shown a static page instead.

Because Drupal is completely unresponsive when this happens, it's not something you can fix within Drupal.

Setting a static fail page is possible within your web server - most likely Nginx or Apache. If you are using a CDN, you can also configure it to display only cached versions of your pages if your server is unresponsive.

You'll have to consult your server documentation to get your answer.


Media 7.x-1 Library tab empty All of the sudden my media library tab becomes empty. I check the permissions and everything seems to be fine.

It looks like when I updated the jquery update module I checked both administrative  and default version to use jquery 1.7. There is a known issue here jQuery Update 7.x-2.4 makes Media 7.x-1.4's Library tab empty. When I changed the administrative pages to use 1.5 everything was ok again.


"Authored by" field to be automatically filled On every creation of a node or edit of a node I need the "Authored by" field to be automatically populated with the username of anyone saving changes.

any ideas how I can do that?

Thanks.

Personally I think that a module like Rules (powerful and awesome as it is) is overkill for something relatively simple as this.

Looking at node_form(), I see that the author is set by populating the author field with the username. I would create a custom module which implements hook_form_BASE_FORM_ID_alter, and set the default value of the author name field to the name of the current user. That would look something like this (disclaimer: untested code!).

<?php

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  $form['author']['name']['#default_value'] = !empty($user->name) ? $user->name : '';
}

An advantage of this solution is that the field is populated in advance with a default value, allowing user with sufficient permissions (eg. administrators) to override the author as they always can. It would be harder to do that in a rules-based approach which only kicks in after the form has been submitted.

update:

The topic starter mentions in another answer that he ended up with the following code:

function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if ($form_id == 'content_type_node_form') {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

Some feedback on this code:

Of course, the if-statement makes sense if you only need this behavior in certain cases. You could even place the global $user; inside the if.
I would recommend that you keep the !empty($user->name) ? $user->name : '' part, instead of simply using $user->name. It may be an edge case, but as you can see in drupal_anonymous_user, the global $user object does not necessarily contain a 'name' property. If, at some point in the future, this form would become available for anonymous users, they will end up with php notices on their screen.


How to render a view in a form I am building a configuration form in an admin menu.  I'll have some input fields inline at top, and below, a table of data.  I'd like to render a view of the data in the table so it can handle the paging, etc.

How can I access the view and render it?

Use view_embedd_view function and you will get the view.

$output = views_embed_view($viewName,$display_id);
print $output;


How to create sql alias in drupal 7 How do you achieve the highlighted 'node' alias when using the Drupal 7 database abstraction language?

This is the original query produced by the view

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, **'node' AS field_data_field_reference_code_node_entity_type, 'node' AS field_data_field_employer_node_entity_type, 'node' AS field_data_field_contract_type_node_entity_type, 'node' AS field_data_field_display_location_node_entity_type, 'node' AS field_data_field_salary_description_node_entity_type**
FROM
{node} node
INNER JOIN {field_data_field_locations} field_data_field_locations ON node.nid = field_data_field_locations.entity_id AND (field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0')
LEFT JOIN {workflow_node_history} workflow_node_current ON (  SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid
WHERE (( (node.type IN  ('job')) AND (field_data_field_locations.field_locations_tid = '56') AND (workflow_node_current.sid =  '3') ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0;

Here my current code, which produces the query but cant recreate the aliases in bold with the addfield method. Tried to escape the quotes around 'node' but drupal stripes it out.

$result = db_select('node','node');

    $join = $result->innerJoin('field_data_field_locations','field_data_field_locations',"node.nid = field_data_field_locations.entity_id AND field_data_field_locations.entity_type = 'node' AND field_data_field_locations.deleted = '0'");

    $result->leftJoin('workflow_node_history','workflow_node_current',"(SELECT max(hid) FROM {workflow_node_history} where nid = node.nid and sid != old_sid ) = workflow_node_current.hid");

    $result->addField('','node')
    $result->addField('node','title','node_title');
    $result->addField('node','created','node_created');
    $result->addField('node','nid','nid');
    $result->condition('node.type',array('job'),'IN');
    $result->condition('field_data_field_locations.field_locations_tid','56','=');
    $result->condition('workflow_node_current.sid','3','=');
    $result->orderby('node.created','desc');

In this link you will see that field method doesn't support alias. Instead supports,

$query = db_select('node', 'n');

But to have alias for fields follow this link which will be,

$query->addField('n', 'name', 'label');
$query->addField('n', 'name', 'value');


How to save/map uploaded image in term field of type image with storage location equals s3:// I'm having 1 field in a taxonomy = 'features' of type image. Image storage location is set to s3.

I have written a hook_form_alter for form_id = article (article is the content type)  where I have created an image field like:

$form['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 's3://s3-bucket',
    '#multiple'             => FALSE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],

     ];

Now in my form submission, I'm trying to save/map this image into my term image field (field_vocab_image) . For this, I'm trying something like:

$term = Term::create([
    'name' => $term_name,
    'vid' => 'my_vocab_name',
    'field_vocab_image' => $img,
  ]);
  $inserted = $term->save();

where $img = $form_state->getvalues()['image_dir']; this image is coming from the custom field created in hook_form_alter.

Above code is successfully saving term name but when I go to edit term , image field is empty. Image is not getting mapped.

An Image type field should contain a file fid of an image file. The following should resolve your issue:

$img = $form_state->getValue('image_dir');

if (!empty($img['fids'])) {
  $img = reset($img['fids']);
}


How do I make a user profile field a link I've created a custom field for users on a site I'm working on that is for their website url. I want to make this field actually link to the website the users enter upon signing up.

Using Drupal 7, customized Bartik theme. The field is a standard text field.

I've tried doing a custom field template for that field, and I've tried editing the page-user.tpl.php file, neither worked.

If I'm understanding the question correctly it sounds like you need an additional module that will correctly validate/display the link in the user profile.  Overview of the steps needed:

Download the Link module:
Add a new field to the user profile of type "Link" (found in confifuration --> people --> account settings --> manage fields)
Set any other config options you need


Why do users with permission to post commenst get "You do not have permission to post a comment"? I have some users with roles administrator, authenticated etc. All such user roles have permission to post a comment.

But when posting a comment it is showing error "You do not have permission to post a comment." along with "Your comment has been queued for review by site administrators and will be published after approval."

How can I solve this issue?

Go to the admin/people/permission check for comment section in permission page where you can see skip comment approval you need to give appropriate permission for the user.

Like below screenshot.


How to send an eMail on specific dates indicated in 3 different date fields? In 'Add user page' I have added extra fields like:

date of orientation
out of date
anniversary date

I want to remind the users by sending a mail on all 3 of the above mentioned dates, but I am not able to figure out what exactly I need to do.

So far, I have tried with the Date Reminder module and walk through admin->site configuration->date reminders. But there I couldn't see any email setup page. I've also gone through a Rules tutorial but I am not getting how to achieve what I want to do.

Is there anybody familiar with the Rules module who has some suggestions about this? Or if some other module is available to do this?

You can perfectly use the Rules module for this. Here are the main steps to do so:

You need "a" field related to the "date" your want to do something with (you're fine with that, you already have 3, so repeat what is below for each of the 3 fields).
Create a rules Component  for sending an eMail (specific to the reminder-eMail you want to send).
Create a Rule to trigger the Rules component from Step 2, which typically involves some date offset (like "how long ahead should the eMail be eMailed?").

For a sample of step 2 and step 3 above (in Rules export format), refer to my answer to the question about "Rule to store user's last post date and scheduled rule based 30 day reminder".

Note: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.


How do I find out the content type within template.php? I'm using THEME_page_alter to give my site a meta description, and is working fine.
However I can't find the variable which defines the content type - I need to use it as an argument to give different pages different descriptions. I tried $node->type

Side question: where on earth can I find answers for such simple tasks like this without having to ask in DA? I did a lot of Googling and looking in the API, and looking at the Globals list... but it seems like the official Drupal documentation doesn't make things easy for you in some respects.

Thanks

Im new to Drupal. Finding variables and displaying them the way i wanted was very important to me. So i used a code that works in any php script. But i recommend you to always to stick with the Drupal API.

Here is the magic code.

<?php var_dump(get_defined_vars()); ?>

This will output all the available variables for the current page. However the page will be very long so don do this on your live production site. Test it on a local site or put your site in maintenance mode.

Also check the http://www.hoomanb.com/cs/QuickRef/drupal-7-theming-cheat-sheet.pdf


Images are not migrated and the body field is empty I tried to migrate a site from Drupal 7 to Drupal 8.1 using drush (migrate-import --all) and the following modules:

Migrate Plus
Migrate Tools
and the D8 core migrate modules.

It doesn't migrate the image of my nodes and the body field is empty. Do I have to create the same content types with similar fields first, or should I let the Migrate module do this?

The empty body looks like a problem with the text format filter. I use the full HTML text format with CkEditor on Drupal 7, but this filter exists on Drupal 8 too, so I don't understand why it happens.

The solution for the body-field:

it must be a translation problem. I changed the language of the Drupal 8.1 site to the same language as the Drupal 7 site and now the body field isn't empty anymore.

But the images are still missing. I noticed that no files were imported. Under /admin/content/files there is nothing! any help in this case?


Display Suite custom function field not firing I need to add a Display Suite function field to a node.  I set up my hook, and my field shows up and I can add it to my content type in display.  However, the function isn't getting called, and it looks like it should.  I stripped my code down so I can debug this.  My custom function is in my .module file.

function MYMODULE_ds_fields_info($entity_type)
{

    if ($entity_type != 'node')
        return;

    $fields = array();

    $fields['splittitle'] = array(
        'title' => t('Split product title'),
        'field_type' => DS_FIELD_TYPE_FUNCTION,
        'function' => 'MYMODULE_ds_field_splittitle'
    );

    return array('node' => $fields);

}

function MYMODULE_ds_field_splittitle($field)
{

    return 'test';
}

Here is the code that worked for me... My Module name is drup_custom

function drup_custom_ds_fields_info($entity_type)
{
    if ($entity_type != 'node') {
        return;
    }

    $fields = array();

    $fields['test_title'] = array(
        'title' => t('Split product title'),
        'field_type' => DS_FIELD_TYPE_FUNCTION,
        'function' => 'drup_custom_ds_field_splittitle'
    );

    return array('node' => $fields);

}

function drup_custom_ds_field_splittitle($field)
{
  return 'My Content';
}

Steps to follow to see results..

Cleared Caches
Enabled Layout in Content Type Settings

Now, you can see your field in disabled list

Assign the field to which ever region you would like, Save Settings

I can see the field content in Node View Page


How do I get the field label from a node object? I've tried guessing

$node->field_name->fieldDefinition->label
$node->field_name->fieldDefinition->label()

and

$node->field_name->label
$node->field_name->label()

but it did not work.

Your first guess was very close, but both are protected properties, so are accessed by getters - functions with the prefix get:

$field_label = $node->field_name->getFieldDefinition()->getLabel();

For reference:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemInterface.php/interface/FieldItemInterface/8.2.x

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldDefinitionInterface.php/interface/FieldDefinitionInterface/8.2.x

Edit:

Btw, in twig you don't need the prefix get, because if you tell twig to get something with the name label, it  tests all possibilities on the object, first it tries to access the property label, then the method label() and finally the getter getLabel().

{{ node.field_name.fielddefinition.label }}


How to migrate revisions I'm migrating contents from D7 to D8. I'm exporting nodes with services_views and importing with migrate.

I would like to import also revisions. How should I do? Revisions on D8 don't seem entities, so what kind of "target" should I use to import them?

The revisions are added to the existing entity. There is an EntityRevision destination in core.

See core/modules/node/migration_templates/d7_node_revision.yml here for an example of how you'd migrate revisions.

Note: translated node revisions are not yet supported, but you can look at a good starting point at #2746541.


Radio button in Drupal 8 According to the Drupal website (Drupal website), the following code should output a group of radio buttons:

$form['settings']['active'] = array(
     '#type' => 'radios',
     '#title' => $this->t('Poll status'),
     '#default_value' => 1,
     '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
);

However, when i put this code into a function (in a bespoke module - in a class), placed in the Controller folder:

public function radioComponent ()
{

    $form['posting_settings']['comment_preview'] = array(

        '#type' => 'radios',

        '#title' => t('Preview comment'),

        '#default_value' => '1',

        '#options' => array(t('Optional'), t('Required')),

    );
    return $form;
}

I initially get an error stating:

  Notice: Undefined index: #title_display in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 20 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

and

  Notice: Undefined index: #id in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 30 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

But, even adding in those tags as follows doesn't produce radio buttons:

public function radioComponent ()
{

    $form['posting_settings']['comment_preview'] = array(

        '#type' => 'radios',

        '#title' => t('Preview comment'),

        '#default_value' => '1',

        '#options' => array(t('Optional'), t('Required')),

        '#id' => 'al1',

        '#title_display' =>'title',

    );
    return $form;
}

Does anyone know why the radios will not render as required?

Has anyone generated any code that would generate a radio button group?

  Is the issue that the radio component will only generate if placed in a form class - housed in the Form folder?  Rather than in a Controller folder.

Thanks.

if you look at /core/lib/Drupal/Core/Render/Element/Radios.php  you'll see it's not a render element, but a form element.

You can't use it without putting it in a form. If you search the code base for extends FormBase, you'll see many examples of forms that you can start from in building your own form, many of them quite simple.

For example:
/core/modules/system/tests/modules/form_test/src/Form/FormTestProgrammaticForm.php


Autopopulate a node with the content of a menu supose i have a site with three nodes of basic page type called "element 1", "element 2" and "element 3". I want to create a menu with the following structure:
-elements
--element 1
--element 2
--element 3
Is there any way to generate a view for the "elements" node containing the children nodes from the menu, a module to do this automatically or somthing like that.
Sorry if that may be an obvious question, but im relatively new in drupal, also pardon my english

Create a new View, Block, Content -> 'Basic Page', fields

once the main Views UI opens you can modify as desired - by default, this will create a view of Titles that act as links in a block you can place wherever you like. You can remove the Title (title) by clicking on the Title Field, and un-click 'Create a label'


Unable to implement photo slider in theme template I downloaded a theme from here and I chose this theme because I wanted to builder a slider photo gallery as shown in the screen shot here.

However, I am unable to achieve the desired effect because I am new at Drupal 7.

I have tried the following steps for implementing the photo gallery. Please help me out by pointing my mistake.

1- Identify block regions. These are as follows:

2- Make a content type with Image type as the field as follows:

3- Then I placed it inside the Slide show block provided by the template as shown in the figure.

4- I even made a view and placed it inside the same Slide show block provided by the template but I am not getting the slider that I want.The previous screen shot shows the view as well.

At best, I get a picture on the front page when I choose it as 'published to front page'.

So, does this mean I cannot implement a photo slider this way? And my only option then is to use a contributed module for a photo slider?

If the latter is true then what use is the template other than a basic mark up for html and css?

Lastly, is the solution to my problem that I use a contributed photo slider module and then place it in one of the pre-defined blocks provided by the theme?

Appreciate your help on this.

What you did in your website is create a new content type that holds a static image for each entry. From what I see in the template link you posted, the theme you chose uses Nivo Slider as the default solution for a slider and even has an installation instructions link (which is not working).

My advice would be to follow the instruction on this link:
Nivo Slider Module, and install the module yourself. It will create a new content type for you to make the slider you need.


Attach a script to a particular node ID or view In Drupal 7, you can use the following code to attach a script to a particular content type:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {

        // include javascript
        drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');

      }

    }

What code do you need to use to attach a script to a particular Node ID or a specific View?

I have tried swapping variables['type'] with various items, but none seem to work.

Node ID:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

View:

function THEMENAME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}


What does testing a patch mean? In drupal.org issues when someone creates a patch, in attachment table there is a column named Test result which has a value like FAILED: [[SimpleTest]]: [MySQL] 32,869 pass(es), 2 fail(s), and 0 exception(es). and in operations column a link to re-test

What does re-testing mean? And what's meaning of the line FAILED: [[SimpleTest]]: [MySQL] 32,869 pass(es), 2 fail(s), and 0 exception(es). ?

(I'm not sure this is specific to Drupal)

In Drupal.org, for projects that are enabled, patches in the issue queues are passed to a test server, which executes the following steps:

It creates a Drupal site
It copies, and installs the module for which the patch has been written
It applies the patch being tested
It runs a set of SimpleTest tests, which has been written by the maintainer of the project wrote for his own module, to verify the patch doesn't introduce any problem

Once the tests are done, the test server reports to Drupal.org the result, which is then shown in the issue where the patch is attached.

This is what essentially happens. I didn't mention all the details, such as:

The Drupal site is created before to run every test
The test server executes also its own tests to verify the created Drupal site is running correctly
The test server periodically executes tests to verify it is running correctly
The Drupal version, and the version of the module that needs to be installed are taken from the issue itself; if the issue is for version 6.x-1.0 of a module, then the test server creates a Drupal 6 site, and installs the version 6.x-1.0 of the module, to which it applies the patch found in the issue report


Why a unnamed  is added to a specific region? I have 2 blocks sitting in a region called "headline".

Drupal 8 seems to add these 2 blocks , into an unnamed div and thus their display:flex CSS layout is cancelled (you can't scatter 2 container items if these are wrapped into one div).

Please see attached image to make sure you understand me.

I have no idea where this inspected div is coming from. I don't recall adding it myself. Only because it seems to be added by Drupal 8 itself, I publish this question here.

The problem can be seen live here.

A Drupal 8 themer might have an idea on why this is happening.

I might need to note that the twig markup also doesn't contain such div.

The regions' twig markup:

{% if page.headline %}
     {{ page.headline }}
{% endif %}

The CSS code I used:

#headline . container {display: flex; flex-direction: column; align-items: center}

@media screen and (min-width: 1080px) {

#headline .container {display: flex; flex-direction: row; justify-content: space-between; align-content: flex-start; flex: 1; margin: 0 auto}

}

It could be coming from region.html.twig:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21region.html.twig/8.2.x


Webform Module can't send email from user anonymous I'm using Drupal 7 and Webform Module for create contacts forms (This problem also what I have in Pressflow 6).

Only authenticated users can send mail through the form. However, I need that anonymous users can also use the form.

The error is as follows:

Error sending e-mail from sender@email.com to target@mail.edu.pe: SMTP Error: Data not accepted.
SMTP server error: 5.7.1 Sender domain not allowed.

How I can make the form send mail with both roles (authenticated and anonymous)?
How I can avoid spam for users anonymous?

Details

Each time you use the contact form (either anonymous or authenticated) to send an email to the person responsible of receiving these emails.

Anonymous users can absolutely submit webforms. On the Form Settings page under submission access, there are permission checkboxes for each role. You can use Captcha or Mollom to help prevent spam submissions.

The error you're having seems like you have SMTP misconfigured. Are you currently using the SMTP module? If so, run a test to send an email to yourself. If that fails, then it's definitely the problem.


Drupal http get Request for external URL? I have to send a request to external Api that returns me the redirection page but it is printed on my side as var dump, the dump is the page it i supposed to be redirected to, any help ?

Code :

$url = 'xyz';

try {
  $response = \Drupal::httpClient()->get($url, ['headers' => ['Accept' => 'text/html']]);
  $data = (string) $response->getBody();
  if (empty($data)) {
    return FALSE;
  }else{
    return $data;
  }
} catch (RequestException $e) {
  return FALSE;
}

Returned $data looks something like this :

    <!doctype html>
<html lang="en" dir="ltr" class="h-100">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="asdsad">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="aaaaa1231231">
    <title>TEST</title>
    <link rel="canonical" href="tamal.com">
    <!-- Bootstrap core CSS -->
    <link href="http:xyz.css" rel="stylesheet">

this actually because of the second argument ['headers' => ['Accept' => 'text/html'] it tells the server to serve a plain text instead of html so your browser will end up print the text instead of parsing it as HTML,so just remove the second argument ['headers' => ['Accept' => 'text/html']

so you code will become like this one :

Code :

$url = 'xyz';

try {
  $response = \Drupal::httpClient()->get($url);
  $data = (string) $response->getBody();
  if (empty($data)) {
    return FALSE;
  }else{
    return $data;
  }
} catch (RequestException $e) {
  return FALSE;
}


add user profiles fields into comment fields I'd like when a user comments, to display his information.

Let's assume I do have in my user profile 2 fields, Job title and Biography.

When a user comments, I would like to get those 2 fields and display them as comment fields.(same for existing comments)
It will then display the comment + job title + bio

What the best solution for that ?

I was thinking about a preprocess to load the $user but maybe there is some configuration which could do it instead.
In this example I added 2 fields in the comment section of my content type then I'm trying to get the user profile infos to the current fields.

function template_preprocess_comment(&$vars) {
      if($vars['comment']->uid !== 0){
        $user = user_load($vars['comment']->uid);
        $vars['field_job_title'] = $user->field_job_title;
        $vars['field_bio'] = $user->field_bio;
      }
}

Final approach was:
For the existing one that what I came out with:

function hook_user_presave(&$edit, $account, $category){
    //get all node we need
    $results = db_select('node', 'n')
                  ->fields('n', array('nid'))
                  ->condition('type', 'my_content_type', 'LIKE')
                  ->execute();

    foreach ($results as $result) {
        $nids[] = $result->nid;
    }
    foreach ($nids as $key => $nid) {
        //get all comment ids
        $result = db_select('comment')
            ->fields('comment', array('cid'))
            ->condition('nid', $nid, '=')
            ->condition('uid', $account->uid, '=')
            ->execute();

        $cids = $result->fetchCol();
        $comments=comment_load_multiple($cids);
        foreach($comments as $comment) {
            //load comment
            // $user = user_load($comment->uid);
            if(isset($edit['field_job_title']) && isset($edit['field_bio']) && $account->uid !== 0){
                //change data of the comment
                $comment->field_job_title = $edit['field_job_title'];
                $comment->field_bio = $edit['field_bio'];
                //save it
                comment_save($comment);
            }
        }
    }
}

function hook_comment_presave($comment) {
    //if not user, otherwise it does it when you do the comment_save($comment) from the user_presave, then it won't work
    if(arg(0) !== 'user'){
        $user = user_load($comment->uid);
        if($user->uid != 0){
            $comment->field_job_title = isset($user->field_job_title) ? $user->field_job_title : NULL;
            $comment->field_bio = isset($user->field_bio) ? $user->field_bio : NULL;
        }
    }
}

and this one to hide the current fields when you comment:

function template_form_comment_form_alter(&$form, &$form_state) {
    $form['field_bio']['#access'] = FALSE;
    $form['field_job_title']['#access'] = FALSE;
}

Your solution is ok. But you could also

Add a field on the comment fields of your content type that uses a reference to the user
On hook_comment_presave fill out the user reference field with the uid of the logged in user
On manage display of your comment fields, just render the user field as a rendered entity
You could use a custom view mode on user that only shows the fields "job title" and "bio".


Best way to drop a field from a content type What is the best way to remove a Drupal 7 field from a content type defined via the GUI? I want to use hook_update_N so the changes can be propagated to multiple servers upon running update.php. However I cannot seem to find a solution. db_drop_table() would make sense to me for custom defined schemas, but not for a content type/field defined through the GUI.

There are two api functions to delete fields:

field_delete_field To delete the entire field (all instances of of the field)
field_delete_instance To delete only an instance of a field - which is how it's attached to an entity.

If you don't want to reuse the field, it might be a bit cleaner to delete the entire field instead of only delete the instance of it on the content type in question. Only you can be the judge of that.


How can I get the entity ID after saving it? I am saving an entity and I would want to get its ID.
$CustomerEntity = CustomerEntity::create([
  'customer_id' => $customer['id'],
  'customer_name' => $customer['name'],
  'address' => $customer['address'],
]);

$CustomerEntity->save();

How do I get the entity ID with that code?

Use $CustomerEntity->id(); after saving your entity.
$CustomerEntity = CustomerEntity::create([
  'customer_id' => $customer['id'],
  'customer_name' => $customer['name'],
  'address' => $customer['address'],
]);

$CustomerEntity->save();
$id = $CustomerEntity->id();


how to remove wrapper for boxes? I am trying Boxes for first time instead of block, however. It is adding some wrapper DIVs. I usually use hook_preprocess_block() to remove them but it is not the case with Boxes

 function HOOK_preprocess_block(&$variables)
{
    switch ($variables['block']->region) {
        default:
            $variables['theme_hook_suggestions'][] = 'block__no_wrap';
            break;
    }
}

How to remove DIVs wrapper for Boxes? Thank you for any help

I have not tried Boxes myself, but looking at its code, it looks like they use a theme function to produce the markup for the boxes.

If you implement theme_boxes_box (found in boxes.admin.inc) in your own theme/module you can just copy the code from it and remove the markup you don't want.

/**
 * Overrides theme_boxes_box().
 */
function MYMODULE_boxes_box($variables) {
  $block = $variables['block'];

  $empty = '';

  // Box is empty
  if ((empty($block['title']) || ($block['title'] == '<none>') ) && empty($block['content'])) {

    // add a class to mark the box as empty
    $empty = ' box-empty';

    // show something if the block is empty but the user has the permission to edit it
    if (boxes_access_edit()) {
      $block['content'] = t('This box appears empty when displayed on this page. This is simply placeholder text.');
    }
    else {
      return;
    }
  }

  $output = "
";
  $output .= '
' . $block['content'] . '
';
  if (!empty($block['controls'])) {
    $output .= '
';
    $output .= $block['controls'];
    $output .= '
';
  }
  if (!empty($block['editing'])) {
    $output .= '
' . drupal_render($block['editing']) . '
';
  }
  $output .= '
';
  return $output;
}


How to hide a user profile based on custom field? I need to allow users to turn off the public display of their profile if they wish too.  I created a Boolean field to store whether the user wanted the profile shown or hidden.  According to this (old!!) documentation on d.o., I should add an if statement at the beginning of the user profile template.

Specifically, is this the proper way to access the value?
Edit: Proper, but must account for possibility that value hasn't been set in existing profiles, thanks!

<?php //check to see that user has chosen to show profile
  if(!isset($field_profile_display) || $field_profile_display[0][value] == 1): ?>

If I put the if statement at the very beginning of user-profile.tpl.php, I see all the fields set to display (with Display Suite), unthemed.  If I put it after , I get a profile page, blank but fo the username as the title.

Where do I put the code to actually prevent the page from displaying?  Does it need to go in page.tpl?

Generally, is this really still the best practice? Would it be better to implement this in a preprocess hook?

This way is absolutely okay.
There is definitely the possibility to achieve the same result with the preprocess hook, but doing it in the template file is also a common "drupalish" way and has (as far as i know) no disadvantages.

One thing:
Do you have already existing users? if so you should check if the variable exists before comparing it with a value... otherwise you could get a php-warning.


db_select with subquery including conditions from 2 tables I spent much time without success to search how to convert with db_select the following query, running perfectly with db_query :

    SELECT *
    FROM job_orders j
    WHERE j.statut = 'To do'
    AND j.job
    IN ( SELECT r.job
    FROM referential r
    WHERE r.category = j.category
    AND r.label = :label
    AND r.activity = :activity ),
    array(':label' => $label, ':activity' => $activity);

Here is the corresponding (?) db_select query I wrote :

$subquery = db_select('referential', 'r')
    ->fields('r', array('job'))
    ->condition('r.category', 'j.category')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);

$query = db_select('job_orders', 'j')
    ->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('j.job', $subquery, 'IN');
$results = $query->execute();

I got no result with this db_select query, while I got answers with the db_query one... could somebody tell me what is wrong in my db_select query ?

Thank you.

To achieve your desired behavior you have two options.

If you really like to filter by using a subquery, you should execute it first, parse its result set to an array and set this array as parameter to the condition method of your second queries db_select:

// Run your subquery first.
$subquery = db_select('referential', 'r')
  ->fields('r', array('job'))
  ->condition('r.category', 'j.category')
  ->condition('r.label', $label)
  ->condition('r.activity', $activity);
$result = $query->execute()->fetchAllAssoc('job');

// Make sure $results is initialized for further evaluation.
$results = array();

// If we have referential results, execute the query on job orders.
if (!empty($result)) {
  $query = db_select('job_orders', 'j')
    ->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('j.job', array_keys($result), 'IN');
  $results = $query->execute();
}

The far more elegant and therefore suggested solution is to using an INNER JOIN on your query. The target query would look like:

SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

You can achieve this solution using db_select by adding a join to your $query:

  // Run the query using an INNER JOIN.
  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();

Edit:
As I don't see any special reason for using db_select in your use case, I'd also suggest on sticking to db_query here for better performance of your application.

Edit 2:
In the above 'solutions' I have overseen you are using two conditions between the tables. In this case, you have to add both conditions to your JOIN:

SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job AND r.category = j.category)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

Which would need the following db_select:

  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job AND r.category = j.category');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();


How to add custom field to image area where Alt and Title fields are showing? I am trying add new field to image widget using hook_field_widget_form_alter

Bellow is the code:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
     $element[0]['custom'] = array(
     '#type' => 'textfield',
     '#title' => 'Custom Field',
     '#default_value' => FALSE,
    );
}

But it add a new field to first image always. I'm expecting the custom field with each image as Alt & Title fields are showing for each image.

If I remove the [0] index like:

      $element['custom']

or

    $element[]['custom']

it show an error, and show the field bellow image field not with Alt & Title field.

Notice: Undefined index: #file in theme_file_widget_multiple() (line 861 of C:\xampp\htdocs\drupal39\modules\file\file.field.inc).

I also try with [#process][] way:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
if (isset($element['#field_name']) && $element['#field_name'] == 'field_gallery_image') {
      foreach (element_children($element) as $key => $child) {
          $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
      }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
$element['custom'] = array(
    '#title' => t('Custom Field'),
    '#type' => 'textfield',
    '#default_value' => isset($item['custom']) ? $item['custom'] : '',
    '#weight' => 1,
);
return $element;
}

This way the Custom field is adding to all images but create one EXTRA custom field bellow the Image field.

I put element in IF condition in MYMODULE_image_field_widget_process and it works fine.
What it does is, it checks for ALT attribute if it is ENABLED so it will then add the CUSTOM field, you can instead add the CUSTOM field visibility option in image setting page and check for that.

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
   if ($element['alt']['#access']) { // IF condition added here
      $element['custom'] = array(
        '#title' => t('Custom Field'),
        '#type' => 'textfield',
        '#default_value' => isset($item['custom']) ? $item['custom'] : '',
        '#weight' => 1,
      );
   }
   return $element;
}


"current-page:title" when adding a node I have a node-type with an image field. while uploading a file I would like to put it in a node-specific directory which is named after the node title.
while using tokens, there is no node->title, while I am creating the node, so the current-page:title is the node->type I am trying to add.
so this works only when adding files to an existing node.

my solution-idea:

should I restrict adding files before the node is already created? the node should be created unpublished.

are there other solutions / a shorter way e.g. a two-step-edit-form?

You will need FileField Paths. See ImageField Tokens for tokens in default values for alt and title attributes as well.


Aegir content types extra fields Is there an official way to add extra fields on a content type on Aegir.
To be more accurate, I want to a comment (text) field for the 'sites'.

It's Drupal, so yes you can add an extra field to the site content type on /admin/structure/types/manage/site/fields.

Warning: you must enable first the field_ui module, as it's disabled by default in Aegir installation profile.

I started a documentation page about this: http://docs.aegirproject.org/en/3.x/extend/frontend/


Links in stage environments are absolute and send users to live enviroment This problem has been driving crazy for years.
whenever I create a stage environment of a site, I copy the database from the production site. some of the links there - whether in the menus or in the content or in the code, are absolute paths in the production site.
so i have links that lead users from one environment to the other.

Ive been looking for a way to alter this behaviour.
so that all link as
live-environment.com/some-page ----> stage-environment.com/some-page

I dont care if it will happen before the render or just after the click. just that the end result will be that the user stays in the stage environment.

How can I do this. (drupal 7)

Thanks a lot for your help

So ive solved it with js

$('a').each(function() {
    if(!$(this)||$(this)=="undefined") return;
    var href = $(this).attr('href');
    if(!href)return;
    if (href.includes("live-environment.org")){
        var live_env_url = href;
        var stg_url = new URL(live_env_url);
        stg_url.hostname = Drupal.settings.basePath.substring(0, Drupal.settings.basePath.length-1);;
        $(this).attr('href', decodeURIComponent(stg_url.href));
    }
});


Restoring tempstore with another session ID I am building the functionality of sign in during payment checkout in Drupal 8, and I am storing all the values in Drupal 8's tempstore variable. I am capturing the session id for this anonymous user. After the user is signed in, his session ID changes, and I am not able to load the tempstore with the session ID of anonymous user. Is there a way to restore the private tempstore by another tempstore session ID?

So, the submit function of my custom sign in form looks something like this:

$anonymous_session_id = session_id();

$user = user_load_by_mail($form_state->getValue('username'));
$uid  = $user->get('uid')->value;
user_login_finalize($user);

$temp_store = \Drupal::service('user.private_tempstore')->get($anonymous_session_id . '_com_reg');

When I do $temp_store->get('some_value'); it does not give me any result since I am not able to restore the values. Can someone please help in this?

I've experienced the same issue while trying to pass private.tempstore data through anonymous to authenticated user in Drupal 8.

The function

user_login_finalize($user);

Performs de migrate() method. This method migrates anonymous session to authenticated session, but only the Native Session Storage (Symfony).

Private.tempstore has to manually be migrated as Ekta tells.

If you can't or you d'ont know how to implement it, just store the data in native $_SESSION['yourkey']

The problem it's that native Session it's loaded every time a page it's called, and with Tempstore you have more control about this. For this reason it's not the better solutions!.

This could be a good issue for Drupal Core in a future, migrate the tempstore too when session login.