texts: User not showing in the user list in the CP but has profile after social login?

texts:
Something strange going on with the user listings in the CP. Using craft v2.6.2794 and social logins v 1.2.4.

I am using the social logins plugin for craft 2 and just updated it to the latest version. It creates a social login and a user and from the social login listing I can browse to the user profile. However when I try to view the user in the listing page it does not show up even after searching or listing as last created but it is there.
Any ideas. There are over 21k users in the db.


texts:
I'm writing a module that loops over lines in a CSV file to save them as entries. For every entry I save with elements->saveElement($element);, SEOMatic will queue a job that regenerates the sitemap for this type of entries. I'm importing more than 1000 lines this way, so there'd be more than 1000 jobs in the queue, all doing the same thing.
Is there a way to disable this hook so it wouldn't get triggered for every entry?

Here's a part of the code right now:

while (($csv = fgetcsv($handle)) !== false) {
    $entry = Entry::find()->siteId($siteId)->section('products')->where(['content.field_productId' => $csv[0]])->one();

    if (!$entry) {
        $entry = new Entry();
        $entry->sectionId = Craft::$app->sections->getSectionByHandle('products')->id;
        $entry->typeId = 1;
        $entry->siteId = $siteId;
    }

    ...
    ...
    ...

    try {
        Craft::$app->elements->saveElement($entry, true, true, false);
    } catch (Throwable $e) {
        throw new RuntimeException($e);
    }
}

try {
    Craft::$app->elements->resaveElements(Entry::find()->siteId($siteId)->section('products'), false, true, true);
} catch (Throwable $e) {
    throw new RuntimeException($e);
}


texts:
I want to write a more complex autocomplete search for a craft site. I know there are already some posts here that go in that direction. As they also tried, I approach this problem first by using the Element API. However, it does not work nicely with multiple queries.
That's my situation:
I have a database with items that have also a category assigned to them and sometimes are linked to a second section.
I would now like the autocomplete to show 3 types of results:

Entries where the title matches the search term (this can be easily done with Element API)
The categories that match the search term, labelled with "Jump to Category: Title"
The entries of the linked section that match the search term, also labelled accordingly.

So the autocomplete suggestions at the end would list all three types of entries, labelled accordingly.
I can obviously run three different calls to element API but that seems rather inconvenient and ineffective.
Is there any better way to do this?


texts: Determine if entry has a specific category

texts:
I am using a supertable (or matrix) to create rows.
In each row, I have a Category Field. Multiple categories can be selected for each matrix row.
As I loop over each row, I want to determine if the category field in that row has a specific category selected.
Example:
Matrix Row1:
-> Colour (Category Field):
--> Red, Orange, Blue

Matrix Row2:
-> Colour (Category Field):
--> Red, Blue

In the above example, in Twig, when I render out the row, I want to know if that row should be "Orange" or not, based on whether or not the "Orange" category was selected in the "Colour" field.
I can loop through every selected category in the category field, and plaintext match against it (example below), but I wondered if there is a cleaner/simpler way to do this.
{% set colourFlag = false %}
{% for class in row.rowSettings.rowColour.all() %}
    {% set colourFlag = (class == "orange" ? true) %}
{% endfor %}
{{ colourFlag == true ? "yes-orange" : "no-orange"}}

Any advice would be grateful.


texts: Possibility to use Craft's search function to search in PDF files

texts:
I have a client who wants to search for specific PDF files when she makes use of Craft's search function. The way she wants the PDF's to be found is that the words inside of the PDF is somehow processed by Craft and when you search for certain words that are included in a PDF it will show results of PDF's that contain these search words.

I have Googled for a module that can do such a thing but so far I have no luck. Does anyone know if such a module/plugin exists for Craft or do I need to hire someone to create that for me?

Thank you for reading.


texts: How do I force a PDF file to be displayed inline?

texts:
Tried using the following block but it isn't the right way.
{% header "Content-type: application/pdf" %}
{% header "Content-Disposition: inline" %}

Should this be accomplished via .htaccess?


texts: ContactForm – How to make fields required

texts:
I'm using the P&T ContactForm Plugin. How can I make more field required?

https://github.com/pixelandtonic/ContactForm

In the version from Github only the message and email field are required.

Is there a way to do this with the ContactForm Plugin?


texts: I have recently discovered our company website is run on Craft CMS. However, I do not like the system and am much more proficient on WordPress. Is there a way to move our site to WordPress without a huge bill or running/migration issues.


texts: What is the best way to append CSRF token without using a form?

texts:
I have built a plugin that simply makes requests to a 3rd party API. I am calling my plugin action via ajax.

I don't have a form on this page currently. Here is what I am using, but I am getting the error The CSRF token could not be verified.

I thought I could just put a hidden input field somewhere on my template:

twig

<input type="hidden" name="{{ craft.config.csrfTokenName }}" value="{{ craft.request.csrfToken }}">

Here is what my ajax call looks like...

jquery

var data = {
    'thing': value,
    'thing': value
};

data[window.csrfTokenName] = window.csrfTokenValue;

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': 'myplugin/doAction',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    callback(response);
}).fail(function (error) {
    // Total fail.
});

Later on in my site I will have a form that accepts user input, so I would like to keep CSRF enabled for the entire site. Perhaps I need to "skip" the CSRF token for these requests?


texts:
Just wanted to check in to see if what i'm seeing is reasonable. Just trying to tweak the performance of a single-page Craft site, and basically working backwards to find bottlenecks. Following all the suggested items (devMode off, static assets caching, minimise db calls, etc).

However, working my way all the way back to a blank template file (no code at all), no plugins enabled, the page still take 250-300ms to load nothing at all. All this while running locally via MAMP.

Is this an expected speed? I'm aware thats pretty fast, but would've thought locally would be near instantaneous. This will only get worse on a server (especially shared hosting).


texts:
how can i output my content in pairs?

like this:

div.row >   entry 1 + entry 2
div.row >   entry 3 + entry 4
div.row >   entry 5 + entry 6

so far i have the following

{% for entry in craft.entries.find({section:'events' ,level: 2 }) %}
<div class="row">

    {% if loop.index0 is divisible by(2) %}
    (entry odd output here)
    {% endif %}

    {% if loop.index is divisible by(2) %}
    (entry even output here)
    {% endif %}

</div>
{% endfor %}

but this just gives me a new row for each entry.
What's the best approach?


texts: I need to add the SameSite directive to my site's CSRF cookie, as explained in these mozilla security guidelines. According to the Craft docs, "Craft handles the cookie creation automatically." Is there a way I can configure the cookie?


texts: How could I submit the Charge plugin using Ajax?

texts:
I am using the Charge plugin to handle my Stripe payments. How could I submit this form via Ajax Post and get the response? I have tried using the following code but it tells me it's a bad request:

this.ajaxReq = $.ajax({
   url: 'charge/charge',
   data: $('#charge-form').serialize()
}) .done(function(data) {
   console.log('success!');
   console.log(data);
}) .fail(function(data){
   console.log(data);
});


texts: How do you page through entries in a structure?

texts:
I have a structure like below and need previous / next links on an entry such that they go back and forth between E, F, G and H. They shouldn't step into D or I.

I've been trying this, but I can't get it not to step into D or I.

{%  set prev = entry.getPrev({section: 'mySection'}) %}

    {% if not prev %}
        {% set prev = craft.entries.section('mySection').last() %}
    {% endif %}

    {{ prev.title }}

    {% set next = entry.getNext({section: 'mySection'}) %}

    {% if not next %}
        {{ craft.entries.section('mySection').order('lft desc').first().title }}
    {% endif %}

    {{ next.title }}

A

B
C
D

E
F
G
H

I

J
K
L

M
N
O
P


texts: How to create clean URLs for category strings?

texts:
This code for linking to a category page:

href="/products/?category={{ category.slug }}"

Generates this URL:  www.website.com/products/?category=category-name

Can someone please tell me how to code links in menus (etc) that will produce URLs without the ?category= string being included in the URL.  So that the URL would become: www.website.com/products/category-name

Many thanks for your help - it is greatly appreciated!


texts:
I'm trying to get an element from it's URL.

For example, say we have a url of http://craft.dev/blog/article1. Is there a function I can call within a plugin and pass over blog/article1 that will return a corresponding element, if one exists, for that specific URL? I'm sure there is a way to do this with the router, I'm just not sure what it is.


texts:
I would like my robots.txt file to be generated by Craft. Things that I have tried that don't work:

a craft/templates/robots.txt template
a craft/templates/robots.txt.twig template
a route for robots.txt that points to a robots.twig template

Both of these work fine for a foo.txt file. The error I get is 404,  not the Craft 404, but the system one - nginx.


texts: Plain text fields defaulting to curly quotes in editor

texts:
I’m running into an issue on my Craft install where plain text fields are automatically being styled with fancy quotes within the backend, particularly in cases of opening and closing quotes. It does not do this in the standard text field, only textarea.

This is a problem as some of these fields are intended to take on HTML input—generally things like tracking codes, for example. I see that there’s a class that gets added to the fields, nicetext, which may be leading to the unintentional styling. There does not seem to be a way to disable this, and to be clear it does not impact the output on the page: If I put in straight quotes and then hit save, it will correctly render them in Twig, but when I reopen the page in the backend, it will try to make the straight quotes curly, which makes me think it’s a Javascript thing.

From a plugin perspective, I use Doxter as my main posting interface, but at this time the Doxter blocks are not causing this problem, I think because I turned off a setting there.

Any idea what might be the issue?


texts: Category list not returning all related entries

texts:
Here's my code:

{% for category in craft.categories.group('artistLocation') %}

    {% set entryCount = craft.entries.relatedTo(category).total() %}

    {% if entryCount %}

            {{ category.title }} ({{ entryCount }})

    {% endif %}

{% endfor %}

For some reason, this is only returning the first six categories with entries associated.

https://www.dropbox.com/s/a2ut7j48acnq1g0/Screenshot%202016-05-06%2010.49.34.png?dl=0

Nothing in the error logs that are shedding any light on it for me.

Any ideas would be awesome!


texts: Output assets within a matrix block using Imager and Craft 3

texts:
I'm having trouble trying to output assets from an Assets field that's within a Matrix block, using Imager. The code below is only outputting the first image that has been added, over and over for each asset, rather outputting each different asset. What am I doing wrong?

I did try changing {% set logo = block.logos.first() %} to {% set logo = block.logos.all() %}, but that gave me an internal server error.

