Drupal JQuery Issue - Need some help I have the following scriptthat runs on $(document).ready where the script alter some form elements such as radio buttons.

When the form is updated via JQuery ,the script is not run.

I need the script to alter radio buttons after successful AND unsuccessful form submissions.

Here is a link to my test site:http://test2.bratpaks.co.za/home

    (function($) {
      Drupal.behaviors.icheck = {
        attach: function (context, settings) {
          $('input[type=radio]', context).each(function(){
          var label = $(this).next(),
          var label_text = label.text();
          label.remove();
            $(this).iCheck({
            checkboxClass: 'icheckbox_line-realred',
            radioClass: 'iradio_line-realred',
            insert: '

' + label_text
            });
          });
         }
       };
     })(jQuery);

You should never use simple document ready in Drupal.

Drupal Behaviors was created specifically to address issues like yours. Nice entry manual can be found here.

Quick example:

(function($) {
  Drupal.behaviors.yourmodule = {
    attach: function (context, settings) {
      // your code here
    }
  };
})(jQuery);

In your code, remember to use context, like $('input[type=radio]') should become $('input[type=radio]', context)


How do I include a Javascript Library from a Twig Extension in Drupal 8? I have a custom Twig Extension that needs to add a Javascript library ONLY when the Twig Extension is used.

Here is my modules/custom/MY_MODULE/MY_MODULE.libraries.yml:

my-twig-extension:
  version: VERSION
  js:
    js/myTwigExtension.js: {}
  dependencies:
    - core/jquery

Here is my modules/custom/MY_MODULE/js/myTwigExtension.js (just for testing):

console.log("Hello World!!! at " + Date.now());

In my modules/custom/MY_MODULE/src/TwigExtension.php I define the extension here:

public function getFunctions() {
    return [
        new \Twig_SimpleFunction('MY_MODULE_widget', [$this, 'MY_MODULEWidget']),
    ];
}

and then it's function:

public function MY_MODULEWidget($MY_VARIABLE)
{
    return array(
            '#theme' => 'twig_extension_MY_MODULE_widget',
            '#MY_VARIABLE' => $MY_VARIABLE,
            );
}

The #theme above is correctly loading my file here modules/custom/MY_MODULE/templates/twig_extension_MY_MODULE_widget.html.twig:

Loading Widget...

Attempt 0:

Added the following twig function to modules/custom/MY_MODULE/templates/twig_extension_MY_MODULE_widget.html.twig:

{{ attach_library('MY_MODULE/my-twig-extension') }}

but that did not work.

Attempt 1:

Tried adding the library in the render array:

public function MY_MODULEWidget($MY_VARIABLE)
{
    return array(
            '#theme' => 'twig_extension_MY_MODULE_widget',
            '#MY_VARIABLE' => $MY_VARIABLE,
            '#attached' => array(
                'library' => array(
                    'MY_MODULE/my-twig-extension',
                    ),
                ),
            );
}

but it doesn't look like BlockBase logic is supported here to load the library.

Attempt 2:

I looked at how the Twig function attach_library works and saw how in Drupal\Core\Template\TwigExtension::attachLibrary($library) worked and tried to implement it here like this:

public function MY_MODULEWidget($job_name)
{
    static $doOnce = true;
    if ($doOnce) {
        $doOnce = false;

        /* @var $renderer Drupal\Core\Render\Renderer */
        $renderer = \Drupal::service('renderer');
        $template_attached = ['#attached' => ['library' => ['MY_MODULE/my-twig-extension']]];
        $renderer->render($template_attached);
    }

    return array(
            '#theme' => 'twig_extension_adicio_rated_job_widget',
            '#job_name' => $job_name,
            );
}

... with the idea of including the library the first time the Twig Extension was called.  But no go.

IMPORTANT: yeah I know I can add the following to my module/custom/MY_MODULE/MY_MODULE.info.yml:

libraries:
  - MY_MODULE/my-twig-extension

but I do not want to load this library (very expensive logic), to every page.

Any assistance would be greatly appreciated.  Thank you.

Partial Answer that works

... but I don't like it because the list of paths in the config never gets reset.  I think I need to figure out how to do Cache Contexts for a proper answer.

In my modules/custom/MY_MODULE/src/TwigExtension.php file:

class TwigExtension extends \Twig_Extension
{
   const CONFIG_KEY_NAME = 'MY_CONFIG_NAME';
...
    public function MY_MODULEWidget($MY_VARIABLE)
    {
        /* @var $config Drupal\Core\Config\Config */
        $config = $this->configFactory->getEditable($this->getName() . '.settings');

        $paths = (array)$config->get(self::CONFIG_KEY_NAME);

        /* @var $currentPath string */
        $currentPath = \Drupal::service('path.current')->getPath();        // returns '/node/47446' not the alias

        if (in_array($currentPath, $paths)) {
            // Good
        } else {
            // Add $currentPath to config
            $paths[] = $currentPath;
            $config->set(self::CONFIG_KEY_NAME, $paths)->save();
        }

        return array(
                '#type' => 'inline_template',
                '#template' => '
Loading Widget ...
',
                '#context' => array(
                    'MY_VARIABLE' => $MY_VARIABLE,
                    ),
                );
    }
}

The above code will add the current path to a config.  Unknown if there's an upper limit to the size of the data in the config; however, in my implementation the number of pages that this is on will be small (< 100).

Then once the path is added to the module's config setting then we read it to conditionally add a library like this using hook_page_bottom() like this in my modules/custom/MY_MODULE/MY_MODULE.module file:

/**
 * Implements hook_page_bottom
 */
function MY_MODULE_page_bottom(array &$page_bottom)
{
    /* @var $paths array of strings */
    $paths = (array)\Drupal::config('MY_MODULE.settings')->get(Drupal\MY_MODULE\TwigExtension::CONFIG_KEY_NAME);

    /* @var $currentPath string */
    $currentPath = \Drupal::service('path.current')->getPath();     // like '/node/47446', not the Alias

    if (in_array($currentPath, $paths)) {
        // Include the library that will modify jQuery(".MY_CLASS")
       $page_bottom['MY_MODULE']['#attached']['library'][] = 'MY_MODULE/my-twig-extension';
    }

}

EDIT 0

Added a hook_build() to my module like this so I could clear the setting manually:

function MY_MODULE_rebuild()
{
    /* @var $config Drupal\Core\Config\Config */
    $config = \Drupal::service('config.factory')->getEditable('MY_MODULE.settings');

    $config->clear(Drupal\MY_MODULE\TwigExtension::CONFIG_KEY_NAME);

    $config->save();

}

Note: $config support fluid interface (e.g. $config->clear(...).

I will still not accept my answer because I still believe I should be using Cache Context for this.


Get current node id from controller I am building a module with reactjs and I need to get the current node id from a controller so I can do certain tasks based on the node id but I always receive a null value, my routing is working correctly and my function is the following:

  public function currentNodeId()
    {
        // get current node
        $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

        return new JsonResponse(
            array(
                'node_id' => $node_id
            )
        );
    }

and in mymodule.routing.yml I have:

 mymodule-currentNode:
   path: '/mymodule/currentNodeId'
   defaults:
     _controller: '\Drupal\mymodule\Controller\MyModuleController::currentNodeId'
     _title: 'Current node id'
   requirements:
     _permission: 'access content'

I can get the current node id from my module file 'mymodule.module' doing the same I did in the currentNodeId function:

   $node_id = \Drupal::routeMatch()->getParameter('node')->Id();

Anyone knows if this is some kind of security or am I doing anything wrong? Thank you

EDIT

This is what I have in my js file, I do this call and I want to get the current node id so then I can do a certain task, in the console I get null or undefined every time I do the request

$.get('/mymodule/currentNodeId/', function (data) {
                        console.log(data.node_id);
                    });

Your route has no node parameter. See the documentation Structure of routes and the example from there:

book.export:
  # This path takes dynamic arguments, which are enclosed in { }.
  path: '/book/export/{type}/{node}'
  defaults:
    # Because this route does not return HTML, use _controller.
    _controller: '\Drupal\book\Controller\BookController::bookExport'
  requirements:
    _permission: 'access printer-friendly version'
    # Ensure user has access to view the node passed in.
    _entity_access: 'node.view'

You can access the route parameters in the controller directly in the function arguments:

public function bookExport($type, NodeInterface $node) {
  // get the id from the controller argument
  $node_id = $node->id();
}

\Drupal::routeMatch()->getParameter() is to get a route parameter outside of the controller, for example in a preprocess hook. For this to work the parameter has to be defined in the current route as well.


Memory Size issue is coming while we have increased a lots of Memory Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 71 bytes) in /home/public_html/includes/theme.inc on line 98

1073741824 bytes = 1GB, so that should be more than enough. I have my development machine set to memory_limit = 256M, which is already pretty much, and I never run into exhausted memory problems.

Your error is probably caused by a mistake or some very inefficient logic in your code. There are a couple of things you can do to find the problem, like:

Switch to a standard theme, to narrow down if the theme is causing the problem.
Disable modules you added recently, one by one, to see which module is causing the problem.
Search for loops in your code that may keep running indefinitely.
Use a step debugger (like Xdebug) to find the point in code where the problem is caused. (Xdebug takes some setting up, but installing it is well worth your time.)
Use a profiler (like XHprof) to see where your memory is going. (Installing and learning XHprof takes time, but if the other methods don't work for you, it can probably answer your question.)


'User Account' menu link does not show to anonymous users When a user is logged in the User menu shows 'My Account' link and the 'Logout' link. However, when logged out the menu disappears.

How do I make a menu link to the user login page that only shows for anonymous users in the User Menu?

If Trey posted his comment as an answer, I would have checked it. I have disabled the block module since I use context. I created a second sitewide context that is triggered by the anonymous user role and placed the menu block with the link for login page in the user region. It works.

I still would like to see this accomplished in code. I tried to access the variables through preprocess functions but the menu links are already rendered by that time.

That is a feature. An anonymous user doesn't have an account nor can he log out, why should there be links to these pages?

You might want to update your question to better explain what you actually want instead of explaining how it works right now :)

