texts: Duplicate view results when adding a filter related to field with multiple values?

texts:
I have a view to list the Voucher content type. I added a filter: Configure filter criterion: Content: Voucher codes (field_voucher_code) NOT EMPTY.

The idea is to show the node only if its field field_voucher_code is not empty

The field_voucher_code is field which has set the Number of values to 10 at admin/structure/types/manage/vouchers/fields/field_voucher_code

The problem is that the view is duplicating each as many time as values has in its field field_voucher_code.

How can I eliminate the duplicates?


texts: Providing a default value for an Entity Reference Field using Views Bulk Operations

texts:
I have a content type called 'Schools' and a CSV spreadsheet that has columns for information such as School Name, Location, Telephone etc...

Using Feeds I can import the information on the 111 Schools to individual pages.

Furthermore I have a field on the 'Schools' Content type that is an entity reference field to an entity  (an entity form - that lets the user contact the school - of widget type 'Select list')

However when I import the school data with my feed the 'entity reference' 'select-list' field defaults to 'none' and the 'Contact form' does not display. Furthermore the entity reference field does not let me set a default value for the 'select list'.

I don't want to go through 111 schools to do this manually. While the previous question on this subject calls for some code...that I do not yet understand...

Therefore is there a way to essentially set a default value for my entity reference ... Perhaps 'Views Bulk Operations' is the answer?


texts: How to use a math field to calculate a product of an existing file?

texts:
I would like to have a field (field_result) that would display a number that results of the product of an existing field (field_1) on the same content type (let's call it book) and a fixed number (let's say 3.5).

As per another user suggestion, I decided to give up using Computed field module and use the Math Field module instead. After reading its documentation I configured field_result as follows:[field_1:0:value] * 3

Unfortunately I didn't succeed on making it work, despite I made sure field_1 exists and has a value: I do not get any result (Blank field). I also tried with 2 + 2 with no results

What am I doing wrong?


texts: Does Drupal Cache work with views rendered programatically?

texts:
I want to understand does the Drupal caching work for views which are called programmatically

I am using views_get_view for my implementation plus hook_views_query_alter to further add a where condition to this view query

I am debugging this because during load testing I found this code calling memcache get request in the order of hundreds ..

views_get_view code

  $product_view = views_get_view('view_name');
  $product_view->set_display('page_1');
  $pager = array(
    'type' => 'some',
    'options' => array(
      'offset' => 0,
      'items_per_page' => 12,
    ),
  );

  if ($count != NULL) {
    $pager['items_per_page'] = $count;
  }

  $product_view->display_handler->set_option('pager', $pager);
      $product_view->display_handler->set_option('pager', $pager);

      $product_view->set_arguments([
        'abc' => TRUE,
        'xyz' => 123,
      ]);

      $product_view->some_property = $some_array;
      $product_view->execute();
      $list = $product_view->result;

views query alter code

function my_module_views_query_alter(&$view, &$query) {
  $view_args = $view->args;
  if (isset($view_args['abc']) && $view_args['abc']) {
    $some_property = $view->some_property ;
    $some_property[] = $view_args['xyz'];
    $query->add_where(1, 'node.nid', $some_property , 'NOT IN');
  }
}


texts: Adding links on top of view rotating banner

texts: I am trying to add a link to a page (about us) on top of a view with a rotating banner. There are three banners and i only want the link to appear on top of one of them. Any suggestions?


texts: Stop send email attempt when cron is run

texts:
I just took over a drupal 7 site and when cron is run I get the follow error
SMTP Error: Could not connect to SMTP host
WD mail: Error sending e-mail (from ???????? to ???????)

I know the previous developer turned some feature/function on that will send an email each time a cron job is run.  Does anyone know how or where to turn this off?

I have checked in the admin-> cron, but there are no settings there to adjust.

Thank you in advance.


texts:
I have this code in the module cleanetica_advanced.

function cleanetica_advanced_menu() {

    $items['ajax/content/%'] = array(
      'page callback' => 'cleanetica_advanced_ajax_load',
      'page arguments' => array(2),
      'title' => 'Ajax content load',
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

    $items['ajax/validate/form/%'] = array(
      'page callback' => 'cleanetica_advanced_ajax_validate_form',
      'page arguments' => array(3),
      'title' => 'Ajax validate form',
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

    $items['user'] = array(
       'title' => 'blogs',
       'description' => 'Listing of blogs.',
       #'page callback' => 'blog_page',
       'access arguments' => array('access content'),
       'type' => MENU_DEFAULT_LOCAL_TASK
     );

    return $items;
}

For some reason the item "blogs" (which I created for testing only, there are no blogs in our site) does not show in the tabs of the page /users. I need to show it in the /users tabs. What is my error?

I checked that cleanetica_advanced module is loaded by inserting some nonsense in the .module file and seeing that the site ceases to work with an error message. (Then I removed the nonsense.)

By the way, does user in $items['user'] refer to the page where the menu should be shown or to the ID of the menu item itself?


texts: Get the value of a field of the taxonomy term referenced with an Entity Reference field

texts:
I have a taxonomy vocabulary "Partners", with boolean field field_1. When I create a user, I attach to it a term from the vocabulary "Partners" with an Entity Reference field. Is there a way to get the value of the field_1 field of that term and to bind it to the user?

(In the first case I need this value to limit the access to a page created by Page Manager to the users whose partners has the field_1 field filled with the value 1. I suppose I need the field value also for other cases later.)

The relation of the user and the partner could be made in another way, too, if it will be easier, more intuitive or more practical.


texts: How do I send a command after submitting a form?

texts:
I need to do something when the user submits a form so that it sends a command to the server, :
 if($_GET["cmd"]=="save")

Got to do something with the thing above,
I thought of using:
Save

But if I do that it will not complete the form action so:
<form action="{{ pageName }}">

Will not be executed...
So how would I fix this problem?
thanks all :)


texts:
I want to create a site in Drupal 7, which has admin user under this main site.

I want to create 3 sub sites whose links I am going to publish in front end of main site.

These three sub sites must have 3 different admins who have the rights to change contents of their respective sites. Once this is done, all activities should be managed by main sites admin user who is super admin.

e.g.

My main site url is http://www.drupalmain.com. It has admin user whose name is admin_main.

Under this main site I want to create three sub sites like

www.drupalmain.com/first  has admin user admin_sub1
www.drupalmain.com/second  has admin user admin_sub2
www.drupalmain.com/third  has admin user admin_sub3

And also these three admin should has restriction for content edit that means nobody can edit content of other users link.


texts: Drupal 6 Form fields not displaying if nested too deep.

texts:
I'm using Drupal 6 to create a form that's pretty big. Basically here is how the client wants this form to act:

Users create engagements, and an engagement can have multiple goals and multiple meetings. Each goal can have multiple recommendations, and each recommendation can have multiple action steps. So far I've been able to use AHAH to dynamically add meetings and goals to engagements, but I've hit a snag as I've started to try adding recommendations to goals. I'm doing something like this for recommendations:

 $form['goals_fieldset']['goal_'.$gid]['recommendations']['rec_'.$rid]['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Recommendation Title'),
    '#default_value' => $title,
  );

This will nest the recommendations array under the goal its attached to, my issue is, the field doesn't show up on the form, is there a limitation to how nested you can go in a form? If I use:

  $form['goals_fieldset']['goal_'.$gid]['rec_'.$rid]['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Recommendation Title'),
    '#default_value' => $title,
  );

The field will show up. I really need the ['recommendations'] piece in there cause it is where I've set the wrapper that AHAH replaces when you click the 'add another' button:

$form['goals_fieldset']['goal_'.$gid]['recommendations'] = array(
  '#type' => 'fieldset',
  '#title' => t('Recommendations'),

  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
);

Any insight as to why my fields won't show up, or insight into how to fix is greatly appreciated. Thanks!


texts: How to get the feeds log entry from hook_feeds_after_import

texts:
I have a feed and I want to email the log entries from feeds_log after it has completed a run. I thought that if I could get the feed_id, I could query the db to get the log entries.

I'm using hook_feeds_after_import(), which gives me access to the $source object, but in looking through some documentation, I don't see a way to get the feed_id.

How can I get the log entries from a feed run?


texts:
Just started a gigantic Drupal build and I'm trying to validate if the Context Module is the correct option for a segmented content delivery system. It appears to be and I am optimistic.

The project calls for about 100 custom "variables" that the site administrators can segment content with. As a test, I've created a custom context condition of time of day. If the condition is set for >= 2PM for example with a reaction of showing the Powered By Drupal block in the footer, everything works as expected - Before 2PM, no block and after 2PM, block. So the context condition is working as expected.

Now, I've enabled page caching with lifetime and expiration set to 1 day. If I clear the cache before 2PM and hit the page, the block does not show as expected. If I hit the page (which is previously cached) after 2PM, still no block.

I have used a "preboot" method to modify the cache key, but in my example above, the cache key would include the hour and the minute, effectively reducing the cached copy of a page to 1 minute. I might as well turn page caching off in that case!

Is it possible to run the context conditions on a cached page? Has anyone found a way to make this happen?


texts: How to add a local task tab to node view?

texts:
I'm trying to add an extra tab to the node 'view' and 'edit' tabs.