{% for block in entry.modules.all() %}

  {% if block.type == "logosBlock" %}

    {% for image in block.logos %}

          {% set logo = block.logos.first() %}
          {% set transformedImage = craft.imager.transformImage(logo, { width: 312, height: 200, }) %}

      {% endfor %}

  {% endif %}

{% endfor %}


texts: Importing content with feedme to single entry in 3 locales

texts:
This is the situation:

I've got 3 locales (en, nl, fr)
I've got an XML file with content in those 3 locales
I've set up the field mapping in feedme

But what I can't seem to figure out is how to import the entries from the XML file into combined entries in Craft, meaning, I want elements from my XML file (the same content in 3 locales) to be 1 craft entry in those 3 locales.

Each time I do the import, I'm stuck with all of them being in the same locale.

Let me know if any additional information is needed.

Any pointers as to what I'm doing wrong would be much appreciated.


texts: Craft 2 use different template for the same structure

texts:
I have a site with projects which each has a projects structure with an associated category and a number of images.

The URL is set as projects/{projectCat.first.slug}/{slug}

I want to use the structure first for a set of thumbnails for each project (easy - no problem) and then for a gallery page with full size images. Both pages will have the same set of images.
The URL for the first is .com/projects/category/project-name.

The only way I have been able to do it is to make the links from the thumbnail page using:

<a href="/projects/gallery/{{ category.slug }}/{{ entry.slug }}">

and then using routing:

/projects/gallery/slug/slug to projects/gallery/_entry

This works but if I have a project in two or more categories with the same name it doesn't take account of the category in the URL and is also a bit messy.

Is there a better way?


texts: I would like to include a file on every block but the last three. How can I accomplish this?


texts: Changing status via entries list in one locale also (unexpectedly) changes status in other locale(s)

texts:
I'm not certain if this is expected behavior but if so the user experience is confusing/unexpected:

When viewing a list of entries in the control panel, swapping between locales shows the expected statuses--either enabled or disabled--for each entry. Accordingly, example, an entry that is enabled in English but disabled in Spanish, is properly displayed as such. However, making a change to the status when switched to either locale applies the status to both locales, rather than just the selected locale.

This seems to indicate that adjusting statuses through the entries list applies only to the entry's master enabled/disabled status, not the selected locale's status (which was my expectation). Should this be the be case? I found out the hard way by switching to my Spanish locale, selecting all entries, and then setting their status to disabled. Switching to the other status showed that they too had been disabled. Bummer.

Any thoughts or similar experiences? Did I miss something in the docs?

Cheers.


texts: Is it possible to set dynamic checkbox group options in a Solspace Freeform form?

texts: I have a form where the checkbox group options I show would ideally be based on details for the logged in user. Is it possible to dynamically set checkbox group or radio group options for a Freeform Form within a Twig template?


texts: Within the CP, how can I filter the listed Entries based on a Lightswitch field value?

texts:
I tried these kind of searches in the CP search field (on top of the Entry list):

fieldHandle:true / fieldHandle:false
fieldHandle:1 / fieldHandle:0
fieldHandle:* / -fieldHandle:*
fieldHandle:not 1 / fieldHandle:'not 1'
etc.

Unfortunately, none of these returns the expected entries.


texts: How to implement radiobuttons field on frontend registration form?

texts:
I want to add a question to a frontend registration form.
The radiobuttons are just 'Yes' or 'No'.

I've created a radiobutton field and added that to users > fields.

If I add this option to the form, new registrations are not submitted.
The page reloads and doesn't redirect to the confirmation page.

Any idea what's wrong with my form?

<legend>Are you a Beekeeper?</legend>
<input type="hidden" name="fields[areYouBeekeeper]" value="">
{% for option in entry.areYouBeekeeper.options %}
    <input id="isBeekeeper{{ option.label }}" type="radio" name="fields[areYouBeekeeper][]"
    {%- if account is defined %}value="{{ option.label }}"{% endif -%}>
    {{ option.value }}
{% endfor %}

Here's the complete form template.

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="{{ siteUrl }}registration/confirmation">

    {% macro errorList(errors) %}
        {% if errors %}

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    Username
        <input id="username" type="text" placeholder="gebruikersnaam" name="username"
        {%- if account is defined %} value="{{ account.username }}"{% endif -%}>

    {% if account is defined %}{{ errorList(account.getErrors('username')) }}{% endif %}

    Email
        <input id="email" type="text" placeholder="somebody@example.com" name="email"
        {%- if account is defined %} value="{{ account.email }}"{% endif %}>

    {% if account is defined %}{{ errorList(account.getErrors('email')) }}{% endif %}

    Password
        <input id="password" type="password" placeholder="password" name="password">

    {% if account is defined %}{{ errorList(account.getErrors('password')) }}{% endif %}

    First name
        <input id="firstName" type="text" placeholder="First name" name="firstName"
        {%- if account is defined %} value="{{ account.firstName }}"{% endif -%}>

    {% if account is defined %}{{ errorList(account.getErrors('firstName')) }}{% endif %}

    Last name
        <input id="lastName" type="text" placeholder="Last name" name="lastName"
        {%- if account is defined %} value="{{ account.lastName }}"{% endif -%}>

    {% if account is defined %}{{ errorList(account.getErrors('lastName')) }}{% endif %}

    <legend>Are you a Beekeeper?</legend>
    <input type="hidden" name="fields[areYouBeekeeper]" value="">
    {% for option in entry.areYouBeekeeper.options %}
        <input id="isBeekeeper{{ option.label }}" type="radio" name="fields[areYouBeekeeper][]"
        {%- if account is defined %}value="{{ option.label }}"{% endif -%}>
        {{ option.value }}
    {% endfor %}

    <input type="submit" class="button expanded" value="Registreer">

</form>

I think the problem is with the for loop. I'm trying to output the radio options with a for loop on an entry, but it's actually not an entry. No idea why I do get the options anyway.
I've managed to get this working with the following code:

<input type="hidden" name="fields[areYouBeekeeper]" value="">

<input type="radio" value="yes" name="fields[areYouBeekeeper]" {%- if account is defined %}value="{{ account.areYouBeekeeper }}"{% endif -%}>Yes
<input type="radio" value="no" name="fields[areYouBeekeeper]" {%- if account is defined %}value="{{ account.areYouBeekeeper }}"{% endif -%}>No


texts: Is there a JavaScript event available for when the parent tab of a custom field is shown?

texts:
I need to have a JavaScript event that is triggered when the parent tab of my field type instance is shown on the entry form. So if the field is on the second tab, the div is hidden on instantiation. The div is obviously shown once the parent tab is clicked. I need this event to reset the map in my field type. If a map is instantiated with a hidden div, it must be redrawn before it can be displayed properly. So when the div displays (after the parent tab click) I need to trigger the method to redraw the map. Is there a JavaScript event available for this and if so, how would I use it?

If no such event exists and if one can't be added, I guess the only other way would be to try to traverse the DOM and add click events to the respective tabs. This feels kind of like a hack though and would break if the DOM changes.


texts: Show time ordered entries from midnight at end of loop

texts:
I'm creating a line up listing page for a festival, across 4 nights. Acts are listed, per day, sorted by a date field in order of a start time field.

The issue I'm having is that midnight until 3am is still considered the night of an event but my time field obviously considers it otherwise.

e.g. an act is performing on the Friday morning at 1am but I need to list this at the end of the Thursday acts.

So the user adds it to the CMS on the Thursday but it appears at the start of the day instead of the end.

Essentially, I just need any acts that appear between 00:00 and 03:00 at the top of a list e.g

Thursday

Act 1 - 1am - 2am
Act 2 - 12am - 1am
Act 3 - 11pm - 12am
Act 4 - 10pm - 11pm

etc

This is the code I have so far

whatDateAreTheyPerforming is a date field

startTime and endTime are time fields

{% set entryIds = craft.entries.section('lineUp').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).find() %}