EDIT: To have a link to the Login page, just create a menu entry that points to /user/login. Just like /user/logout, this link will only be shown if you can log in (which means that you are not already logged in).


Image upload functionality for drupal 7 content I am using CKEdtor and i want image uploading functionality in drupal 7. What is the solution for that ?

Install the IMCE file browser module.  This will let you integrate direct file uploading while editing content, which of course includes images as well.  Follow the directions on the module's homepage for linking it with CKEditor.


How can I write an input selector for the states API? I'm trying to use the #states API but my input selector isn't being picked up.  This is the code I've added to hook_form_alter() in a custom module:

  case 'my_form':
    $form['revision_information']['#access'] = FALSE;
    $form['field_guide_link_hosting']['#states'] = array(
      'visible' => array(
        ':input[name="field_guide_types[und]"]' => array('value' => 's'),
      ),
      'required' => array(
        ':input[name="field_guide_types[und]"]' => array('value' => 's'),
      ),
    );

And here's the rendered form for field_guide_types:

  How can you help tourists? 必須

 <input type="checkbox" id="edit-field-guide-types-und-o" name="field_guide_types[und][o]" value="o" class="form-checkbox">  Answer questions and offer information online

 <input type="checkbox" id="edit-field-guide-types-und-m" name="field_guide_types[und][m]" value="m" checked="checked" class="form-checkbox">  Meet in person

 <input type="checkbox" id="edit-field-guide-types-und-s" name="field_guide_types[und][s]" value="s" class="form-checkbox">  Provide a place to stay (like through AirBNB, CouchSurfing, etc.)

drupal_process_states() has a great set of information on handling inputs for different types of input elements.

You have checkboxes, so you have to use checked assertion.

case 'my_form':
    $form['revision_information']['#access'] = FALSE;
    $form['field_guide_link_hosting']['#states'] = array(
      'visible' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE),
      ),
      'required' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE
      ),
    );

Notice I replaced the value assertion with a checked, and also changed the jQuery selector to use the full name attribute of the checkbox.


Logout user programmatically without redirect I need to logout the current user in my code.
For now I use : user_logout(); but this function seems to have a redirect at the end.

How can I logout a user without any redirect ?

It need to be for a single case, not a hook to every logout.

Thanks.

The logout controller (UserController::logout()) does this in a separate step.

  public function logout() {
    user_logout();
    return $this->redirect('<front>');
  }

You can alter the controller class for the user.logout route to replace this with custom code.

What do you want to do instead? Building an anonymous response a redirect seems to be the most straightforward solution.


How to change the value of a user field through Restfull? I can’t change the value of field_motherid field through restfall. GET running, PUT disabled, PATCH enabled and configured. When I do GET there is no user field.

Assuming the user rest resource is enabled and PATCH requests are configured, also that the requesting user is authenticated to update the user, then:
send a PATCH request to: https://example.com/user/$uid?_format=json
Where $uid is the user id to update (e.g 12)
The request body should look something like this (json format):
{ "field_motherid":
  [
    {"value": "new_value"}
  ]
}


how to call a webservices on hook_form_FORM_ID_alter but not when the form is submitted and validation raise no error? I have to call a webservice than dynamically modify the form. I used hook_form_FORM_ID_alter to do that. The problem is hook_form_FORM_ID_alter is also called on submit event when the form is not going to be displayed again to the user.

How can I avoid calling the webservices two times? The information gathered with the webservice are not important for the validation...

This is also linked to this question hook_form_FORM_ID_alter called twice after submit

The reason why your alter is called twice is because Drupal needs to build the form at least two times: one for the first time is delivered to the user and a second time when the submit is done. The second build is needed because Drupal needs to know the complete form that was delivered to the user (for validation and security reasons).

You have two approaches to solve this:

Form API

As other have answered modify the form API behavior to avoid that second call:

Detect the second call and do not call the webservice (checking $form_state['triggered_element']['#name'] as told): it's ok but take into account that if the form built in the second call is different form the first one you may have problems with Form API complaining about invalid user input,
Enable form cache ($form_state['cache'] = TRUE). This way Drupal saves the form when is built for the first time, so the second time during submit, form is fetched form DB.

Cache webservice results

A second call to the webservice is not a problem if you cache webservice data  because you retrieve the results from the cache instead of call it again. I think this is the best option if the nature of the webservice data allows to cache it.

This way the problem is solved in the webservice area while the other solutions involves that other components solve the issue (your form API code solves the webservice problem). If there's another similar use case you will have to solve again the proble, but if you solve it using webservice caching the problem is solved for all use cases.


Altering Nodecomment $links I am trying to alter the "reply" links added to Nodecomment comments when the nodes are listed beneath the topic. The problem I have is that I want users to be restricted to the inline submit form, but Nodecomment is adding links to the standalone reply page.

While trying to ovveride the links using hook_link_alter(), I ran into an issue with Nodecomment comments are treated much like regular comments in that hook_link_alter() doesn't seem to be run on them. Here is an example:

/**
* Alter module links.
*
*/
function mymodule_link_alter(&$links, $node) {

    // This is an example of altering links that works as expected
    if (isset($links['comment_add']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }

    // This is an example of altering nodecomment links failing.
    // When rendering a list of topic replies, the comment_reply link
    // will not be altered.
    if (isset($links['comment_reply']) && node_access('create', $node)) {
      $links['comment_reply'] = array(
        'title' => t('reply'),
        'title' => t('Link altered'),
        'href' => 'http://example.com',
      );
    }
}

I am looking for solutions which can (ideally) be packaged in the site's custom module rather than theme.

Reading the documentation for hook_link_alter() I find the following sentence.

  Perform alterations before links on a node or comment are rendered.

The hook implementation you are using is missing the last argument: the definition of the hook given by the documentation is hook_link_alter(&$links, $node, $comment = NULL).

Looking at the code of comment_render(), which is the function that renders all the comments of a node, you can notice that hook_link_alter() is invoked right after the data is loaded from the database (and after hook_link(), of course).

if ($comment = db_fetch_object($result)) {
  $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
  $links = module_invoke_all('link', 'comment', $comment, 1);
  drupal_alter('link', $links, $node, $comment);

  $output .= theme('comment_view', $comment, $node, $links);
}

hook_comment is invoked from theme_comment_view().

if ($visible) {
  $comment->comment = check_markup($comment->comment, $comment->format, FALSE);

  // Comment API hook
  comment_invoke_comment($comment, 'view');

  $output .= theme('comment', $comment, $node, $links);
}
else {
  $output .= theme('comment_folded', $comment);
}

hook_comment(), which is invoked with a call to comment_invoke_comment(), is not called for comments that are not visible.

The implementation of hook_link_alter() you created should at least check which comments it is altering, if it is supposed to alter only specific comments. At least, it should check the last parameter ($comment) is not NULL; if that happens, the hook is invoked to alter node links, which is not what you want as you need to alter comment links.


How to use multiple values for an exposed filter via url On my current setup I'm exposing a view that outputs json through a service.

The view can be called like this: http://domain.com/api/books.json.

I also exposed a filter to a referenced content type "Author". I'm NOT using context filters, I'm using the regular Filters and exposed that particular filter to the user, this way I can give my filter a nice argument name author_nid.

So now I can call this: http://domain.com/api/books.json?author_nid=38. And this returns all books of the author with that nid.

But I can't seem to figure out how to get the list of books of both author 38 or author 32.

The things i tried:

http://domain.com/api/books.json?author_nid=38,32

http://domain.com/api/books.json?author_nid=38+32

http://domain.com/api/books.json?author_nid[]=38,32

http://domain.com/api/books.json?author_nid[]=38+32

http://domain.com/api/books.json?author_nid[0]=38&author_nid[1]=32

I seem to have the feeling that this isn't supported right now. Am I correct? If so, what are my options? I'd like to give my arguments a name because I'm about to expose 10 to 15 filters (some optional, others required). Using context filters and filtering like this: args[]=2&args[]=43,23&args[]=44 isn't very readable/maintainable.

If using ?author_nid[]=38&author_nid[]=32 as suggested by milkovsky doesn't work you may need to look at using contextual filters. Or, as I think might be your only option, use hook_views_query_alter where you can build your own views query WHERE clause based on $_GET parameters.


Pre-processing a field in a views table Right out front, I am working with Drupal 8.3.1.

I have a view that uses the table output format.  One of the fields it outputs is a multi-value date field in the content type.  It takes all the dates and puts them into an <ul> element that it then renders in the table cell.

I want to be able to preprocess that date field, to assign classnames to the individual <li> elements in it.  I've tried to use template_preprocess_views_view_field, but by the time that fires, the list has been built and rendered to HTML and is presented as a #markup value.

I've looked at various other preprocess hooks and none of them seem to be able to let me hook in and do this.  Is this a limitation of Views? Or am I missing something.

In the settings of the view field you can use this option (located in STYLE SETTINGS):

  [x] Use field template

Now the field is rendered by the same field template you use in the content type including preprocess hooks.

To see the added theme hook and field template enable Twig debug and look at the html source in the browser.


Show a field to logged-in user in Drupal 8 views I have some fields in my views called products but only logged in users will be able to see the product price field.

I am using twig.

I tried using.

{{ uc_product_image }}

{{ title }}

  {% if logged_in %} {{ price }} {% endif %}

  Item # :  {{ model }}

In custom text

but still not working.

If you want to hide the price field globally to anonymous users, consider using something like field permissions.

https://www.drupal.org/project/field_permissions

This could potentially hide the price in any context it is displayed.

If you need to use twig, other solutions include overriding the templates for the view(s) and/or the field itself.

I would recommend addressing this kind of override from a code side, as it could potentially reveal sensitive information based on the front-end.


user_profile_form doesn't show profile2 information I'm trying to modify the user_profile_form, but it isn't working. My regular user edit information shows up, but not my profile2 information.

    function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/jvectormap.min.js'; // You should place jvectormap js files into MYMODULE/js folder
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/jquery-jvectormap-mi-counties.js'; // This is US counties generated file (see #1).
    $form['#attached']['js'][] = drupal_get_path('module', 'conduit') . '/js/county-select.js';
    $form['mi_container'] = array(
        '#type' => "container",
        '#states' => array(
            'visible' => array(// action to take.
                'select[name="profile_main[field_states][und]"]' => array('value' => 187),
            ),
        ),
    );
    $form['mi_container']['micounties_markup'] = array(
        '#markup' => '

', // Define own width and height.
    );

  }
}