My module is enabled fine and I have cleared cache, but my new tab doesn't appear. What am I missing?

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

  $items['node/%node/performance'] = array(
    'title' => 'Add a performance',
    'page callback' => 'add_performance_action',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
* Page callback.
*/
function add_performance_action() {
  return t('Hello');
}


texts: Effecient modules which will give me users location and country information

texts: I am using drupal 7. I searched and found lot many modules to give users location and country information. So just wanted to know which is the efficient module which i should use.


texts: Grab Data from non form elements and send as POST using AJAX

texts:
I am looking for an alternative solution to the way my form is being submitted right now. The problem is that the validation function does not work because I gave the submit button on the form an attribute of onclick=return(false) and added the following AJAX code to listen for the submit button being pressed.

jQuery("#edit-submit-order").click(function() {
        var orderForm = jQuery("#order-form-form").serialize();
        var orderTable = JSON.stringify(hot.getData());
        var extraOrderTable = JSON.stringify(hot2.getData());
        var formType = jQuery("input:radio[name=form-type]:checked").val();

        jQuery.ajax({
            type : "POST",
            url : '/sites/all/modules/order_form/post-order.php',
            data : orderForm + "&orderTable=" + orderTable + "&extraOrderTable=" + extraOrderTable + "&formType=" + formType + "&orderTotal=" + parseFloat(updatePricing()).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),

            success : function(result) {
                if (result) {
                    jQuery('#order-form-form').empty();
                    jQuery('#order-form-form').append(result);
                    //jQuery("#order-form-form").html("
Submitted Order Form Successfully
");
                } else {
                    jQuery(".message").html("
" + result.message + "
");
                }
                jQuery(".message").children().fadeOut(5000);
            }
        });
    });

The orderTable and extraOrderTable are the elements I need to send with the POST request. They are part of an HTML table I am using called Hands on Table. It is a very nice excel like table editor. The getData() command returns an array of all values in the tables.

Ideally I would like to remove the onclick=return(false) from my submit button and have the order form submit using Drupal's AJAX method, making sure to validate the fields I marked as required but also submitting the table data in a single POST request. Can this be done or is the solution I have already made the best way to do it?


texts: How do print term image field as background style attribute in views-view.tpl.php?

texts:
How do print term image field as background style attribute in views-view.tpl.php or in views-view-unformatted.tpl.php file?
I have view which lists terms of taxonomy vocabulary. All terms have title and image fields. I need to lists terms like:

Title

Title


texts: db_select with mysql reserved word in the statement

texts:
This seems to be fairly easy question, but I could not find simple answer to it.

Using db_select when database column happens to be a reserved mysql word (when in this case) results in an error.

Table:

+-----------------------------------+------------+--------+
|               sort_id             |    when    |  user  |
+-----------------------------------+------------+--------+
| 1                                 | 1448270950 |    123 |
| 3                                 | 1448270955 |     12 |
| 50                                | 1448270959 |     45 |
+-----------------------------------+------------+--------+

Standard drupal7 select using db_select:

$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', 'when', 'user'))
    ->condition('user', $uid)
    ->execute();

BUT column named when is the problem here.

I know I can write the query using plain SQL:

db_query("SELECT sort_id, user, `when` FROM {naughty_table} WHERE user = :user", array(":user" => $user_id));

But there should be a way to solve this using regular db_select?

IMPORTANT:

I have tried to use backticks like this:

$query = db_select('my_table', 'd')
    ->fields('d', array('sort_id', '`when`', 'user'))
    ->condition('user', '123')
    ->condition('`when`', '1448270950')
    ->execute();

But backticking like this does not seem to work whatsoever.


texts: Howto get ID on newly created content through Drupal 8 REST POST

texts:
I have a working decoupled/headless setup working using Drupal 8 beta 10 as a backend, and a html5/js webapp as frontend, on seperate servers.

For this scenario, I'm succesfully able to post new content (an article node) as an anonymous user, using the REST /entity/node endpoint.

This works fine, I receive a 201 "Created" response, but now I'm trying to figure out a way to get the ID of this newly created node so I can GET and render it.

The current documentation and response does not provide a return (N)ID. Am I overlooking something or is this a bug?


texts: Creating multiple entities in rules based on a quantity

texts: I have a field which is a select list of numbers, 1 -10. In rules I would then like to create multiple entities, how many dependant on the quantity selected. Is the possible as I can' for the life of me work it out.


texts:
I have a content type with 6 select-list fields.
Each field has several available values, multiple selections allowed via checkboxes. A group of users each submit the content once.

Select List Field 1

user001 answered     | user002 answered     |user003 answered
1|oranges            | 1|oranges (x)        | 1|oranges (x)
2|apples (x)         | 2|apples (x)         | 2|apples
3|bananas (x)        | 3|bananas            | 3|bananas
4|mangos             | 4|mangos (x)         | 4|mangos (x)

Select List Field 2

user001 answered     | user002 answered     |user003 answered
1|eggs               | 1|eggs (x)           | 1|eggs (x)
2|fish (x)           | 2|fish (x)           | 2|fish (x)
3|nuts (x)           | 3|nuts               | 3|nuts
4|berries            | 4|berrries (x)       | 4|berries (x)

Views, showing Content of type, contextually filtering on the group id, displays selections from each user in the group. A list of all selected values is shown, including many duplicates.

Apples
Bananas
Fish
Nuts

Oranges
Apples
Mangos
Eggs
Fish
Berries

Oranges
Mangos
Eggs
Fish
Berries

Instead of showing this list (above), I would like to display the number of times each value was selected in total by that group of users.

Fish     (3)
Apples   (2)
Berries  (2)
Eggs     (2)
Mangos   (2)
Oranges  (2)
Bananas  (1)
Nuts     (1)

I have tried Views aggregation, but so far have only been able to count how many values were chosen for a given field, instead of counting how many times each specific value was selected.

It seems like this should be easy to accomplish, like I am missing something simple. How can I achieve this?


texts: Access User Data from external script inside a custom module

texts:
The method mentioned at Php Access User Data from external script works for me but only if the script is at the document root. If I move the file into my custom module the user returned is the anonymous user.

So, is there something else to do in order to keep all my files in my module and avoid starting to add custom scripts in the Drupal root folder?

Thanks!


texts: Varnish 3.0 and Drupal 7, get registered user to always have non-cached content

texts:
I have issue with Varnish on Drupal 7 detailed here: http://drupal.org/node/1886218

Basically, what happens is:

User visits the certain page as anonymous, gets content served by Varnish Cache (OK)
Logs in
Clicks the link of the page that he visitied as anonymous previosly, but he gets cached page, instead of user-specific (that should not happen)
If he reloads page (f5), he gets backend served page, but if he clicks that link on the menu, he gets cached page.

It turns out that cached page was delivered by browser, not by Varnish; anyway, that should not happen, because user thinks he is logged out (I have user specific block in header).

How i can deliver such cache-control in header, so Registered users always get updated (not cached) content, even if they browsed site as anonymous before they have logged in ?

Thanks for help!

HTTP response:

The url we checked: www.mydomain.com
    HTTP/1.1 200 OK
Server: Apache (removed from security)
X-Powered-By:   PHP(removed from security)
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Tue, 15 Jan 2013 08:38:54 +0000
Cache-Control:  public, max-age=10800
ETag:   "1358239134-1"
Content-Language:   hr
X-Generator:    Drupal 7 (http://drupal.org)
Link:   <http://www.mydomain.com/>; rel="canonical",<http://www.mydomain.com/>; rel="shortlink"
Vary:   Accept-Encoding
Content-Encoding:   gzip
Content-Type:   text/html; charset=utf-8
Content-Length: 33254
Accept-Ranges:  bytes
Date:   Tue, 15 Jan 2013 08:49:22 GMT
X-Varnish:  1420616326 1420614128
Age:    622
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    HIT


texts: Form element validation #element_validate not working

texts:
I am porting this contrib module to D8 and need some help.

The module is shipped with a custom node type. Certain elements options in the node_form will be populated dynamically. Also other modules needs to able to provide options for these fields.

hook_form_FORM_ID_alter calls the wrapper class MyModuleManager that performs several helper duties. All is going well except that I can not get the custom element_validation to work.

Upon form validation a warning is generated

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'FilebrowserManager' not found in Drupal\Core\Form\FormValidator->doValidateForm() (line 282 of core/lib/Drupal/Core/Form/FormValidator.php).

together with the fatal error:

Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /var/www/drupal8/core/lib/Drupal/Core/Field/WidgetBase.php on line 376 and defined in Drupal\Core\Field\WidgetBase->massageFormValues() (line 511 of core/lib/Drupal/Core/Field/WidgetBase.php).

The fatal error occurs exactly when validating $form['my_field']

class MyModuleManager implements MyModuleManagerInterface {
  use StringTranslationTrait;

  public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
    ...

    return $form;
  }

  public function addFormDefaultOptions(array $form, FormStateInterface $form_state) {

    // Replace MyModule_hook by Events
    // ...
    // Events returns dynamic $options

    $form['my_field']['widget']['#options'] = $options;
    $form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

    return $form;
  }

  public function myModuleValidateTrue() {
    return;
  }

}

As the warning tells it can not find the callback in FormValidator I suspect the problem might be the way I wrapped my code in this class. Being new to OOP I would appreciate all help.


texts: Add an extra class to views exposed filter “select” if default option is selected

texts:
I have some views exposed filters and need to add an extra class "test" to each list if it has default option selected.
I try to implement it using jquery with the following code:

function ($) {
$(document).ready(function () {
    $('.form-select option:eq(0)').prop('selected', true);
      $(".form-select").addClass("test").on('change', function() {
      var optionIndex = $(this).find('option:selected').index();
      $(this).toggleClass('test', optionIndex === 0);
   });
});
})(jQuery);

Question is how to make this code to act properly in Drupal 7? Currently it adds the "test" class to all the dropdown lists after the page load. But if you chose any not default value in any list the "test" classes of all lists (even where default option is selected) disappeared and never appeared again until the page reload.


texts: How to get only parent term ids of a given term, without loading the terms

texts:
I want to find all parent ids of a given taxonomy term id recursively, without loading them. Existing taxonomy functions like taxonomy_get_parents_all() and taxonomy_get_parents() are loading the terms.

