texts: Craft 3: Upload user photo from front end

texts:
How do I allow logged in users to change their user photo on the front end in Craft 3?

I am creating an "Edit Profile" page and I followed the answer to this question for Craft 2 to create a form updating to Craft 3 syntax where necessary (code below). When I submit the form, the text/textarea fields get updated, but the image does not. Can anyone point me in the direction as to how to get this working?

Thanks in advance!

      <form method="post" enctype="multipart/form-data">
        {{ csrfInput() }}

        <input type="hidden" name="action" value="users/save-user">
        {{ redirectInput('users') }}

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
        {% endmacro %}

        {% from _self import errorList %}

        <input type="hidden" name="userId" value="{{ currentUser.id }}">

        {% if currentUser.getPhoto != '' %}

        {% endif %}
        <input type="file" id="userPhoto" name="userPhoto" value="Upload">

        First Name
        <input id="firstName" name="firstName" value="{{ currentUser.firstName }}">

        Last Name
        <input id="lastName" name="lastName" value="{{ currentUser.lastName }}">

        Bio
        <textarea id="bio" name="fields[bio]">{{ currentUser.bio }}</textarea>

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

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

        <input type="submit" value="Save Profile">
    </form>


texts: Responsive images using Imager when original asset isn't large enough

texts:
Anyone here using the Imager plugin and creating responsive images using srcset and sizes?
Any ideas on how to avoid creating multiple versions of the same image if the original asset uploaded is smaller than the set transforms? I added the setting 'allowUpscale'       =>      false, but this has resulted in 7 versions of the same image (same dimensions etc)
https://github.com/aelvan/Imager-Craft

For example:

/imager/resources/general/359/Golden-Retriever-Isolated_b4a9cbfcf0e16c2bbe8891faf2f17377.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_46442a24ab3b20705cf025765c954564.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_dc3d89e10897fe49613e23ec867b72c7.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_13d85085a2b68d4289e86166bdc76d2f.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_033ae678b7fe3957fc7ac9eab98c2dac.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_78f5cce99e1c3c7765fb260eb99fceaa.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_3907e8c0ed1757af4be1f9f097fb579b.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_6e4e16791425f7dfc1ab06a09cd800f4.jpg 302w,
/imager/resources/general/359/Golden-Retriever-Isolated_042ca14a1382a40b78a83ee7d3f8e3dd.jpg 300w

Edit: here is my code as requested.

{% case "image" %}
{% set image = block.image.first() %}
{% set transformedImages = craft.imager.transformImage(image, [
        { width: 1680 },
        { width: 1430 },
        { width: 1350 },
        { width: 1150 },
        { width: 840 },
        { width: 715 },
        { width: 660 },
        { width: 450},
        { width: 300}
    ], { mode: 'fit' })
%}
<figure{%- if block.position != "full" %} class="img-{{ block.position }}--small"{% endif -%}>
    <img
        src="{{ craft.imager.transformImage(image, { width: 715, mode: 'fit' }) }}"
        srcset="{{ craft.imager.srcset(transformedImages) }}"
        sizes="{{ (block.position == 'full') ? '(max-width: 60em) 100vw, 61.5vw' : '(max-width: 37.5em) 100vw, (max-width: 81.25em) 30vw, 400px'  }}"
        alt="{{ image.altText ?: image.title }}"
    />
    {% if block.caption|length %}
    <figcaption class="figcaption">
        {{ block.caption }}
    </figcaption>
    {% endif %}
</figure>


texts:
Is there anything in craft that can take an xml feed and display it on my site.
It doesn't need to be saved as entries or anything. Simply just display the data.
It's a sports xml feed and there will be fixtures/results and league tables.

I have seen this: https://craftcms.com/docs/templating/craft.feeds
But you only seem to be able to access a few fixed fields.


texts: Filtering/Searching fields with enumerated data (e.g. Smart Map) in an ElementCriteria model

texts:
I have an ElementCriteriaModel in which I need to find elements that contain a particular value for "state", which is a property of a "Smart Map" field ($element->smartMapField->state).