Why wouldn't this work?

You've implemented hook_form_FORM_ID_alter(), which only fires for a single form (user_register_form in this case).

If you want to catch multiple forms in a single function, you need hook_form_alter():

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
  ...
}


Add html to wrap custom panels layout programaticly How to add html to wrap custom panels layout programaticly?
I know that i can change html in *.tpl.php but i want to avoid it.
Also i want to know, how to add class to panals programaticly too.

UPD:
I create custom panels layout and want to add html with custom class to wrapp regions of custom panel layout.
I found good decision to use module Semantic panels, but it add markup to field, not to whole region.

This is part of my html

 <?php if ($content['left'] || $content['middle'] || $content['middle_two'] || $content['right']): ?>

            <?php print $content['left']; ?>

  <?php endif ?>

I want to make it like that

 <?php if ($content['left'] || $content['middle'] || $content['middle_two'] || $content['right']): ?>

            <?php print $content['left']; ?>

  <?php endif ?>

UPD2: I try to add variable through themenaame_preprocess_panels_pane, but it doesn't appear in .tpl.php file.

Code

function dmits_preprocess_panels_pane(&$vars){

$vars['custom_article_class'] = 'seriveces-wrapp';
  kpr($vars);

}

The module suggested (in a comment) by Danny Englander helps me (thank you!).

I.e. module drupal.org/project/panels_extra_styles

Since Dany only posted it as a comment, I'm adding it as a "real" answer (so that I will also be abe to "mark it as accepted".


Create custom URL pattern Using the pathauto module, we could have created custom URL patterns using the hook_pathauto(). I could not find any such way to achieve the same in D8.

ref. https://envisioninteractive.com/drupal/using-the-pathauto-api-drupal-module-a-simple-example/

Can someone please explain is this possible in D8 and if so how.

Thanks

In Drupal 8, pathauto patterns are configuration entities. You have  at least two choices to provide them with your custom module:

(1) Provide your pattern as YAML configurations in your module's config/install folder. They will be considered and installed to your Drupal, when your module will be installed. Easiest to create using the UI and doing a configuration export afterwards. Just remove the generated UUID of the pattern.

(2) On run-time or in your install/update hooks, you can use Drupal\pathauto\Entity\PathautoPattern::create() or the \Drupal::entityTypeManager() to create them dynamically:

$data = [
  'id' => 'my_pattern_machine_name',
  'type' => 'canonical_entities:node',
  'pattern' => 'my-path/[node:title]',
  'weight' => 0,
];
$pattern = \Drupal::entityTypeManager()->getStorage('pathauto_pattern')->create($data);

You can then use the returned pattern entity in $pattern to add selection conditions (e.g. bundles, language, ...) as required. Don't forget to save the entity afterwards, and - of course - check, if the pathauto module has been installed before or make it a dependency of your custom module.


Post Private Message to Selected User I've built an iOS app on the Drupal iOS SDK. That said, I want my logged in user to be able to send a message to another Drupal user. Right now, I'm successfully pulling received Private Messages from my services endpoint - but does anyone know how I would go about successfully posting a message to a specific user id? Are there any tutorials out there for this?

here is a rough sketch of how you could go about this:

iOS Side: Add a node using DIOSNode's add

Drupal Side:

Create you own custom content type, e.g. CustomMessage, with a UserID field for collecting the target user of each message. This could be a simple text field, or an Entity Reference field, single or multi-valued.
Create a Services View that will use a user's UID as a contextual filter, in order to display all messages targeted at a specific user.


What do I need to pass to the Image class as the first parameter? I'd like to use the Image API directly to perform few simple operations with images (I'm aware of image styles and for various reasons I would prefer to not use image styles for the application I'm working on). The trouble I'm having is what I need to pass to the Image class as the first parameter. The constructor of the Image class expects an ImageToolkitInterface $toolkit as the first parameter. I'm not sure what to plug in for it.

Hunting around the forums, I see people have used \Drupal::service('image.toolkit') to pass in as the first parameter however this isn't working for me.

Here is a snippet of one of the operations I'm attempting to perform. Feel free to pan my whole approach.

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Image\Image;

class myImageController extends ControllerBase {

  public function imageHeight() {

    $image_path = 'public://path/to/image.jpg';

    $image = new Image(\Drupal::service('image.toolkit'), $image_path);

    $image_height = $image->getHeight();

    ksm([$image_height]);

    return [

      '#markup' => $this->t('Did this work?'),
    ];
  }
}

Does anyone know what I should use to pass in as the first parameter? I'm only using the default GD2 Image toolkit. Also, I'm on Drupal 8.6. Thanks!

$image = \Drupal::service('image.factory')->get($image_path);

See the whole usage


How do I create a Zen's sub-theme using Drush? I am trying to install Zen theme and create a new sub-theme from STARTERKIT. I am using the following Drush commands.

drush dl zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

The first two commands work; the third one throws an error:

  The drush command 'Name machine_name' could not be found

Does anyone know how to do this?

EDIT

My mistake must be that I'm running Drush from my local machine. I downloaded Drush for Windows from the Drush site. I should be running it on my server where my Drupal site is right?

Reading How to build your own sub-theme (7.x-5.x) using Drush, I get that the commands should be the following ones.

drush dl zen
drush en zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

In order, the commands:

Download the Zen theme
Enable it
Clear the cache
Create the sub-theme
The reason of the second command is explained in the linked page.

  Ensure drush knows about the zen command

  After you have downloaded Zen and placed it in your sites/all/themes directory, you need to enable the Zen theme and clear Drupal's (and Drush's) cache so that it will notice the Zen drush command. Type drush en zen followed by drush cc all.

As for running Drush on the remote server or in the local server, see this answer from one of the Drush maintainers for How to use Drush in remote server?

  It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed.  This is possible because the Drush commands drush rsync and drush sql-sync work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.

  In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias.  Otherwise, Drush will try to use Drush on the remote system to look up these values.  See example.aliases.drushrc.php for more information.

  Note that it is really useful to be able to at least run drush updatedb on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster.  The Resources page on drush.org lists some hosting providers that are Drush-friendly.

Keep in mind that you could create the theme on your local site, and then copy the files over the remote site, or in a git repository that you then use when deploying your server.


Create an admin page from template I want to create a completely bespoke admin page for some custom functionality. I don't want to hack the concept into render arrays as it will get messy fast.

I've got a menu declaration with a callback function, in here I can include and render templates. Using buffer streams, however, this only renders the file i'm passing.

Is it possible and if so how, to extend Drupal's default admin layout (header/footer/scripts/css) and print my 'template' in where $page would normally go?

I know I could view source and copy the code required, but I feel that would be an awful approach so please don't suggest.

Attempted solution not working.

function MYMODULENAME_menu() {
    $items = array (
        'admin/content/xxx' => array(
            'title' => 'xxx',
            'page callback' => 'MYMODULENAME_timetable_admin',
            'access arguments' => array('access content'),
        )
    );

    return $items;
}

function xxx_theme() {
  return array(
    'funky_admin_page_content' => array(
      'variables' => array(),
    ),
  );
}

function xxx_funky_admin_page_content() {
    echo "hello world";
  return 'hello world';
}

function MYMODULENAME_timetable_admin() {
  return array(
    '#theme' => 'xxx',
  );
}

Hello world isn't found in view-source. So I can only gather that the function isn't firing. I've cleared caches several times. Am I missing something obvious?

Absolutely, it's quite straightforward.

You'll need a path for the page:

function MYMODULE_menu() {
  $items['admin/foo/bar'] = [
    'title' => 'Foo',
    'page callback' => 'MYMODULE_admin_page_callback',
    'access arguments' => ['whatever makes sense'],
  ];

  return $items;
}

A theme declaration:

function MYMODULE_theme() {
  return [
    'funky_admin_page_content' => [
      'variables' => [],
    ],
  ];
}

Your function to build/get the content. Note that you could also put this in a template file, see hook_theme() for more details.

function theme_funky_admin_page_content() {
  // Build your HTML, return it as a string.
}

And your page callback:

function MYMODULE_admin_page_callback() {
  return [
    '#theme' => 'funky_admin_page_content',
  ];
}


Grant temporary permission during function call on registration page I am geocoding an address supplied by an anon user on the registration page through ajax and then displaying the point on a map for them. I don't want to have this geocoding permission open to anon users though and just want to make an exception for it in my ajax function. I remember seeing something like this on my past Drupal travels but can't find it for the life of me now. Can someone point me in the right direction?

What you want is not possible. Drupal does its best to prevent cross site request forgery, but same site request forgery is not even an established term.

Any candidate for a solution can be circumvented by a script that automates downloading and parsing the registration form, creating the appropriate HTTP request for the AJAX call and sending it to the server.


Drush 8.1 Drupal 8 throws PDOException: SQLSTATE[HY000] [2002] on MAMP After installing Drupal 8 (via installation wizard), trying to run any drush command, getting below error:

drush en views_ui
PDOException: SQLSTATE[HY000] [2002] No such file or directory in core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php on line 79 Drush command terminated abnormally due to an unrecoverable error.