Since I will be using this result in an API function, it is important for me to get the parents with a minimum performance overhead. All I need to get the parents in a simple array like: $parents = array(6, 3, 2);


texts: Seeking advice on using/attaching View displays for my Nodequeue collections

texts:
On my organization's Drupal 6 site, we use Nodequeue to curate "collections" of content, modeled somewhat after the functionality of scoop.it. Nodequeue fails to provide any information about the queues, so I created a content type called Collection that has a field in which the author can enter the number of the queue to be displayed with the description and metadata of the collection node.

The default view of a collection is a nicely visual tile view (again, similar to scoop.it) but I also developed a list view with exposed filters which makes the collections much more interesting and useful for people browsing them. In a previous version of this feature, I based the view on the URL argument and required the collection node and the queue to have the exact same name the argument would be the same. However, some names could not translate to URLs that would feed back correctly into views, so I changed to using the custom field with queue ID and used the "node content" view display type to attach the tiled collection to the node.

The problem with this approach is I can't figure out how to let the user also see the list view. I tried making it an additional "node content" display in the view, but then they both show up. I tried the QuickTabs module for switching, but it doesn't pull in the view at all.

I feel like I'm very close to getting this to work, but I am just missing one crucial piece of understanding about arguments in Views. I'm also using Panels because they are already used for displaying nodes with different variants for different content types. If it helps, the collections can be viewed at http://www.hastac.org/collections and I'm attaching a screenshot of my view.


texts: Rules scheduler reacting on last comment?

texts:
I have a content type with comments activated and would like to have a rule that triggers a component when there is no new comments posted after a week. The component works as designed with rules scheduler, but I am having problems with creating a rule.

I have tried to create a rule that reacts on the event "After saving new comment". However, without proper conditions every comment will be scheduled to trigger the component one week after is is posted. The rule needs to overwrite existing scheduled actions if a new comment is posted on the same node. How can I achieve this?


texts: Send email with URL of same page as the email link?

texts:
We have a page that displays a logged-in user's selections from a Flag Lists process. The page includes code to generate the specific URL of that page, so it can be copied and pasted elsewhere. (essentially a "share this" type of thing, but this is definitely not intended for social media) That code is:
    " onclick="this.select();" />

We want to provide an email link (ideally, a button) which sends a preformatted message including this URL, to a specific person's email address. (i.e. always to the same person) I am having trouble visualizing how this can be done, since the interface I am using for adding an email link (via CK Editor) isn't able to process the "current-page:url" PHP code and just displays it as code in the resulting message.

Any suggestions? -- Thanks! --


texts: Using Docker4Drupal in Production vs. its commercial Wodby solution

texts:
I've been playing with https://github.com/wodby/docker4drupal on a DigitalOcean droplet and am utterly amazed at how it all works.

However, it recommends that people use https://wodby.com/ for production and I'm wondering if I have to; it seems like an unnecessary step when my testing has four sites running perfectly in "production mode".

Does anybody know in what way Docker4Drupal is designed to be run in a local environment when it seems so well on a regular server?

This isn't a question of money.. Just effort. I'm a one man show and don't need dev/staging/production for what I'm working on right now.


texts: I am adding a content type in Drupal 7. I want to add a simple node-reference field. Isn't this included in Drupal 7?


texts: Add where condition in hook_views_data with join?

texts:
I want to join my custom table with node fields. In my custom table there is a nid field for which I have used join and another is uid field for which I want a condition where uid = current_user_uid. But adding this in custom handler it giving me duplicate record if I have three [nid, uid] pair.

For ex : I have [1, 1] and [1, 2] and [2, 1] pair then it should be give me first and third record if I am logged in using first user and second pair if I am logged in using 2nd user. But it is giving me all the records.

My Code sample :

  $data = array();

  // Create a new group by which the of this module plugins would be grouped.
  $data['custom_table']['table']['group'] = t('Event');

  // Join the table with default node table.
  $data['custom_table']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

  $data['custom_table']['id'] = array(
    'title' => t('Unique Id'),
    'help' => t('Unique Id id.'),
    'field' => array(
      'handler' => 'views_handler_custom_field_id',
    ),
  );

  return $data;

Edit :

I didn't found any way to do this in my custom module. Somehow I managed to do it with view's template file.


texts: If I install the same module in sites/all/modules vs sites/example.com/modules, which is used?

texts: I assume that example.com would use its own version of said module, but I don't know. I have the same question regarding themes.


texts:
I've been researching this matter for a while with no clear answer yet.
So, here are a few questions ...

I'm assuming (correct me if I'm wrong) that Drupal 7 doesn't support reset buttons. It appears, according to the form API (as discussed in Pro Drupal 7 Development), that all the buttons (input type="submit", button, and image_button) are by default submit buttons. There doesn't appear to be a way to override the defaults either.
So, if I wanted to add functionality to my forms for my users to clear forms (if they choose), would I have to create a module?

Would I be able to pull this off by using the general button type with executes_submit_callback set to false and by adding some type of Ajax function to the mousedown event?

** EDIT: I added the following to my hook_form_alter() **
$form['reset'] = array(
'#input' => TRUE,
'#name' => 'reset',
'#button_type' => 'reset',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => TRUE,
'#process' => '',
'#theme_wrappers' => array('button'),
);

I got the following error message & warning:

Notice: Undefined index: #type in _form_builder_handle_input_element() (line 1949 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).
Warning: Invalid argument supplied for foreach() in form_builder() (line 1763 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).

Is there a way to add the "reset" button type to the types of buttons without crashing the entire form.inc?


texts: How do I render a field value including its format?

texts: I'm reading a field value and its format from the database. How would I render that value with the format?


texts: which hook to change the node order in a view?

texts:
I have a custom view but now I want to put the nodes created by a specific user role on top.

I want to do this using code so I can easily implement this throughout multiple web pages.

I'm thinking to alter the query or to put an array sort before the nodes are rendered.

But I don't know which hook would be useful for this.

edit:
using hook_views_pre_render as suggested by Jimajamma

function vacancies_views_pre_render(&$view) {
  dsm($view->result);
  $view->result = array_reverse($view->result);
  dsm($view->result);
}

But that doesn't change the order of the nodes in the view ( putting a dsm($view); in the if statement ensures me that it is this view that is called. )


texts: Static image management module for Drupal 7

texts:
I want to display a couple of static images on my Drupal 7 site. I could store them in a specific directory I could create in my theme directory (for example).

However, I was wondering whether there was a module to load such images and let Drupal deal with these. I know it is possible to create image fields, but this is (IMHO) overkill compared to a specific directory solution.

Does such module exist? I can't find any. Thanks.


texts: Attach files uploaded with the contact form to mail

texts:
By default uploaded files in a contact form are uploaded to the server and a link is placed in the mail send to the recipients.

Is there a way to attach the uploaded files to the mail itself rather than/in addition to uploading them to the server?


texts: Question about AuthorizeNet ARB functionality with UC Recurring Module

texts:
I am confused about how the AuthorizeNet ARB functionality is supposed to work in Ubercart 2, and am hopeful that someone here has experience with AuthNet ARB recurring orders. I have the UC Recurring Payments and Subscriptions module and my AuthNet gateway set up. I created a recurring test order, and the recurring information is being displayed properly in my AuthorizeNet account. Last night, the first recurring charge took place, and I see that charge in my AuthorizeNet account, but it did not create any new order or any other message within my Ubercart account. The Recurring Fees screen for the order in question still shows that it has all of its recurring charges remaining. I ran cron, but that did not update anything.

The only thing I did not do in my AuthorizeNet gateway setup in Ubercart is the "Log reported ARB payments in watchdog." setting... I do not have that setting enabled, and I did not add the url to the Silent POST URL setting in AuthorizeNet. Is that what I'm missing? Or does it sound like there is something else missing?

Thanks!


texts:
I want in add content have a link(or button) when user click on lt the popup (modal or any popuping method like dialog,modal,lightbox,colorbox ) will open, in that form I want have some field, like hierarchical select and long text fields, after user submit that form, the submitted values passed back to add content form,

appreciate any idea


texts: Is it possible to use Devel to create a "mad libs" style profile2 registration page?

texts: I've got the template file working, however <?php dpm($page); ?> and <?php dpm($content); ?> aren't getting me what I need to isolate the forms. I saw this post https://stackoverflow.com/questions/4812949/how-would-you-approach-creating-a-mad-libs-style-form-in-drupal but it's a little over my head.


texts: Immediately check if field content already exists in a node form

texts:
I am struggling with a problem which I thought might be answered simply... Any help would be appreciated!

I have a content type called 'review'. Each review has a field called 'location'. As a user creates a new review, once they have filled in the location field, I would like a small message to appear in case that same user has already created a review for the same location.

Doing it when the user is about to save the node is not too complicated. But I actually want it to happen as soon as the relevant field is not empty.

Thanks


texts: Entity reference field pointing to a Configuration Entity

texts:
I develop a custom statistics module to log all node views of a chosen bundles, file downloads and the keywords used to filter a view.

Then I build my Entity Log with a user reference (who does the action), a node reference and a file reference. I want to know if I can make a views reference to point the View (as a configuration entity) that the user searched for some keyword.

I don't know if this is crazy... Is it possible to reference a view from an entity?

I'm using drupal 8


texts: How to attache multiple nodes of a node type to another node of another node type?

texts:
Currently I am making a advertisement website for restaurants. Now I am putting the restaurant basic information (name, address,etc) in a node.

What I want to do is making a menu list for the restaurant,
Say each menu item is a node (with the type of 'item') while the restaurant is another node type 'restaurant'.

In database level, the relationship between node (restaurant) and menu item node type is one-to-many.

So how can I do this?

Thanks for any help!

Cheers!


texts: How to use other properties in hook_entity_property_info_alter()