{% for category in categories %}

  {# Fetch all of the entries related to this category #}
  {% set entries = craft.entries.relatedTo(category) %}

  {# Group entries by date and order by start time #}
  {% for date, entries in entries.order('whatDateAreTheyPerforming', 'time(startTime) desc')|
  group('whatDateAreTheyPerforming') %}

DAY HERE - {{ date | date('l') }} {{ date | date('jS') }}

        {% for entry in entries %}

{{ entry.title }}
              {{ entry.whatDateAreTheyPerforming | date('l') }} - {{ entry.startTime | date('G:i') }} - {{ entry.endTime | date('G:i') }}

        {% endfor %}

  {% endfor %}

{% endfor %}

I hope this makes sense, any guidance will be appreciated.


texts: Moving site to new server - admin area not working

texts:
I am trying to move a Craft site to a new server but am having difficulties.

I have backed up the whole site and database an replicated it on a new server.

3 pages work fine, one page only loads the header, and the admin page lets me login but the dashboard is blank but there are no console errors in chrome.

I have changed my host files on my mac to point the domain to the new server so I'm not sure if this might cause issues?

Or is there something else I am missing?


texts: Accessing the attributes of an Asset field

texts:
Specifically looking at these attributes http://d.pr/i/1ilbr

I can access Alt text by {{ entry.assetHandle.first().altText }} and similarly can do {{ entry.assetHandle.first().sourceUrl }} but Source Name continues to be elusive.

I'm confused as to whether this is an attribute or part of the AssetSourceModel? Although would assume attribute given it's editable.


texts: Displaying entries from a specific custom date year

texts:
I've a list of entries, all with custom dates.
Is there a way to show entries from a specific year, just using the custom date rather than the posted date?

Any help is much appreciated!


texts: Rendering pages from Craft CMS as static HTML

texts:
Has anyone tried creating a process whereby the pages/entries generated from Craft could be presented as static HTML?
I am keen to know what different approaches have been taken in the past as we are considering it for a company website.


texts: Why am I unable to use Twig conditional on entry.type property?

texts:
Where entry.type is equal to meetingsEventsOverviewPage, I would expect the following to return true:

{{ entry.type starts with 'meetingsEvents' }}

And

{{ entry.type in ['meetingsEventsOverviewPage', 'meetingsEventsContactPage'] }}

However that doesn't happen.

If I test the string explicitly, it does work:

{{ 'meetingsEventsOverviewPage' starts with 'meetingsEvents' }}

And

{{ 'meetingsEventsOverviewPage in ['meetingsEventsOverviewPage', 'meetingsEventsContactPage'] }}

Is there some kind of parse order going on here that I need to know about?


texts:
I'm writing some pretty huge articles consisting of multiple (80+) Matrix blocks of various types. They're so long they'd benefit from in-article navigation for skip-links.

WordPress has a plugin called autogen_menu which creates linked navigation from the header hierarchy in a post. You just put in a small snippet where you want the generated nav to go and it generates all the links (and presumably id's on the headers) itself. Has Craft got anything similar, I've not been able to find a plugin that does this?

Or, would this be better outside of Craft entirely and done as JS?


texts: Solspace Freeform Upload file dynamic location and duplicate file avoidance

texts:
Using Freeform for forms which have multiple file upload fields.

Is it possible to have a unique asset directory for each submission? For example: uploads/maindirectory/submission.id/ I'm trying to make it easier for the website admins to see all of the uploaded files in one location, but mainly to prevent multiple users uploading files of the same filename.

Users are requested to upload scanned documents, so file names such as "scan1.jpg", "scan2.jpg" could be a common theme and would not work in this case as craft natively doesn't allow the same file uploaded twice meaning freeform throws a validation error.


texts: slugs in asset picker not working until page is published

texts:
I have setup a page that has image asset pickers on it and image asset pickers in a matrix field.

I have setup the fields to allow a single directory and a { slug } for the normal field pickers and { owner.slug } for the matrix field destinations.

So far so good, if I work with a saved page it all works beautifully, the images get saved in the folder with the name of the page :)

But it doesn't seem to work for a new page, when I pick an image the dialog that comes up does not show the { slug } folder and when upload and select an image it shows a broken image in live preview mode. Once I save the page and go back in it all comes good.

Ok my description was poor, I am certain this is a bug, here are the details...

I have an asset repository called property-images
I have a section template with 2 image fields mainImage, searchImage and another image inside a matrix field
mainImage and searchImage are set to use a single source (property-images) with the location set to {slug}
the matrix image is the same with the location set to {owner.slug}

I create a new page and save it (so the page is created and has a slug)
I go back into the page and select mainImage, it works beautifully, and loads images into a sub folder correctly.
If i create a new matrix block and select an image, I don't get the asset in my sub folder display but some sort of tmpassets folder. OK I kind if get this, because the block isn't created yet, I don't like it but I can live with it.
Now when I look at live preview the image doesn't preview, the image url it renders doesn't exist.

So I save my page and come back in...

Now the image I picked in the block has been moved to the correct assets folder but still doesn't render anything, the transformed images aren't there

If I remove the image from the matrix block and re-pick it now it all works fine.

So it seems to explain to the content editor how to use this I need to tell them whenever they create a new matrix block they need to publish the page and come back in and then pick the image and then it's good. I can tell you that is not going to fly with this client!

I've also experimented with a page in draft but a different set of weird things results.

Oh one more thing! I'm using transforms in code, so something like:

  {% set lrg = {
                            mode: 'crop',
                            width: 1400,
                            height: 866,
                            quality: 75,
                            position: 'center-center'           }       %}
  img src='{{ image.getUrl(lrg) }}'

I wonder if predefined transforms are better?


texts: What does the 'modifyEntrySources' hook do?

texts: What does the modifyEntrySources hook do exactly, and when might one use it? Can someone help clarify this please?


texts:
I've got a Assets field which is limited to 1 asset inside a Matrix field. Is there a better way to fetch the image without using a forloop?

At the minute I've got:

{% for image in block.backgroundImage %}
    {{ image.getUrl() }}
{% endfor %}

But it just doesn't seem right using a forloop when I know there is only one image.

Thanks


texts: I found the php.ini file, but I don't see where to change max execution to 120.  Thank you for your support.


texts: How do I relate a user to a channel entry from a form?

texts: I have a channel which has a relate to user field, how do I setup the front-end form which is a user details update form so they can select a channel entry from a drop down and when saved, have it relate that user to the channel entry.


texts: How to handle client expectations regarding page building and layout within Craft

texts:
I love Craft CMS and use it for nearly every site I build. There isn't a better tool (in my opinion) for managing custom data.

And using a matrix field as content builder solves the majority of my client's publishing needs.

But with so drag and drop page building tools on the market, I find that sometimes clients expect to find the same drag and drop page layout ability within Craft as they would find in Squarespace or Weebly or Mail Chimp Templates.

Other than educating a client that Craft is not a layout tool and there are times when you use different tools for different jobs, what solutions do you suggest?

Is there a way to accomplish minimally viable layout with becoming very dependent on plugins?

Is there are way to use a 3rd party page builder and embed the content in Craft?

Or is best not to even try?

Have you approached handling client's layout expectations within Craft CMS?


texts: Is there a way to reset the focal point in Craft?

texts:
As the question states. Is it possible to reset the focal point in the CMS?
I cannot see any obvious setting?
If not could this perhaps be a feature request for a reset focal point button?


texts: Plugin - Possible path problem in MAMP - Could not find the task component type

texts:
I have a Craft plugin that works fine on a live site and on Macs. I have recently installed MAMP (Windows) on my development machine and now, when I try to run one of the plugins commands by using GIT to CD to the Yiic console ... /c/mamp/htdocs/websitename/craft/app/etc/console ... and run the command ... php yiic pluginname commandname ... I get the error message ... Encountered an error running task 700 (plugin_task): Could not find the task component type.

I am pretty sure that the problem is that the task file is not being found, but I think I have the upper/lower case elements correct:

\pluginname\consolecommands\PluginnameCommand.php

<?php
namespace Craft;

class PluginnameCommand extends BaseCommand
{
  public function actionUpdate($testError = false)
  {
      $task = craft()->tasks->createTask('pluginname_event', 'Updating data', [
            'testError' => $testError,
      ]);
      craft()->tasks->runTask($task);
  }
}

\pluginname\tasks\Pluginname_EventTask.php

<?php
namespace Craft;

class Pluginname_EventTask extends BaseTask
{
}

Have I the cases wrong, or am I missing something in setup?

Note that this is a followup to ... Running console (yiic) under MAMP (Windows) ... which was a path problem solved by modifying the yiic file.


texts: What's the best way to build URLs for dynamic content collections?

texts:
I'm working on a project where we need to post publication Editions, each containing any number of Stories, of which there can be one of three entry types. The URL structure we're shooting for is foo.com/pub/edition-slug/story-slug, and I'm not sure how to set the "URL Format" field for each Section.

For example, I've set the Editions Section to pub/{slug}, and have tried setting the Stories Section to the following...

pub/*/{slug}: literally includes */ in resulting URL
{parent.last.uri}/{slug}: only results in foo.com/story-slug

My questions, then:

Is it possible to dynamically reference a parent Section's slug when we're not in a Structure?
If no to #1, is there a more appropriate layout (rather than two independent Sections) that'd allow the Edition > Story relationship given that Editions and Stories are distinctly different? (I'm avoiding a Structure because I can't rely on editors not to make a Story top-level with nested Editions, for example—no way I understand to enforce that Edition > Story hierarchy.)

I can get the URLs working with a custom route, but at the loss of a proper Live Preview and the other benefits of clean URLs like sitemap generation, etc.


texts: Error when creating a Matrix or installing a Plugin

texts:
We have 2 computers with a new Craft Pro trial installation. The files are exactly the same on both computers. We both use the same DB with the same db.php config settings.  We can both see the site and login to the /admin section.

The only issue is that on 1 computer I can not create a Matrix field or install a plugin. Then I get the error:

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'COLLATE=' at line 8

The other computer has no problem creating a Matrix field or installing a plugin. Any suggestions? Thanks!


texts: Asset Field: Select a folder instead of all images

texts:
Is there a way to pick a folder from an asset field?

The goal is to render a dynamic gallery from an asset folder (which is on S3) instead of selecting all images inside a folder by hand.

Use case:
In an asset field, I select folder 'XYZ' and render a gallery from all images which are inside. If a user uploads a new image to the folder 'XYZ', the gallery will be updated automatically.

Problem:
Currently, I can only handpick the images from a folder. If someone uploads a new image, he/she also has to pick the new image in the asset field. So it is not dynamic.

Thanks in advance!


texts:
For some reason the CraftCMS URL rewrite is not working on GoDaddy shared hosting server.

Currently by .htaccess file looks like this

Options +FollowSymLinks -Multiviews
<IfModule mod_rewrite.c>
   RewriteEngine On
   # Send would-be 404 requests to Craft
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
   RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

Has anyone encountered this problem? Can someone help me solve this?

Update

I am not sure any more if this a url rewrite problem. As when I access an entry such as http://aspaceboydream.com/comic/so-this-is-me, it loads correctly. But when I use the function:

url('comic')

to construct the urls of the different channels, the URLs are being constructed as http://aspaceboydream.com/index.php?p=comic


texts:
I tried to write next class:

<?php
namespace Craft;

class TaskShortcutPlugin extends BasePlugin
{
    // ...
    // Shortcut sample [task id="42"]Reference to task with id = 42[/task]
    public function task($attributes, $content, $tag)
    {
             $id = $attributes['id'];    // 42
             $content;                   // Reference to task with id = 42
             $tag;                       // 'task'

             return ''.$content.'';
    }
}

So, what next, how to implement it into CMS? Or I should use it into Twig templates?


texts:
I am putting together a proposal for an eCommerce site - one of the (obvious) requirements is inventory management. I do not see anything specific in the Commerce 2 docs. Basically, want to enter stock levels for each product and then have that number change as orders are placed. Is that possible or does it require  a plug-in?

Thanks!


texts: Looping through Entries based on MultiSelect Field Selection

texts:
I’ve got a people entry type that has a peopleCategory multiselect field. I’m wanting to loop through all the people and grab the ones that have a a specific item selected in the multiselect field (in this case - that they have been marked as being in 'leadership'). I was using

{% for entry in craft.entries.section(‘People’).peopleCategory(‘leadership’) %}
    {% if entry.peopleCategory.contains('leadership') %}

but in conjunction with another if statement

{% if loop.index==1 %}
{% elseif loop.index==2 %}
{% elseif loop.index==3 %}
etc

and that ended up throwing off the formatting in the template  - so now I’m tyring to find a new solution using something like:

{% set leadershipTeamTest = allPeople.peopleCategory('leadership').peopleCategory('leadership') %}

or

{% set allPeople = craft.entries.section('People') %}
{% set leadershipTeam = allPeople.peopleCategory('leadership').peopleCategory.contains('leadership') %}

but having trouble where it’s either returning everyone, or no one.

I'm still a pretty new to Craft - but would appreciate any help ( was using this - https://craftcms.com/docs/multi-select-fields but couldnt get it going)


texts: Passing data to includes - overrides & defaults

texts:
I am trying to create a reusable component with a set a default variables that can be overridden when included in a template:

includes/social.twig

{% set padding, size, color, hover = '2', '4', 'pink', 'black' %}

page.twig

{% include '_includes/social-links.twig' with {
  padding: '10',
  size: '2',
  color: 'blue',
} %}

When using this, variables that haven't been set in the include statement would remain as defined in the include file, and those that have would override the variables set in the include file. This doesn't happen - nothing gets overridden.

I can achieve a working version of this using:

includes/social.twig

page.twig

{% set padding, size, color, hover = '2', '2', 'blue', 'black' %}
{{ include('_includes/social-links.twig') }}

This involves not setting the vars in the include file, but setting them in the page template - this approach seems more error prone and less maintainable than the version I am trying to achieve.


texts: Craft 3 Deprecation Error from Twig/Extension/Core.php. How to fix?

texts:
I'm getting a deprecation error from not using .all() to query my elements:

Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.

This is usually very easy to fix because Craft normally tells you which template and line to add the .all() to.  However, when looking at the origin, I see:

/Users/Me/Sites/Project/vendor/twig/twig/lib/Twig/Extension/Core.php:577

This is pointing to something in Twig's vendor library, which I obviously don't want to fix for updating reasons.  Does anyone know what this is referring to in my templates?


texts: Is it possible to cache variables using the {% cache %} tag?

texts:
I would like to cache a variable and compare the cached variable with a parameter from the query string.

Is it possible to somehow cache a variable ?

{% cache using key "cacheId" %}
  {% set id = 1 %}
{% endcache %}


texts: How to setup conditionals within a matrix?

texts:
In my matrix field, I want to be able to upload my image, and then upload another asset (in this case it would be a document) so that that image I upload links to that document.

I have my Matrix field setup like so:

Image ->
  -Image
  -linkedDocument

How can I set up a conditional where only add in the  tag if I add an asset there?

Here is my relevant code:

% elseif block.type == "image" %}

        {% set image = block.image.first() %}

        {% if image %}

            {% endif %}
        {% endif %}


texts: How to compute UK style VAT in Craft Commerce?

texts:
I'm encountering a problem with how to show UK style VAT tax on an item. I've created a tax rate called VAT at 20% that is included in the taxable subject.

However when this tax is computed on say £8,000 rather than showing the tax as 20% or 1/5th = £1,600 it shows it as 1/6th = £1,333.33. I can't figure out why the tax isn't applying properly. Settings below:


texts: CDbException warning 1265 after updating matrix field

texts:
A testimonial matrix field has existed in our system for a couple of months. I've just deleted a block that's no longer needed, and am now receiving a SQL warning related to another one of the blocks. The warning occurs when I set the Max Length to anything lower than 145. Here's the warning text:

CDbCommand failed to execute the SQL statement: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'field_testimonial_quotation' at row 1. The SQL statement executed was: ALTER TABLE `craft_matrixcontent_testimonialmatrix` CHANGE `field_testimonial_quotation` `field_testimonial_quotation` VARCHAR(110) NULL

I've checked all of the Entries that use this matrix block, and none of them are close to the Max Length limit.


texts: Saving entries in plugin: How are Assets relations handled?

texts:
I'm importing an existing ExpressionEngine site's content into Craft, using content exported in XML on the EE site, and stepping through each entry.
This includes hooking up Assets files, where the Assets field/upload location is pointing to the same S3 bucket that Channel Files was on the EE site.
In my first load of these entries, I was able to successfully map the Assets fields using the following code:
$assets = craft()->elements->getCriteria(ElementType::Asset);
$assets->filename = $referenceFile->filename;
$assets->limit = 1;

foreach ($assets as $assetMatched)
    $assetId = $assetMatched->id;

$assetsToSave[] = $assetId;

if ($saveAssets)
    $entryToSave->getContent()->referenceItemFiles = $assetsToSave;

On a re-run of the import, where I check for a match on the imported entry at each pass, I began receiving an FK error on the Assets field, but I want to set that aside for now. I reverted my database and ran the 1st time import again. I'm now seeing the following error:

S3Exception
S3::copyObject(reference-materials, 1610-10-01-001-0000015-supertrust_final_prospectus_may_29_1992--pp_33-end.pdf, reference-materials, 1610-10-01-001-0000015-supertrust_final_prospectus_may_29_1992-pp_33-end_1.pdf): [NoSuchKey] The specified key does not exist.
/Users/markreeves/Projects/Clients/40Act.com/craft_site/craft/app/lib/S3.php(816)

Based on a) the copyObject text and b) the _1 in the second filename, I'm now concerned. My question:
What's being done here when I save a new or existing entry in plugin code that includes an Assets field?
Is Craft trying to copy files? I'm now seeing a bunch of files in my S3 bucket with today's date as timestamp, and I'm not seeing corresponding activity on the live site using the same bucket, so it seems that Craft is not just creating relations for those files, but is actually touching the files, too. This is not what I would expect.
What should I expect to happen when I map asset IDs to an Assets field based on files that already exist? I had Craft index the S3 bucket via the admin prior to running this code, so that the database has records of those files.
Update: It looks like Craft has renamed files in the existing bucket, causing them to break on the other site. Specifically, it looks like Craft has replaced -- in the filenames with -, removed ,, etc.
Thanks!


texts:
I'm new in the Craft CMS world. Today I start so build my first website with Craft.

I have a Structure with 2 Levels. Now I want so get the children from level 2. The level 1 entries are overview-pages for the content in the level 2 pages. I've build 2 entry types. One for the content and one overview pages.

Thx for your help :)
Alexander