Drupal version: 8.2.x

Drush version:  8.1-dev

Make sure your database host setting is 127.0.0.1 instead of localhost.


Drupal 8 devel dpm does not expand Drupal\node\Entity\Node I'm getting a feeling that Devel got pretty much useless with D8. When I try to dump most of the drupal objects I get only (Object) Namespace\Class output. No fields data is printed. print_r is able to print a lot of information but it's close to useless because it's output is virtually unreadable.

Is there a way to nicely print (dpm?) contents of objects in D8?

dpm() does not print any protected properties and it also doesn't know about methods. That's especially bad for content entities but applies to most objects in 8.x now.

The issue referenced in the answer from Daniel Wehner adds Kint, which is already much better, as it will give you protected properties and methods.

However, for content entities, it still won't be that helpful as the values are all within ->values and ->fields and it's not trivial to understand how those work, especially with multiple languages.

That's why we're also working on better integration for content entities with Kint, so that it will display the fields and their values, see the screenshot in that issue.

Until then, you can also always use the following to debug what's inside a node or other content entity:

<?php
dpm($node->toArray());
dpm($node->getFieldDefinitions());
?>

At least the first one also works well with debug(), which has the advantage that it also works when running tests.


Upload a flash based banner as easy as image Is there a way to add a field that can process a Flash file just like an image and print that file for what it is, just like an image, in a node or whatever?

Use the Media module for your requirement.


D7 block view to only show child nodes based on taxonomy Using Drupal 7

I have a hierarchical taxonomy each node in the site is assigned a taxonomy to identify where it sits in the site structure.

On certain pages (landing pages) I would like to show the children of those pages but not the page itself nor importantly any peer pages

so in the following taxonomy

parent1

child1
child2
child3

parent2

child4
child5
child6

I have two nodes assigned the "parent1" taxonomy and a node assigned to each of the child taxonomies

If I go to one of the nodes assigned the parent1 term I should see in my block view all the nodes assigned to child1-3

Currently using "taxonomy term with depth" I see all the correct children, but I also see the other node assigned to the parent1 term because taxonomy term with depth, returns all children plus the parent nodes.

Hiding the node I am on is easy with exclude, but I cannot see a way of hiding other nodes with the same term as the page I am on.

How can I select only the child nodes, not the child plus parent nodes?

It turns out the problem was not as hard as I thought. The hard part was to know what relationship to set up and what contextual filter to implement.

I solved it by doing the following

Created a view of content using fields
Created a contextual filter using "has taxonomy term with depth"

Selected default value of taxonomy term ID from URL
Set it to depth 1 to pick up children
Limited to my vocabulary

That part was obvious. The next part is what caused issues and was not obvious. I could not find an example anywhere on how to do it.

It is easy to exclude the current page by using the nid contextual filter and using the "exclude" option under the "More" section. This is the answer found by searching online. The problem is it does not resolve the "peer" content issue. It would only remove the current node and not other nodes with the same term.

To fix that problem I found that when I added a relationship, a new contextual filter previously not available was added to the list and it had the all important exclude feature.

So I

Added a relationship using my taxonomy (Content)
Added a new contextual filter "term ID" previously not available

Selected default value of taxonomy term ID from URL
Limited it to my vocab (probably not necessary)
Set exclude under the More section

This removed all the nodes with the same taxonomy term as the current node, including the current node, leaving only the children nodes


Choose specific format for hms field token I'm using a token to include an hms field in an email sent with Rules. I'd like to include the hms field in the format m:ss, but it's displaying as seconds.

I've tried enabling the custom display setting "Tokens" in the Manage Display tab for the specific Entity containing the field, and choosing the m:ss format there, without luck.

To answer my own question: I succeeded in showing the correct formatting as m:ss by enabling the module Token and using this token (with low hyphens) [entityform:field_length] instead of [entityform:field-length].


Adding a class to current taxonomy term link Hi I wrote a SQl query to generate a list of taxonomy terms, I want to add a class to each taxonomy term when its clicked, like when I click any term  it goes to its term page, on that page I want some class should be be added to this taxonomy term.

I tried with jquery when I click any term, the class gets added but the page refreshes as it goes to this term page, the class is removed. I can do with cookie procedure, but I think there might be any other way in drupal.

The only thing to think about here is the page you end up on (the term page), so don't worry about links that appear on any other pages.

So what you want to do is on taxonomy/term/% pages, add a class to links that match that page.

Seeing as we are adding a class to an a tag, we want to be altering/overriding the markup output of an a tag.

So then you just have to find the best way to do that.

There are a lot of places that a link might come from in drupal, so to try to cover the most you possibly can, you want to be as general as possible, which in this case means theme_link(), which as the name indicates, handles the themeing of a link.

For more information on overriding themeable output see About overriding themable output. There are also many other examples across the internet.

In this case you will want to do something like this...

In your theme's template.php file add this:

/**
 * Theme a link tag.
 */