texts:
I want to extend the entity properties of OG-Membership to use it as a token in rules.

It works fine adding the property (for example the string 'test' as returned in the getter_callback is printed in a reaction rule (sending email)).
But I could not find out, or how to debug/access, the other properties present in OG-Membership in the rules context. To put it differently:

How can I access the group id ($gid) of the OG-Membership in my getter callback?

This works well:

function mymodule_entity_property_info_alter(&$info){
  $properties = &$info['og_membership']['properties'];

  $properties['og_custom_property'] = array(
    'label' => t('My custom Label'),
    'type' => 'test',
    'description' => t('OG Membership Custom Property.'),
    'getter callback' => 'mymodule_callback'
    );
  return $info;
}

But here I cannot access the $gid, or anything, for that matter:

function mymodule_callback(){
  //do some stuff with the $gid and $etid of the OG-Membership
}

Any help is appreciated; maybe someone knows how to debug the in rules available properties?
Thanks.


texts: How do I add fields and hide them from client?

texts:
I added fields to a Client profile using Profile2, such as first name and last name. But I added another fields, let's call it "Assigned Consultant".

But the "Assigned Consultant" field...

I don't want it to be available on registration
I don't want it to be available on the Client view user profile page
I don't want it to be available on the Client edit user profile page

I just want the "Assigned Consultant" field to be available to Administrator users.

How can I do that?


texts:
I have content Type "School", that has title, some term reference fields (geographic region,for example).
A School can has one or more (multiple) Clusters

Cluster is another content type that is being referenced from the School content type.

Each cluster has
  type (1 to 4)
  year (2011 till 2014)
  checkbox fields (yes, no)

What would be the best way to structure the data if I want to setup the filters with search/facets api, so that I can filter on Cluster's "year", checkboxes,as well as the School georegion.

Thanks in advance !.


texts:
Is it possible to get the title of the currently active secondary tab?

I'd like to re-use the the title of this tab later on in the content.  I found menu_local_tasks(1) which comes close, but this returns full themed output.  I just want the title as I've defined it in hook_menu().

Edit:
My hook_menu structure (trimmed to just the elements in ,not including sibling elements):

$items['events/%node'] = array(
    'title' => 'Events',
    'page callback' => 'page_events',
    'page arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
);

$items['events/%node/stats'] = array(
  'title' => 'Stats',
  'access callback' => TRUE,
  'page callback' => 'page_stats',
  'page arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 3,
);

$items['events/%node/stats/year'] = array(
  'title' => 'This Year',
  'access callback' => TRUE,
  'type' => MENU_DEFAULT_LOCAL_TASK,
  'weight' => 0,
);

$items['events/%node/stats/lastyear'] = array(
  'title' => 'Last Year',
  'access callback' => TRUE,
  'page callback' => 'page_stats',
  'page arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 1,
);

For example, when at the page events/%node/stats/year, I'd like to get 'This Year'.


texts: how to setup cron to run everytime when new file is generated in drupal files folder

texts:
I created webform and saving submitted data into text file in drupal files folder. A remote script performs calculations and outputs new text file  to the same folder . I want cron to run everytime text file is generated, so that i can print result from text file to webform and also save them to database

So far i created custom module for webform and used hook_cron() as shown below

function simulation_ignition_view_cron()
 {
  $uri = 'default/files/simulation/generatedfile.txt';
  if (file_exists($uri)) {
  drupal_set_message("hello cron");
 }
}

Please let me know if my explanation is not clear and please give some suggestions


texts: Add class to Menu Block UL unique to each Menu Block instance?

texts:
I've seen lots of answers, but they only allow you to add classes to all Menu Blocks, or to specific Menus.

I have multiple menu blocks with the same menu behind them (1st level block, 2nd level block, etc.)

I need each menu block to have a unique class based upon the name of the Menu Block. Is this possible?


texts:
I have multiple OG groups where a person posts within the group and the group is private. I need to have a field on each node that shows the serial/count/id of that node within its group.

Example:

Group A:

nid=1 & post_id=1

nid=2 & post_id=2

nid=4 & post_id=3 --node 3 was created in group B, but post_id is only for group A.

Group B:

nid=3 & post_id=1 -- This is the 3rd node created on the site but the first in group B.

How do I display/create a value like post_id in a node template file? Can this be done through Rules when creating a node, or calculated on the fly within the template file?


texts:
I have a site that is accessible both through http and https. I see  the security review complains that base_url is not defined in settings.php.

However when I define it as http://example.com, and flush all caches, my template in https is not rendered.

When I comment out the $base_url line in settings.php everything comes back to normal.

How can I resolve this problem?


texts: Requirements issues while setting up a D7 website

texts:
I'm trying to set up an old D7 website, but I stumble upon some issues.

As you can see in the image below, I work with PHP 5.4.8 and Apache 4.2.3.

I don't use things like XAMPP. I've configured Apache, MySQL and PHP myself on my Windows 7 machine.

In my php.ini-file I've enabled all the necessary extensions I believe...:

extension=php_bz2.dll
extension=php_curl.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_imap.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_openssl.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll

But still, I get the errors above. What should I do next?


texts: How do I enable a REST resource for a custom content type?

texts:
I've created a bunch of custom content types like "Car Makes" and "Car Models", but I can't seem to figure out how to enable a REST resource for them. In my REST settings page, I see the default content, content type, user, user registration enabled and a lot of disabled types below it. This list doesn't contain any of my custom created types.

If I go to the permissions page, under "RESTful Web Services", I only see "Administer REST resource configuration" and "Access POST on User registration resource". How can I enable "Car Makes" as a REST resource and directly GET/POST with it?

I saw this screenshot, but I don't get anything like this in Drupal 8.4:

In this screenshot, Todo is a custom resource, which requires writing a plugin. Do I have to write a plugin module just to expose each of my custom content types in REST?

I can work directly with the content endpoints, i.e. POST /node/123, but I would like to POST /carmakes, for example.


texts: how to fetch user related tables from live sever with drush sql-sync

texts: If you have a live server where some people have registered to your iste and you push new content from your dev,server regularly. What is the best workflow to fetch user related data from the server before you sql-sync and r sync an updated site to the live server with drush?


texts:
Is there any module for drupal 6 I can use to create a rotating banner with no images for drupal 6 site

Thanks

Colin


texts: Mixing pre-created content type blocks on the same page?

texts:
I'm trying to figure out if something like this is possible in Drupal:

The general idea is creation of a free-form content page where I could mix and edit several pre-created content "blocks"
I would pre-create several custom content types (for example, a content type with fields for an image and a line of text; and another content type with fields for two images)
then want to be able to create a new content where I would add these pre-created content types to build free-form structures out of them, basically, creating a matrix of content where each individual block would consist of fixed fields, and where there blocks can be mixed in any number or order.

For those who might by familiar with CraftCMS, their Matrix functionality is exactly what I'm trying to figure out if it's possible to replicate in Drupal.

At a minimum, just a knowledge of possibility/viability of this approach is fine. But if someone could point to into the right direction for further research, that would be appreciated.


texts:
Solution: Ayesh K provides the correct answer below.

What is required to get a custom module to appear in uninstall list?  I thought all you had to do was specify a database schema in hook_schema(), but I've done so and my module does not appear in the uninstall list.  Currently my module consists of the following code in the .install file:

<?php

/**
 * Table schema definition for the Events Sponsors module.
 */
function event_sponsors_schema() {
    $schema['event_sponsors_sponsors'] = array(
        'description' => 'A collection of event sponsors.',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => "Unique ID for the sponsor.",
            ),
            'name' => array(
                'type' => 'varchar',
                'length' => '255',
                'not null' => TRUE,
                'description' => 'The name of the sponsor.',
            ),
        ),
        'primary key' => array('id'),
        'unique keys' => array(
            'id' => array('id'),
        ),
    );

    $schema['event_sponsors_sponsor_relations'] = array(
        'description' => 'Maintains sponsor and node relations.',
        'fields' => array(
            'sid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The sponsor ID, as can be found in the sponsors table.',
            ),
            'nid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The node ID as can be found in the node table.',
            ),
            'ordinal' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The order this sponsor appears alongside the node.',
            ),
        ),
        'primary keys' => array('sid','nid'),
        'unique keys' => array(
            'sid' => array('sid'),
            'nid' => array('nid'),
        ),
    );

    return $schema;
}

Any insight is appreciated.


texts: I believe there are many ways to achieve single sign-on within drupal. I would like to know the approach that *.drupal.org sites have been using. If I visit any drupalconf sites http://chicago2011.drupal.org/user or http://london2011.drupal.org/user it authenticates me with the user credentials given in drupal.org site. I would appreciate if anyone can point me to the modules or handbook pages on achieving this. Thanks in advance.


texts:
I would like to edit the way a basic article is structured.
For example, I want to place the title under the image followed by content and at last the date.
Already looked at Structure -> Content Types -> Article -> Manage fields, couldnt find anything about reordering those things.


texts: How to show pages other than nodes with the default language prefix

texts:
Content on our site exists in several languages. The default language is 'en'. Prefixes are shown in URLs, such as http://example.com/en/my/path or http://example.com/nl/my/path.

However, pages like the home page, and various views and custom pages, should not be localized -- they should show on the default language URLs, even if they list nodes in other languages.

The problem we face is that after somebody visits a page in non-default language, e.g. http://example.com/nl/my/path and they then go to the home page, the home page is on http://example.com/nl. This means that our the same non-node pages exist in several copies, each with only a different URL language prefix. Confusing for search engines, confusing for users, and heavy for the server (multiple page caching).

In other words, the home page and other non-nodes should always have the default language prefix, independently from the language of the previously visited page.
Can this be achieved elegantly (without having to write custom .htaccess redirects)?