texts: Plugin Development: find source group used by field

texts:
I'm writing a plugin that works with Fields in various ways, one thing I need to do is get the category source groups available to a particular category field. I have the field's handle and id and can get it's FieldModel instance from that. But that fieldModel doesn't appear to have any information about what sources it is using.

So for example, I have a Category field named 'peopleClassification', and it has the category group 'peopleWhoWorkHere' as it's source set in the field settings page.

When I inspect the FieldModel object for the peopleClassification field, I'd expect to see the id or handle for the peopleWhoWorkHere group somewhere inside the object. I'm dumping the variables and checking the API docs, and I don't see a way to do that.

I thought that the CategoriesService might have a method for returning sources for a given field ID, but I couldn't find anything.

Does anyone have suggestions on where in the API I can connect these two? It's obviously possible, else Craft wouldn't work at all.

To clarify, I'm not working with specific entry objects here, I'm trying to match field handles to group handles.

@carlcs answer got me to the info I needed (thanks). Here's how I completed it.

$field->getFieldType()->getSettings() returns an array with various pieces of meta data including a source field with a value like group:42. That number is the category group ID I needed to create an instance of category group object.

list($type, $gid) = split(':', $field->getFieldType()->getSettings()['source']);

Then use $gid to load an instance of the Group from categories service

$categoryGroup = craft()->categories->getGroupById($gid);

$categoryGroup contained the info I needed, including the group's handle, which I used to create a list of categories.


texts: How to reference an entry field in a guest user form?

texts:
I'm new to Craft.  I've been trying to wrap my head around how to design the concept of Events and Event Registrations.  Currently I have both Events and Event Registrations as their own Sections as Channels.  An Event Registration has an Entry field to tie it back to an Event.  Our admins will create an Event, but we want the public to be able to register for an event via a form.  I'm using the guest-entries plugin and am very close to getting this all tied together, but am unsure how to pass the reference to the Event in the form.

I can pass it in via the url http://example.demo/register.html?eventId=99

But what do I reference so that the correct info will be sent to identify the Event entry when the form is submitted?

I assume I can send it via a hidden field, but am not sure what value to send:

    {% set eventId = craft.request.getParam('eventId') %}
    <input type="hidden" name="fields[event]" value="{{ eventId }}">

OR

If anyone sees a better way to design this, I would be open to other ideas.


texts:
I'm having a few irregular errors after upgrading via the automatic update. When trying to visit the dashboard I get:

Internal Server Error
Passed variable is not an array or object, using empty array instead

My max_execution_time and memory_limit are set pretty high, and I believe the upgrade completed successfully. But I cannot view the dashboard or settings pages. Everything else seems to be fine.
Do I have to fully revert and re-try the upgrade via the manual method?


texts:
How can i redirect to the first child if an entry has children?

Something like this:

{% if entry.hasDescendants() %}
    {% redirect "{{ entry.getChildren().first().url }}" %}
{% endif %}


texts:
I have run into an issue where the following code will only return 100 blocks, despite the fact that there are more. Is there some limit I am not aware of? Running the latest version.

{% for block in entry.supporters.type('individuals').order('firstName') %}


texts: Get Entries From Any Section Matching a URL segment

texts:
I have 2 issues that I need help with:

I want to load ENTRIES from any section where the first URL segment of the entry matches jobs.
I am using the code below to load any SECTION where the first URL segment matches jobs.  This code works to load the sections. I'm just wondering if there's a more efficient way to write this to load the sections.  This is separate from loading the entries.  I need to do both.

{% set allSections = craft.sections.getAllSections() %}

{% for section in allSections %}

{% set sectionURL = section.getUrlFormat()|split('/')[0] %}

{% if sectionURL == "jobs" %}
    {{ section.name }}
{% endif %}

{% endfor %}


texts:
Deploying on production is giving me this error.
Applying changes from your project config files ... No site settings exist for section 20
Deploying to stage is working no problem. Production isn't live yet. It uses the same database copied from stage.
Any ideas?


texts:
In EE, if there was a template /foo/bar.html, one could access the contents of that template by going to either example.com/foo/bar or example.com/foo/bar/more/segments/here. The additional URL segments didn't prevent EE from loading the most-accurately-matching template.

Moving over to Craft, bar is now an entry's slug. The section for that entry is properly set up with the "Entry URI Format" and "Template" pointing to foo/{slug} and foo/_entry.html, respectively. Is there a way to get the same "most-accurate" template-matching behavior in Craft? Perhaps with routes? I would want the {{ entry }} variable to be automatically available for either URL.


texts: How to use Super Table to create an Image Carousel?