Filtering after a find would be easy, but I need to do this in the ElementCriteriaModel, as I am passing it to the 'criteria' option for ElementAPI (https://github.com/pixelandtonic/ElementAPI).


texts:
I have a matrix block called team that has an assets field within it that has all of the companies headshots. However, there are more than 30 images, but the design is to only have 6 showing on load, and then on click of a load more button the next 6 will show, etc.

However, I'm not sure how to achieve this within a matrix block as all the examples I've seen elsewhere are for pages and sections. But I just need to load the images from within the matrix block.

Below is my code for the images. Can someone help?

{% for headshot in block.headshots %}

  {% if headshot | length %}
  {% set transformedImages = craft.imager.transformImage(headshot,
      [
          { width: 180, ratio: 4/5 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 80,
          position: headshot.focalPoint,
          interlace: true
      }
  ) %}
  {% set tabletl = craft.imager.transformImage(headshot,
      [
          { width: 142, ratio: 4/5 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 80,
          position: headshot.focalPoint,
          interlace: true
      }
  ) %}
  {% set tabletp = craft.imager.transformImage(headshot,
      [
          { width: 230, ratio: 4/5 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          jpegQuality: 80,
          position: headshot.focalPoint,
          interlace: true
      }
  ) %}
  {% set mobile = craft.imager.transformImage(headshot,
      [
          { width: 360, ratio: 4/5, jpegQuality: 65 },
      ],
      {
          format: 'jpg',
          allowUpscale: false,
          mode: 'crop',
          position: headshot.focalPoint,
          interlace: true
      }
  ) %}
  <picture>
  <source srcset="{{ craft.imager.srcset(mobile) }}" media="(max-width: 767px)">
  <source srcset="{{ craft.imager.srcset(tabletp) }}" media="(min-width: 768px) and (max-width: 991px)">
  <source srcset="{{ craft.imager.srcset(tabletl) }}" media="(min-width: 992px) and (max-width: 1199px)">

  </picture>
  {% endif %}

{{ headshot.title }}

{{ headshot.jobTitle }}

{% endfor %}


texts: What is the least intrusive way to allow a user to change their email address on the front-end?

texts:
I have a page that will allow the user to change their name, email address etc.

If I have an email field on my page and submit I get this error.

Param “password” doesn’t exist.

I have read that in order to change a users' email, they need to enter their existing password. I don't have the password field on my profile page...I suppose I could.

Or should I make the whole thing an ajax submit, if the email has changed - show a modal or something asking for a password?

How have others solved this?

Thank you for any suggestions!


texts: How can additional custom fields be added to the Sites settings?

texts:
In Craft 3 Sites, there are some default fields like language, handle, etc.

I would like to add additional fields. Is this possible. Specifically, I want to add an Image field so we can add a flag that we will use in the front end switcher. We also use Geo location and the Geo location databases have their own country identifiers (e.g. Maxmind returns GB for UK), and so I would like to have a field for the Maxmind country code when creating a site so we can match it.

Is this possible? I could probably create a new channel or globals in which we can enter the Site handle, then fetch this data for the site on the front end, but it would be cleaner to have additional fields in the Sites settings.

Thanks


texts:
I'm using A&M forms which is working great. However when a form is submitted the reply to address is the address set in the Control Panel. Ideally one could fill this in with a variable so that it uses the email address submitted by the end user.

is this possible?


texts:
I have a dynamic form that creates entries in Craft 3 Pro. These entries are displayed in a "Profile Page" for each user, but it only shows the newly created entries after hitting refresh 2 or 3 times. This is the code I use to fetch them:
Craft entries loop
{% extends "layout" %}

{% block content %}

    {% set entries = craft.entries.section('cotizaciones').authorId(currentUser.id).orderBy('dateCreated desc').search('statusDeCotizacion:recibido OR statusDeCotizacion:enProceso').limit(null) %}
    {% set countEntries = craft.entries.section('cotizaciones').authorId(currentUser.id).orderBy('dateCreated desc').search('statusDeCotizacion:recibido OR statusDeCotizacion:enProceso').count() %}

    {% if countEntries > 0 %}
        {% for entry in entries %}
            {% include "..." with {'active': true} %}
        {% endfor %}
    {% else %}
        NO ENTRIES
    {% endif %}

{% endblock%}

I've run some tests on Incognito and it seems to work a lot better, is there a default cache that I can bypass to make this process more seamless?
EDIT: jQuery form code
$('.entry__form').submit(function(ev) {
    ev.preventDefault();
    var entryData = $(this).serialize();
    ...

    $.post({
        url: '/',
        dataType: 'json',
        data: entryData,
        success: function(response) {
            if (response.success) {
                console.log("Entry success");
            }
        }
    });
});

This does console out "Entry success" and adds the entry to the database.


texts:
I have one page under https:// how do I deliver the images there via https? Whith the whole site under https it's easy via environmentVariables but what if there is just one secure page?

Is there a realtive url transform variable? Or do I need to set a separate environmentVariables just for the assets on this page?


texts: import _self throwing ElementCriteriaModel could not be converted to string

texts:
{% import _self as mcr_home %}

is throwing

  Object of class Craft\ElementCriteriaModel could not be converted to string

How is this possible and how do I fix it?


texts: Any workarounds for image resizing in Craft 2.5 Redactor II?

texts: Since imageResizable was deprecated for some apparent reason which I have no idea why they would do that. Does anyone know of a workaround or a plugin/config setting to enable this again?


texts: Can admin receive email notifications of new user registrations?

texts: I would've thought this would be core functionality, but does it require additional plugin functionality?


texts: User not being logged out when visiting {{ logoutUrl }} link

texts:
I have a login area on a site which basically just shows a users profile fields. I'm using the {{ logoutUrl }} tag for my logout link and when the user goes to the logoutUrl they're redirected to the homepage however if they visit the profile page URL again, they can still see the content (as if they're logged in) until they do a hard refresh (CMD + SHIFT + R). This seems to be the case in three different browsers. I have tried both of the following to determine if the user is logged in:

{% if craft.session.isLoggedIn %}

And

{% if currentUser %}

Both seem to be effective at showing the content once they login but it's as if the session is being cached or something as these tests are still true after logging out.

Note this happens when I either click a link to the profile URL or manually type it in the address bar. I am not clicking back in the browser.

Also I have also set a custom path with "logoutPath" in the config but this doesn't seem to be affecting the issue I'm having.

Any help would be greatly appreciated!


texts: composer update missing zip extension (ext-zip) on MacOS

texts:
When doing a composer update in a Craft project on MacOS Catalina, I suddenly get the following error:

***** requires ext-zip * -> the requested PHP extension zip is missing from your system.

Any ideas?


texts: Migrating categories from Entry to Asset

texts:
Is it possible to migrate content like categories from an entry to an asset easily?
Each entry has an image asset and I'd like to move all the categories on the entry to the asset.
Would this require a SQL operation or is there any easier way?


texts: Good afternoon, I was wondering to what extent you can change (the order for example) the existing contentblocks on the pages. Thank you in advance!


texts: How do I set all Assets fields in entry to same directory?

texts:
I posed this question in the Craft Help Slack channel earlier but still don't have resolve.

Background on my field setup:

Entry
- Matrix
-- Image Block (matrix.imageBlock) (assets)
--- Mobile Image field (mobileField) (assets)

The image block field in the Matrix is using a restricted upload folder {owner.slug}; which is the entry slug (so its saved to /uplaods/entrySlug/). I also have a child asset field added to the image block to add a mobile specific image. Prior to Craft 2.5, using {folder.path} would put those images into the same /uploads/entrySlug/. Now when I "double click" the asset field to add the mobile image, {folder.path} returns This field’s target subfolder path is invalid: {folder.path}.

I was given a few ideas to pursue as it was thought that maybe the dynamic path had not resolved yet, but they didn't work.

I'm thinking that it does indeed revolve around dynamic paths, however, I can't seem to figure it out. All I'm looking to do is save the child asset field files to the same directory that all the other images go to (one image bank, so to speak, for the entire entry).


texts: How can I specify order when getting all products of a given type?

texts:
I am getting a list of all products for a specific type within commerce. All is well & working great.

I would like to know how I can dictate order. In my case, I always want the cheapest product first; the most expensive last. A perfect example would be if I were purchasing a level of membership in that "level" is a product.

So on my product index page:
mysite.com/memberships

I want to always have the cheapest membership listed first, all the way up to the most expensive.


texts:
I'm trying to set up redirects for some pages (specifically pages in structure sections that are there purely for structure, which I want to redirect to their first child). Craft's  "routes" seem to be geared towards routing a request to a template. But how can I simply route a request to a different URL?

I know I can use Twig's {% redirect %} function, but to be honest I'd much rather just set up all the routes I want redirected outside my template (in order to allow me to avoid (hopefully) unnecessary conditional URL-handling logic in the template). Is this possible at all? If not, is there an elegant way of handling it inside a template?


texts:
I am trying to display the assets on entries.

I created the assets group.
Uploaded the bunch of images to that group.
Added assets to the entries.

Now I didn't understood how to write a code in templates/index.html to display those images.

Right now I want to understood how to display one image.

Thanks


texts:
Is there a way to use Craft javascript API to fetch all Matrix rows of a specific field on the entry edit page?

If not, could that be added? Would be useful, for example in terms of fetching the handle/id and using that in the frontend to simulate Matrix inside Matrix.


texts: Importing User Orders into Craft Commerce with Sprout Import?

texts:
I'm attempting to migrate customer orders from a Wordpress website using Woocommerce to an out-of-the-box install of Craft Pro + Craft Commerce. I've been able to export the user orders as a CSV file, so I'm in the process of converting them to JSON and using Sprout Import to get them into Craft.

I'm using a slightly modified version of the example order template provided by the plugin. The purchaseableId values are set to products within the default Craft Commerce install (A New Toga and Romper for a Red Eye respectively.)

[
    {
        "@model": "Commerce_OrderModel",
        "attributes": {
            "currency": "USD",
            "billingAddressId": "6",
            "shippingAddressId": "7",
            "shippingMethod": "freeShipping",
            "paymentMethodId": 1,
            "customerId": 1,
            "orderStatusId": 1,
            "isCompleted": 1,
            "dateOrdered": "2017-07-02 01:08:38",
            "datePaid": "2017-07-02 01:09:38",
            "returnUrl": "/commerce/customer/order?number={number}",
            "cancelUrl": "/commerce/checkout/payment"
        },
        "content": {
            "title": "Test Order",
            "fields": []
        },
        "lineItems": [
            {
                "purchasableId": "5",
                "qty": "3",
                "options": []
            },
            {
                "purchasableId": "9",
                "qty": "1",
                "options": []
            }
        ],
        "payments": {
            "firstName": "John",
            "lastName": "Doe",
            "number": "4929000000006",
            "month": "5",
            "year": "2017",
            "cvv": "123"
        }
    }
]

When I try to import the above JSON, Sprout Import seems to stall out indefinitely.

Could I get some insight on what I'm doing wrong? Additionally, could someone provide a simple example of importing orders into Craft Commerce with Sprout Import?


texts:
I am trying to develop a loop in a craft template that adjust the numbers of rows and awards per row based on the total number of awards.  The numbers are all coming back correct but I am struggling with getting the syntax of the loop correct. Below is the type of loop I am trying to execute.

for ($i = 1; ; $i++) {
if ($i > 10) {
  break;
}
  echo $i;
}

But I am getting errors because my syntax is not correct and I cannot seem to find this, although I realize I am probably either just missing it somewhere or not recognizing it.

I was trying something like this, along with other variations, but it keeps throwing errors.

{% set exactRowsNeeded = count / 7 %} <!-- correct -->
{% set rows = ceil(exactRowsNeeded) %} <!-- correct -->
{% set exactAwardsPerRow = count / rows %} <!-- correct -->
{% set awardsPerRow = ceil(exactAwardsPerRow) %} <!-- correct -->

{% set r = 1 %}
{% for r %}
{% if r <= 2 %}
  {{ r }}
{% set r = r++ %}
{% endif %}
{% endfor %}

Here throws an error at the "for r" line.  It seems to be looking for something like "for r in rows" or something.  Even just a link to an example would be awesome I just cannot seem to get this syntax correct.


texts: Sort entries by global variable category

texts:
I'm picking a season category (spring, summer, fall, winter)  in a global variable that should dictate what entries come to the top of non-season category pages. These entries are already on a category page, sorted by their main category. I need extra sorting to showcase the "Spring" entries, for instance. Something like this:

Without the season global variable chosen

Test post 1 (Summer)
Test post 2 (Spring)
Test post 3 (Spring)
Test post 4 (Winter)
Test post 5 (Winter)

With the global variable "Spring" chosen

Test post 2 (Spring)
Test post 3 (Spring)
Test post 1 (Summer)
Test post 4 (Winter)
Test post 5 (Winter)

Basically, I want to bring the entries that are using the chosen Global Variable Category to the top, the remaining entries can be sorted by postDate descending. These entries are in a Structure btw, if that matters.

Structure = 'generalContent'
Category Field = 'season'
Global Variable = 'season.season'

Simplified code of my category page.

{% paginate craft.entries.section('generalContent').relatedTo(category).order('lft desc') as entries %}
  {% for entry in entries %}
    {{ entry.title }}<br>
  {% endfor %}
{% endpaginate %}


texts: How can I pull my Username into the transformer of the ElementAPI plugin?

texts:
The username that is entered in URL. I need to pass this data to my transformer as well since I have an EntryModel combined with a Matrix Field.

My problem is that I have a matrix field where there are multiple matrix blocks. I need to query them based on the user field.

This is added on to my original question: How do I query data using the Element API Plugin based on a custom field?

I don't know if there is another criteria setting that I could set so that the matrix would only grab the data for the requested user.

My only other idea was to loop through the matrix blocks and check to see if the username requested was equal to the matrix blocks username field. If it is -- then grab the data that I need and set that in a variable to output in the JSON.

However, I can't do this unless I can figure out how to get the username inside the 'transformer'.

Thanks in advance for all the help. I am learning a lot about this plugin and it is an excellent addition to CraftCMS.


texts:
When you create a Plain Text field it asks if you want to allow line breaks, but they are ignored when output in the template.

I don't want to have to use a rich text field just to enable editors to add a simple line break, but is that my only option?


texts:
I'm trying to create an email newsletter template to make it easier to send out blog newsletters by looping over entries and generating the email straight out of craft. I did this often with Wordpress.

However I'm getting twig syntax errors because of the inline CSS. I know you can do this <style>{{ source('file.css') }}</style> but that's not going to cut it for all the tables I need to add inline CSS to.

Am I missing a Twig filter that I could wrap all my HTML code it?

Just to be clear I am only trying to generate, not send the email newsletter through Craft.


texts:
I imported German text through Feed Me, but the special characters show up as unicode characters:

“Ich interessiere mich sehr f\u00fcr Alte Musik”

I tried a filter when outputting the text, but no success: |convert_encoding("ISO-8859-1","UNICODE-1-1")
However, would prefer to have the text be readable in the backend as well not just on the frontend with the filter.
Any help would really be appreciated!


texts:
Is it possible to perform a search and have the results grouped/prioritized by sections?

e.g. something like:

craft.entries.section(['sec3', 'sec5', 'sec1']).search(...).limit(6) as page_info, page_entries

I want sec3 entries first, followed by sec5 and sec1 entries.

Note that I want to use the built-in pagination mechanism and would not like to use hacks such as searching tons of entries and manually group the results by sections.


texts: Filter entries by month regardless of year using custom Date/Time and paginate them

texts:
I am looking to filter entries by a given month regardless of year. The filter would be based on a custom Date/Time input.  My last goal would allow them to be paginated.

{% set firstDayOfMonth = year ~ "-" ~ month ~ "-01" %}
{% set daysInThisMonth = firstDayOfMonth|date('t') %}
{% set lastDayOfMonth  = year ~ "-" ~ month ~ "-" ~ daysInThisMonth %}

{% set thisMonthsEntries = craft.entries.section('messages').messageDate('and', '>= ' ~ firstDayOfMonth, '<= ' ~ lastDayOfMonth) %}

{% paginate thisMonthsEntries as entriesOnPage %}
    {% for entry in entriesOnPage %}
        {# ... whatever your code does... #}
    {% endfor %}
{% endpaginate %}

This is my original code. My first guess is I would need to have an array of years and loop through each year applying to the above code, however I am unclear on how to get a unique list of years that my entries are related too. Then I would probably have multiple sets of entries which would then need to be merged some how for output.


texts: Updating Search Indexes failing because of "rouge" invalid field handle

texts:
I'm on the latest build 3.5.3. I created a Lightswitch field type within a Matrix field in my local dev env and called it "colorBlock". No problems there. When I recreated this in my staging env I got an error trying to save the Matrix config saying I couldn't use the name "colorBlock". So I changed it to "colorBlock1" and everything worked fine.
I'm now trying to troubleshoot a persistent Updating Search Indexes -> Failed alert and tracked it down to a message in my logs: "Invalid field handle: colorBlock". I am not using this label for any field type I've created. When I grep all the files, I see instances of "ColorBlock" in CustomFieldBehavior.php and delta.yaml.
Any advice on how to resolve?


texts: Craft 3 wont update in Laravel Valet development enviornment

texts:
I'm using Laravel Valet with Craft 3 (Craft 3.0.0-RC13) and Sequel Pro.

I can't seem to get Craft to update. I just get a warning sign and a message saying that it couldn't back up the database.

When I looked at my log file, it contained the following:

  FROM craft_info
  2018-03-27 09:54:43 [127.0.0.1][1][-][error][craft\controllers\UpdaterController::actionBackup] Error backing up the database: The shell command "mysqldump --defaults-extra-file="/Users/richardclark/Sites/lorindafontainefarris/storage/runtime/temp/my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --single-transaction --no-data --result-file="/Users/richardclark/Sites/lorindafontainefarris/storage/backups/lorinda-fontaine-farris_180327_135443_jfivi9ibwf_v3.0.0-rc16.1.sql" lorindafontainefarris && mysqldump --defaults-extra-file="/Users/richardclark/Sites/lorindafontainefarris/storage/runtime/temp/my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --no-create-info --ignore-table=lorindafontainefarris.craft_assetindexdata --ignore-table=lorindafontainefarris.craft_assettransformindex --ignore-table=lorindafontainefarris.craft_cache --ignore-table=lorindafontainefarris.craft_sessions --ignore-table=lorindafontainefarris.craft_templatecaches --ignore-table=lorindafontainefarris.craft_templatecachecriteria --ignore-table=lorindafontainefarris.craft_templatecacheelements lorindafontainefarris >> "/Users/richardclark/Sites/lorindafontainefarris/storage/backups/lorinda-fontaine-farris_180327_135443_jfivi9ibwf_v3.0.0-rc16.1.sql"" failed with exit code 127: sh: mysqldump: command not found
  2018-03-27 09:54:43 [127.0.0.1][1][-][info][application] $_GET = [
      'p' => 'admin/actions/updater/backup'

I tried adding a PATH reference to my export PATH=$PATH:~/.local/bin/mysqldump in the .bash_profile file, but that didn't seem to do anything. Do I have to add something to the CraftValetDriver file, or is my PATH reference incorrect?

Any help would be greatly appreciated.

Thanks,

Richard


texts:
I created a controller that returns XML and is not related to Twig rendering in any way.
Can I still display the debug toolbar when I enter this controller URL to check if my database queries are performant?


texts: Getting admin to work on a "dev-sounding" subdomain

texts:
I am trying to migrate my local dev environment to a staging site, but am receiving You’re running Craft Pro with a Craft Personal license.

Initially I tried access the admin at http://project.staging.company.com/ where I received the upgrade message. After emptying all caches, I then tried accessing from http://staging.project.company.com and still get the upgrade message.

Looking at this answer I assumed Craft would recognise this as a "dev-sounding" domain.

Is this still the case? What do I need to go to get this working on staging?

At this stage I am not sure what will be the final domain, so I was hoping not to purchase the licence until we were ready to go live.


texts: Link to Global Fields like you can with the entries fieldtype

texts: Is there any way to link to a global using a field in a entry form, much like you would use the "Entries" fieldtype to link to entries?


texts:
I have an issue that I really do not expect. When using the image function in the Redactor wysiwyg editor, images come up broken. In the editor, and in the rendered entry. All that is missing is a / in the img tag and they work. So redactor is rendering,

and but what it needs is the beginning /

Have I configured something else wrong?


texts:
I'm trying to figure out how to do the following:

Person registers as new user
User creates a new entry with a front-end entry form
Entry is saved as disabled so it's not publicly visible
User has the option to make entry public by making a payment with Craft Commerce.
When the Craft order is complete it updates the entry in step 3 to enabled so that is will be publicly visible.

I think I should be able to use this event commerce_orders.onOrderComplete but I'm not sure how to pass the entry ID into this event and also how to check if the order that has just been completed is the order that applies to this event checkout.

Any thoughts on how to accomplish this?


texts:
I can't edit my entries. The entry page has no input fields. See attachtment

I run the latest Craft version. Cleared the cache, tried different browsers.
No errors in my console.

It looks like that no javascript file is loaded on the page.


texts:
I have a site with ~ 25000 entries, and around 130 custom fields.  I tried to rebuild the search index and it didn't complete after 8hours of running none stop.  Whilst I'm sure this can be blamed on the Server to some degree, I can see that my search index table has just short of 700000 rows, which I'm guessing takes a reasonable amount of time to create.

I was sure that I'd seen somewhere a way to hide/exclude fields from the search index, but looking now I can't find anyway to omit specific fields from the search index, which I would expect to reduce the load on the search indexer, there are only very few fields that I actually want the system to actually search by so I'm hoping there's a solution to this, I can reduce the load on the server and speed up the reindexing.

Thanks


texts: Including a variant segment in product type template route in Commerce 2

texts:
Is it possible to use a wildcard when specifying the template path for a Commerce 2 product type?

I want to format my URLs as /type/product/variant
Where 'variant' could be a custom field applied to the product variant.

In the settings for my product type I've tried a few things, including setting the "Category URI Format" to variations of /type/{slug}/{variant.customField} all to no avail. The template isn't found as soon as I include that third segment to the URL.

I feel this should be possible to do with Routes but having much the same problem.


texts: Database error when setting up Craft CMS with Composer

texts:
I have come across a problem when trying to install Craft CMS using composer. I'm hoping someone maybe able to help me out.
I'm trying to install Craft CMS using composer for the first time. In the past I have usually downloaded the files manually. I have setup the project within the VS code built in terminal but have run into an error when trying to setup the database. After creating a MySQL database on a Linux/Windows server, I don't seem to be able to connect to it through my local project. All the details I'm using are correct and have been checked numerous times.
After I have input all the details the setup asks for, I get this message
Testing database credentials ... failed: could not find driver
Can anyone help me out with why this maybe happening. I'm not experienced at all with setting up Craft in this way. Much appreciated.

I am working on Windows 10. My PHP version is 7.4.9. Composer 1.10.10


texts: How to create a simple shopping list (but not ecommerce)

texts: I'm trying to create a way to create a list of items, similar in appearance to a cart. You have products, you add them to a list and can adjust quantity. The list will follow you throughout the site. However, price is not a factor, there's no payment processing. You're essentially creating a list of products that you want, where then you can submit them to the company. You'll then get a call from them. The products are bespoke so a standard x = $4 situation won't work here. I think something like the Commerce plugin seems like overkill and not sure it can do this (without payments anyway). Any ideas?


texts: How can I delete a cookie from a plugin?

texts:
I am able to set a plain old cookie like this:

$cookie = new HttpCookie('myCookie', 'myValue');

I am trying to delete it like this:

$cookie = new HttpCookie('myCookie', '');
craft()->request->getCookies()->add($cookie->name, $cookie);

When I make a call to check the cookie, I get this returned:

{"name":"myCookie","value":"","domain":"","expire":0,"path":"\/","secure":false,"httpOnly":true}

I can see that the value is getting cleared, but is there any way to just totally wipe out the cooke?


texts: Getting all entries posted on any given weekday

texts:
Super simple request, not sure if it's possible...

Can we pull all entries that were posted on a Monday, for example? Or pull all entries but group them by the day name they were posted on?


texts: Enabling CSRF Protection for Mailchimp Subscribe plugin and other forms

texts:
I'm using the MailChimp Subscribe for Craft plugin to embed several subscription forms on a website I'm building.

The following code appears via my master _layout.html file:

<form action="" method="POST">

    <input type="hidden" name="action" value="mailchimpSubscribe/list/Subscribe">
    <input type="hidden" name="redirect" value="successfully-subscribed">

    {# MailChimp List ID #}
    <input type="hidden" name="lid" value="XXXXXXXXXX">

    {% if mailchimpSubscribe is defined %}
        {% if (not mailchimpSubscribe.success) and (mailchimpSubscribe.errorCode!='1000') %}

An error occured. Please try again.

        {% endif %}
    {% endif %}

        Name
        <input type="text" placeholder="Name" name="mcvars[NAME]" value="{% if (mailchimpSubscribe is defined) and (not mailchimpSubscribe.success) %}{{ mailchimpSubscribe.values.vars.NAME }}{% endif %}" required>

        Email:
        <input type="email" placeholder="Email Address" name="email" value="{% if (mailchimpSubscribe is defined) and (not mailchimpSubscribe.success) %}{{ mailchimpSubscribe.values.email }}{% endif %}" required>

    <input type="submit" name="" value="Go!">

</form>

When I hit go, I get the following Bad Request error:

I've temporarily fixed the error via general.php by disabling CSRF Protection (not recommended).

How do I implement CSRF Protection on this form? I've followed this article, but replacing the name and value fields will surely disable the plugin's functionality?

Should I also implement the method shown here for other forms like Am Forms?

Update:
There's a pull request on the plugin git page regarding this.


texts:
I need your help, please.

At https://docs.craftcms.com/v3/installation.html#step-1-download-craft I have this instruction:

  "To create a new Craft project, run this command (substituting  with the path where Composer should create the project): composer create-project craftcms/craft "

I get

  "[InvalidArgumentException] .Could not find package craftcms/users/lestone2 with stability stable"

on entering composer create-project craftcms/Users/lestone2.

I get the same message on entering php composer.phar create-project craftcms/Users/lestone2

Can someone help me to set up the instruction correctly? Or do I have a permissions issue? (I am logged on as the admin.).

I found one related question at: https://stackoverflow.com/questions/36897084/could-not-open-input-file-composer but the issue there is not the same as mine.

Thanks in advance.

P.S. I downloaded v1.7.3 of composer at https://getcomposer.org/download/ , and the file's integrity was confirmed.


texts: Updating a single custom field within an Entry

texts:
I've got the beginnings of a simple plugin to track views of an article page, just an entry with custom fields including 'dataViews' used below.

Within Twig:

{% do craft.demoPlugin.incrementView(entry) %}

Variable above set with:

<?php
namespace Craft;

class DemoPluginVariable
{
    /**
     * Increment count
     *
     * @param EntryModel $entry
     */
    public function incrementView(EntryModel $entry)
    {
        craft()->demoPlugin->incrementView($entry);
    }
}

Here's the service code which picks up the

<?php
namespace Craft;

class DemoPluginService extends BaseApplicationComponent
{
    /**
     * Increment view count
     *
     * @param EntryModel $entry
     */
    public function incrementView(EntryModel $entry)
    {
        $entry->setContentFromPost([
            'dataViews' => 1234,
        ]);

        $success = craft()->entries->saveEntry($entry);
        Craft::dd($success);
    }
}

The above fails when passed an entry, with $success reporting false. Logging the error this is due to other fields on the entry being required and not passed through.

Could anyone point me in the direction for updating just one field within a record?


texts:
I'm moving a site from craftcms/commerce-paypal to craft/commerce-paypal-checkout but I'm having an issue with the redirect after payment.
Steps to reproduce:

Choose Paypal as my gateway
I choose pay with Paypal
Paypal screen pops up
I make payment
I get redirected back to /store/undefined
Order is not completed in the backend - still in Active carts.

Everything looks to be rendering correctly on the frontend and the code works for the other gateways and the old Paypal, but the new Paypal gateway is redirecting to "undefined"

Is there something I need to do differently for the new Paypal gateway?


texts:
I had my Craft CMS site working on my local hosting. I then moved it over to bluehost VPS. I moved the database and uploaded the files to the server. I've put the database user information in the .env file and the server location. But site comes back on domain:

  Service Unavailable
  Our site is temporarily unavailable. Please try again later.

When I try to admin in it tells me:

  Service Unavailable
  Craft isn’t installed yet.

Any suggestions would be of great help.


texts: Conditional to check position of previous matrix block

texts:
I'm referencing the Pixel & Tonic sample craft template Happy Lager where in the article body template there's a macro to get the position of a block.

I'm trying to setup a conditional to check if the previous position of a block has been set to 'left'.

{% if prevPosition == 'left' %}

But that doesn't seem to work at all.

https://github.com/pixelandtonic/HappyLager/blob/master/craft/templates/_includes/article_body.html


texts: Can I exclude a commerce address by ID when retrieving a list of addresses?

texts:
I would like to retrieve a list of all commerce customer addresses except for one. When working with entries, this can be done with the {id: 'not ' ~ some.id } parameter. This doesn't seem to work with craft.commerce.customer.addresses.

I'm currently achieving what I need with the following code:

{% set customerAddresses = craft.commerce.customer.addresses %}
{% for address in customerAddresses %}
    {% if address.id != craft.lhngroups.orgCommerceAddressId %}
        output the address
    {% endif %}
{% endfor %}

This works, but it throws off some {{ loop.index }} operations I'm trying to perform since the actual array of addresses contains 1 more address than what I'm displaying.


texts:
I currently have an asset upload field, but I'm trying to make it call errors back if the image isn't an extension that's set within the field, allowing users to understand why the form didn't save.

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

          Featured Image

              <input id="inputGroupFile01" type="file" class="custom-file-input" name="fields[networkImage]">
              Choose file

I can't seem to find any documentation on error calling for this certain scenario? Or a catch-all error for the form field would be great!


texts: After upgrading to PHP 7 I started getting "storage folder isn't writable by PHP" errors

texts:
I just recently upgraded to PHP 7. The browser is now showing following error

/home/xxx/craft/storage isn't writable by PHP. Please fix that

Have not changed any permissions on any of the folders. How to fix this problem?


texts: Edit a table field type from the front end

texts:
Similar to this question, I'm trying to make a table field type editable from a front end form.

When I update from the CP, the changes are reflected on the front end, but the following code doesn't allow updating from the front end form itself.

Is there anything I'm missing?

(perhaps adding how each field type can be edited from a front end form should be added to the docs)

    {% for row in currentUser.providerCredentials %}

        Institution
        <input type="text" id="accreditingInstitution" name="fields[accreditingInstitution][]" value="{{ row.accreditingInstitution }}">

    {% endfor %}


texts: Forgot Password - Success Message/Flash Message after setting new password on the login screen

texts:
Quick question about password reset (forgot a password on the front-end)
So I have set my
'setPasswordSuccessPath'           => 'login'
so that when the new password is set, they will be taken to this login screen.
Is there anyway i can detect this has come from this process, so I can show a little flash message to confirm their password has been reset? I'd like to give some visual feedback, without a whole separate interim page.


texts:
In my module I have the following:

$client = new Client(['base_uri' => myBaseUri]);

$response = $client->request('GET', myQueryString, [
    'headers' => [
        'Accept'            => 'application/json',
        'Accept-Encoding'   => 'deflate,gzip'
    ],
    'connect_timeout' => 3,
    'verify' => false,
    'timeout' => 5,
    'http_errors' => false
]);

$json = $response->getBody();
$data = json_decode($json, true);

How can I cache this so it only does the request every 5 minutes?


texts: Is it possible to force Craft to recheck available sever modules?

texts:
One of our servers hosting a Craft site has recently had ImageMagick installed on it, as we noticed that transformed animated GIFs weren't animating.

The 'Requirement Report' at /admin/utils/serverinfo is still reporting a 'warning' against ImageMagick (as it was before it was installed), and Craft seems to still be using GD as the freshly transformed animated GIFs still aren't animating.

Is there a way to force Craft to 'recheck' the available modules on the server (and so in my case, for it to recognise that it can now use ImageMagick)?


texts: Amazon S3 plugin uploading to different directory

texts:
I was using Amazon S3 with Craft 2 fine, now after updating and installing the plugin I am having issues.

We use a folder inside our bucket as the root Assets location - e.g. /bucket-name//folder

When specifying /folder/ in the subfolder field existing images display. e.g. /bucket-name//folder/image.jpg.

However, on uploading, new images are being sent to /bucket-name/folder/image.jpg - which means they don't display on templates.

If I then specify the folder as //folder/ in the subfolder field, and remove the trailing slash from the base url, images do not get uploaded to the correct place, and existing images do not load on the site, as it thinks I am calling ///folder/image.jpg.

Any suggestions would be great, as I'm going round in circles!

Also no image resizes are working, which I currently assume is due to the folder discrepancy.


texts: Sprout Email not triggering from Sprout Form

texts:
I'm getting the following error:

An exception has been thrown during the rendering of a template ("Craft\SproutForms_EntryModel and its behaviors do not have a method or closure named "CONTACTFULLNAME".") in "CONTACT FORM ENQUIRY FROM: {{object.CONTACTFULLNAME|raw}}

The form has the following fields:

contactFullName
email
message

The email notification fields for the first email Contact Form - Thank You message contain:

Subject: Contact Form - Thank You {contactFullName}

Message: Thank you for contacting us, {contactFullName}. We will be in touch soon.

And for the other email:

Subject: Contact form enquiry from: {contactFullName}

Message: You have received an enquiry Enquiry from {contactFullName} - {email} “{message}”

Can anyone shed any light onto why this capitalised reference to the CONTACTFULLNAME missing method or closure (by this I presume field) appears in the logs? The form is getting saved, but no email sent due to this message.


texts: Pass last segment to solspace freeform field

texts: Using freeform on another CMS, I was able to pass the last segment of the previous page url (when navigating to the form page) to a form field in the freeform composer, is this feature possible in the Craft version? Or alternatively, would this be possible passing an entry title? Thanks


texts: Asset field empty in graphql query response

texts:
I have a problem with a graphql query which includes an asset field. The asset field is always an empty array. There are no errors in the graphiql tool.

The graphql api is not public unfortunately but if anyone has any ideas on how I could troubleshoot that would be appreciated.

The query itself is pretty simple:

{
   entries(section: "posts") {
        title
        ... on posts_posts_Entry {
            testText
            imagetest {
                id
            }
        }
    }
}

Response:

{
  "data": {
    "entries": [
      {
        "title": "Headline",
        "testText": "testing",
        "model": [ ]
      }
    ]
  }
}


texts: How to create menu in backend using Craft 3

texts: How to create menus from admin panel of Craft 3 so I can render into frontend header and footer?


texts:
I've been looking for an Event Reference doc for Craft 3 just like what we had for Craft 2, but couldn't find one. The only events doc I found for Craft 3 is the plugin updating guide: https://docs.craftcms.com/v3/extend/updating-plugins.html#events.

Did I miss anything? Appreciate if someone can post a link here.

Also, for Craft 2 events, we used to be able to do $event->params[$paramName] to get the params passed into the events, but I struggle to find a way to do similar things in Craft 3. Any suggestions?


texts:
I’m having some trouble getting a contact form to submit and function correctly. The live instance of the site is on Windows Azure but my staging and local versions are unix. Is there any reason for Pixel & Tonic's Contact Form plugin not to function because of the platform? Perhaps it's a lower level issue with PHP setup or my Craft configuration on Windows.

Any help much appreciated.


texts: PHP 7.0 and 7.1 PDF error with Craft Commerce orders

texts:
Switching over to a new server and using PHP 7.0 (and 7.1) everything looked to be fine until I tried to view an order PDF within an email from Craft Commerce. Even using the email template provided by the plugin. The error is:

No block-level parent found. Not good.

I can't remember which DOM-PDF issue thread I came across it in, but the solution is to remove

<head></head>

from the document. Does anyone know of a more elegant solution? I don't think it's my server.


texts: Allow users to change email address on front-end form

texts:
I've got a front-end user profile form working on a client site I'm developing, but the one thing that I'm having trouble with is allowing users to change the email address associated with their account via this form.

When I use my email field to attempt an email address change, I get a verification email generated by Craft sent to the new email address, but the email change is not reflected in either the CP or on the front-end when I refresh the form.

I've pasted an abbreviated version of my form below with some irrelevant fields omitted.

What am I missing?

 <form method="post" accept-charset="UTF-8" enctype="multipart/form-data">

    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="account/my-account?m=updated">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    {% macro errorList(errors) %}
        {% if errors %}
            {% for error in errors %}

{{ error }}

            {% endfor %}
        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <fieldset>

        Username
        <input id="username" type="text" name="username" value="{{ currentUser.username}}">
        {% if account is defined %}
            {{ errorList(account.getErrors('username')) }}
        {% endif %}

        First name
        <input id="firstName" type="text" name="firstName" value="{{ currentUser.firstName}}">

        Last name
        <input id="lastName" type="text" name="lastName" value="{{ currentUser.lastName }}">

    </fieldset>

    <fieldset>

Fill in both fields below to change the email address associated with your account

        Email
        <input id="email" type="text" name="email" value="{{ currentUser.email }}">
        {% if account is defined %}
            {{ errorList(account.getErrors('email')) }}
        {% endif %}

        Current Password
        <input type="text" id="currentPassword" name="password" />
        {% if account is defined %}
            {{ errorList(account.getErrors('currentPassword')) }}
        {% endif %}
    </fieldset>

    <input class="btn btn-primary btn-large" type="submit" value="Save changes" />

</form>


texts:
If validation fails in plugin, how can I redirect it bank to previous URL with errors?

craft()->urlManager->setRouteVariables(array(
    'errors'    => $errors
));

gives 404

My Controller:

class DB_LogsController extends BaseController
{
    protected $allowAnonymous = true;
    public function actionStoreDances()
    {
        $this->requirePostRequest();
        $f = craft()->request->getPost('logs');
        $dances = new DB_LogsModel();

        $errors = $dances->getAllErrors();
        craft()->urlManager->setRouteVariables(array(
            'errors'    => $errors
        ));
        $redirectUrl = '';
        //$this->redirect('http://db.craft.dev/admin/db/',true);
    }
}


texts:
I'm trying to display a notification badge on how many new entries were posted today only. But I cannot get the following to work.
{% set timeAgo = now|dateModify('today') %}

{% set recentMerchantsOffers = craft.entries.section('offers').postDate(timeAgo).relatedTo(recentMerchants) %}

Any help would be great :)


texts: How to add custom options or fields to an Order Adjuster?

texts:
How do you add options or custom fields to an OrderAdjuster in Commerce 2?
I'm migrating a website from Craft2 to Craft3 and need this, this is how I do it in Commerce 2:
$promotionsAdjuster->optionsJson = [
    'lineItemsAffected' => [$lineItem->id],
    'affectedDiscountId' => $adjustment->id,
    'removeAffectedDiscountAmount' => $adjustment->amount - ($lineItem->total*$adjustment->optionsJson['percentDiscount']),
    'percentageDiscount' => true
];


texts: How can I add banner slider on my home page?

texts: I want to add slider on my home page. How can I add slider?


texts: Setting an entry in a dynamic route template

texts:
I have some routes i want to use like
"/my-url/locationZ"
"/my-url/locationX"
This loads a template /dynamic.twig
In the template dynamic I am trying to get the content from an existing entry like:
{% set entry = craft.entries()
       .id('2268')
   %}

But the entry is always null.
How can I pull the entry into my dynamic.twig template when the route is used?


texts:
I'm trying to use a conditional to do something if the first segment matches This or That. But I'm unable to come up with the right operator for the "or"

{% elseif craft.request.firstSegment == 'This' || 'That' %}

What's the proper operator here? Thanks!


texts: Can I get a row from a table without looping trough the whole table?

texts:
I wanted to use a table to add global glosery, for translation purposes. (The page is in Norwegian, but need to be understandable for the whole team.) Also it should be accessable for copywriter to change the text. I was first making a matrix for this, to be able to access each word that are being translated. But then I was thinking it would be easier to use a table, since you then can have a default translation, that the copy writer later could change.
Is there anyway to access a table row?


texts:
I have a multi-language site. So I need to show slightly different address data, depending on the current locale. Especially regarding the city and country field.

Example:

DE

Venloer Str. 200
Köln
Deutschland

EN

Venloer Str. 200
Cologne
Germany

I tried marking the field as translatable, but it hasn’t worked out of the box and I couldn’t find any documentation on this.

Any hint would be much appreciated.


texts: Craft Commerce - No closure name "Customer"

texts:
I am taking my first real stab at working with the commerce beta. This plugin is pretty fantastic btw - awesome job guys. I can't comprehend all of the tiny details that went into this considering all of the rabbit holes.

I am running into a snag though, on the last page of checking out it seems everything is going through (using the dummy account) as I can see the pending order in the CP. Perhaps it is something as a mis-configuration on my end (quite possible).

However, I am seeing this error when I click "Pay"

Commerce_AddressModel and its behaviors do not have a method or closure named "customer".

The url is:

www.mysite.com/commerce/customer/order?number=70829108ec467679afb90e2a857e6701

I am using this page to snag a valid visa CC number.

Steps to recreate:
I have enabled guest registration on my page. I used that option to create a new user. I received the confirmation email, clicked and was able to log into my site as the newly created user.

I clicked on the product, entered shipping info (free shipping), entered a valid CC number and clicked "pay".

That's when I see the error. But, the order is showing in the CP.


texts:
I'm using Smart Map for Craft 3 to develop this filterable map for Columbia, Missouri. Here's the staging site:
http://visionzerodev.org/map-alpha/
This works brilliantly. Huzzah.
Now, I also need to add a couple of KML layers to it.
Here's where I'm developing the KML proof of concept:
http://visionzerodev.org/map-bravo/
BUT — I get the this error: "Invalid KML file".
I'm sure I'm missing something obvious.
The KML is importable in Google Maps:
(It was previously used as is in FusionTables)
https://drive.google.com/open?id=1J4epYVJPZXFrmQjq19PSfQuMiTGWmcbt&usp=sharing
The KML file is publicly accessible here:
http://visionzerodev.org/assets/data/high-crash-network.kml
Here's my Twig:
  {% set kmlFile = '/assets/data/high-crash-network.kml' %}

  {% set options = {
    height: 600,
  } %}

  {% if kmlFile %}
    {{ craft.smartMap.kml(kmlFile, options) }}
  {% endif %}


texts:
Is there an equivalent to Yoast's real-time content analysis for Craft?

I've looked at SEOmatic and Sprout, but neither of them have the handy traffic light system that Yoast has on WP (despite both are looking to be great for everything else SEO related).

I'm trying to get my company to switch from WP to Craft (for the bigger projects at least), but my director considers the traffic light check-list to be an important time saver for non-techies/clients to post quality content.

This feature will clinch the deal! Help me Craft Stack Exchange Kenobi, your my only(ish) hope.


texts: Get the section name based on a url segment

texts:
I'd like to retrieve the name of a section based on a url segment. Normally I would use {{entry.section.name}}, but this doesn't work, since there is no entry available.

I've got this working:

{% set entry = craft.entries.section(craft.request.getSegment(1)).first %}

<h2>{{entry.section.name}}</h2>

This means that I first have to get an entry and then reverse retrieve the section it belongs to.

Is there no direct way to get the section name based on a url?


texts: Template not found error when template file does exist

texts:
I am getting a Template not found error.

Template not found error: case-studies/_category

However the template does exist (see screenshot).

I have tried clearing the template cache but still the issues perssits.

Update

I'm doing tests with other files - like image files - uploading them to the server. They are not getting picked up as existing and throw up 404 errors.

Update - Fixed

Looks like we moved the server droplet and were uploading files to the wrong location.


texts: Replacement for deprecated AssetsService

texts: Im developing my first plugin and was interested in using the findFolder() method from AssetsService but i noticed the class is depreciated. What is the proper way of achieiving the functionality of findFolder() without using the deprecated class? TIA!


texts:
I'm trying to extend the Craft UserController class, in order to add some extra validation to the actionSaveUser action, before the rest of the code in that function executes.

I've got no problem hitting my controller and even calling the parent::actionSaveUser which seems to be working, except for getting the validation error messages.

function actionSaveUser()
{
    parent::actionSaveUser();
    $this->renderTemplate('profile/index.html');
}

For brevity, I've not included any of the validation just yet. The template being rendered does display errors if routed to the Craft controller action, but not through mine.

The main reason for doing this is because uploading of a non-image for the profile image (e.g. uploading a php file) causes a php error, not a value in the returned errors array.

Any idea why the errors are disappearing when routing through my controller first?

Thank you in advance

Update

Looking through the UserController::actionSaveUser action, I can see

craft()->urlManager->setRouteVariables(array(
    'account' => $user
));

Looking through the urlManager documentation; I can see that _routeVariables is being updated but can't see a way of accessing this array to get the account value.

Am I looking in the wrong place?

Update The Second

Ok, even sending the form directly to users/saveUser isn't yielding any errors (account object isn't defined). But, if all fields are filled in, it correctly saves

Any suggestions?


texts: Craft 3 front end form file uploads not saving if filename exists?

texts:
I have a front end save entry form which users can attach photos too, it all works fine unless a photo with the same filename is saved, in this instance the entry saves but the asset field is just left blank, can't find anything in the docs,

Any help or a point in the right direction appreciated!

<form id="addCompanyForm" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
  {{ csrfInput() }}
  <input type="hidden" name="sectionId" value="7">
  <input type="hidden" name="enabled" value="0">
  <input type="hidden" name="action" value="entries/save-entry">

  <input id="title" type="text" name="title">
  <input id="companyLogo" type="file" name="fields[companyLogo]" accept=".png, .jpg">

  </form>


texts:
We've got a HeroSlider on our website, and I no longer wish for the slider to slide (if that makes sense?).

Currently the homepage is 3 slides, however when I remove the 2 slides I don't want, the 1st slide still tries to slide, and in doing so disappears.

I need it to be static.

As far as I can see the code for the slider is:

        var $heading    = $('.heroslider-text h2');
        var $para       = $('.heroslider-text p');
        var $btn        = $('.heroslider-text .btn');

        // Define animation sequence for hero elements.
        if($para.length){
            this.seq = [
                { elements: $heading, properties: { opacity: [1, 0], translateY:[0, 50] }, options: { duration: 250 } },
                { elements: $para, properties: { opacity: [1, 0], translateY:[0, 50] }, options: { delay:60, duration: 250, sequenceQueue: false } },
                { elements: $btn, properties: { opacity: [1, 0], translateY:[0, 50] }, options: { delay:60,  duration: 250, sequenceQueue: false } }
            ];
        } else {
            this.seq = [
                { elements: $heading, properties: { opacity: [1, 0], translateY:[0, 50] }, options: { duration: 250 } },
                { elements: $btn, properties: { opacity: [1, 0], translateY:[0, 50] }, options: { delay:60,  duration: 250, sequenceQueue: false } }
            ];
        }

    };

    this.runSequence = function(){
        if($('.heroslider-text').hasClass('animated')){
            $.Velocity.RunSequence(this.seq);
        }
    };
};

Thank you very much.


texts: How do I publish entries with a specific category id?

texts:
How do I publish a list of three most recent entries within a 'blog' section that feature the category id '42'?

I presently have this code:

{% for entry in craft.entries.section('blog').limit(3).find() %}

        {{ entry.title }}

{% endfor %}

However, I am having trouble properly implementing the .relatedTo() filter within this snippet, and all of the examples that I have read reference a category title rather than id.


texts: How to use checkboxes to filter categories on the front end?

texts:
i am trying to filter the various categories i have. Currently my url formats the following : www.site.com/news?cat=industry-news&cat=architecture-design

I understand that i have to change this to a comma separated list but how do i do that and how do i make the filtering works so it does not only shows the first selected filter only?
here is my code:

`
{% set queryCategory = craft.request.getParam('cat') ?? '' %}
{% set categoryId = craft.categories.group('news').slug(queryCategory).first().id %}

{% paginate craft.entries.section('news').relatedTo(categoryId).limit(10) as entriesOnPage %}

<form class="js-category">
{% set urlCategories = craft.request.getQueryString() %}
   {% for category in craft.categories.group('news') %}
     {{ category.title }}
   <input {{ category.slug in urlCategories ? 'checked="checked"' : '' }}   name="cat" type="checkbox" value="{{category.slug}}">

    {% endfor %}
</form>`


texts: Is it possible to reorder globals in the back end?

texts:
Right now Globals are listed in alpha order in the back end.

I was wondering if it would be possible to reorder them somehow? Maybe when working under Settings > Globals, etc.?


texts:
I have entries that are getting grouped, but I've noticed that it will return nothing if there's nothing within a group. I'm looking to see if there's a possibility of showing an empty state to a user?

{% set loopCount = 0 %}
{% for status, proposals in proposalsByGroup %}
  {% if proposals|length %}
  {% set loopCount = loopCount + 1 %}

    {{ status }}
      {% for proposal in proposals %}

                {% include 'proposal/_proposalInfluencer.html' %}

      {% endfor %}

  {% else %}
    There's nothing here!
  {% endif %}
{% endfor %}

Unfortunately, the above does nothing as no group actually exists so it won't run the code?


texts: How can I cache a list of entries with pending postDates and have it automatically invalidate the cache appropriately?

texts: I have a listing page of entries, some of which may have future-dated postDates. I want to cache the output, but only until one of the pending entries goes live.


texts: Is there a way to define an attribute setter method on a model?

texts:
I want to ensure that any attempt to set a date attribute on a model by way of populateModel() or myModel->foo = 'bar' (basically any method of setting a value) is intercepted so I can set a default if the value isn't valid.

Put another way, if you attempt to set a date prior to today (or a string that's not a date), I want to set the attribute to be today's date.

Currently I'm doing that in my populateModel() method but that doesn't catch the setAttribute('foo') approach or the myModel->foo approach.

For example in Laravel, we can create a setter method: setFooAttribute() so I was hoping for something similar.


texts: Custom plugin settings add on admin nav bar

texts: I want to control my plugin on the admin navbar but I can't found a way for that.


texts: Dates Expiring By Custom Field date_modify

texts:
Can I somehow set the expiration date of an entry based on a custom-field. I ask this because I don't want the site-owner to have to manually set the expiration date (for multiple reasons)but they are setting a 'start' date in a custom field. I am currently outputting entries and limiting them by doing this:

{% for event in entries %}
                    {% set count = 0 %}
                    {% if count < 5 and event.dateTime|date_modify('tomorrow 5am')|date('U') > now|date('U') %}

It would be really fantastic though if i was able to use that same date_modify to expire the entry and remove the entries from the loop all-together due to being expired.


texts: Check if title field has a string in ElementAPI

texts:
I am trying to retrieve search suggestions for a search form. I sent the parameter entered by the user, but how do I do it in the criteria?
I tried this:

'criteria' => [
    'search' => 'title: *'.Craft::$app->request->getParam("key").'*'
],

but it does not return any results. What am I doing wrong?
this is my entire endpoint:

'suggests' =>function(){
        return [
            'elementType' => Product::class,
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => 'title: *'.Craft::$app->request->getParam("key").'*'
            ],
            'transformer' => function(Product $product)  {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ];
    },


texts: SEOmatic for some reason isn't picking up any 'Title' fields from the entries, which leaves it displaying '| SiteName' within the browser tab. Currently my 'Site SEO Title' is empty, but can this accept Craft variables to inject the page title?


texts:
Is it possible to add a redactor field to the search index? I'm importing about 160 posts from a WordPress blog and the client has said it is absolutely essential that the posts themselves are searchable.
So far I've run /craft resave/entries  if I run with the flag --type 'blog' it only saves the titles, if I run --type 'postContent' (or --section) I get this error: No entries exist for that criteria.  (I'm not 100% on my knowledge of --type and --section).
None of the actual post content is in the search index and my entries are unsearchable.


texts: How can I create a dropdown field programmatically with a plugin?

texts:
I'm trying to create a Dropdown field and add it to the User field layout. I've successfully created an empty dropdown field (no options) and added it to the User field layout.

Here is my current code for that:

$subscriptionStatusField = new FieldModel();
$subscriptionStatusField->groupId = 1;
$subscriptionStatusField->name = "Subscription Status";
$subscriptionStatusField->handle = "subscriptionStatus";
$subscriptionStatusField->translatable = false;
$subscriptionStatusField->type = "Dropdown";

What I'm having trouble with is how to add options to the dropdown field. How can I do this programmatically?


texts: How do you get the user id on the front-end?

texts:
I'm using Craft Pro to make a website where users have a private area. Users register and when login happens they are redirected to a page in the private area with respective info about that user.

When i use {% requireLogin %} with {{ currentUser.id }} Craft 3 outputs the ID of the user that has active login in the CP (control panel).

But what I need is the ID of the user that made login in the frontend to access private area and not user ID that is logged in CP.

I'm reading the Craft 3 docs but I didn't find the answer I'm looking for.

Any suggestions?


texts: How to seperate asset folders by locale?

texts:
I have a website where the client can add links to assets (pdf, doc, etc.) anywhere on a page. So I would like to avoid having a assetField on every template. I would like them to upload all assets in the CP on the assets page and than link to them from a page. That's doable.

But, I have one page where I need to list all assets from a certain source. Also doable. But that source has 3 subfolders, one for every locale. However, when files are uploaded in the CP on the assets page, they automatically have properties for all locales.

I only want to fetch the files for a given locale (so a given subfolder). I can do that by using folderId.
But if a file doesn't exist in one locale, I'd like to default to the same file in another locale. That is the issue I can't get right. How would I proceed? There is no real link between different files which are essentialy the same files but in different languages.


texts: How can I use operators within Twig hashes?

texts:
I'm looking for documentation on how to use operators in hashes in Twig. Someone mentioned this in the Google+ support group the other day and I was unable to find any docs or examples.

{% set eventParams = {
  section       : 'events',
  order         : 'startDateTime asc',
  startDateTime : '>= '~now
} %}

If I wanted the startDateTime hash to use a range of dates, say ( >= now and <= now + 5 days ) how would I specify that in the startDateTime hash?

Is this a hash syntax that is specific to Twig?


texts: Is there a way to check if any fields in a global set have content?

texts:
I have a global set called socialNetworkContent.

Is there a way to setup a conditional to check whether any of the fields within this set have content?

So the section wouldn't display if all the fields were blank.

Something along these lines:

{% if socialNetworkContent|length %}

Follow Us

            {% if socialNetworkContent.branchFacebookProfile|length %}

{% endif %}
            {% if socialNetworkContent.branchTwitterAccount|length %}

{% endif %}
            {% if socialNetworkContent.branchLinkedInAccount|length %}

{% endif %}
            {% if socialNetworkContent.branchGooglePlusAccount|length %}

{% endif %}
            {% if socialNetworkContent.branchInstagramAccount|length %}

{% endif %}
            {% if socialNetworkContent.branchYoutubeAccount|length %}

{% endif %}

{% endif %}


texts: Should I use cache on data pulled from within files?

texts:
I've read documentation and it says, that We shouldn't use cache tags on static text.

I have a files, that are static in that way, that the data are pulled from within a file, or in some case, data are pulled from outside a file, where cache tags are.

For example - language and territory data, static navigation.

Within cache tags I have pretty computationally statements and looping, where documentation says, that it's exception.


texts: Adding Google Analytics to an RSS feed via server-side tracking?

texts:
Google Analytics provides a server-side API for sending data to their servers; this is the generally approved way of tracking views of a page that can't include Javascript, such as an RSS feed. You just send a specially formatted http request to Google's servers when the page is requested.

Has anyone got a plugin or other solution for sending either (a) GA requests specifically or (b) just HTTP requests in general from a Craft template? If so, then I can set that template not to cache, and get at least some rough idea of how many views I've got on the feed. (And if not, I'll break down and write my own plugin, but I'm hoping not to have to.)


texts: Action URLs from CP to a Craft 3 plugin controller

texts:
I'm working on my first Craft 3 plugin and want to add some buttons to my plugin's control panel section which post form data to a controller.

My plugin is called 'myplugin', the controller I wish to post to is called 'products' and the method in that controller is 'get-products'. I figured I should therefore create the URL on the forms as

{{ actionUrl('products/get-products') }}

However this yields a 404 error

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Page not found.
↵
Caused by: Invalid Route – yii\base\InvalidRouteException
Unable to resolve the request "https:/local.mydomain.co.uk/index.php?p=admin/actions/products/get-products".
in /Users/pete/projects/myclient/dev/build/vendor/yiisoft/yii2/base/Module.php at line 537

If I call the URL directly by using https://local.mydomain.co.uk/admin/actions/myplugin/products/get-products then it behaves as expected.

Obviously I'm missing some really important bit of knowledge here and would love if someone could help me understand what's going on.


texts:
Does it make sense to use Craft CMS as a Product Information Management system?

I have already used Craft 3 for a couple of sites, and I understand part of its capabilities. I was a bit puzzled though when I started to look at defining objects or entities with inheritance.

For example, how would you use Sections in Craft CMS to model this entity structure?

Thing

Name
Primary Image
Description (multilingual)

English
Norwegian

Type

Product

Category
Features

Name
Image
Description
etc...

etc...


texts: Get all entries attributed with category

texts:
Maybe I'm going mad here, but I can't figure out how to get all entries which are in a certain category.
Following the syntax laid out here: http://buildwithcraft.com/help/entries-related-to-category
you'd think something like this would work, but I get nothing:
{% for entry in craft.entries.relatedTo('Naming') %}

'Naming' is my category, and I have several case study entries with that category attributed.
I also tried adding more params, like restricting it to just the case study section:
{% for entry in craft.entries.section('ourWork').relatedTo('Naming') %}
This would be outside the category page or related case study page btw, ie on the homepage.


texts: Image thumbnail generation (on S3/Cloudfront integration) returns blank when first generated

texts: For a client site with S3/Cloudfront integration, we are seeing that images will not be able to load for the first time if they have not been generated before. I'm guessing this is because it takes time for the generated thumbnail to be saved to S3 then propagated to Cloudfront, so images will always return nothing the very first time. Is this correct, or are we missing something, or are there workarounds?


texts:
I'm trying to make a form redirect to the current page, but it's currently redirecting itself to the homepage every time the form submits? I can't see anything wrong with the code itself?

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
  {{ csrfInput() }}
  <input type="hidden" name="action" value="users/save-user">
  <input type="hidden" name="redirect" value="{{ craft.request.url }}">
  <input type="hidden" name="userId" value="{{ currentUser.id }}">
  <textarea id="summernote" name="fields[userAbout]">{{ currentUser.userAbout }}</textarea>
  <button class="btn btn-primary btn-md semi-bold mt-4" type="submit">Save Profile</button>
</form>


texts: Retrieving an entry based on the request URI in a plugin controller

texts:
I'm working a plugin and part of the task is to grab the entry based on the current URI using craft()->request->getRequestUri().

Is there a way to grab the entry based on the URI from the request?


texts: View all discounts applied to a cart and remove discounts from cart

texts:
On my cart page I have the coupon code form to apply discounts to the order. Underneath the form I want to list all the coupons applied to the cart with an button to remove each discount.

As in the example template I can access the latest coupon applied to the cart, but am no sure how to list all that have been applied to the cart and how to remove a coupon if a customer wanted to.

Thank you.


texts:
Currently it's possible to set a max block value for the collection of block types. However I have a case where it would be great if I could set block type limit.

For example I have a situation where I need a carousel matrix. A block type with assests for the carousel but also a heading and text block type describing the carousel. I want the assets block type to have x amount of repeatable entries but the description and title block type limited to 1.

How would you currently achieve this? Would it be worth requesting adding it to the roadmap?


texts: Routing: How can I ignore a parameter in route definition?

texts:
I'm trying to route users to a "locations" structure entry that normally has a URL structure that looks like: locations/<slug>

My client wants to use the structure of links from their old site to preserve SEO and wants to have the URL structure of: locations/<state>/<slug> where state is a 2 letter string. So, I'm trying to set up a route rule that just ignores the  parameter and redirects to the regular route.

In routes.php I have the following rule:

'locations/<state:[a-z]{2}>/<slug:{slug}>' => 'locations/<slug>'

But when I try to hit a route (for example locations/ca/slug-name) I get an InvalidRouteException and an error message saying:

Unable to resolve the request "locations/slug-name"

So it looks like it's stripping out the state parameter successfully but I'm not sure why locations/slug-name isn't recognized as a valid route.

Is there something I'm missing? Is there an easier way to do this?


texts: Assigned Files in entries won't get synced on localization

texts:
I've got an entry-type, which has images and sound-files assigned through an asset-field.
When i create an entry, those fields won't be synced in my other languages, even though the mark for "This field is translatable" is checked.


texts: Template query: Advanced section query to get unique items from custom entry type field

texts:
I'm trying to build a filter for a blog section in Craft 3.

I'm fairly new to Craft and my client now wants a dropdown filter where they can filter out authors. Thus, I want to write a query that fetches a unique list of authors from my blog channel structure.

The structure is:
section: blogEntries (Channel) with an entry type blogEntry.

Each blogEntry has a content (matrix) and and writer entry field which is connected to one or more employee entries.

So; blogEntries > blogEntry > writer(s) > employee

What I want is something like

craft.entries.section('blogEntries').column('writer').distinct().all()

This is what I have:

{# Way too slow #}
{% for item in craft.entries.section('blogEntries').all() %}
    {% if item.writer|length %}
        {% set person = item.writer.one() %}
        {% set name =  person.firstname ~ (person.surname|length ? ' ' ~ person.surname : '') %}
        {% if name not in writers %}
            {% set writers = writers|merge([name]) %}
        {% endif %}
    {% endif %}
{% endfor %}

Terrible solution, terrible performance.

How can I improve this code? Any ideas would be appreciated.


texts: Rotate image according to EXIF orientation not working from a plugin

texts:
I am using a front-end form to upload images and store them as assets on an amazon S3 bucket.

My server has imagick installed an uses it and in my config I have "rotateImagesOnUploadByExifData" set to true.

When uploading an image I use this code to get the image and store it as an asset:

$file = UploadedFile::getInstanceByName('file');
$tempFilePath = $file->getTempName();
$folder = craft()->assets->findFolder(array(
    'sourceId' => craft()->config->get('assetSourceId', 'myPlugin'),
    'id'       => craft()->config->get('assetFolderId', 'myPlugin')
));

// Turn the file into a managed asset within that folder
$response = craft()->assets->insertFileByLocalPath(
    $tempFilePath,
    $file->getName(),
    $folder->id,
    AssetConflictResolution::KeepBoth
);

Everything is working as expected, an asset is created, files get transferred to Amazon S3 bucket, but when transforming the image it shows rotated.

So I investigated:
The function 'insertFileByLocalPath' calls the function 'insertFileByPath'

In its turn this function performs the following check:

if (IOHelper::getFileKind(IOHelper::getExtension($localFilePath)) == 'image'
            && ImageHelper::isImageManipulatable(IOHelper::getExtension($localFilePath))
)
{
    craft()->images->cleanImage($localFilePath);
}

The cleanImage function should rotate the image and strip the exif data afterwards.

But since these functions work with the temporary file name (which is e.g. "/tmp/phpZB1A8y") this does not pass the test in the previous code. (it is not recognized as an image filename since it has no extension)

Any idea how I could work around this issue?


texts: Comparing current date to multiple entry matrix date fields

texts:
I need to display an entry only if the date fields within its Matrix are current. So, only display if the startDate is greater than or equal to today and the endDate is less than or equal to today.

Currently I have this code and am having trouble finding how to compare multiple dates.

{% for entry in craft.entries.section('sectionHandle') %}
    {% set present = now|date %}
    {% set entryStart = entry.matrixHandle.startDate %}
    {% set entryEnd = entry.matrixHandle.endDate %}

    {% if entryStart >= present and entryEnd <= present %}
        display entry information
    {% endif %}
{% endif %}

I'm guessing that I'm using the operators incorrectly or that "and" isn't allowed. Either way, it's not displaying anything and yes, I have a made sure that I have an entry with dates that would activate this if statement.


texts:
I can't find this anywhere so I'm going to assume it hasn't been asked.

Is there a way to duplicate my products from my primary site to my subdomain? It seems like it should have done it automatically but it hasn't.


texts:
My question:
How can I use entry data in the craft backend?
An example for the use-case:

Author creates an entry for the section "Generate item". The entry has only a title/single word.
That created entry should be shown as a selectable item in a selection box.
Users can upload pictures and can select this newly created item in the upload form.
So pictures should get associated to the selected word.

I'm aware that I can use element queries in PHP or Twig.
My problem:
The use-case is simply that I need categories/entries should get created by authors (that have no access to real backend) and these should be relatable to another entry - but on the fly.
Thanks in advance for any kind of help!


texts: How do multiple date queries differ between Craft 2 and 3

texts:
After spending a lot of time solving this for myself I thought I'd share it.
In my Craft 2 template I had this query:

{% set result = craft.entries({
    section: 'events',
    eventDate: ['and', '<' ~ now.w3c(), '> ' ~ now | date_modify('-6 days')],
    results: ':notempty:',
    order: 'eventDate desc',
    with: ['imageGallery'],
    limit: 3
}) %}


texts: Is it possible to show more entries of the same entry type as the current entry?

texts:
I'm creating a tumblr-esque blog with a bunch of different entry types.

One of the entry types will be named "Image". When I'm on the entry page for an "Image" entry, I'd like to be able to show 10 more entries with the same "Image" entry type.

Is this possible?


texts: Fixed order with limited set, then resume normal order

texts:
I have a news page (/news). You can open an article (i.e. /news/test-article) which uses the same listing template, but has an accordion open with content for that article (javascript/push state magic).

In the event someone goes directly to /news/{slug} I want to make sure that article is the top one in the list.

Is it possible to go i.e.

$criterea = craft()->elements->getCriteria(ElementType::Entry);
$criterea->section = 'news';
$criterea->order = 'postDate desc';
$criterea->ids = [$startArticle->id, {magically fall back to default sorting!}];
$criterea->fixedOrder = true;

Or am I going to have to futz with the array manually after the search?

Thanks.


texts: Saving entry from Sprout Forms into channel entry

texts:
I'm basically wanting to manipulate user-submitted forms through the use of SproutForms. Basically, the user enters their form data, submits it, where it's recorded as a SproutForm entry. When that happens, I also want it to create an entry in a channel with the same data, so that I can freely use them in templates (showing users a list of their submissions).

All this would be simpler if SproutForms had some templating tags to output entries, but from looking through the plugin, I don't think thats possible.

Anyway, so an additional plugin could have something like this:

public function init() {

    // Support Sprout Forms plugin
    craft()->on('sproutForms.saveEntry', function(Event $event) {
        $entry = $event->params['entry'];
        craft()->entries->saveEntry($entry);
    });

}

But that doesn't seem to work. Any ideas, or a better suggestion?


texts: Controller action redirection when called via route

texts:
I have a route set up in routes.php that calls a controller action using something similar to what is described here: https://straightupcraft.com/articles/how-do-i-setup-a-route-to-point-to-a-controller-action-instead-of-a-template

This works much better for my purposes than POSTing a form to the controller. However, I'm not sure how best to handle redirects. Ideally I would like to redirect back to the page where the user clicked on the link, but calling

$this->redirectToPostedUrl()

doesn't work when using a route like this. The URL just remains the URL as defined in the route.

Is there a different method I can use to make sure users are returned to the page where they were when they clicked the link?


texts: Bulk moving asset folders, from one source to another

texts:
I'm moving all of my assets from a local folder to Amazon S3. I've got my S3 source all set up, and I've been migrating folders over to it by dragging & dropping.

The problem is, I have thousands of asset folders. I did the math, and it'll take me 4+ hours to drag & drop each of them.

Is there some way to bulk move asset folders?

If it's not possible in the CP, I'm open to plugin suggestions as well.


texts: {% if loop.first %} and {{ loop.index0 }} not working with Matrix

texts:
I have a problem with {% if loop.first %} and {{ loop.index0 }} with the following snippet:

{% for block in entry.locationSlideshow %}
  {% switch block.type %}
    {% case 'upload' %}
      {% for image in block.image %}
        <button {% if loop.first %}class="is-active" {% endif %}data-slide="{{ loop.index0 }}">{{ image.title }}</button>
      {% endfor %}
  {% endswitch %}
{% endfor %}

The problem is that all buttons get the class is-active and 0 instead of 0, 1, 2, 3...

This is working fine outside of a Matrix field. Any ideas what I am doing wrong here?

Regards
Ben


texts:
I need to prepend a URL to the beginning of an asset URL in order to track stats for a podcast via Blubrry.

What are the options?

Specifically I need to drop the https that would appear in my URL by default.


texts: Entry URLs are not returning URL with locale in the path

texts:
I set up 2 sites (locally) running Craft 3.6.7:

English (Handle: english, Base URL: '/en/')
German (Handle: german, Base URL: '/de/')

I've made a blog section that is enabled for both languages with a 'blog/{slug}' URI for both and they also use the same template '_blog/_entry'.
There is a single blog post which translates on both languages, with slugs 'test-english' (for the english locale)' and test-german' (for the german locale).
Both posts are accessible as expected using '/en/blog/test-english' and '/de/blog/test-german'. The problem is when I try to link to an entry, the URL that's returned is always 'blog/test-english' or 'blog/test-german', without the Base URL, so the german URL never works ('blog/test-german' doesn't exist).
I've been looking everywhere trying to find if this is the expected behavior, but everything points in the direction it's not. Thank you in advance!
Edit:
This is part of my current navigation that shows the 2 latest posts related to the current site. One of the URLs it returns (without '/en') is: 'blog/get-upselling-inspiration-with-the-deal-library'.
{% set latestPosts = craft.entries().section('blog').siteId(currentSite.id).limit(2) %}

{% if latestPosts.exists() %}

    {% for post in latestPosts.all() %}

          {% if post.singleImage|length %}
            {% for image in post.singleImage.all() %}

            {% endfor %}
          {% endif %}
          {{ post.title }}

    {% endfor %}

{% endif %}

Edit 2: Solved it for now like this, but I don't think this is how it's supposed to work
{% for siteForEntry in entry.getSupportedSites %}
  {# get the site #}
  {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}
  {# check if it's the current site #}
  {% if site.id == entry.siteId %}
    <option value="{{ site.handle }}" selected>{{ site.name }}</option>
  {% else %}
    {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}
    {# if it's not the current site, get the entry for this site #}
    {% if entryForOtherSite.uri == '__home__' %}
      {% set prettyUrl = site.baseUrl() %}
    {% else %}
      {% set prettyUrl = site.baseUrl() ~ entryForOtherSite.uri %}
    {% endif %}

    <option value="{{ site.handle }}" onclick="location.href='{{ prettyUrl }}';">{{ site.name }}</option>
  {% endif %}
{% endfor %}


texts:
I'm trying to add a new input called sessionDesc to a custom field I have in Craft, and I'm getting this error: Property "Craft\Registrar_EventSessionRecord.sessionDesc" is not defined.

I've added sessionDesc to the setAttributes function in the Registrar_EventSessionRecord like this:

    protected function defineAttributes()
    {
        return array(
            'id'           => AttributeType::Number,
            'elementId'    => AttributeType::Number,
            'fieldId'      => AttributeType::Number,
            'title'        => AttributeType::String,
            'startDate'    => AttributeType::DateTime,
            'endDate'      => AttributeType::DateTime,
            'price'        => AttributeType::Number,
            'taxable'      => AttributeType::Bool,
            'ticketCount'  => AttributeType::Number,
            'registerable' => AttributeType::Bool,
            'visible'      => AttributeType::Bool,
            'attendees'    => AttributeType::Number,
            'sessionDesc'  => AttributeType::String,
        );
    }

Here's a screenshot of the errors

Any help is much appreciated.


texts: Is it possible to update a Freeform submission via twig?

texts:
I'm making a google map feature where you type in a search and it drops a pin on the map (standard stuff).
I want to log all the searches for reporting. So, I'm using a Freeform form to collect the location search and display a map on the result page (using the token approach to get the submission info). The result page uses Smart Map to turn the search into a lat/lng and then render the map. I've got that all working great.
What I'd also like to do, for reporting purposes, is to update the Freeform submission with the lat and lng that gets calculated on the result page.

I haven't found a way to update a submission via twig in the docs. Is this possible? Or are there alternative approaches I should consider?


texts: How do we create a pre-defined Asset upload field in a plugin that integrates with the native Craft Assets file manager?

texts:
We've got a plugin.  It doesn't have the ability to add custom field types.  We're pre-defining all of the fields.  One of the fields needs to be an Asset field.  A user should be able to upload an Asset using the native Craft Asset UI, store that Asset locally or on Amazon or any supported cloud platforms.

How do we do this?

Where do we create the relationship between the uploaded Asset and the database record we want the Asset related to?

If we were allowing custom fields we could have our custom table relate to a Field Layout ID, and have any number of fields relate to that Field Layout.  But in our case, we're defining all of the columns we need in our template, in our own record, and don't really need to create any fields within Craft's fields table as we're setting them all up beforehand.

Do we need a Field Layout in this situation?  Do we need to create a Field within Craft under our own context (like Matrix blocks) to be able to control the settings such as where to upload the assets to, and whether to restrict the upload to a single folder, or single image?

I feel I have lots of pieces of the puzzle, but can't yet see how they fit together.


texts: Combine .htaccess. ( http to https AND www to non www AND remove trailing slash ) extending normal craftcms .htaccess

texts:
I can't manage to combine all above options. Tested with several options and examples only the most examples focusses only on on problem.

The example of .htaccess below is okay but i cannot manage to add the trailing slash combining with www and the http.

Testing with: https://htaccess.madewithlove.be/

SEO company want's to get rid of trailing slash. I see that most of CraftCMS installs responds to slash AND non slash.

See : craftcms website pricing and pricing/

are also both okay....thats also not ideal while you can introduce duplicate pages for google.

Recap:

http://www.domainname.nl  -> https://domainname.nl
http://www.domainname.nl/products/ -> https://domainname.nl/products (without trailing slash)

https://domainname.nl/products/      https://domainname.nl/products (without trailing slash)

    RewriteEngine On

# Redirect www to non www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Redirect http to https
RewriteCond %{HTTPS} !on

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# 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]


texts: How can I retain entry category filtering on entry pages' pagination

texts:
I have a list of entries, with an option to filter them by categories.

If no filter is applied, clicking an entry should (and does) take you to the permalink URL for that entry, as defined in the section settings:

{{ entry.title }}

Results in:

Gin

However, if a filter is applied, I'd like to "remember" the category, and apply it to the entry's {{ entry.getNext() }}-style pagination.

In other words, imagine a "Consumables" section, with entries of "Gin", "Lasagne", "Noodles", & "Vodka" (with the obvious categories of "Beverages" and "Food"). You filter the entries on the listing page by the "Beverages" category, & click on the "Gin" entry therein. What I want is for the "Next Entry" link on Gin's page to go to "Vodka", not "Lasagne".

So far, the solution I came up with is to modify the URL for when entries are filtered so that the applied filter results in a URL of /consumables/category/beverages. I also have a route set up so that when a fourth segment is present, it tries to match it up with an entry, eg. /consumables/category/beverages/gin.

Now, I don't know if this is the best solution for this issue, but if it is, the remaining problem is figuring out how to modify the links to the entries on filtered pages so that they include the category. Something like {{ entry.url('consumables/category/' ~ entry.category) would be nice, but it doesn't seem to work like that.


texts:
I'm considering the Solspace Calendar plugin for a project.

Can the plugin send automatic e-mail notifications when an event has been submitted from the front-end?
Can the plugin save events submitted from the front-end as drafts?

Thanks.


texts: CSS uploaded to S3 is not rendering in the browser

texts:
I have created a separate asset source to upload my css on Amazon S3 cloud service. Initially, it was not allowing me to upload the files to S3. After adding CSS in the extraAllowedFileExtensions in the config>general.php file, I was able to upload the CSS file.

Here is the code in the template to load the css

<head>

{% for cssfile in craft.assets.source('css') %}
        <link rel="stylesheet" type="text/css" href="{{ cssfile.url }}" />
{% endfor %}

I can see the link tags for each CSS file in the HTML source code, the URL is functional. However, browser refuses to render those files. If I go into chrome console>sources, I can see all the CSS files listed there but they are empty!

When I create a new css asset source locally on the server, everything works (without changing anything inside the template)

I am really confused. I have never ever encountered a problem where browser refuses to read the css file.

Other assets such as js, images etc are loading properly from amazon S3. The only issue seems to be with css

Any ideas?


texts: Some paths and settings being ignored in config

texts:
I've tried to set some things in my general.php config file but they're being ignored.

I have the following but all are being ignored. For example, when the user receives the activation email, upon clicking the link the account is activated but they're not taken to my template 'user/activation-success' but instead the homepage and also not automatically logged in, like I'm setting. Any ideas?

return array(
    'setPasswordPath' => 'user/set-password',
    'activateAccountSuccessPath' => 'user/activation-success',
    'autoLoginAfterAccountActivation' => true
);

I'm running 2.5.2757.

Updated to show my full config file:

<?php

return array(
    'setPasswordPath' => 'user/set-password',
    'activateAccountSuccessPath' => 'user/activation-success',
    'autoLoginAfterAccountActivation' => true,

    '*' => array(
        'omitScriptNameInUrls' => true,
    ),

    '.local' => array(
        'devMode' => true,
        'userSessionDuration' => false
    ),

    '.co.uk' => array(
        'cooldownDuration' => 0,
    ),

    '.com' => array(
        'cooldownDuration' => 0,
    )
);