texts: A table was not created by _schema() function

texts:
I added this function to cleanetica_advanced module and after this ran /update.php

function cleanetica_advanced_schema() {
  $schema['videos'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

But the table videos was not created.

What have I missed in order for the table to be created?

The module cleanetica_advanced is enabled and I checked that it really loads by inserting a nonsense (non-PHP) there and seeing that the site crashes with an error. (After this I removed the nonsense.)


texts: Removing Duplicates with hook_views_prerender

texts:
I have a view (filtering on content) that is returning duplicates. I am trying to used hook_view_prerender to remove those duplicates... but even after running this, I still get duplicates... Any ideas? Here's my function (and yes I know the function is running):

function customedm_views_pre_render(&$view) {
  $used_nids = array();
  if ($view->name == 'new_resources'){
    echo ('hi');
    foreach ($view->result as $row){
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
      }
    $view->result = $new_view_result;
    }
  }


texts: Linking to front page with current selected language

texts:
<?php print $base_path; ?> Links to the front page with default language, So If site's default language is set to A and a user has selected language B, this code redirects user to the front page with language A.

Is there away to link to front page while keeping the current selected language?


texts: How to set an AJAX callback for my drop down list select in my form?

texts:
I am about to create a filter views handler extended from views_handler_filter_string
(you can see the class under views/handlers), so I have to override my method value_form to create a new value form form my filter handler.

function value_form(&$form, &$form_state) {
    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['value']['country'])?$form_state['values']['value']['country']:key($countries);

    $values = array(
        'country' => array(
            '#type'    => 'select',
            '#title'   => t('Country'),
            '#options' =>$countries,
            '#ajax'    => array(
                'callback' => 'country_state_dependent_dropdown_callback',
                'wrapper'  => 'dropdown-states',
            ),
        ),
        'state' => array(
            '#type'    => 'select',
            '#title'   => t('State'),
            '#prefix' => '
',
            '#suffix' => '
',
            '#options' => _country_state_get_second_dropdown_options($selected_country),
        ),
    );
    $form['value'] = $values;
    return $form;
}

I am trying here to set an ajax callback for my drop down list select. Usually we implement our callback function and we return $form['element'], but in my case it gives no result.

Anyone who has tried to override the value_form before to add some AJAX able to help me resolve this issue?


texts: Json-Import of nodes with taxonomy terms

texts:
I'm running Drupal 8.3.6 and I try to import a json stream originating from typo3. It is essentially a list of blog posts in this format:

[{
    "id": "1",
    "title": "Title",
    "bodytext": "Bodytext with html Mark-Up",
    "datetime": "1269437640",
    "keywords": "term1, term2, term3, term4,..."
},{
    "id": "2",
    "title": "Title 2",
    "bodytext": "Another Bodytext with html Mark-Up",
    "keywords": "term6, term3, term9, term7,..."
}]

I came up with a small module following these instructions, which works well for the title and bodytext:

protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

However I'm struggling to get the terms created and referenced by the nodes. I tried something like this, but it doesn't work:

protected function createBlog(string $json) {
    $jsonout = json_decode($json, TRUE);

    foreach ($jsonout as $blog) {
      foreach ($blog['keywords'] as $tag) { // Loop through each blog entries keywords and create terms
        $term = Term::create(array(
          'name' => $tag,
          'vid' => 'tags',
        ))->save();
      }

      $node = Node::create(array(
        'type' => 'blog',
        'langcode' => 'de',
        'uid' => '1',
        'status' => 1,
        'title' => $blog['title'],
        'field_tags' => $blog['keywords'], // I would need to have the terms from above in an array to add them here, right?
        'body' => ['value' => $blog['bodytext'], 'format' => 'full_html'],
      ));

      $node->save();
    }
  }

The terms do not get created and if they would, I wouldn't know how to associate them with the nodes. Also if it would work, there would be the problem that on creation of the terms I do not check if a term already exists. This would be necessary because nodes can have the same terms.

Is it possible to achieve this with my approach? If yes, can you tell me how? I also looked in to migrate_plus but I find it quite complicated.

Any help would be appreciated!

Andi


texts: How to find the user avatar filename in Drupal 7

texts:
In my custom module for Drupal 7 I've been using the following 2 SQL queries to find the user's avatar picture and the city (a custom text field):

function pref_block_view($block_name = '') {
  global $user;
  $viewer_id = $user->uid;

  if ($block_name == 'pref_main') {

    $result = db_query('select field_city_value from {field_data_field_city} where entity_id=:uid', array(':uid' => array($viewer_id)));
    $city   = $result->fetchField();

    $result = db_query('select filename from {file_managed} where uid=:uid', array(':uid' => array($viewer_id)));
    $avatar = $result->fetchField();

and at first this worked well (probably because each user hat just 1 picture - namely the avatar).

But then users attached pictures to blogs and books and now this query doesn't really work:

 # select * from drupal_file_managed where uid=1;
 fid  | uid |           filename           |                      uri                       |  filemime  | filesize | status | timestamp
------+-----+------------------------------+------------------------------------------------+------------+----------+--------+------------
  631 |   1 | 111.png                      | public://111_0.png                             | image/png  |   289191 |      1 | 1303376737
  843 |   1 | etud18.png                   | public://etud18.png                            | image/png  |   893838 |      1 | 1305905585
  527 |   1 | yaro-3.jpg                   | public://yaro-3.jpg                            | image/jpeg |    89814 |      1 | 1302367745
  529 |   1 | yaro-4.jpg                   | public://yaro-4_0.jpg                          | image/jpeg |   122129 |      1 | 1302367789
  638 |   1 | etud015.jpg                  | public://etud015_0.jpg                         | image/jpeg |   116956 |      1 | 1303459359
  835 |   1 | pref.jpg                     | public://pref_0.jpg                            | image/jpeg |    95079 |      1 | 1305838610

So I'm obviously using wrong query. Any help please?


texts: How to call php snippet which is save as basic page?

texts:
I have a php code as below:

$("#tbMGroup tr.odd").click(function() {
              $("#m_id").val($(this).attr("m_id"));
              $("#form1").first().attr("action", "search.php");
              $("#form1").submit();
            });

but,
I have add search.php to a basic page. now, these code need to call search.php when mouse click, I don't know how to call search.php snippet, because search.php now is not a independent file, it is a snippet.
Thanks for your help...


texts: How to add a base field for an entity reference to a specific vocabulary

texts:
I have an Entity: EntityX.  It installs correctly and works the way that I want it to; with, of course, one exception.

I want to attach an entity reference to a specific vocabulary.  I have tried:

My vocabulary's machine name is: custom_vocabulary

In EntityX's definition I have the following defined in the baseFieldDefinitions function:

$fields['my_custom_vocabulary'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Vocabulary'))
  ->setDescription(t('What was this tagged with.'))
  ->setSetting('target_type', 'custom_vocabulary')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

But when I go to install it, I get the following error:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "custom_vocabulary" entity type does not exist. in /brew/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

While looking at the article defined in the installation profile for Drupal, I see that they use it as a field and not a true entity reference.  Is there no way for me to do it this way?  I can't have this all nicely bundled into one single entity.

What I don't know how to do is add a term from a vocabulary to an entity type.


texts: Adding a custom field that contains a few different field types

texts:
Trying to figure out how to create a custom field type that is a bundle of individual fields. I want to do this specific field in a native way.

At a minimum, each row needs to provide:

Entity Reference field (to User)
Text plain (for published name)
Formatted text (no summary need)

The field itself will be unlimited cardinality.

I initially built this as an extension of the EntityReferenceItem field, but now that I need to add the formatted text field (new requirement), this does not seem right anymore.

Is this a simple endeavor or should I just use Paragraphs? I wanted to go the native route because to change the storage now would mean a change in the way migration definitions are scripted to change how the data would be captured (by switching to Paragraphs) which I would like to avoid doing (means redoing work, tests, etc).

There will be a Solr search consideration here as well - and I would like these same UIDs to be facets. Would Paragraph on the node also support this?


texts:
I want to run 4 cron jobs inside Drupal, in four different times.

How can I achieve that? Is there any module for that?


texts:
I have a content type called college facilities. This displays ALL the college facilities that are added. I would like to create more content types called:

Services
Food
College Supplies
Other

I was wondering is it possible to create a drop down filter on the college facilities page so that if a user select all then all of them are displayed or Food then only food content types are displayed?

This is what I would like it to look like with ALL being pre selected.
Is this possible?
I apologize I am very new to drupal and Im using Drupal 7.


texts:
I have a node with ID equal to 60, which has a URL alias that is "mynodes/about-us." I would like to change the access callback of that node to myfunction().

It doesn't work when I use the URL alias:

function celsis_forms_menu_alter(&$items) {
    $items['mynodes/about-us']['access callback'] = myfunction;
}

function myfunction() {
     return FALSE;
}

But it works when I use the node number:

$items['node/60']['access callback'] = myfunction;

How can I get the url alias to work and would it be possible to change the access callback for all nodes with alias starting with mynodes/*?


texts:
I own a lightweight blog hosted on GoDaddy. I could not get cron to automatically run, so I manually run it when necessary.

How should I configure cron tasks to make them automatically run on GoDaddy?


texts: Drush command with Url::fromRoute PHP Fatal error: Allowed memory size of

texts:
If i create a custom drush command than run a method than exec a loop than 2000 items. For each item i call a Url::fromRoute method:

$url = Url::fromRoute('route.custom',
      [ 't' => 'text,
      ['language' => $language])
      ->toString();

The drush command finish successfully but i have always this error:

PHP Fatal error:  Allowed memory size of 536870912 bytes exhausted (tried to allocate 31457312 bytes) in /var/www/html/sitename/prod/vendor/drush/drush/includes/backend.inc on line 466

(this error is caused from Url::fromRoute becouse i had try remove this and don't had a error)

(i can't make a batch, this command is necessary in loop)


texts: Connect to remote DB using global php drupal 7 views

texts:
I am using Views PHP module for custom coding in views.

I tried using mysql_connect function to connect to a remote database using the "GLOBAL PHP" field and get some data through custom coding. Is it safe to connect to database through the "GLOBAL PHP" field? Or are there any security risks?


texts: How to add the Quantity field to Entity Reference views

texts:
There is a problem with adding the "Quantity" field in views to Entity Reference.

When you add the Commerce Product:Quantity input field (from module Commerce Extra) - the field is added, but empty inside (in the back comment "form-item-add_to_cart_quantity--0", wrapped in span, and in the front is empty.

Need to "toppings" is not only mentioned, but also had the opportunity to change their quantity.


texts: How can I add a tab to the admin/content page

texts:
I'm new to drupal, so sorry if this is a stupid question.

While developing a module, is it possible to add a tab to the /admin/content page (where by default there is content, comments, files)

Currently using 8.0.6


texts: Change weight of CSS file loaded in custom module with #attached?

texts:
Im working on a custom module which loads a CSS file:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
);

How can I change the weight of the file so that its loaded after the other CSS files? I thought it would be something like this:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  'weight' => 1000,
);

Or this:

$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  '#weight' => 1000,
);


texts: Feature gate custom module from sites/all in Drupal 7 multisite

texts:
I am working on a legacy drupal 7 multisite and want to see if I can "feature gate" a module in sites/all/custom instead of loading it per individual site. For example, lets say I have 5 sites in my Multi site:

SiteA

SiteB

SiteC

SiteD

SiteE

right now a custom module lets call my_custom_module resides in the modules/custom dir of Sites A-D but not E. For reasons I won't go into, the powers that be want to move my_custom_module out of the other sites and into sites/all/modules/custom and only have it work, again, on Sites A-D but not E. I have thought about doing some fancy feature gating by setting a variable called use-my-custom-module in A-D but not E and then checking for it via:

if(variable_get('use-my-custom-module', FALSE) === TRUE) {
  // use some function
}

but that seems an awfully un Drupal and clunky way of doing things. Is there a more Drupally and non clunky way of getting at this? Or should I tell Powers That Be not to try this. Again, "Reason not the need..." here, its a weird rabbit hole to go down. I just want to back up my assumed "no" answer.


texts: Migrate with Cloud Files fopen:Too many open files

texts:
I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

  (/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608)
  Invalid response: (curl error: 35) error:02001018:system
  library:fopen:Too many open files: Failed [error] to obtain valid HTTP
  response.

What is causing the problem?


texts:
I'm really stuck on a problem that I'm seeking assistance on. I currently have 3 content-types (Article, Photo and Video) and all of them use the same Taxonomy Vocab I've called Category. I've configured the PathAuto module:

for Category terms: [term:name] --> CCK Field created and shared across content-types called: field_category
for Articles: [node:field_category]/articles/[node:title]
for Photos: [node:field_category]/photos/[node:title]
for Videos: [node:field_category]/videos/[node:title]

The problem I'm experiencing is having to create a dynamic View page for each term. Basically, if from the root I navigate to a particular category (eg: /politics), I expect to see a page with all content under that term, plus allow me to then filter by content-type.

Similarly, if I navigate to articles under a particular category (eg: /politics/photos), I expect to see a page showing me all photos under that category.

I don't know if I've chosen a very elaborate (and unnecessary!) organisation of content, but this makes sense to me. I'm probably going to kick myself, for I feel that there is a simple solution to this! This is my first time using Views-3 UI, having only minor experience with Views-2 in D6. I'm currently using Views 7x-3.5.

I thank you much in advance for any assistance you can provide!

EDIT: I'm going through whatever online documentation I can find for Views-3, and so far it's quite overwhelming. I do know that I need to use contextual filters and view page paths with %.


texts:
I am very new to Drupal and is still learning. Please excuse if I have done my coding wrong.

Problem:
I wanted to add two buttons to my Content type.

1st button for Save Form - save the form and not publish it.
2nd button to Submit Form - save the form and submit it.

My Save Form button works right and it uses the default submit handler.

My Submit Form button is calling a custom submit handler and here is the code:

  function submit_Form(array $form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $node = entity_create('node',$values);
  $node->save();

  drupal_set_message('Your form has been submitted. It will be reviewed by the team.');
  $redirect_path = "/user";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);

}

I am getting this error:

  Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type node in Drupal\Core\Entity\ContentEntityStorageBase->doCreate() (line 83 of /var/www/clients/client1/web2/web/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php).

Thank you for looking at this.


texts: Disable click event on Next button on checkout form's first step if all cart products are removed

texts:
I am new to learning jQuery and JavaScript. I have small task that is becoming hard to solve.

On step one of a checkout form #ps-cart-checkout-form, I have to disable
Next
 when cart table is empty or emptied by clicking an "X" image in cart table row So that user does not go forward. Button's location and HTML is:

Side 1/2

Next

Cart table (.table-cart) when having one or more products it contains
 tag but when empty the
 becomes
 with one row  in it.

My approach:

I have tried to create a module that add js on hook_form_alter. and in js file. I have created :

(function ($) {
Drupal.behaviors.myModule = {
  attach: function (context, settings) {
      var $form = $("#cart-checkout-form");
      if($($form.find("thead").lenght == 0) {
        $(".button").unbind( "click" );
        }

      });
   }
}(jQuery));

With above code I am trying to find out if there is no
 that means table is empty and therefore above code should disable the click next button.
There already having a jQuery code that handles click event on Next div.


texts: Do not import configurations if already exists

texts:
I have built a custom module and there are two configuration files in config/install directory of my module. When the module is installed the configurations are installed correctly.
When I uninstall the module and try to reinstall it, I get the error that that the `

  fields already exist in the database

These fields are defined in the configuration files and I want that they should be installed only if they not exist.

`


texts: hook_views_query_alter if date field empty sort with another field postdate

texts:
I have a view that show all contents of type NEWS
NEWS has like fields :

Content = Title

Scheduler = publish-on

and in sort criteria : I want sort contents with two option :
With scheduler (publish-on = DESC)
and With post date

I want sort content with scheduler, and when scheduler field is empty he sort with post date. I have created hook views query alter
and I have a problem, how can I sort field with condition if publish_on is empty then sort with postdate

function custom_sort_views_query_alter(&$view, &$query) {

    if($view->name === 'articleview') {
        $view->query->add_where(1,'publish_on',  'NOT IN');
        $view->query->orderby[0]['field'] = "CASE WHEN publish_on IS NULL THEN created ELSE publish_on END";
        $view->query->orderby[0]['direction'] = "DESC";
        $view->query->orderby[1]['field'] = "created";
        $view->query->orderby[1]['direction'] = "DESC";
    }
}


texts: Views slideshow overlapping right hand sidebar block

texts:
I'm using the default bartik theme and have created a views slideshow.  I have a url for this and have marked this as the front page under the admin section.  All great so far, in that when the (unauthenticated) user first visits the site they see the slideshow.  Once they log in, I have a block that appears in the right hand side sidebar.  However, the width of my slideshow is too wide in that it appears overlapped with this block on the right.  What is the best way to address this?  I could fix the width of the slideshow, but then that means I loose the flexibility to easily change the theme.

Also, can anyone point me to documentation that would help me understand why this happens?

Thanks in advance,


texts:
I have a couple of drupal sites running from the same host, using apache vhosts to do domain name forwarding.

I have many domains/url's dns entries pointing to this server's ip address, some of which are not currently live websites (they fail/default over to my main website).

When a user registers on one of the sites, or the site sends me an email alert, it includes a link at the bottom of the email where I can click and view the user account, etc.

The problem is, it seems the domain/url in the link changes randomly, and is not always the domain/url of the actual site it's from. They are all domains I own and are pointing at the box, so it's like drupal does a DNS lookup on itself, then uses one of the returned domains to include in the email instead of the sitename set in the settings.

How can I fix this so emails will include a link to the proper domain they originated from?


texts: How to assign a product to particular user in drupal commerce programmatically?

texts:
I am using drupal commerce in my site I need to assign a product programatically to user for this I am using this code.

$selpro = product id.
$line_item = commerce_product_line_item_new(commerce_product_load($selpro));
commerce_cart_product_add($user->uid, $line_item);

But this code is not working for me.


texts:
I've got a content type called PartyGuest. That content type has an entity reference field for "Primary Guest", so if I'm inviting Bob and Jane to the party, Bob and Jane are both content nodes but I only want to send one invitation so I make Bob's "Primary Guest" value equal to Jane. That way I know that Bob should be included on Jane's invitation.

When I'm looking at Jane's node (or editing Jane's node), I would like to be able to see a list of everyone else who is on Jane's invitation.

I've created a View Block with a contextual filter so that it lists the names of all other PartyGuests where the Primary Guest is equal to the contextual filter value. That part works... sort of.

61 is Jane's nid. If I type "61" into the "Preview with Contextual Filters" box, then my results are exactly what I expect. It shows Bob in the list. However, if I change the Preview with Contextual Filters value to by "node/61" or "node/61/edit", then I get no results at all.

How do I make my context filter grab the value from the url?

I've set the Contextual Filter to provide a Default value and to pull it from the 2nd URL path component, but it doesn't seem to work. Even when I have it set this way, it only works if I put "61" into the Preview box, but does not work if I put "node/61" into the preview box.

I've also tried setting the Default value to be the Content Id from the URL with no luck.

What am I missing?


texts: How to set up drush on Cloudways / Digital Ocean?

texts:
I have been experimenting with Cloudways and Digital Ocean as a hosting solution.

I am attempting to set up Drush and have been following some instructions provided by GoDaddy.

The notes appear up to date and well written - See https://uk.godaddy.com/help/how-to-install-drush-on-cpanel-shared-hosting-12396 . I am not using cPanel but I do not think this should matter.

When entering

echo "alias drush='~/drush/drush'" >> .bashrc

The system returns

echo "alias drush='~/drush/drush'" >> .bashrc
bash: .bashrc: Permission denied

The same also happens with sudo

After continuing with rest of the instructions Drush is now installed but does not seem to be available for the public_html directory. I'm guessing that the GoDaddy instructions are missing a step or are not quite compatible with this environment.

I have provided an example of a Features download (below) and as can be seen, the download is being placed in the drush directory and not sites/all/modules

[master_vkhgjqkyfv]:public_html$ drush dl features
Project features (7.x-2.8) downloaded to /home/master/.drush/features.

Can anybody say what I need to do to get this working properley?


texts: How can I prevent a form from being displayed in the privatemsg module?

texts:
I am trying to remove the "Block a user" fieldset, username text and input field, and "Block user" button from the "Blocked users" page as shown below.

The code I'm trying to change is in the pm_block_user module:

/**
 * Formbuilder function to build a simple form to block users.
 */
function pm_block_user_list() {
  global $user;
  $form['new'] = array(
    '#type'   => 'fieldset',
    '#title'  => t('Block a user'),
  );
  $form['new']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#autocomplete_path' => 'messages/user/autocomplete',
    '#description'        => t('Separate multiple names with commas.'),
    '#required'          => TRUE,
  );
  $form['new']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Block user'),
    '#validate' => array('pm_block_user_block_validate'),
    '#submit' => array('pm_block_user_block_submit'),
  );

  $header = array(
    array(
      'data' => t('Username'),
      'field' => 'u.name',
      'sort'  => 'asc',
      ),
    array(
      'data' => t('Operations'),
      ),
  );

  $select = db_select('pm_block_user', 'pmb')->extend('PagerDefault')->extend('TableSort')
    ->fields('pmb', array('author'))
    ->condition('pmb.recipient', $user->uid)
    ->limit(20)
    ->orderByHeader($header);

  // Only show existing users, therefore join users.
  $select->innerJoin('users', 'u', 'u.uid = pmb.author');

  $rows = array();
  foreach ($select->execute() as $row) {
    $rows[] = array(
      theme('username', array('account' => user_load($row->author))),
      l(t('unblock'), 'messages/block/' . $row->author, array('query' => drupal_get_destination())),
    );
  }
  $form['#header'] = $header;
  $form['#rows'] = $rows;
  return $form;
}

Here is the code I tried in my template.php based on these instructions for removing unwanted elements from forms:

function MYMODULE_pm_block_user_list($form) {
  unset($form['new']['#title']);
  unset($form['new']['#type']);
  return drupal_render($form);
}

However, this code hides the "Username/Tom/Operations/unblock" section, not the "Block a user" section which I am trying to hide.


texts: Print success message only if field is altered

texts:
I have created a checkbox in user edit using form alter and based checkbox state I want to print the message. For this I used below code

function module_form_user_profile_form_alter(&$form, &$form_state) {

  $form['account']['checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => 'Test check',
   );
   $form['#submit'][] = 'module_simplenews_unsubscribe';
}

//~ //Submit handler for Subscribe/unsubscribe newsletter.
function module_simplenews_unsubscribe($form, &$form_state) {

  if ($form['account']['checkbox']['#value'] == 0) {
    drupal_set_message(t("You are checked"));
  }
 if ($form['account']['checkbox']['#value'] == 1) {

    drupal_set_message(t("You are unchecked"));
  }
}

It works fine. When a checkbox is checked/unchecked and user saves the profile it prints respective message. But when user doesn't modify this checkbox field and modifies some other field and saves, again it prints message based on checkbox state.

I want to display the message only when checkbox field is modified. How can I achieve this?

I have tried this https://drupal.stackexchange.com/a/180079/50991 but not working.


texts: Array $field_instance is occassionally empty

texts:
I am trying to determine why, on certain nodes, my address fields are not geocoded to my geofield. I think I have it tracked down to this part of geocoder.widget.inc (line 347).

function geocoder_widget_get_entity_field_value($entity_type, $field_instance, $entity) {
    $field_name = is_array($field_instance['widget']['settings']['geocoder_field']) ? reset($field_instance['widget']['settings']['geocoder_field']) : $field_instance['widget']['settings']['geocoder_field'];

If I add dpm($field_instance), on one node update, it will show me that array. On a different node update, there is no devel message (i.e. no array). Both nodes have addresses.

The problem is, I cannot figure out why one would be blank while the other would not be.


texts: Uploading image to a node via Angular to Drupal 8 using REST

texts:
I have figured out how to upload files from Angular to Drupal 8

......
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id; // the file ID of the newly created file entity.
  });
},
......