texts:
I'm very new to Craft and am having some trouble creating an image carousel from a Super Table. I created a Matrix field called 'rotator' it has one field called 'rotatorContents' which is a Super Table:

rotatorContents has 3 fields: slide image, slide description, and slide title. I'm using a for loop to loop through the rows of the Super Table

{% if module.type == "rotator" %}
    {% for row in module.rotatorContents %}
        {% set slide = row.slideImage.first() %}

        ‹

     {{need prev slide title here}}

    {% set title = row.slideTitle.first() %}
    {% set description = row.slideDescription.first() %}

{{ title }}

{{ description }}

       ›

     {{need prev slide title here}}

 {% endfor %}
 {% endif %}

As you can see from the code above I am not sure how to reference the previous row in the Super Table. From a user standpoint they can input as many slides as they like. So at any given time there should be an active slide that is displayed and arrows linking to the previous slide and next slide.

How do I go about fetching the slide that's before the active slide and the slide that's after the active slide? Or in other terms getting the previous row and the next row after the current one in the Super Table?

Also I'm sure there are also some other things I'm referring to wrong since this is my first time using Super Table, such as my usage of .first().


texts: How to solve "fatal error: out of memory"

texts:
I am getting the error in the image below.  It is not always generated by the same file (in this case ".../IOHelper.php").

I can't quite figure out what is causing this, Can anyone provide some insight into what can cause this error specifically (I understand there is a memory issue) and maybe point to where I could be looking as far as a culprit.

My hunch is it could be due to this relational query being done on users (team is what it is called here).

{% set relatedDepartment = craft.entries.section('departments').relatedTo({
     sourceElement: teamEntry,
     field: 'departmentLabel'
}) %}

My understanding is this is set up correctly and should only pull the department information related to that entry in the loop?

the whole block looks like this

{% for teamEntry in craft.entries.section('team').order('title').find() %}

    {% set relatedDepartment = craft.entries.section('departments').relatedTo({
        sourceElement: teamEntry,
        field: 'departmentLabel'
    }) %}

        {% set mad = teamEntry.imgMad.first() %}
        {% set disgusted = teamEntry.imgDisgusted.first() %}
        {% set sad = teamEntry.imgSad.first() %}
        {% set neutral = teamEntry.imgNeutral.first() %}
        {% set content = teamEntry.imgContent.first() %}
        {% set happy = teamEntry.imgHappy.first() %}

        {% if neutral | length>0 %}

        {% else %}

        {% endif %}

{{ teamEntry.title }}
{% for department in teamEntry.departmentLabel %}{{ department.title }}{% endfor %}

            View Profile

 {% endfor %}


texts: I have a section of type structure where I need the url to be /5minutes. I cannot make this work (note that I have changed the handle to fiveminutes. But everything I would like to be 5minutes. I even tried setting a route for 5minutes. My question then is this. Is is simply not possible to begin a route or section with a numerical value?


texts: I have a site where I want to set up a "tour" of a software screenshot, and I need to allow users to select points on an image to insert the tour "stops". Is there an add-on like DevDemon's Entry Mapper for Craft? Or does anyone have a suggestion for a way to do this that doesn't involve explaining to a client how to figure out coordinates on an image and then entering them into a Matrix field?


texts: How to limit selected items that appear on special page

texts:
I have a client that wants to select "featured" entries to appear on their home page, and in a specific order that they can set and change. My initial idea was to set up a featured check box and just search for that, but I need to limit the possible number of total entries selected to 5.

The entires come from multiple sections so I cannot just limit one section, and I need to limit how many they can select on the backend, not just how many appear in the view (that I can do).

right now the set up is with the featured checkbox, but the problem is they can just keep checking boxes and if they do not uncheck another one it will not have the expected behavior.


texts: Guest entries - send confirmation mail to person who filled out entry

texts:
Inherited a site which uses guest entries for a job application form.

Postmaster plugin is being used to notify someone that a new entry has been posted but now they'd also like to send the person who applied for the job a confirmation mail after submitting the guest entries form... any suggestions on how to do this?


texts: How can I set the dateCreated attribute on an EntryModel?

texts:
I've tried this but it doesn't seem to be working:

$entry = EntryModel::populateModel(array(
    'dateCreated' => DateTimeHelper::formatTimeForDb($someTimeStamp),
    'sectionId' => 1
    'typeId' => 1
));

craft()->entries->saveEntry($entry);


texts: Redactor extension plugin loading JS before Redactor.js

texts:
As I want to use two different Redactor plugins, table.js and properties.js, I decided to write a simple Craft Plugin to load the JS using includeJsResouce in the init() function, as so;

function init() {

    if ( craft()->request->isCpRequest() && craft()->userSession->isLoggedIn() )
    {
        craft()->templates->includeJsResource('myextensions/js/properties.js');
        craft()->templates->includeJsResource('myextensions/js/table.js');
    }

}

However, I have found that these JS files are being loaded in the HTML before the Redactor.js file, so I get a JS error in the console, as Redactor is undefined. [Uncaught TypeError: Cannot read property 'prototype' of undefined]

Is there a way to ensure that my plugin JS is loaded after Redactor that does not entail hacking the core of Craft?

The version of Craft I am using is the current, Craft Pro 2.5.2753.


texts: How do you set a flash message in the template in Craft 3?

texts:
How does one set a flash message in the templates? I can't find any documentation about this, only for plugins or getting the message.

My use-case is, I am checking if a user is allowed to access a certain page and if they cannot I want to set a flash message, then redirect them to another page. I prefer this than to keep them on the same page and is if else logic to show the message or the rest of the page.

Thanks


texts: amforms - Specific entry in the notification template

texts:
How can I get a specific value from the submitted form? E.g. the fullName field.

The default template loops through all the fields with a switch but I just want to output one specific field. Can't get it to work.


texts:
I have a group of different regions which would like to have region admins who can't approve content from each other's region but also have a super admin who can approve content from any regions. I will outline below the how this is laid out and would like to know if its possible with Craft.

Super Admin (master admin - approval master)

Region 1 (region admin - approvers)

Location 1 (location admin - drafters)
Location 2 (location admin - drafters)
Location 3 (location admin - drafters)

Region 2 (region admin - approvers)

Location 4 (location admin - drafters)
Location 5 (location admin - drafters)

Region 3 (region admin - approvers)

Location 6 (location admin - drafters)

Super Admin can approve any item created by location admins and region admins.

Region Admins can approve only content created by location admins within their region only

Location Admins can only create drafts


texts: Craft CMS throws Internal Server Error 500

texts:
I got given a Craft CMS project build with composer and npm. Pointed valet to the correct folder, installed all the dependencies and started the app with npm run watch.
http://localhost:3000 just gives me an "Internal Server Error" though...

There is nothing in the logs apart from sth inside storage/logs/web.log which does not sound like a showstopper:
2020-12-07 06:59:06 [-][-][-][error][yii\base\ErrorException:8192] yii\base\ErrorException: Method ReflectionParameter::isArray() is deprecated in /vendor/yiisoft/yii2/web/Controller.php:133 Stack trace:
Error 500 bugs are really hard to track down, any hints would be appreciated!


texts: Different template for an entry in section

texts:
If I have a Section called "Pages" that uses the "page.html" Entry Template.

How do I override that template for a single page in this Section?

I thought I would be able to use Craft Routing but the Entry request (#4) is picked up before the Dynamic Routes (#5).

Is there a nicer solution to this rather than a bunch of if statements in the template?

{% if craft.request.getPath() == "about" %}

    {% include '_includes/about.html' %}

{% endif %}

I also found this solution, but not sure if it's overkill if I only want to override 1 Entry?


texts: Commerce - Live Environment - "Trying to get property of non-object"

texts:
I have a site and been tested locally and on staging server and it checks out fine.
I have moved it to the clients live server (Windows 2016) but when I hit the pay button via dummy gateway or Worldpay Gateway I get the error:

Trying to get property of non-object:

Why is this only occuring on the Live Environment - PHP version is the same locally as the server - 7.1.7


texts: Import JSON feed data automatically without FeedMe

texts:
Can JSON feed data be displayed in a Craft site automatically?

I have a page: URL/asdfh3
I've been dynamically using 'asdfh3' to pull in data from the JSON feed that is associated with 'asdfh3'.
This template works - BUT ONLY if an entry for 'asdfh3' already exists in craft.

Whilst this can be achieved by running a feed update using the FeedMe plugin, it isn't a satisfactory method - as the site breaks if new data is entered into JSON without a feed update in Craft (no template found).

So, how can Craft display external content without having to set up entries for each piece of external content?


texts: How can I translate checkboxes on a frontend user registration form to lightswitch custom fields?

texts:
I've got a frontend user registration form working that's populating a whole set of custom fields I've set up on my user profiles in Craft.

But I've got a set of lightswitch fields on my user profiles that I'm trying to set via checkboxes in the registration form but the values are not transferring over when submitting the form.

Here's an example of my checkbox code in the frontend form (the corresponding lightswitch field handle is memberShowEmailLink):

<div class="checkbox">
  <label>
    <input type="checkbox" id="memberShowEmailLink" name="fields[memberShowEmailLink]" {% if account is defined %}value="{{ account.memberShowEmailLink }}" checked="checked"{% else %}value="0"{% endif %}>
    Show a link to contact me via email in the member directory?
  </label>
</div>

Is there a way to change it to make this work?


texts: Getting 403 when trying to update from Craft 3.3.20.1

texts:
I just updated Craft Pro to 3.3.20.1 and went to run the next set of Craft updates (all from the cp). But now when accessing the updates page, the "checking for updates" spins continuously and I get these messages in my console:

POST https://www.my-domain.com/index.php?p=admin/actions/app/cache-updates 403 (Forbidden)

Uncaught (in promise) undefined

Everything else in the CP and front end seems to work ok. I'm not certain how/where to go next to fix this. Any advice would be greatly appreciated.

EDIT: I'm not certain how/if this is related but I do have a PHP error that may have occured around/at the time I tried to run this update:

[17-Jan-2020 14:03:31 America/Detroit] PHP Fatal error:  require(): Failed opening required '/chroot/home/signamoc/craft/vendor/composer/../danielstjules/stringy/src/Create.php' (include_path='.:/opt/nexcess/php72u/root/usr/share/pear:/opt/nexcess/php72u/root/usr/share/php:/usr/share/pear:/usr/share/php') in /chroot/home/signamoc/craft/vendor/composer/autoload_real.php on line 66


texts: We are experiencing incredibly slow site performance. Any tips on where to find out how much memory the site is using, or if increasing this will increase internal site loading and navigating speed? Thanks for your help!!!


texts: I have a simple rss feed in my Templates directory, appropriately named "feed.rss". I'm trying to create a link to that file but I don't want that to show up if the file doesn't exist. How might be the best way to only show the link, if the file exists?


texts: Translating the option labels of Dropdown, Checkboxes or Multi-select fields

texts: Is it possible to have the labels for any of these fields be translatable in templates? I don't mean make the whole field translatable - the same option values would be shared between locales, I would just like the output the label in the correct language.


texts: Failed to add a custom field in settings

texts:
I'm trying to add a global set, with a Matrix and two required fields for a product. This always works.

Now that I am in version 2.6.2791 it fails to add the fields with error:

Warning
: Declaration of Craft\UserSessionService::login($username, $password, $rememberMe = false) should be compatible with CWebUser::login($identity, $duration = 0) in
/Applications/MAMP/htdocs/craft-app/2.6.2791/services/UserSessionService.php
on line
17

Warning
: Declaration of Craft\UserSessionService::afterLogin() should be compatible with CWebUser::afterLogin($fromCookie) in
/Applications/MAMP/htdocs/craft-app/2.6.2791/services/UserSessionService.php
on line
17

Warning
: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/craft-app/2.6.2791/services/UserSessionService.php:17) in
/Applications/MAMP/htdocs/craft-app/2.6.2791/framework/web/CHttpRequest.php
on line
1519

Warning
: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/craft-app/2.6.2791/services/UserSessionService.php:17) in
/Applications/MAMP/htdocs/craft-app/2.6.2791/framework/web/CHttpRequest.php
on line
1507