function YOURTHEMENAME_link($variables) {
  // If we are on a term page.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) {
    // The easiest way to check all possibilities, like absolute & relative
    // paths and path aliases and real paths is to compare via the url function,
    // which will normalise all this stuff.
    if (url($variables['path'], array('absolute' => TRUE)) == url($_GET['q'], array('absolute' => TRUE)) {
      // Add the class to the link definition so that it will be
      // added to the rendered link.
      $variables['options']['attributes']['class'][] = 'your-class-goes-here';
    }
  }

  // Print the link as usual.
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

After adding this function to your template.php you will have to clear the drupal cache for it to take effect.

Note that if your theme or any modules print links without using the l() function or theme('link') or similar then it won't be affected by this.

If you have user entered content that has these links in them then they will also not be affected by default.
The easiest way to make it so they are also handled is to enable and configure the pathologic module.

The other option is javascript, but that is not ideal as it isn't really necessary in this case and doesn't work for users that don't have javascript.

In that case you need to include your script on the taxonomy/term/% pages only (see drupal_add_js()), then in the script check for the current page matching any link hrefs and add the class.


Custom compound field update hook I have a custom compound field working beautifully. Below is what I have defined in the hook_field_schema function:

function MODULE_field_schema(&$columns, &$indexes, &$keys) {
  $columns = array(
    'meat' => array(
      'type'        => 'int',
      'description' => 'Meat'
    ),
    'potatoes' => array(
      'type'        => 'int',
      'description' => 'Potatoes',
    ),
  );
}

Now I need to modify the schema like so:

function MODULE_field_schema(&$columns, &$indexes, &$keys) {
  $columns = array(
    'meat' => array(
      'type'        => 'int',
      'description' => 'Meat'
    ),
    'potatoes' => array(
      'type'        => 'int',
      'description' => 'Potatoes',
    ),
    'carrots' => array(
      'type'        => 'int',
      'description' => 'Carrots'
    ),
  );
}

The problem is that I am using this field on a few content types and I need a way to update those associated tables. Basically I need to know what hook I need to create to make this happen.

I completed this in hook_update_n:

function MODULE_update_7201(&$sandbox) {

  // get all field names
  $field_names = array();
  $fields = field_info_instances('node');
  foreach ($fields as $node) {
    foreach ($node as $node_field => $field) {
      $field_names[$node_field] = TRUE;
    }
  }

  // load schema to update
  $columns = array();
  MODULE_field_schema($columns);

  // load all fields and check for type
  foreach ($field_names as $field_name => $junk) {

    // load field info
    $field = field_info_field($field_name);
    if ($field['type'] == FIELD_NAME) {

      // loop schema and check fields for existance
      foreach ($columns as $db_field_name => $db_field_schema) {
        if (!db_field_exists('field_data_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_data_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
        if (!db_field_exists('field_revision_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_revision_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
      }
    }
  }
}


Use single create content flow to create many nodes I am building a site for a charity. Amongst other things, the site lists a number of upcoming events. I have created a custom content type for these events (with fields like title, body, date, location). I want users to be able to upload photographs taken at these events, and am not sure what is the best way to do it.

I was going to create a new content type called something like Event Photographs, and by using a module like Entity Reference I could require the users to select an event.

But our users will probably have many photographs to upload for each event.

Is it possible for my users to follow a single add node / create content flow but upload many photographs at once to create many nodes?

An alternative is to have a single node, with multiple fields, but then I lose the benefits of each photo being its own node (e.g. commenting).

Bulk File Nodes is the solution for you to upload many files/pictures and create a node of it. Rest depends on your Logic how you implement it.


Boost VS Drupal Cache I'm using Boost and Drupal internal cache on two different websites and i m remarking that the site with internal cache is more quickly than the site with the Boost module .
So I'm asking which between the two methodes are suitable ?
Thank  you very much

Boost bypasses execution of Drupal's PHP and serves static files.  So unless you have other problems, it should always be much faster than the standard Drupal cache.  Be aware that it only works for anonymous users.

View source on your pages when running boost and make sure they have a comment at the end that says cached by boost.  Boost puts that comment there by default.  If you haven't disabled it, and it's not there, boost isn't working properly.  It's usually caused by incorrect or missing .htaccess rules.  If you don't see this comment, you won't see an error on the status page.  Your site will work normally, but is not being cached.

It looks like this:

</body>
</html>
<!-- Page cached by Boost @ 2012-10-30 15:01:23, expires @ 2012-10-31 15:01:23 -->


Creating a view that uses fields from two content types I'm reeally struggling with this one. I just can't seem to wrap my head around the way Drupal and Views handles this pretty simple thing...

I have two content types:

Card
Card Content

Card has the following fields:

Title
Body
Display Order
Linked ID

Card Content has the following fields:

Title
Body
Linked ID

In Views, I would like to display:

Card Content - Title
Card Content - Body
Card - Display Order

If I were to write this as an SQL statement, it would be simple:

SELECT a.title, a.body, b.display_order
FROM card_content AS a
  INNER JOIN card AS b
    ON a.linked_id = b.linked_id

How do I achieve this?

Things to note: I originally had the Linked ID as a select box, taken from a set of predefined taxonomy terms. I have since migrated these to entity-references, that pull the data from the taxonomy terms (if that makes sense)?

EDIT: Okay, to clarify things a little...

Linked ID is a select box that's linked to a taxonomy vocabulary. This is purely to limit what a user can input.

As requested, here are screenshots of my Card and Card Content.

Best way is to use entity reference

Below is the youtube link which will provide you step by step explanation of using entity reference module with views.
https://www.youtube.com/watch?v=4Pdii7aFIvc


Performance is notoriously slow This feels like a repeat post but I can't find an actual answer. I just installed Drupal 8.4.4 on an Azure App Service (S3 Standard 4core 7GB RAM / PHP 7.0.6) and Azure Database for MySQL (Standard 100 computes / v5.6.26.0). I've been told the host isn't the issue.

Out of the box, the admin side is incredibly slow, like 4-5 seconds per click. I enabled page caching, and CSS/JS are aggregating. Dog slow. I worked through this and created my content types, added a couple of extensions, and enabled BigPipe (reported to help but didn't).

What am I missing? How do I improve performance before I ask my content authors to start loading up content?

Status report from Drupal. (I have since fixed the reported trusted host settings error)

Performance of the page in Chrome. Looks like 2.8s waiting on the page

I created a test.php file, and queried mysql directly, the key_value table, and dumped all of that to the page, about 576 rows, and it returned instantly. Appears to be Drupal specifically?

Devel bar on public page 182 DB queries

Devel bar on admin page 233 DB queries

It appears Azure's docker container services, which App Services leverages, is the cause of the problem.

Two big pains with Azure's app service (as explained by Azure support):

First, the docker containers are spread out across multiple drives, and PHP/Drupal's nature in using file caching causes it to run slower than it should.

Second, setting PHP settings to setup xdebug for instance, were lost when the service was restart. A "feature" in Azure, the container since it's a PHP image, everything outside of the home directory gets reset. This could be fixed by using an empty container, but then I'd probably still have the first issue.

My solution was to spin up a VM in Azure and manage it there. Runs MUCH faster, more reasonably now.

THANK YOU ALL


Where is the content of a node's body stored? In the node table, you'll find everything except the actual body. Where can I find this body text? I'm assuming it's being stored as a blob somewhere.

In Drupal 7 the body has been moved to the field_data_body table.


How to set up a date field based scheduled newsletter with Simplenews? On my Drupal 7 site I have on the one hand a news letter set up with the module Simplenews. On the other hand I have a content type with a date field. Now I would like the newsletter being scheduled by the date field. To be more precise:

The news letter should work as a reminder. Two days before the date saved in one of the date fields the news letter should be send.

How would that be possible. Actually I think, this does not work with rules, as there is not any triggering event, that could generate scheduled rule.

You could schedule a rule when the content type with the date field is generated.  You'd need to create a rule component that sends the email you want.  Schedule the component on content creation with the date field as the execution time.

I'm using this mechanism to delay some heartbeat activities on my site.  Works a treat.


Print $Messages in node.tpl.php file In Drupal 7, by default the $messages variable is printed in page.tpl.php.

Is there a way to print $messages in a node.tpl.php file (e.g. $node-mycontenttype.tpl.php).

Just putting <?php print $messages; ?> or
<?php print render($page['messages']); ?> does not work.

There's a tutorial here for printing $messages in a block, but I would like to put it in my node.tpl.php file.

Actually, what you want to do is this:

function YOURTHEME_preprocess_page(&$variables) {
  // This disables message-printing on ALL page displays
  $variables['show_messages'] = FALSE;
}

function YOURTHEME_preprocess_node(&$variables) {
  $variables['messages'] = theme('status_messages');
}

How this works:
Drupal core checks the value of show_messages in theme_process_page. If it is TRUE (default) then it calls theme('status_messages') as above, and effectively empties the messages storage, so calling the same theme function later will just return an empty string. However, if we set that variable to FALSE, this prevents said theme function from being called in process_page, allowing us to get all the messages using the same theme function, in a template of our choosing.


The clean URL test failed Drupal and Openshift I want to clean URL in Drupal but get the test failed, and that what I have done in my httpd.conf :

<Directory "/php/">
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

I have also enabled the mod_rewrite but got an error! Any idea?

It's a little hard to answer your question without knowing your setup, e.g. operating system, drupal version and the location, where your site is hosted (are you trying to view it on localhost or on a remote host?).

If you are running Drupal 7, clean urls should be enabled by default.
So, maybe the following does help:

If the url you are accessing is

http://www.your-site.com/?q=admin/config/search/clean-urls

change it to

http://www.your-site.com/admin/config/search/clean-urls

... and test again. Does it still fail?

source:  https://drupal.org/node/1572984#comment-6751806


Convert db_query in EntityFieldQuery I have the following query, which works.

  $email = db_query('
    Select u.init as email
    FROM user__roles as r
    JOIN users_field_data as u ON r.entity_id = u.uid
    WHERE u.status = 1
      AND r.roles_target_id = :role
  ', array('role' => 'pubblisher'))->fetchAll();

I want to convert it to use EntityFieldQuery, but I didn't find any Join function in the documentation. How do I convert my code to use EntityFieldQuery?

As long as you only query for fields, entity query does the joins automatically for you.

Note that entity query can only return entity ID's, you then need to load them.

$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('roles', 'pubblisher')
  ->execute();

$users = User::loadMultiple($ids);


How to set Link field value via entity metada wrapper? I'm using Link field.

I need to populate link field programmatically. Currently I'm using EMW a lot, so I'm wonder if it possible to set Link field value via EMW.

Try this code:

$node = node_load(nid);
$wrapper = entity_metadata_wrapper('node', $node);
$link = array(
  'url' => 'url',
  'title' => 'title',
  'attributes' => array()
);
$wrapper->field_link->set($link);
$wrapper->save();

Don't missing $wrapper->save();


Form type select with multiple values I have a form field with type select. The results values are taken from the database.
If the select list is with single value I'm displaying the value title on the submit like this:

   $selected_index = $form_state['values']['select_list']; //the field is select_list
   $display_value = form['select_list']['#options'][$selected_index];
   dpm($display_value); //it's showing the selected option value title.

When I'm using '#multiple' => TRUE; into the form field, It's showing error: Warning: Illegal offset type in...

How can I display the titles of the multiple values?

EDIT:

This is my code:

function mymodule_page($form, &$form_state) {

global $user;

$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid and type = :type', array(':uid' => $user->uid, ':type' => 'outlets'));

$droplist = array();
foreach($result as $record) {
    $title = $record->title;
    array_push($droplist, $title);

    $form['select_list'] = array(
       '#type' => 'select',
       '#title' => 'Select list',
       '#options' => $droplist, //I'm getting this list from my database
       '#multiple' => TRUE,
   );
}

function mymodule_submit($form, &$form_state) {
   $selected_index = $form_state['values']['select_list'];

   foreach($selected_index as $key => $sindex)
   dpm($sindex);
}

In case of multiple values, the return value is an array of all selected values. Therefore, $selected_index is now an array and not a string.


Core Update: Which Is Safer, Patching or Drush? We have a number of production sites (mostly on one AWS instance) that require an update of Drupal Core from 7.34 to 7.35.

I have tested an update on one development instance using the following drush command:

drush up drupal

I also have tested an update on another development instance using a patch from this site:
http://fuerstnet.de/en/drupal-upgrade-easier
The commands were:

patch -p1 --dry-run < drupal-7.34-to-7.35.patch

patch -p1 < drupal-7.34-to-7.35.patch

There are no db updates involved.

It seems to me that on the one hand, drush backs up the core files but on the other hand, the patch is faster.

So, which would be safer?

At the end of the day, by whatever method you use, what you have accomplished is changing the code on your Drupal site.  In theory, both methods you mention should produce the same result.

What I recommend is that you first upgrade and test on a dev machine, and then, once you have tested everything and are convinced that the set of code files that you have is correct, move those exact files to production.  There are a number of ways you can do that.  Some people like to commit all of the files to git, and then use git push / git pull to deploy.  Rsync is another common way to move the code files over.  Then, you just need to run updatedb (unless you determined in testing that there are no updates required), and bring your site back online.

So, in summary, "safer" depends on your deployment plan, not your upgrade technique.


How do i control validateForm? how do i control: validateForm

public function validateForm(array &$form, FormStateInterface $form_state) {
  // form validation here
  // if validation success then proceed to submit
  // else dont submit and send notification to the respective field
}

i have done my fields validation inside that method, however, how do i control from there?

how to stop the submit process if the validation failed?
and
how to send notification/error message to the respective field?

Thank you,

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $values = $form_state->getValues();
  if ($values['your_field'] == 'some_forbidden_value') {
      $form_state->setErrorByName('your_field', $this->t('This value is forbidden!'));
   }
}

About setErrorByName().


Single site vs Sub-sites vs Multi-site installation + Scalability I am beginning a new Drupal project that needs to very scalable and I need to determine what the structure should look like based on the current and eventual project needs.  I have previously used all separate Drupal sites to accomplish similar goals, but would like to at least consider something a little less maintenance-intensive if it makes sense.  Any ideas or advice on how to proceed is much appreciated... thanks.

Players:
-Organization A (main organization)
-Organization B
-Organization C
-Organization D
(and there may be more in the future)

Functions:
-Main public "front area" of site where all organizations land: orga.site.com
-Access-restricted area for members of Organization A: orga.site.com
-Access-restricted area for members of Organization B: orga.site.com/orgb
-Access-restricted area for members of Organization C: orga.site.com/orbc
-Access-restricted area for members of Organization D: orga.site.com/orgd

Access-restricted areas have similar functions between organizations but not exactly the same, and look and feel (theming) would be different for each organization in the restricted areas.

Additionally, each organization's restricted access area would have sub-areas that are further restricted to a smaller group of people, e.g.:

Organization B:
-Main front: orga.site.com
-Restricted area accessible to all members of Org B: orga.site.com/orgb
-Area restricted to a sub-group in Org B: orga.site.com/orgb/groupa
-Area restricted to a different sub-group in Org B: orga.site.com/orgb/groupb

This type of sub-site differentiation would be typical for each different organization.

Normally when I map a project out like this I have a good handle on how to proceed; in this case my head is still spinning a bit, so any input is helpful.

There are many possible ways to build out a site like this.  Right off the top, I would recommend against using a multi-site setup.  c.f. Drush pm-update and multisite.  If you did want to use multiple Drupal sites for this, I would use aliases in your vhost conf file to point /orgb, /orgc etc. to a separate Drupal root.

However, in this particular case I think you would be best off using a single Drupal site with Organic Groups and Organic Groups Theme.  Disclaimer: the latter module is minimally maintained, and I have not used it personally.   If you wanted to support orgb.site.com instead of orga.site.com/orgb, then you could use the Domain Access or Subdomain module instead, although if you use Domain Access you should be aware of the issue Domain Access and Organic Groups.  Try a couple of experiments and see how they fit your use case before diving in and doing the whole implementation; you should be able to set up something pleasing fairly easily.


AJAX call, hook_menu the requested url does not exist I want to create an AJAX request, so therefore I implement hook_menu and add this code in my .module file:

$items['aug_store_front/get-products/ajax'] = array(
  'title' => t('Get products from specific product group'),
  'page callback' => 'aug_store_get_products',
  'access arguments' => array('access content'),
);

I also add this callback function:

function aug_store_get_products($value) {
  if($_POST['id'] = 6) {
    return drupal_json_output(array('status' => 'success'));
  }
  return drupal_json_output(array('status' => 'failure'));
}

And at last, I'we added this code in a JS file:

jQuery(function($) {
  $(".view-aug-store-frontpage li a").click(function(e) {
    e.preventDefault();
    $.post('/aug_store_front/get-products/ajax', {
      id: 6,
    });
  });
});

Now when I click on the list element, the request is made but I get a 404 error.

What have I done wrong?

You've confused access arguments with access callback. It should be:

$items['aug_store_front/get-products/ajax'] = array(
  'title' => t('Get products from specific product group'),
  'page callback' => 'aug_store_get_products',
  'access arguments' => array('access content'),
);


google alerts RSS feed on homepage feed module I am trying to import a google alert, which I have chosen to be a feed, onto the homepage of a drupal site I am creating.

The goal is to be able to automatically display the results of the rss feed but also to not publish everything right away as I would like to potentially screen the results before they are posted.

I just want to link to the articles respective webpages not necessarily store them as articles within our own drupal site.

I am trying out the module feeds http://drupal.org/node/622696

It might be a lot more than what I need but maybe the only available module. If you know of something better that suits my needs let me know.

I am new to drupal and this module required me to also install:

CTools
Job Scheduler

both of those were listed in the readme, but when I went to the modules admin page I was told I was missing:

features
views

So I went ahead and installed those as well. Is it normal that I had to install those even though they weren't included in the readme at all?

In any case.. I was able to import a feed but it seems to store all rss feed items as articles.

I also do not see any settings for setting how many posts should be visible, how much content should be shown right away (just want headlines). Although I may need to dig deeper into the code to change this stuff.

I guess what I am really asking is if there is a better/easier way to do what I want.

You should only need Features and Views if you enable the Feeds News module. I think you can import from an RSS feed without that (by changing the Fetcher and Parser settings). However, IIRC, the Feeds News module does automatically create a View interface for you that manages all the feed items from a specific source so it can be handy.

Your setup sounds similar to one I implemented in D6, and it works well for the client. Once the items are imported, use Views to customize the output: a Views block can be configured to show the desired number of posts, titles as links, etc.

You may also want to implement VBO to manage the publishing of the feed items from your administrative page.


Using Pathauto and custom nodes I have 2 sections that are accessed as section1, section2 that have thier own node templates. Each section has a resource subsection, which should share a node template (node--resources.tpl.php).

How can I configure my url using Pathauto such that urls section1/resources and section2/resources, both use the node--resource.tpl.php? Is this possible? All attempts have failed.

You can define custom tokens such that they can be replaced by pathauto.

See Implementation with a custom Module

The idea is to define tokens such that they get displayed in pathauto's admin page. and we manage the token from our code; after checking conditions.

AS OP's request here's my D6 code that i've implemented.

function MODULENAME_token_list($type = 'all') {
  $tokens['MODULENAME']['fullname'] = 'The Use\'r Display Name';
  return $tokens;
}

function MODULENAME_token_values($type, $object = NULL, $options = array()) {
  $tokens['fullname'] = _MODULENAME_get_display_name($object->uid);
  return $tokens;
}

function _MODULENAME_get_display_name($uid) {
  //load corresponding user and  get $displayname
  return $displayname;
}


Menu settings missing from all node edit forms Apart from what I mention in the title, there are also a couple of other things that give me the impression that they may be related to the same issue:

Can’t add link to any menu from
admin/structure/menu/manage/my-menu/add. What does happen when I try
to add a link to any menu is that it ends up in the Navigation menu
that comes OOTB.
Can’t assign any menu to taxonomy menu. Having taxonomy_menu
enabled, I noticed that when configuring the vocabulary via
admin/structure/taxonomy/gamma/edit  there is no possiblity to assign
any menu as taxonomy menu. The only option in the drop-down list is
=NONE=

There is also A list of modules on which I did this series of events: disabled the module, cleared cache, checked if the problem persisted (which it obviously did), and enabled the module again:

Here is the list:

Big Menu
Jump Menu
Mysite configurator (custom)
Mysite (custom)
Store locator (custom)
roleperm_import (custom)
mforms
mforms example
Menu Block
Menu import
Menu translation
Taxonomy menu _ custom paths
Taxonomy menu
Administration views
Backup and Migrate
Taxonomy translation
Menu translation

Needless to say the core Menu module is enabled.

Went looking on the internet, found this issue (https://drupal.org/node/358844) on drupal.org but this was drupal6 plus the big problem there was that the everything menu related seemed to be missing. The solution there was that menu permission weren’t right, which I have verified on my site that they are ok.

"Menu settings missing from all node edit forms"

You need to enable the menus for use on each content type. This can be achieved on pages via Structure->Content type->Basic page, then click on the "Menu settings" vertical tab and toggle which menus should be enabled.

Also, if you're using the revisioning system in core, or any kind of workflow type module (workflow or workbench), unpublished pages in the menu won't show up in your list of menu items in Structure->Menus->Main Menu (for example), as well as the obvious rendered menu on the front end too.


q?=admin page accessible for anonymous How do I prevent this? I'm not sure what is causing this. This site is running over 60 modules now and yesterday I noticed something changed my admin_menu toolbar layout, but don't know if this has to do anything with this.

Check the user permissions. The anonymous role might have one too many permissions granting access, such as "Use the administration pages and help".

You aren't running any sort of caching setups that might be caching a logged in experience and displaying it for anonymous users are you?


Can't get the key of webform's select field in the results Im facing a problem with Durpal Webform,
Ive created a select field and added options like said in the description (safe_key|Readable value)

The options are like :

w|Woman
m|Man

When I submit my webform, I would like to get the key in the results ('w') or at least in the excel file when I export it. But the Drupal default behavior is to display the selected readable value in the result ('woman') ...

How can it be done ?

For me it doesn't seem like a normal behavior, since when you create an html form with a select list, you can define the 'value' attribute (in which you can put a key) and you can define the displayed value (which will not be submit).
Drupal seems to use only the Readable value ...

Thanks !

It is a bit of a pain. Looks like you have to do this each time, but here goes...

Go to your Webform in question...

Click the Results tab
Click the Download button
Open the Select List Options section
Under Select Keys, choose "Short, raw options (keys)"
Set any other options as you need and then click Download

You should have a file where the select option columns are populated with the keys rather than the values.


Drupal 7 Webform - Find input regardless of fieldset I have created a webform hook (using hook_form_alter) which searches for a particularly named input and appends an ID for JS code to make changes on the front end.

It works fine however I have come across an issue where if that input is made part of a fieldset, it can no longer find it. This is to do with how the $form array is rearranged to include children inputs in the fieldset array.

My question is: how do I find an element by name regardless of whether it is part of a fieldset or not?

This is the code I'm using, which works fine for parent level inputs but not when it is part of a fieldset. How do I get this to work where I don't need to know what the fieldset is called (because I won't always know).

function MODULE_form_alter(&$form, &$form_state, $form_id){
  $form['submitted']["certain_name"]['#default_value'] = '';
  $form['submitted']["certain_name"]['#attributes']['id'] = 'new-id';
  $form['submitted']["certain_name"]['#ajax'] = array(
    'event'    => 'change',
    'callback' => 'module_js_lookup(this.value)'
  );
}

Unfortunately, to access/modify and form fields in Webform using the form API and hooks, you have to know/include the fieldset hierarchies in the array calls as you observed.

For example:

$form['submitted']["fieldset_machine_name"]["certain_name"]

or

$form['submitted']["outer_fieldset_machine_name"]["inner_fieldset_machine_name"]["certain_name"]

Rather than set a callback function on the form element in your hook_form_alter, you may just need to find the element type with particular machine name using vanilla javascript or jQuery in either:

your theme's assorted javascript files as Drupal behavior
the custom module as a separate script


How do I structure node data that records time and quantity? I have a node that will have one field that will be updated often by adding a field with a time and quantity of an item. I would like to output the data as a table.

Some fields the node will have are:

Title
Description
Type
Year

Then it will have data that is updated attached to it:

Monday | 4
Tuesday | 7
Friday | 3
Sunday | 9
Monday | 3
Friday | 7
.
.
.

I need a field to contain both the data/time and the quantity. Do make a new entity to contain this information and have a mutli value entity reference field? Do I create a field collection? Do I instead make a two value field with the field API? What is the simplest way to store this data? The field will be updated programmatically.

These are just my opinion...

A custom entity would probably be overkill, unless you plan to extend the functionality at some point. If your end game is just to store those key/values pairs, the extra code and DB complexity doesn't feel worth it.
To extend on that, Field Collection already implements that entity for you, plus all of the entity/field/views niceness. Add the Field Collection Table module as a table formatter, and you'll be probably be ready to go in about 10 minutes.
A custom field (and formatter for the table) would be reasonably straight forward to implement, but is tricky to extend if you decide, for example, you need another data column. It does have less DB overhead than the Field Collection method (as there isn't another entity involved), though, in case performance is a major issue.

If you're looking for simple, I'd say Field Collection is the way to go.


view query alter : Subselects/query don't work with out brackets I was trying to alter a view query with a subselect that looks like:

$subquery1 = (db_select('users_roles', 'r')
   ->where('r.uid = users_node__users_roles.uid and r.rid=10'));
$subquery1->addExpression('COUNT(r.rid)', 'rid');
$query->add_where(1,'1', $subquery1, '<>');

where $query is the main query.
But when i run the view, the query

  ...AND (1 <> SELECT COUNT(r.rid) AS rid FROM users_roles r WHERE
  (r.uid = users_node__users_roles.uid and r.rid=10))...

if i put brackets for the sub select query it will working fine.
ie;

  ...AND (1 <> (SELECT COUNT(r.rid) AS rid FROM users_roles r WHERE
  (r.uid = users_node__users_roles.uid and r.rid=10)))...

So my question is;
How can i put the subquery inside brackets?
sorry if my question is stupid?

Thanks in advance,
PREM

I had found the soln myself; put NOT IN instead of <>.
NOT IN will make the value part inside the brackets


How do you target a specific type of content? I have the content type (node), article, page, recipe.
The code below can be used to flag any type of content.
How do you target a specific type of content ?
For example I only want to flag the article and recipe content type.
<?php

/**
 * @file
 * Holds hook implementation for the Admin Task Notify module.
 */

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_node_update().
 */
function admin_task_notify_node_update(Node $node) {

    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $account = \Drupal\user\Entity\User::load(1);
    $flag_service->flag($flag, $node, $account);

}

You need to configure your moderate_node flag in either the UI or in configuration management.
In the flag module, a flag entity is defined by the entity type (i.e. node) and bundles (e.g. article, page, recipe) that are allowed on it. If no bundles are specified, then all bundles are allowed.
In your example code, $flag->getBundles() method will return the bundles that are allowed (empty means all). Once set, the $flag_service->flag method will kickback exceptions if you try to flag bundles that do not apply to that flag. You'll need to adjust the code accordingly to handle those scenarios.


Using placeholders in watchdog function I know this is simple. I have a callback function callback below:

function callback($id = '121-01927'){
    watchdog('print', '%message : Sample',array('%message' => $id), WATCHDOG_DEBUG, $link = NULL);
}

After executing the callback function, I viewed watchdog table in my database, and it says there.

%message : Sample

It seems my placeholder %message is not substituted by the variable $id. Where am I missing?

The placeholders are not supposed to be substituted in the database.

This is because the watchdog() function can be called from anywhere, for any user, with any language.
Mid you call t() function, which usually does the placeholder substitutions and translation, that function used the current language to translate to. Now, if you call watchdog() to log an error for user A, whose language is de, the message should not be saved to the database as the de-translated string. That is why the english untranslated strong is stored.

When an administrator views the log (From Admin -> Reports -> Recent log items), Drupal does the translation call (t()) at that very moment. All entries will then be translated to the language the current user has configured.


Prevent Drupal from rewriting # as %23 in URLs I have a field where I am rewriting the output, trimming it and providing a read more link. The read more link contains a # because it's a page anchor that triggers a views accordion on the destination page.

Views is converting the # character into %23 in the actual displayed link, which is breaking the link.

How can I convert it back to a # character in the url?

function drupal_urlencode($text) {
  if (variable_get('clean_url', '0')) {
    return str_replace(array('%2F', '%3F', '%3D', '%26', '%2523'),
                       array('/', '?', '=', '&', '#'),
                       urlencode($text));
  }
  else {
    return str_replace('%2F', '/', urlencode($text));
  }
}


HTML displayed in product title I have a Drupal commerce webshop with two main products having multiple variations.

Those variations have labels containing HTML tags.

My problem is when I add to cart HTML tags are displayed in text...
Does someone know how to solve this ?

Thank you

For this you have to select text format to full html  check in admin/commerce/products/types/product/display or in admin/commerce/products/types/product/ your field name and check for format option.


Is it possible to put Drupal.settings javascript in separate file I am trying to place all javascript in external files, is it possible to place Drupal.settings javascript in an external file? It is displayed like:

jQuery.extend(Drupal.settings, { "basePath": "/", "fbconnect": { "user_pictures": "allow", "language_code": "en_US",...

Yes - this won't make a difference to Drupal where the file is coming from. In Drupal, you can load this using drupal_add_js:

drupal_add_js('http://example.com/example.js', 'external');

Note that these files will not get aggregated when preprocessing is on.

The other thing to watch for with external javascript is to make sure you are testing for the existence of functions / variables if you are calling them in your file since you can't control the order / speed that they are loading in.


Apache solr with rules module, on refresh, rule viewing node triggers it in search page I'm building a site in free Acquia cloud env with apache solr running, I need to count when a node (for one content type) is being full displayed, that’s already working fine, but every time I refresh results page (viewing only teasers), it triggers not once, twice in all nodes within the content type, so my node full displayed count is not correct, Rules only option is 'when node is being viewed' and not 'node being displayed', I have to mention that this count field is to set solr sort results with a custom module (already working), any suggestions please?

I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

So in your case, it'd be interesting to find out what result you'd get by using (system) event Drupal is initializing instead ... definitely worth a try I think ...

Be aware: this applies to D7 ... and D6 is another story.


How to call CCK as block? Actually I created user's request mail form as CCK.This CCK displayed page name as node/add/laptoprepair.I want to display this CCK page as Block for the purpose of calling multiple page.How to create this CCK as block?

In user's  page it is displayed as,

Please refer these modules, would be helpful

nodesinblock and nodeblock


Resource for understanding Drupal Core functions? I'm looking for something to help me understand drupal core and its functions. I've gotten a hang of writing modules, and I've found plenty of resources, such as books and blog posts. But I'm still stumbling when I find I'm needing to manipulate basic core functions such as creating nodes or manipulating users.

Of course, there is the documentation of each function, but it doesn't tell you much beyond what that function does.

For instance, I wanted to create some nodes automatically in my module. I know about node_save, but I didn't know what fields I had to set in order for my new node to be saved properly. The documentation says that node_save saves a node to the database -- so it doesn't tell you anything more than what the function name already says. My node creation in my module is not working. Then I hear somewhere along the about about node_save_prepare for creating new nodes -- maybe I need to do that? But its documentation says that it prepares a node for editing. So I look in my module dev resources, and they talk about the various hooks... which assume some basic understanding of core functionality. So after some more hacking and trial and error, I get my nodes created... with the title only. Do I set the body with $node->body = "blah" or $node->body[0]['und']['value'] = "blah" (and what is all that stuff, anyway)?

Of course I can source dive, but that doesn't really tell you any more about the right way to do things. So I'm looking for something comprehensive about "how do to things". Does there presently exist such a resource?

One book I have read is Pro Drupal 7 Development, and while it's a great resource for understanding hooks, it doesn't go into core functions in a comprehensive, foundational way.

Please note: It's okay to answer "No such single comprehensive resource exists" or "You'll have to piece it together from multiple sources." If that's the reality of the situation, I want to know that rather than continuing my holy grail quest. I'm not looking to be pointed to more piecemeal resources. I'm asking if there's one comprehensive one for understanding core api functions.

The Examples module is a good way to see "how to do things".  Another useful tool is grep - you can download all of contrib, and search for examples where other developers have implemented the hook or function that interests you.  You can "upgrade" to ack for more powerful searching.
The book "Pro Drupal Development" used to be a good resource, but sadly the 7.x edition is rubbish.


Views Filter Criteria "Now" not working on webform submitted data field:event date The closest I have found to this is This Question which sounded perfect but didnt work for me.

I need to show a list of results in my view equal to or greater than todays date. In the past, on a value formatted as a date, I use "now" and it works a treat.

I have built a view using webform submission data from the latest webform release, which enters a date field as plain text into the database rather than timestamp. So i have the raw value 2014-05-08 from the database.

I can test it by entering the date into the filter value as "2014-05-08" and it works perfectly, but of course I need todays date to update automatically.

I have tried using token filter to use a current date token, for a custom date type I created ('Y-m-d'), but nothing happens.

I have also installed views-php module, which hides a row if value returns true, but the following test didn't work

$date = date('Y-m-d');
if ($row>value_1 == $date) {
return TRUE;
}

Is there any way to use tokens in the Configure filter criterion: value field?

EDIT:

There was a bug in the views-php module that this patch fixes.

I used a Global:php field to convert my text to date, but my next hurdle is that you cant use an exposed filter to filter results from a global:php field.

$eventdate = strtotime($row->value_1);
echo date('Y-m-d', $eventdate);

I don't really understand the problem. When a date isn't a date anymore and you can use php you can just convert it back to a date.

You even almost use the correct function.

$submittedDate = $row>value_1;

$Cdate = date('Y-m-d');
$Sdate = date_format(date_create($submittedDate), 'Y-m-d');

if ($Sdate == $Cdate) {
    return TRUE;
}

Shouldn't that do the trick?


How to validate links before moving to different location This would be most simple functional question in Drupal 7.
Now below mentioned things are mandatory to do and cant change the functionality.
1) I have created a custom block in module.
2) I have included form like below:-

function usercontent_block_view($delta='')
{

   $block = array();
   switch($delta)
   {
     case 'user_front_page' :
       $block['content'] = drupal_get_form('genre_all_login');
     break;
   }
   return $block;
}

3) Now I have some other content in block but which put me in trouble is shown below:-

function genre_all_login($form) {
  $form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com'),
    );
    return $form;
  }

4) So it includes a link which will move me to Google once clicked.
5) Now I want to validate certain content inside the block before user navigates to Google.So if the condition doesn't match then I will stop the user by showing an error message and hence user cannot traverse to Google.

Please tell me if it is possible or should I use different technique to handle this scenario.

You can achieve this using a client side validation. Like below,

Add an ID attribute to the external link

$form['new_user'] = array(
  '#type' => 'item',
  '#markup' => l('Add New User','http://www.google.com', array('attributes' => array('id' => 'external-link'))),
);

Add a JavaScript code to validate and preventi the click.

jQuery(document).ready(function() {
  jQuery('#external-link').click(function(event) {
    // Perform your validation. If the validation fails prevent events default behavior.
    validated = false;
    if (!validated) {
      event.preventDefault(); // You can also use return false instead of prevent default.
    }
  });
});

Hope this helps :)


metatag for custom path I need to set some info for SEO and sharing. I know that I can use the Metatag module for nodes, views and front page. In fact, I use it for them. Now I need to set some information for custom paths (create via hook_menu()). I know that I can use something like drupal_add_html_head($metatag_description_custom, 'description'), but I want to give to my client the possibility to change this and others tags (e.g. og:description, og:image).

Is there a way (or a module) to do this without create and change a custom module's code?

It can be done with Path metatags module

  Path metatags module helps you to create metatags for any page with any selection rules and load any entity from the URL!


D7: function calls too early (before DOCTYPE) and mess my page I have included a class file in my module:

function MYMODULE_init() {
  require_once(drupal_get_path('module','MYMODULE')."/jcart/jcart.php");
}

where I declare a function

public function display_container(){

  echo "
";
  echo "
";
  echo "

\n";

}

I called this function in another module (they are all the same level default/modules)

The problem is this func displays its content before the html doctype causing the layout to mess:

<!DOCTYPE html>

You need to return your HTML string as the page callback rather than outputting it directly...otherwise what your doing is incompatible with the the Drupal theme system, and is why you're getting the problem you're getting at the moment.

Without seeing all of your code its impossible to debug this completely but suffice to say that in whichever page callback function you're calling display_container() you want to do this instead:

// Start the output buffer
ob_start();

// This will perform the echo to your new local buffer, not the screen buffer.
display_container();

// Get the temporary buffer content into a variable.
$output = ob_get_clean();

// Return the page callback to Drupal as normal
return $output;

If you're in a block view (which I seem to recall you might be from one of your previous questions) that last line would be:

$block['content'] = $output;

The other, perhaps simpler method here, would be to simply change your display_container() function to return the string rather than output it directly:

public function display_container(){
  $container = "
";
  $container .= "
";
  $container .= "

\n";

  return $container;
}


Node Access Product + UC Marketplace I want store owners to be able to offer node access to people who purchase their products.

The only problem with this, is when I give the permission "Create and edit NAP" to the developer/store owner role, it gives the permission to ALL nodes.

I've looked for a setting to change this, so that it is only for nodes who have the same author as the current logged in user, and I'm not seeing a way to do this anywhere.

What am I doing wrong? Is there a different module to accomplish this? Should I custom code something?

Can you give more detail on the problem and your setup. For example what is a store owner, is this just and administrator of a single site or do you have many store owners on one installation, for example some kind of marketplace?

What do you mean by node access? you want customers to buy a product and then be able to view or edit it.

What version of ubercart/drupal are you using?

If the scenario is you have only one store owner per site and you want a customer to purchase a product and then have view access to a specific node I would look into using the following modules

node reference / entity reference - create a reference to a node from
a product
content access - this allows fine grained permissions for individual
nodes or for content types etc
Rules - create a rule that after successful checkout grants
permission to the node that is referenced on the product


Is it possible to create sub-node that can assign on a node? The idea is to create a chapter(sub-node) that can assign on a book(node:page). I know this can be done with taxonomy, but I dont wanna have 1000+ of taxonomy on my site. Is it possible, if so, how?

Do you mean you want a Book that has chapters and you want them linked like a book? There is a module for that in Core called book. https://drupal.org/documentation/modules/book


how to adjust size of an existing field through api in hook_update? I have a textfield that is part of a field-collection belonging to a content type made in a custom module.
I am looking for a way to expand the size of the field on the update hook of my module.

I've tried the following:

function spelersfiche_update_7200() {
  field_update_field(array(
    'field_name' => 'spelersfiche_va_antwoord',
    'cardinality' => '1',
    'type' => 'text',
    'settings' => array(
      'max_length' => '511',
    )
  ));
}

In this the max_length setting has been increased.
When i try to run the update for my module i get the following error:

The following updates returned messages
spelersfiche module
Update #7200

Failed: FieldUpdateForbiddenException: field_sql_storage cannot change the schema for an existing field with data. in field_sql_storage_field_update_forbid() (line 229 of D:\drupal\volley3\modules\field\modules\field_sql_storage\field_sql_storage.module).

From what i understand it says i can't change this setting for a field that contains data.
But in my case it's just to make the field larger, so any previously contained data should still be able to fit into the field.

Is there any way around this, because uninstalling and reinstalling is what i was trying to avoid since that will delete all the data contained in the field.

If you want to get around the restrictions imposed by the FieldAPI, and you're positive the change won't cause any data loss, you could just do it manually:

$field_name = 'spelersfiche_va_antwoord';

// Get the current settings
$result = db_query('SELECT data FROM {field_config} WHERE field_name = :name', array(':name' => $field_name))->fetchField();

// Change the settings
$data = unserialize($result);
$data['settings']['max_length'] = '511';

// Write settings back to the database.
db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', $field_name)
  ->execute();

// Update the value column in both the _data and _revision tables for the field
$new_field = array('type' => 'varchar', 'length' => 511);
$col_name = $field_name . '_value';

db_change_field("field_data_$field_name", $col_name, $col_name, $new_field);
db_change_field("field_revision_$field_name", $col_name, $col_name, $new_field);

// Flush the caches
drupal_flush_all_caches();


Page Manager user/%user/edit selection rule only called when user has 'administer users' permission I have a page manager page for user/%user/edit.

This page has a selection rule, for which I wrote a ctools access plugin.

(In my case the selection rule checks if the logged in user is the owner of an organic group, and the user being viewed is a member of that group).

The problem I have is that I get access denied.

In the debugger, the code does not even touch the ctools access plugin. It just checks if the user role has permission 'administer users'. The role doesn't have this permission, so I get access denied.

Interestingly, if I give the role the 'administer users' permission, then the code in my ctools access plugin runs!

In other words, page_manager_user_edit_page() is hit when the user has permission to get to the page anyway. What I need to happen is for page_manager_user_edit_page() to be hit always, because of course my og owners do not have global 'administer users' permission.

EDIT:

I ended up fixing the problem using hook_menu_alter() to call the function in the ctools access plugin.

In my case, it looks like this - I have a custom module (sites/all/modules/custom/og_user_admin/og_user_admin.module) where I call the access function.

 function og_user_admin_menu_alter(&$items) {
   $items['user/%user/edit']['access callback'] = 'og_user_admin_access_edit_callback';
 }

use context rule in page manager page.

Home » Administration » Structure » Pages-> selection rule-> from drop down select role-> add-> assign role(selecting by check box).

done.


How can I alter an existent CCK field? I have a "first name" field, and I would like to programatically change its attributes. I want to modify this field, but not to create one new field again.

Is it possible?

In this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields and his relation with the function to alter forms, called hook_form_alter(). in few words, you must also use an after_build() function.


How can we apply filter in view for a content type by start date-time and end date-time? I want to show the latest exam on a tablet based notice board. I am using Drupal 7.

For this I need to show an item from a content type called Exams which has a start date and end date with time. After the time ends I need to show the next item if there any.

We can apply start date and end date filter, but I want to check the time also.

For e.g.

  An exam starts on 28/01/2015 10:00 am and ends on 28/01/2015 11:30 am.
  If I will add another exam starts at 12:30 pm at the same day after the
  first exam I need to show the second one automatically.

How can I accomplish this condition ? Seeking the help from Drupal experts.

Try the Scheduler module, then just create a view with published exams.

This module allows nodes to be published and unpublished on specified dates.
Dates can be entered either as plain text or with calendar popups. To use calendar popups you need to install the Date Popup module, which is part of the Date module.


Questions about Blocks and Menus I'm new to Drupal, so bare with me...

I created a menu that I placed inside the Sidebar First Region.

1st question: I was able to place my menu in the Sidebar First Region by going to the blocks page "admin/structure/block". Is a menu seen as a block, since i am able to assign a region for a menu inside the BLOCKS page ? or is just the name of the page misleading, since it can take care of both blocks and menus ?

2nd question: How can i import/export a menu that has a bunch of links inside it ? i want to export it from local to staging and prod. Features doesnt seem to work? i found menu Block and menu_import to say to be able to do that, but is there another easier or better way ?

Any other suggestions and tips are more than welcomed...

Thanks

A menu is not a block, it's just a collection of links... but the core menu module from Drupal renders the menu as a block to be easier for you to place it in the page and change its location.
There are multiple ways to export or import a menu. Yes, features module is one of them, but for a beginner I would suggest a module only for this, it should be easier. You can try this module.