My question is, what if I have a content type that has an image field in it? Specifically, my content type is of type community and contains a field called field_banner_image. Below is what I have now, however, it produces 422 Unprocessable entity with a response of:

{"error":"Unprocessable Entity: validation failed. field_banner_image: This value should not be null."}

field_banner_image is required hence the error, but I have no idea what field_banner_image expects me to send it.

.....
submitCommunity: function(params) {
  var package = {
    "_links":{"type":{"href":"http://dang.dev:8888/rest/type/file/file"}},
    "filename":[{"value":Math.round((Math.random()*1000)).toString() + '.jpg'}],
    "filemime":[{"value":"image/jpeg"}],
    "data":[{"value":params.bannerImage}] //params.bannerImage = B64 encoded string of the image
  };
  $http.post('http://dang.dev:8888/entity/file', package, config).then(function(response) {
    var fileId = response.headers().id;
    package = {
      _links: {'type':{'href':'http://dang.dev:8888/rest/type/node/community'}},
      type: [{'target_id': 'community'}],
      title: [{'value': params.title}],
      body: [{'value': params.body}],
      field_banner_image:[{'value': fileId}]
    }
    return $http.post('http://dang.dev:8888/entity/node?_format=hal_json', package, config);
  });
},
.....

I've tried field_banner_image:[{'fid': fileId}] and some other combos of key values, but I think I am attacking this wrong. Documentation on this is kind of sparse right now and a lot of it is old D8 beta stuff. Any Ideas?