The CSRF token could not be validated.

Any ideas or fixes would be great!


texts:
Good Evening,

Please bear with me I'm very new to Craft 3. I'm getting deprecation errors when outputting information.

I'm trying to output a single entry from a section using the following:

{% for entry in craft.entries.section('homepage') %}{{ entry.richText }}{% endfor %}

It is giving me the following error:

  Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.


texts: When to choose a Structure over a Channel?

texts: Structures look interesting because you can reorder entries manually, generate breadcrumbs and visually see a hierarchy of entries. Besides this, what are the primary consideration when choosing a Structure over a Channel?


texts:
I have been a wordpress user for the longest time, a friend of mine now uses Craft, I took a look at his backend and really liked the way he creates his content in it. I also like that it uses Twig.

I watched some of the Craft movies on the website about the entry types, structures etc. but it would be of some help if some experienced user could help me with the question if Craft is the right choice for me:

I have a small magazine website about movies, so I would need the following structure:
- Movies (a list of movies, when I click on a movie I would like to have a list of all news, reviews regarding to this movie)
- News
- Reviews
- Directors (a list of directors, when I click on the director I would like to display a list of all of this directors movies)

Is this possible out of the box with Craft CMS? I'd be thankful for any hint on how you would realize this.

Best regards
Florian


texts:
I've been reading on here about suggestions on implementing commenting systems. I'm aware of disqus integration but I want/need  built in commenting.

I have seen it mentioned a couple of times that one approach would be to create a section (presumably a channel) dedicated to comments and the relate that to an entry via an entries field.

I just can't quite wrap my head around how that works out. Do the entries have to be manually selected in order to relate them?

If anyone's built something like this then I would love to know how they tackled it!

One thing to add is that only registered members will be commenting. And there would be several different sections needing comments.

Thanks!


texts: Display entries with matching checkbox field values

texts:
I apologize if this question has been asked before. I'm new at this and am struggling to figure out if what I need to do is possible/the right way to do it or if I need to structure my content differently.

My entries in a section have a field that use a checkbox field type. I would like to display entries that have a matching value based on that field.

Example:
 Field: Vitamins,

  Field Type: Checkboxes
              Option: Vitamin A  | Value: a
              Option: Vitamin B  | Value: b
              Option: Vitamin C  | Value: c

Section: Vegetables

 -Entry: Broccoli
       Vitamins Field Values: a, c

 -Entry: Corn
       Vitamins Field Values: a, b

 -Entry: Squash
       Vitamins Field Values: a, b, c

I'm trying to figure out how to display all entries that contain Vitamin A.


texts:
Is there a way to output the currency symbols for each accepted payment currency in a Craft Commerce site?

Consider the following simplified example;

{% set currencies = craft.commerce.paymentCurrencies %}
{% if currencies|length > 1 %}
<select name="paymentCurrency">
    {% for currency in currencies %}
        <option>{{ currency.iso }}</option>
    {% endfor %}
</select>
{% endif %}

Instead of the currency ISO code being output in the option, I also want to show the symbol. I can't find a method for doing so.


texts:
So I raised a previous thread here.

https://craftcms.stackexchange.com/questions/16741/conflict-with-htaccess-htpswd

Basically with the site behind a htpasswd (as it is a staging url) after entering the correct u/p I would get redirected to a 404 which was in fact a 401 error.

After further investigation and some support from CPanel. I understand that there is a requirement to add the following line to the htaccess file before the rewrites (in the Craft rewrites).

RewriteCond %{LA-U:REMOTE_USER} !^$

So the Craft rewrites now look like this;

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{LA-U:REMOTE_USER} !^$
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

This only became an issue this week. Previously it all worked fine before this. The above solution does seem to be a fix. But I'm a little stumped as to why this is required now and was working ok before. Has anyone else come up against this?

CPanel seemed to think it wouldn't have ever worked without this line. But it did and I am sure others have it working without a need to add this.

The difficult thing is that I am unable to get a clear reason as to why this is now required and what has changed to enforce this. Over the past week a few things have occurred and so I cannot pinpoint. These updates to the server have included;

Updating Apache 2.2 to 2.4
Upgrading to easyapache 4 from easyapache 3
Updating Craft after the latest releases.

If anyone can shed any additional light on this it would be useful. Also if anyone can confirm if they also need to include the RewriteCond %{LA-U:REMOTE_USER} !^$ into their htaccess.


texts: Craft 3 multi-site route to template (no entry)

texts:
I have a Craft 3 multi-site site - / for the main site, /site1/ for site1, etc. I have a template templates/foo.twig, and /foo hits it for the main site, but /site1/foo does not hit it for site1. I think it should. What am I doing wrong?
I am trying to get case 4 of the Routing algorithm to work with multiple sites:

Does the URI match a template?

Finally, Craft will check if the URI is a valid template path. If it is, Craft will return the matched template. Note: if any of the URI segments begin with an underscore (_), Craft will return a 404. Craft hides from direct access any template path segments that begin with an underscore.


texts:
I'm trying to create a plugin to create/update users' profile data. I figured out how to create a user but updating... not so much.

Here is the code I'm using:

$user = craft()->userSession->getUser();
$user->setContent(array('middleName' => "Dave"));
craft()->users->saveUser($user);

From what I understand the "saveUser" method is used for both creating and updating user data. Whenever I run the code I get the following error:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-en_us' for key 'craft_content_elementId_locale_unq_idx'

If "saveUser" is truly used for creating and updating what am I doing wrong?


texts: Is there a limit to outputting entries in 'free' version of Craft CMS?

texts:
I am outputting all my entries and it seems that on the front end, it isn't displaying entries from N to Z. I see those entries in the backend. The entries on the front end:

http://www.colorcomputergames.com/games

The template conditional doesn't have any limits on N to Z or the number of entries to show. The entries are enabled.

Is this due to using the free version of Craft CMS or some other setting?

My template code is:

{% extends "_layout" %}
{% set title = "Games" %}
{% set entries = craft.entries.section('games').order('title') %}
{% block content %}

    {% for entry in entries %}

            {{ entry.title }} ... {% set publishers = entry.GamesPublisher %}{% for publisher in publishers %}{{ publisher.title }} {% endfor %}{% if entry.GamesGenre is not empty %}{% for category in entry.GamesGenre %}{{ category.title }}{% endfor %}{% endif %}{% if entry.GamesReleaseYear is not empty %} {{ entry.GamesReleaseYear.format('Y') }}{% endif %}

    {% endfor %}

{% endblock %}


texts: Is there a way to react to Control Panel changes to an order?

texts:
One of the major issues I have been having with my current project is how to reconcile changes to an order in the control panel (product amounts and the like). I thought I might be able to react to Order events but it would seem that the ADD_LINE_ITEM_EVENT and the like are only called from the user-facing side (ie a Cart).
I need to be able to update quantities available from the changes to the Order in the Control Panel, any suggestions?
An Example:
Jane Doe orders product A, our friendly staff member gets notified and speaks with Jane to complete the transaction. Jane decides she actually wants 2 of product A and heck, why not product B. Friendly staff updates her order, redoes the authorization, captures it, and thinks they are done. Now though, we have not updated our stocks for product A and B of which there is a limited amount and we can now potentially oversell!
What are we supposed to do here?


texts:
I'm getting an interesting (new) error when adding (or editing) entries in Chinese. If the slug is in Chinese I now get the following error:

URI is not a valid URI

It's interesting because I wasn't experiencing that with Craft 2.2. It was allowing me to save entries with Chinese characters in the URI. After upgrading to Craft 2.3.2615 it looks like all Chinese language URIs are now disallowed?

Is this intended behaviour?


texts: 'Variable "assetSourceOptions" does not exist' after updating to Craft 2.6

texts:
When I try to add another field, suddenly I get this error:
"Variable "assetSourceOptions" does not exist"

This started after I updated to Craft 2.6


texts: Edit FreeForm lite from front end in Craft 3

texts: I currently have a freeform which allows a user to register his/her information. I'm looking to build an edit page for each of these entry's so the user can come back and edit it if they've made a mistake.


texts: Fetch all entries with dateUpdated after a given time

texts:
I'm trying to grab all Entries that were updated after a given date and time.

It seems like I can grab all entries updated after a date using the following:

{% set timeLimit = now | date_modify("-2 min") %}
{% set updated = craft.entries({ dateUpdated: '>=' ~ timeLimit }).section('myChannel') %}

The problem is, that code doesn't actually seem to take time into account at all, just date. timeLimit in the above will always return something like 2014-08-21.


texts: Craft Commerce - For a discount, can we include all products in the product count but not include the sale items that receive the discount?

texts:
What I would like is for a 10% discount to be applied to non sale items after the total cart quantity reaches 10 total items. I would ONLY like this discount on non sale items. Is that possible?