texts: is there a safe way to convert a pressflow website to drupal 6?

texts:
I have a website that was built on Pressflow, and the client wants to upgrade it to Drupal 7.

Is there a way to convert Pressflow to Drupal 6?


texts: Why does Drupal run slow on localhost wamp?

texts:
I'm using an i3 8GB RAM computer and Drupal is as slow as like using some cheap hosting provider.

So what could it be? I am using a freshly installed version of D7 and just browsing through site, going to Reports takes some time and I am not even talking about clearing cache or running cron.

Also using Drush via Git Bash also runs commands slow, like simply 'drush dl libraries' and then enabling it takes like 10 seconds and I am on 100MBit line.

I did some changes to php.ini file like memory_limit = 2G and etc. but it's as slow as if it was 128M.


texts: my module template_preprocess is not called

texts:
I can't figure out how to correctly implement the theme mechanism in my module. The hook just doesn't get called, after flushing registry ofc.

My mymodule.module contains a function (this function gets called, no problem, I give it just for illustration):

function mymodule_node_view($node, $view_mode) {
  ...
  $node->content['mymodule_tocteasers'] = array(
    '#markup' => theme('tocteasers', array('tocteasers' =>  "whatever")),
  );
}

As I understand the theme mechanism, in order to render tocteasers hook, the module should implement it. Here is my module's implementation, which is not called at all, ever:

function template_preprocess_tocteasers(&$variables) {
  $variables['content'] = "something!!!";
  dsm($variables); print "hello";
}

^^I also tried function mymodule_preprocess_tocteasers(&$variables) without success

In addition, I have a file named tocteasers.tpl.php in my module directory, containing:

<div>
  <?php print "!!"; ?>
  <?php print $content; ?>
</div>

This also does not get printed or called.

Can someone plese advise me, how to make this implementation so that the tocteasers.tpl.php file is used and gets the $content variable as intended?


texts:
I want to create a new image field output to make it work with my lazy load script. For this I want the output to look like:
<img data-src="/sites/default/files/styles/lazy_load/image.jpg" src="/sites/default/files/styles/placholder/image.jpg" width="110" height"300" class="lazy">

To fix this I have this code:
function hook_preprocess_image(&$variables) {
    if ($variables['style_name'] == 'lazy_load') {
        /* @    -- Change src and add data-src */
        $datasrc = $variables['attributes']['src'];
        $src = str_replace('styles/lazy_load','styles/placeholder',$datasrc);
        $variables['attributes']['src'] = $src;
        $variables['attributes']['data-src'] = $datasrc;
        $variables['attributes']['class'][] = 'lazy';
    }
}

This does what I want but...the image with the placeholder image_style is not rendered so it can not be found.
I also tried getting the right url via:
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('placeholder');
$url = $style->buildUrl($variables['uri']);

This again did give me the right URL but still the image is not rendered. How can I solve this problem?
Update
I tried using the hook_preprocess_image_style like thfunction
hook_lazyload_preprocess_image_style(&$variables) {
    if ($variables['style_name'] == 'lazy_load') {
        // The image.factory service will check if our image is valid.
        $image = \Drupal::service('image.factory')->get($variables['uri']);
        if ($image->isValid()) {
            $logo_render_array = [
                '#theme' => 'image_style',
                '#width' => $image->getWidth(),
                '#height' => $image->getHeight(),
                '#style_name' => 'placeholder',
                '#uri' => $variables['uri'],
            ];
        }
    }
}