So, say I have 2 Products in my cart:

Item A - $20 on sale for $10, qty 9
Item B - $20, qty 1

This makes my total in cart quantity 10 line items even though 9 of them are sale items.

What I would like is for Item B to be discounted 10% making my cart total $108

( (10*9) + (20 * .9) ) = 108

As it currently stands, if I toggle Exclude this discount for products that are already on sale it doesn't count the sales items towards the total.


texts:
I'm iterating through a folder using craft.assets, to select the folder I'll use the folderId.

What's the best way to find the folderId of a specific folder?

The only way I've found is to go the the Asset Settings page in the CP and hovering over a folder to see the url in the status bar in my browser.

Related Problem:

I created a folder in the CP Fields page (see image) and there seems no way to get this folderId as I cannot get to it in the Asset Settings page. As I only have a small number of folders I was able to figure it but it got me wondering if I was missing the obvious somewhere?

Thanks

John


texts: Show 2 random entries based on checkbox in Super Table

texts:
I have a Super Table field (entryType) with a checkbox field "featuredIn" and some values.

This is how it looks when creating a entry:

I can't figure out how to mix "slice" and "orderBy RAND" with filtering by that field.

This does show me 2 random entries from all:

{% set entries = craft.entries.section('blog').orderBy('RAND()').all() %}

{% for entry in entries|slice(0, 2) %}
  {{ entry.title }}
{% endfor %}

This shows me only the entries where "showInRandom" is checked (but not random and not only 2):

{% for entry in craft.entries.section('blog') if entry.entryType.featuredIn.contains('showInRandom') %}
  {{ entry.title }}
{% endfor %}


texts: How to save multiple related entries on the frontend with 1 checkbox?

texts:
I have a frontend form and would like to save multiple related entries by checking 1 checkbox.
I have this working to save 1 related entry:

<input type="checkbox" id="user-type-select-{{ userType|kebab }}" name="fields[hasUserTypes][]" value="{{ userType.id }}" />

But how do I pass multiple userType.id values in there? I tried various syntaxes such as comma seperated, enclosed in brackets like an array or a comma seperated string with the |hash filter as seen here but nothing worked.

What is the correct sytax?


texts: How can I add fields to my Sprout Form plugin?

texts:
I am not sure what I have done wrong, I am working with a fresh install of Sprout Forms.

When I create a new form and then click "Add Field" in the layout designer, this is what I am seeing.

Any suggestions are appreciated!


texts: Issue with twig loop.first loop.last contained in nested for statement

texts:
I'm trying to pull out selected categories in a front-end user profile. The cats have 2 levels and need to be pulled out into a nested list with only the selected options. I've tried different ways of doing this but nothing seems to work by using one for loop. So have nested the second level cats in a second for loop. This will work but the loop.first and loop.last variables are using the parent for loop and not the nested one? Or is there a better/easier way of doing this?

{% for challenge in user.challenges.level(1).options %}

        {{ challenge.title }}
        {% for child in user.challenges.level(2).options %}
            {% if child and child.getParent().id == challenge.id %}
                {% if loop.first %}
{% endif %}

{{ child.title }}

                {% if loop.last %}
{% endif %}
            {% endif %}
        {% endfor %}

{% endfor %}


texts:
Have been using nystudio107 scripts to manage database workflow. Just launched first Craft 3 site and noticed that when i went to sync the database locally from server the /tmp partition on the server maxed out in seconds and brought the whole server down when trying to copy the database.

The culprit turned out to be 5G of cache content in craft_templatecachequeries which maxed out the partition tmp size (4GB)

I had added cache tags around main for loops, but i spotted that i had lazily tried to cache the whole news index page with the news index template being cached from top to bottom. I have removed these.THe cache table size has improved to a more stable 1GB but that seems incredibly high still.

Is this normal for Craft3?
(I guess there is a possible separate issue with scripts for db sync/pulling)


texts: I can't get Tags and Archive pages to appear

texts:
Necessary disclaimer. Web design dilettante, so I ll probably have trouble following your answers if they get too technical.

I am building a blog. I am am trying to use tags bellow posts and when the user clicks on them, go on a page that shows all the relevant posts containing that tag.

I followed the instructions on this page and while I can get the tags bellow the blog post, when I click on them, I am getting a 404 page.

Similarly, I tried creating an archive page by following the instructions on this page but while I can get the code to appear if I append it at the end of my index.html page, I cannot get it to appear on a separate web page.

I suspect I am making a blindingly obvious mistake, but I can't figure out what. Do you have any suggestions of things to try?

Thanks


texts:
I'm looking to try and build a site that allows users to register an account and then add all of their social media profiles in one place, similar to addme.fun. Their profiles would then have public URLs that they could share, and it would also give them the ability to add more content and edit their profiles. Is Craft a good CMS for that?

I've built some really great projects with Craft and overall I love it, but I just want to make sure that it has all the capabilities that I'd need before I put too much time into it. Thanks, all!


texts:
I've got a news website built and I am in the process of improving it's performance. What would be the best way to measure the performance of my templates?

I can use Chrome Developer tools to measure how long it takes for the server to respond but is that the best way of doing it or can I do it internally?


texts: Wrong urls printed for small subset using getNext and getPrev

texts:
I have a related question regarding previous and next throwing a template error for some entries.  This is similar, but different.

A few entries in the same section depict the wrong previous and next ent.   Instead of linking to the previous or next entry they link to the About or 404 page.  It only impacts 2 or 3 out of 100 entries - but always the same 2-3 entries.

There are no templates errors - just the wrong urls being printed for a small subset of the entries.  Here is the code...

`
                {% set prev = entry.getPrev( 'posts' ) %}
                {% set next = entry.getNext( 'posts' ) %}

        {{ entry.postDate | date('F d, Y') }}

`

Thanks


texts: How can I use a WHERE statement in my template?

texts:
I am trying query against URL segments. Where I am hung up is how to pass those arguments to a related field.

For example, here is my current query:

twig

{% set profiles = craft.entries({
    section: 'profiles',
    with: ['userAccount']
}) %}

userAccount is a user field that is related back to the user.

I get all entries along with the user account information & all is well.

I would like to query against the userAcount field to only return the appropriate entries in the profile section given url segments.

For example: www.mysite.com/profiles/foo/2017

From the userAccount field:

foo is a checkbox field (name is userOptions. Options are: foo, bar, baz)

`2017 is a plain text field.

This is what I am trying to accomplish (obviously is not correct)

{% set profiles = craft.entries({
    section: 'profiles',
    with: ['userAccount'],
    where: ['userAccount[0].year', '=', craft.request.segment('3')],
    where: ['userAccount[0].userOptions', '=', craft.request.segment('2')],
   limit: null
}) %}

I am getting entries bak when I only query against the year. I haven't checked if they are correct but at least I get something. Where I'm thrown is since userOptions could be any value, how can I check that field if a selected option matches the url segment? Any user could have foo and bar selected. I think I need something like a WHERE IN or something...

Thank you for any suggestions!


texts: Show multiple products (urls/pages) on the front-end with dynamic titles/descriptions/meta based on a single product in Craft Commerce

texts:
I am considered the best way to set this up in Craft and how to handle this with front-end Urls, templates and routes?

So I products with variants for Wheel Spacers, (Wheel Spacers are a product type), these wheel spacers will be related to specific vehicles (vehicles is a separate channel). As these spacers will be related to several vehicles, it doesn't make sense to duplicate them as multiple products.

However, the part I am stuck with is how to list these products in multiple instances on the front-end so that it uses the same product but various information is pulled in from the vehicle. As an example.

Say the product 4x100 56.1 Wheel Spacers (4100561) relates to the following vehicles:

Audi Q7 (2009-15)
Mini Cooper S (2002-2006)
Mini Cooper S (2006-2012)
Mini Cooper (2008-2012)
Mini Cooper (2012-)
BMW Z1 (2012-)

I would like to show the product  4x100 56.1 Wheel Spacers (4100561) as separate pages for each of those models. With each one showing dynamic information for the SEO meta,  and description, this would be pulled in dynamically e.g

Audi Q7 (2009-15) 4x100 56.1 Wheel Spacer
Mini Cooper S (2002-2006) 4x100 56.1 Wheel Spacer
Mini Cooper S (2006-2012) 4x100 56.1 Wheel Spacer
Mini Cooper (2008-2012) 4x100 56.1 Wheel Spacer
Mini Cooper (2012-) 4x100 56.1 Wheel Spacer
BMW Z1 (2012-) 4x100 56.1 Wheel Spacer

At the same time user will be able to browser by product types (Wheel Spacers, Adapters, Fixings etc) but also by Vehicle Manufacture (Audi) and Model (Q7 (2009-15)) etc

If anyone can give me thoughts on the best way to structure this in Craft CMS and how to best structure the templates, the URLs and routes?

Thanks,


texts:
I'm pretty new to CraftCMS and am trying to install updates for a client. I am getting this error and I don't really know what it means. Any help of brief explanation for this would be appreciated.

Error: The "https://asset-packagist.org/packages.json" file could not
be downloaded: allow_url_fopen must be enabled in php.ini (https://
wrapper is disabled in the server configuration by allow_url_fopen=0
failed to open stream: no suitable wrapper could be found) Output:
Loading composer repositories with package information.


texts: What are best practices for using Matrix fields to establish a grid layout

texts:
I am using a Matrix field for content blocks like heading, text, images, ... similar to the HappyLager demo site. Now I would like to combine this with common CSS grid systems (e.g. from Bootstrap, Foundation, ...).

Typically they need to wrap rows in a
 and columns in e.g. a
. The easiest way would be to provide dummy matrix blocks for opening rows and columns (with a radio-button field to specify column with) and blocks for their corresponding closing tags. But of course the user should not forget to close the blocks otherwise the layout breaks. Is there a better way to do this?


texts: What are the most common template performance gotchas to avoid?

texts:
I'm coming to Craft as someone experienced with Expression Engine templates. When I'm coding for EE I try to avoid certain big ticket performance hits, for example:

Using embeds excessively.
Using the disable parameter.
Using simple conditionals vs. advanced conditional when possible.
Keeping a close eye on the query count.
Etc.

In the Craft/Twig world, are there similar common pitfalls to avoid when thinking about template performance? What kind of things should I watch for?


texts: Live Preview failing in Safari and Firefox only

texts:
New Craft user here and I am working on wrapping up my first Craft site and am running into a Live Preview error.

When Live Preview is activated in either Firefox or Safari, I just get a blank white page and am getting this error thrown in the console:

  XMLHttpRequest cannot load http://mysite.com/section/slug. Cross-origin redirection denied by Cross-Origin Resource Sharing policy.

I'm not really sure what that is other than it sounds like I need to give something access that doesn't have it.   And I'm not sure why this error doesn't get thrown in for Chrome or IE.

Any help would be appreciated!


texts:
Having an issue with using the event \craft\elements\User::EVENT_AFTER_SAVE in a plug in. I am adding a new user to a group. My goal is to have the newly added user automatically added to the same user group as the logged in user. This is my code:

Event::on(
    \craft\elements\User::class,
    \craft\elements\User::EVENT_AFTER_SAVE,
    function(ModelEvent  $event) {
        if (Craft::$app->getUser()->getIsAdmin() == false){
            $loggedInUser = Craft::$app->getUser();
            $userGroupUser = new UserGroup_User();
            $userGroupUser->groupId = $loggedInUser->getIdentity()->getGroups()[0]['id'];
            $userGroupUser->userId = $event->sender->id;
            $result = $userGroupUser->insert();
         }
    }
);

I have put a breakpoint on the code after the if statement and then checked the users table - the new user is not in the users table yet.

I would expect that the new user would be in the table at this point. Is this transaction being saved and executed later? If so is there something I can do to force the transaction to save the new user?

Is this possible a bug?

I do not get any error messages. Why?

EDIT: I should also mention that the usergroup has permission to add users in their own usergroup.


texts:
I have one user group created, several users in it excludes admin.
I've tested it includes admin to that user group, but with no effect.

If you create an entry in channel as admin and check at front end for author of the entry, you'll see not admin, but actually the data of a first user created in Craft.

Is it done on purpose? If so, What is it, so I understand that.


texts: Checking the link type from a LinkIt field returns the whole path

texts:
I'm doing a project in Craft 3, there are many types of links so I installed the LinkIt plugin. I'm facing problem with this because I didn't find a method to check link type.

If I use {{ entry.linkItField.typeHandle }} it returns the whole path (e.g. "fruitstudios\linkit\models\Url"), not just category, entry, URL etc.

Also, using {{ entry.linkItField.url }} only works on custom links.


texts:
{{ entry.url }} is generating a https:// link. I don't have SSL on this site, so the page errors out.

Settings > General > Site Url is "http://..."

My .htaccess is below (though I've read the redirect doesn't work on shared hosting).

    RewriteEngine On
    RewriteBase /
    RewriteCond %{SERVER_PORT} 443
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Aside from "Get an SSL certificate," any suggestions on a fix?


texts: Show content if logged in user is in userGroup1 OR userGroup2?

texts:
This is so simple in ExpressionEngine and yet I've tried everything for several hours and can't find a way to get it working in Craft???

I have 2 User Groups: userGroup1, userGroup2

If the currently logged-in User belongs to either of those groups, show them "==SECRET CONTENT==" that guests (not logged-in users) do not see.

The following IF will only show "==SECRET CONTENT==" to userGroup1:

{% if currentUser and currentUser.isInGroup('userGroup1') %}
    ==SECRET CONTENT==
{% endif #}

Now, based on everything I've found and read, it would seem the following SHOULD show ==SECRET CONTENT== to Users belonging to EITHER userGroup1 OR userGroup2:

{% if currentUser and currentUser.isInGroup('userGroup1','userGroup2') %}
    ==SECRET CONTENT==
{% endif #}

But it only shows ==SECRET CONTENT== to userGroup1. And if I switch the isInGroup values to the following, only userGroup2 see the ==SECRET CONTENT==

{% if currentUser and currentUser.isInGroup('userGroup2','userGroup1') %}
    ==SECRET CONTENT==
{% endif #}

I've tried Group IDs. I've tried every variation of formatting, array syntax, etc.
I've searched the docs and StackExchange dozens of times...

How can I display "==SECRET CONTENT==" to users belonging to userGroup1 OR userGroup2 ??


texts: Get radio button's value from a form by PHP

texts:
I have been developing validations for my form.

It is possible to get text input's value like;

$password = Craft::$app->request->getBodyParam('password');

However, this function seems not to work for radio button fields. Could you tell me how to get radio button's value?


texts:
So I want to edit date type filed on entry save, but I don't know how to format it. It times out on string and don't seem to accept DateTime objects either.

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(ElementEvent $event) {
        if ($event->element instanceof \craft\elements\Entry) {
            $entry = $event->element;
            if($entry->sectionId == 16){
                $entry->rangeStart = date_create_from_format('d/M/Y:H:i:s', '01/01/2019:19:00:00');
                Craft::$app->elements->saveElement($entry);
            }
        }
});


texts: Populate Lightswitch field from Frontend Entry Form

texts:
I have the following buttons on my frontend entry from (user editing one of their entries). The idea is to turn the lightswitch "on" (green) when entry is being marked as draft and "off" when submitted for review. The turning it "on" part seems to work. I just cannot seem to control its "off" state.

        <button class="btn btn-primary btn-lg btn-block " style="margin:10px 15px 0 0;" type="submit"  name="fields[gistDraft]" value="true">Save as Draft</button>

          <button class="btn btn-success  btn-lg btn-block " style="margin:10px 15px 0 0;" type="submit"    name="fields[gistDraft]" value="false">Save &amp; Submit for Review</button>
        </form>


texts: Is it possible to login automatic the user right after he validate his email address


texts: Controller redirect not working in craft 3

texts:
I am working with Craft 3 and in my controller, I am trying to do this
$this->redirect('https://foobar.test');
But it is throwing me back to the root url of my craft site. I am confused, what else do I need to do?


texts: How to add a tags-field to an entry form?

texts:
I use the following entry form (front-end): https://craftcms.com/docs/templating/entry-form

How can I add a tags-field to this entry form?


texts:
I am very new to this CMS and I was able to set it up, import some content from csv files.

I have set up templates and right now if someone clicks on the article, the URL is www.example.com/articles/{slug} of the article. This is all fine if I wasn't migrating from another system and we have a ton of articles and the URL was based on SEO requirements.

I have set up a channel type and one of the fields is Category type. I have 2 more category type fields but I don't use them to create the URL.

Here is the screenshot of what it looks like

A lot of content from olden days doesn't have the second category (so would just belong to Analog/ Mixed Signal ICs) but the newer content (from last 3 odd years most likely has it). So when the Url is display I want the URL to be either www.example.com/Analog_Mixed_Signal_ICs/Title
or
www.example.com/Analog_Mixed_Signal_ICs/Amplifiers/Title

I am not sure if this simple or complex but I would appreciate if someone can tell me how to achieve this.


texts: Feedme import formatting into Refactor from JSON

texts:
Having had a bit of a nightmare trying to get content out of Wordpress into Craft via Feedme have written an intermediary script to sanitise the WP XML export into something more palatable (JSON).
However still having issues and it looks like Feedme is breaking the supplied string for HTML content into an array (breaking on commas).
For example:
"content":"

Importance of passing your MOT first time<\/h2>
At Rygor, we understand that …
"

Is being passed into Redactor (via the Feedme debug) as:
(
    [type] => text
    [enabled] => 1
    [collapsed] =>
    [fields] => Array
        (
            [body] => ["

Importance of passing your MOT first time&lt;\/h2&gt;

At Rygor","we understand that it is important to …
        )
)

Oddly the body string has no closing quote.
Any thoughts how best to encode my HTML string or to avoid FeedMe breaking my string into an array?


texts: Checking if Matrix fields are empty or not?

texts:
In a Matrix field i want to check if block.logolink (simple text) OR block.logolinkDropdown (dropdown with empty field) are empty or not:

{% if block.logolink or block.logolinkDropdown %}

If i check them with {{ block.fieldHandle }} they're empty. But still it passes the condition.

Where's my mistake in this statement?

{% for block in entry.logomatrix %}
{% switch block.type %}

{% case "logo" %}
{% if block.logobild %}
    {% for logo in block.logobild %}
    {% if block.logolink or block.logolinkDropdown %}
        {% if block.internerLink %}

        {% else %}

        {% endif %}
    {% else %}

    {% endif %}

    {% endfor %}
{% endif %}

{% case "textbutton" %}
...

{% endswitch %}
{% endfor %}


texts: Does CSRF protection for controller actions require POST?

texts:
I've got a controller action which will work as the callback URL for OAUTH authentication with an external, third-party API. After authenticating, the external API will issue a GET request to my callback URL, which means I need to allow anonymous access for the action method. However, I'd like to use CSRF protection for it.

I've set enableCsrfProtection to true in my config/general.php file, and the tokenParam setting is token. I've also added protected $allowAnonymous = array('actionAuthCallback'); to my Controller.

Here's how I create the callback URL:

$callbackUrl = UrlHelper::getUrlWithToken(UrlHelper::getSiteUrl('actions/myplugin/mycontroller/authCallback'), craft()->request->getCsrfToken());

The resulting URL looks like this:

https://mysite.com/actions/myplugin/mycontroller/authCallback?token=2423552353djfsjfdsfjsdfsdfrandomrandomawesome

I've validated that the correct action method fires, so all good so far.

Here's the important bits for the action:

public function actionAuthCallback()
{
    $this->requireToken();
    ...
    $this->returnJson(array(
        'success' => true,
    ));
}

If I call the action URL without the token query parameter, stuff works as expected – Craft throws a 400, as it should.

However, if I do include the token parameter in the URL, Craft throws a 404. What's even more confusing, this happens even if I leave out the $this->requireToken(); call in the actionAuthCallBack() method – as soon as Craft sees the token query parameter in the URL, the 404 exception is thrown.

What am I doing wrong? Does CSRF protection require POST requests?


texts: Check if Assets Field Contains File of Type

texts:
What’s the best way to check if an assets field contains a file of a certain type?

Something to the effect of: if assetsField.contains.file-of-type('image')


texts:
Sorry to repeat this question but not yet found a fix:

Followed the install and when I try and navigate to:
site/admin

I get: "The requested URL /admin was not found on this server"
Have tried moving files around/permissions as 777, and changing the $craftpath but no joy as yet.
I use MAMP set up for other projects so is there an approach without changing MAMP settings?
Or am I missing something obvious?

Appreciate any help albeit a very basic question as want to get started!

Cheers