But still no succes. What I'm I missing here?
Thanks in advance


texts: Strange Page not Found, Permissions, Clear cache

texts:
On my D7.80 I have developed a custom module:
    function wrong_answer_menu() {
    dd('it entered in hook menu');
  $items['wrong-answer/%id'] = array(
    'title' => t('Wrong Answer Dashboard'),
    'page callback' => 'wrong_answer_dashboard',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Callback: hook_menu.
 */
function wrong_answer_dashboard($node_param=NULL) {
dd('it entered in dashboard');
....
}

Everything was fine, I was developing the menu nicely accessing the
mydomain.com/wrong-answer
and everything was fine.
Then I wanted to add permissions to my custom module, so that only the admin can access this page hence I added the wrong_answer_permission function and in the dashboard function I checked if the user had permission to access the page
/**
 * Implements hook_permission().
 */
function wrong_answer_permission() {
  return array(
    'wrong_answer_' => array(
      'title' => t('View the wrong answer'),
    ),
  );
}

    function wrong_answer_dashboard($node_param=NULL) {
     dd('it entered in dashboard');
     if (!user_access('wrong_answer_admin')) {
      return;
     }
    ....
    }

At this stage, when I accessed the page mydomain.com/wrong-answer I could still access it even though I did not assign the permission to it. Then I cleared the cache from the Performance menu via the admin/config/development/performance, and then I got the error message
The requested page "/wrong-answer/717" could not be found.

I get the same error for acessing just mydomain.com/wrong-answer.
Then I thought it was all fine, I added the permission wrong_answer_admin to the admin role, but then I still got the same error "The requested page .... could not be found.
Afterwards, I:

cleared the cached
removed the code that I had added on the permission and checking the user access
rebuild the registry_file by emptying the table and running the update.php
assigned the permission to the wrong_answer_admin to all the roles, including anonymous role
deleted the wrong_answer_admin row in the permissions table in the database
disabled and re-enabled by custom module

but nothing worked, I still get the error "The requested page cannot be found".
Then I noticed the strangest thing, that whenever I would clear the cache at, I would would get an entry in the drupal_debug.txt
it entered in hook menu

I do not get this entry in the drupal_debug.txt when accessing the wrong-answer page, I only get it when clearing the cache.
Could you please help me understand what is going on? why can't I access the wrong-answer page anymore?
Many thanks


texts: How is a form rebuild if it fails validation?

texts:
I wondering how it is rebuild if validation fails.

Say you have several inputs. Change them all and submit. A certain rule isnt validated so the form validation fails (with a form_set_error).

What is the process to redisplay the form ?

Im struggling with input/validation erros and from what I've seen, it doesn't rebuild, even if I would use REBUILD=TRUE


texts: Creating a View feed: Do not summarize, but show whole post

texts:
I've created a feed in a view, and it seems to automatically summarize the info. I'd like the entire post to be available.

How do I go about doing that?


texts: how to change the url based on region and language selection in drupal 7

texts:
I have five different regions and five different language. When loading my site url like
domainname/regionname/langname .When user change the language or region url will be  change selected region name or language.how can i done this drupal?


texts: Find target bundle(s) for a specific entityreference field

texts:
I am creating a simple administration page that shows all content types and some details about each content type field.

I am getting the list of content types with node_type_get_types()
I am getting the list of fields with field_info_instances()

When the widget module is entityreference I'd like to display the target bundle(s) of that entity reference field.

foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
    }
  }
}

Thanks in advance for any help on that!


texts: db_insert() execute() without auto_increment primary key is returning 0

texts:
I'm trying to determine whether a database insert query was successful or not by checking the return value of execute(), but it seems to be returning 0 even though I can see the data has been inserted into the database. The table I'm adding data to has a primary key but it's not set to auto increment.

$result = db_insert('my_table')
                    ->fields(array(
                      'user_id' => $user_id,
                      'my_value' => $num,
                    ))
                    ->execute();
print_r($result); //Prints 0, even when successful

How can I check to see if the db_insert() was successful or not if I'm not using an auto increment primary key?

Many thanks


texts: Deleted content type shows in the "Add content" menu

texts:
I had some content types I wanted to delete so I went to Structure >> Content types. I deleted the content types that I didn't want to have anymore, and I cleared all the cache through drush and performance.

I also went to my database and look through to double check if they were deleted, and I found they were deleted correctly.

I have also restarted my MAMP local server.

The problem is that the deleted content types appears on "Add content" but they are not clickable. I don't want them to appear there. why does this happen?


texts: If I add more than 15 checkboxes element in a field my form stops working

texts:
I'm building a form and I need to include a 'checkboxes' field.

This is my code:

$form['page-options-' . $nid]['mondi-' . $nid] = array(
    '#title' => 'Mondi Azzurra',
    '#description' => 'Seleziona i mondi azzurra di interesse',
    '#type' => 'checkboxes',
    '#options' => $mondi
  );
}

The $form['page-options-' . $nid] field is a simple fieldset.

For some reason if I sobstitute this

'#options' => $mondi

with

'#options' => array_slice($mondi, 0, 15)

limiting the array to 15 elements it works but if I set it 25 stop working again..

Changin field type from checkcboxes to select [with #multiple attribute set to true] the form works.

This is my hook_form_submit()

function adv_sumbission_form_submit($form, &$form_state) {
  dsm($form_state);

  drupal_set_message('The form is submitted');
}

and this is all my hook_form()

function adv_sumbission_form($form, $form_state) {

  $form['pages'] = array(
    '#type' => 'fieldset',
    '#title' => t('Pagine'),
    '#weight' => 1
  );

  $nodes = node_load_multiple(array(), array('type' => 'pagine_adv'));
    foreach($nodes as $nid => $value){

      $form['pages']['page-' . $nid] = array(
        '#title' => $value->title,
        '#type' => 'checkbox'
      );

      $form['page-options-' . $nid] = array(
        '#type' => 'fieldset',
        '#states' => array(
        'visible' => array(
           ':input[name="page-' . $nid.'"]' => array('checked' => TRUE)
         ),),
        '#attributes' =>  array('class' => array('page-options'))
      );

      if( isset($value->field_mondi_azzurra[LANGUAGE_NONE])
        && count($value->field_mondi_azzurra[LANGUAGE_NONE]) > 1 ) {
      $mondi = array();

      foreach($value->field_mondi_azzurra[LANGUAGE_NONE] as $mondo){
        $term = taxonomy_term_load($mondo['tid']);
        $mondi['term-'.$term->tid] = htmlentities(t($term->name));
      }

      $form['page-options-' . $nid]['mondi-' . $nid] = array(
        '#title' => 'Mondi Azzurra',
        '#description' => 'Seleziona i mondi azzurra di interesse',
        '#type' => 'checkboxes',
        '#options' => array_slice($mondi, 0, 25),
        '#required' => FALSE,
     );
   }
} // end foreach $nodes

$form['submitform'] = array(
  '#type' => 'submit',
  '#value' => t('Invia richiesta'),
  '#weight' => 6
 );

  return $form;
}

I need to know why there is a kind of limit to the checkboxes I can add and how I can debug where the form elaboration stop not serving to my form_submit my form data.


texts: db_select condition with subquery causes PDOexception

texts:
I want to build a relative simple select query with a subquery in its condition. What I want to achieve is to get the list of users updated after a given timestamp.

The working SQL-Query which I want to build as dynamic query is:

SELECT uid
FROM `users`
WHERE `vid` > (
  SELECT vid
  FROM `user_revision`
  WHERE `timestamp` > 1379494886
  ORDER BY `timestamp` ASC
  LIMIT 1
);

I've written the following code to build above query with Drupal's Database API:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1);

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $subquery, '>');

$result = $query->execute()->fetchAssoc();

But, I'm getting the following PDOexception error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in
      your SQL syntax; check the manual that corresponds to your MySQL server version for the right
      syntax to use near 'SELECT ur.vid AS vid FROM user_revision ur WHERE (ur.timestamp >
      137949488' at line 1: SELECT u.uid AS uid FROM {users} u WHERE (u.vid > SELECT ur.vid AS vid
      FROM {user_revision} ur WHERE (ur.timestamp > 1379494886) ORDER BY ur.timestamp ASC LIMIT 1
      OFFSET 0) ; Array ( ) in MYMODULE_page_callback() (line 22 of
      /path/to/the/module/includes/page_callback_file.inc).

What am I doing wrong building the subquery?


texts: Preserve node changed timestamp during update migration?

texts:
I'm using the migrate module and Drupal 7 to update existing node content, much of which was not migrated. System of record is set to DESTINATION.

Everything works fine, but I'm having some trouble preserving the "changed" timestamp in Drupal, which I'd rather not update.

As explained here, the problem is that node_save() always updates this value, so the challenge is where in the migrate framework to (1) save the existing value and (2) restore the value?

Saving is pretty easy in prepareRow:

  function prepareRow($row) {
    $row->last_changed = node_last_changed($row->Nid);
    drush_print_r($row);
  }

Restoring the value is trickier. I was thinking I could use prepare, but that seems to be too early, and the value is reset to current time when the node is saved.

For the moment, I am using a hack in the complete method like this:

  public function complete($entity, stdClass $row) {
    db_update('node')
      ->fields(array('changed' => $row->last_changed))
      ->condition('nid', $row->Nid)
      ->execute();
  }

Complete fires after the node is saved, so this does work.

I believe hook_node_presave () would also work, but it seems awkward since it doesn't run in the context of the migration.

Is there a better way to do this?


texts: How to create a 'most popular content' view?

texts:
I'd like to get a view block listing the most viewed articles.

What are the options to do that with drupal 8?

Note: I have activated the core module named 'statistics' and configured 'Increment a counter each time content is viewed.' But I cannot select that field for sorting in Views.