texts: Getting value from response (Craft Commerce)

texts:
I'm in the process of adapting the old RealEx gateway to work in Commerce 2 since that's what we're using and there isn't native support in V2.

I've got payments and 3D secure working, now I'm trying to get refunds sorted but running into issues.

Firstly, the old plug-in has a get/set for OriginalTransactionId which I guess was something in V1?? Would anyone happen to know how to get the original transaction ID?

Would $this->getTransactionId() suffice?

Also, how would I get a value from the original response? I need to grab authcode from this response saved in the DB:

{
    "@attributes": {
        "timestamp": "20191007113507"
    },
    "account": "XXX",
    "authcode": "12345",
    "authtimetaken": "0",
    "avsaddressresponse": "M",
    "avspostcoderesponse": "M",
    "batchid": "707751",
    "cardissuer": {
        "bank": "AIB BANK",
        "country": "IRELAND",
        "countrycode": "IE",
        "region": "EUR"
    },
    "cvnresult": "M",
    "merchantid": "XXX",
    "message": "[ test system ] AUTHORISED",
    "orderid": "XXXX",
    "pasref": "XXXX",
    "result": "00",
    "sha1hash": "XXXX",
    "srd": "XXXX",
    "timetaken": "0"
}

The old code used:

public function getAuthCode()
{
    return $this->getParameter('authCode');
}

public function setAuthCode($value)
{
    return $this->setParameter('authCode', $value);
}

But this returns empty.

I appreciate any help anyone can provide.


texts: See the SQL query that gets executed when saving entry

texts:
I'm creating a pretty specific entry with some fields. And I want to create the from a third party app. For that, I'd like to see the SQL query that get executed.

I've tried it with events, entries.onBeforeSaveEntryand content.saveContent but I cannot get the query itself.


texts: Is it possible to make links open in a new tab by default?

texts: I have a website where by default I would like all external links to have the "open in a new tab" option to be selected by default. I'm wondering if this is possible either through craft or redactor? I came across this but think it may be overkill so I'm wondering if its possible without a plugin.


texts:
Trying to get users in a members group related to multiple categories.

{% set services = craft.categories.group('services').slug('service-1, service-2') %}
{% set locations = craft.categories.group('locations').slug('location-1') %}

{% set members = craft.users.group("members").relatedTo("and", { targetElement: services }, { targetElement: locations } ) %}

{{ members | length }}

Number of members returned is zero.

Any ideas?


texts: Adding 301 permanent redirections in Craft CMS

texts: I am not able to redirect any dead page. Although I have added the redirection but it is not getting reflected. Please help.


texts: Order entries based on date field in the Control Panel

texts: I have some entries and I want to order them in the Control Panel based on a date field of those entries. Is that possible ?


texts: Translating static text in JavaScript files

texts:
I've got some static text that is dynamically being displayed on the frontend with JavaScript.

Now considering the site has 3 locales, how do I best translate those static texts?

I know I could put the JavaScript code in my twig files and use the translate filter, but that is what I'm trying to avoid as I like to keep the HTML & JavaScript separated.

Is there a way to pass on certain messages to a script?

From this answer, I learned there's such a thing as Craft.t but I can't seem to access it from the frontend. Can it be included?

EDIT - To clarify what I'm looking for, it's something in the likes off this Wordpress concept, where you can pass some variables from the server to a javascript script. It would allow me to make some global fields to store the translations in, and make those translations editable from the backend.  But I'm guessing that's not possible?


texts: How do I make the "%20" in URL's show as "-"

texts:
I'm building a site where I am linking entries based on their tags. If you click on a tag you go to a dedicated page with all entries that share the same tag.

{% for tag in craft.tags.relatedTo(entry) %}

{{ tag.title }}

{% endfor %}

The problem I have is that if a tag has more than 1 word, the URL displays like this:

http:/site.com/tag/two%20words

How do I change "%20" to a dash?


texts:
Is there any plan on supporting SQLite someday? It would be very interesting for small instances where we can't create any MySQL or MariaDB databases for example (in my case, free tier hosting coming with the domain name which offers PHP, 30Mb storage but no MySQL database).

Thanks a lot!


texts: I see there is a freeform forms fieldtype available after the plugin was installed. What exactly does this field do and how to render it correctly (within matrix)?


texts: Explanation of how to link to a structure from a structure

texts:
I've searched these boards and haven't been able to find the answer to my specific question.

I'm working on building my navigation, and I want to build it in a structure. It will be a multi-level navigation, which is why it makes sense for a structure. However, I've already built a separate structure for a sermon catalog that I want to keep separate from the navigation structure.

Basically, I want to be able to link to a separate structure within my navigation structure. Is this possible? Is there a better way to do this that I haven't grasped yet?

Navigation Structure Example

1.Home

2.About

Directions
Staff

3.Watch (I want this to link to my sermon structure)

4.Kids & Students

Highschoolers
Middleschoolers
K-5th

EDIT: I've tried adding in an entry type to navigation and linking to the structure, but it won't let me link to the actual structure. Just entries inside the structure. Which is not what I want. Any thoughts?


texts: Cache/ColdCache & checking for ungenerated image transforms

texts:
This issue is very similar to the following issue, but this goes a little bit further. Cache tag won’t cache in a template

I have a page which is made up of hundreds of lazy loaded images similarly to this:

 <img data-original="{{ image.getUrl(transform) }}" src="/img/placeholder.png" alt="" />

The page takes anywhere between 2 and 5 seconds to load, and yet the server isn't under powered in any way.

The majority of the images on the page aren't transformed within a few page loads. It's quite possible that there are images that no one will ever look at, therefore will never be transformed... Craft will hold off on caching until all the images are transformed; which might never happen.

I could duplicate the template, and turn off lazy loading, and get my client to load that page every time they make changes, but I would prefer not having to ask my client to anything like that.

Apart from loading stuff via ajax when needed, does anyone know of an easy way to get all the images transformed or to get caching working so that it doesn't require all assets to be transformed?


texts:
Is there a limit to the number of different entry types a section can have? For this project I might need 50+.
I think I need more content to meet the quality standards so I'll explain: my client wants to create multiple reports for her customers to fill in. My client is comfortable with craft backend and knows how to create fields/sections/etc. I want to keep all the report entries together. Ergo a Reports section with a different entry type for each report.


texts: How do you wrap text with HTML within a Plain Text field?

texts:
I have a Plain Text field used for product names. Some of these product names have a Registration Mark or a Trademark, which needs to be formatted within a superscript.

Here is code within my template:

{{ product.name | replace({'®': '®' }) }}

Which publishes this:

Acme ABC Widget®

When what I really want to achieve is this:

Acme ABC Widget®

Does Craft persistently render Plain Text fields as raw text? I was hoping Twig filters could extend the use of Craft's Plain Text field.

My preference is to continue using the Plain Text field to avoid additional formatting breaking the layout.


texts: Is there a way of displaying an entry twice depending on postDate and a custom field date in one loop?

texts:
I'm building a feed of entries mixed from different sections. One section contains a postDate and a custom field date called releaseDate. I want these entries to appear in the feed with their postDate, but when the releaseDate is equivalent to now I want the entry to return in the feed in order of appearance. Is this possible?

I've tried something like this:

craft.entries.section(['section1', 'section2']).order(['postDate DESC', 'releaseDate DESC'])


texts: Show related entries grouped by category with category title and description

texts:
Anyone able to direct me on this?
I have a page that allows you to pick related entries (cables) within the page I want to output the related entries (cables) but group them by their category. I have the following code by this is adding each cable into each category and not just the cable within the right category.

    {% set categories = craft.categories.group('cables') %}

    {# {% set cables = craft.entries.section('cables').order('title').limit(null) %} #}

    {% set cables = entry.cables %}

    {% for entry in cables %}
        {{ entry.title }}
    {% endfor %}

    {% for category in categories.relatedTo(cables) %}

{{ category }}

                {{ category.description }}

                {% for entry in cables %}

{{ entry.title }}

                {% endfor %}

            {% for entry in cables.relatedTo(category) %}

                            Close

                                {{ entry.title }}

{{ entry.cableDescription }}

            {% endfor %}

    {% endfor %}


texts: Headless CraftCMS as mobile app backend, requiring login

texts:
Currently building a mobile app with Phonegap, I'm able to use the Element API for many features, but when comes the time to use Craft as a loggedin user, I run out of ideas.

I read a lot of things about headless Craft, but I found nothing about the proper way to authenticate outside the Craft installation itself.

First, I achieved something semi-decent with a JWT system and a custom controller to perform a login validation, which works great, and allow me to read from Craft on my controller (with $allowAnonymous = true;, unfortunately)

(For curious eyes, it's far from perfect: https://gist.github.com/rtrudel/49b96ebc93bfd6774ebbe841426e4b6c )

But I do not want to turn off CSRF globally, and I need to use users/save-user to save user profile in-app). The CSRF token value returned by Craft::$app->getRequest(); seems not right for the next ajax calls, which return Bad request, unable to verify your data submission.

So, this brings me out of ideas... do I have another way to login my user from my mobile app and to retrieve the CSRF token correctly in order to do that, and for all the ajax calls my app will do once logged in?

My JWT approach is maybe not as good as expected in the use-case, perhaps I have to think different? I'm open to any idea to make it work as it should.

My main concern is security and efficiency.

Thank you!


texts: How can I handle the identical SEOmatic config for multi-sites?

texts:
I'm using the amazing SEOmatic plugin in a multi-site config in craft 3.

I have a total of 18 sites and they share a lot of identical data. So I was wondering if it was possible to export the configuration I made for the main site and import it to the others.

Is there a way to avoid configuring 18x the same thing? It will save me a bunch of time.

Thanks !


texts: How can you display entries filtered by localisation/localization?

texts:
Supposing you have a structure of products but you only want some to be available to certain localities?

I am sure you could add a field to the entries E.g (Available in: eng | fr) and then test the local in the template before listing the entires. However, I'm not sure this is the best way of approaching this.

Initially, it may be that the category the product is within dictates its availability in a country but this is not guaranteed in the future.

Any ideas appreciated.


texts:
I have a category listing template where I'm having trouble passing in some variables.

top of the template I have this snippet where I'll set the channel and category field name based on the segment

{% set segment = craft.request.segment(1) %}

{# set channel based on segment_1 #}
{% if segment == "business-intel" %}
    {% set channelName = "businessIntel" %}
    {% set categoryName = "businessIntelCategories" %}
{% elseif segment == "foo" %}
    {# do nothing #}
{% endif %}
{# end set channel #}

Then further down the template I have this:

{% include ('_includes/cat_sub_with_article') with { 'categoryName' : categoryName } %}

And then the included template looks like this:

 {% for category, catEntries in entries | group('categoryName.first().title') %}

{{ category }}

    {% set featuredThumb = {
        mode: 'crop',
        width: 370,
        height: 168,
        quality: 90,
        position: 'top-center'
      } %}

        {% for entry in catEntries %}

                {% set image = entry.featuredImage.first() %}

                    {{ entry.postDate.format('M d, Y') }}

{{ entry.title }}

{{ entry.featuredSummary }}

Learn More

        {% endfor %}

 {% endfor %}

If I hardcode the category field name into line 1 of the above block everything works. However if I try to use the passed varialbe. I get this error, which I don't know how to fix:

  Craft\EntryModel and its behaviors do not have a method or closure
  named "categoryName".


texts: Is there any way of specifying a default category for a category field?

texts: I've set up a channel using categories to distinguish between different blog post types. The majority will probably be in one category, so it would be great to be able to specify a default category. However, as far as I can see the Category field type (unlike, say, the Drop Down field type) doesn't give you the option to set a default... Is there any way of doing this?


texts: Checking for first time an entry is "published" i.e. saved with a Live status

texts:
Is there a way, via an Event or otherwise, to catch the first time a post is saved and isn't in disabled mode? I want to send out an email alert to users when a new entry is published, but I want it to be possible to work on it in disabled mode first.

If I use the entries.onSaveEntry event, it comes with the a param for isNewEntry, but I can't use this because it's only true the very first time an entry is saved, even if it's saved in disabled status. After that it will always return false.

It wouldn't be difficult to add an additional field to the entry that would track whether or not emails were sent, but I was wondering if there's a more straightforward way to handle it.


texts:
If an model/element gets changed then I can know about it by listening to an event like onBeforeSaveEntry. This will provide me with the latest version of the model/event, but doesn't give me the changes. Something like this would be great.

craft()->on('elements.onSaveElement', function (Event $event) {
    $element = $event->params['element'];

    // $changes = ['uri' => ['old' => 'index', 'new' => 'index2']]
    $changes = $element->getUnsavedChanges();
}

I generate a routes.js that the client uses to generate menu and other stuff. I would like to listen to uri/slug changes so I can clear my (varnish) cache to update internal links. I'd like to prevent clearing my whole site if just one tiny thing gets changed. Any idea's how I can get the model changes or work around this issue?


texts:
We're building out a Commerce site that needs an "Insurance" option set on an order. Based on the selected option, a percentage of the subtotal should be added to the total amount in the cart.

I've added an adjuster for this, added a field to the order to keep track of which option the customer selects and I can add the adjuster to the order (as in: the type & amount are added to the cart in the backend).

But it seems I can't add that amount to the cart total. In the docs I found this:

  Included Adjustments

  If you mark the adjustment model’s included attribute as true, the
  adjustment does not make any changes to the orders value, but simply
  records an amount that was included in the price of the order.

  The only included adjustment we use in the core system at the moment
  is included taxes.

Is there a way do this?

Thanks!


texts: Filter locations by country in Smart Map

texts:
I'm using Smart Map to find locations ordered by distance. But I can only set 3 parameters: target, range and units. However, when my range goes beyond the country borders I obviously get results in other countries. I want to list all locations within a country by distance, but limited to that country.
Is it possible to do this? I tried related items, but can't seem to get it to work. And I don't see any option in Smart Map either.


texts: How can I Link a category entry to a Subsite?

texts:
I have a Structure Section:

Home

Sub 1
Sub 2

About

List item
List item

Info

How can I link the «Home»-Entry in a Structured Section to the «Sub 1»-Entry?

Any help is much appreciated. Thanks in advance.


texts: What password requirements exist for new users?

texts:
My site contains a front-end registration form. New users will be automatically activated, and can begin using their account immediately.

What password requirements exist?

I vaguely remember a 6-character minimum... Is that accurate, and are there any other requirements to be aware of?


texts: Cannot update Craft, only download the zip

texts:
Recently I cannot update Craft on a server. From versions 2.6.2778 and 2.6.2779. I only can download the zip to install it myself. What could be wrong here?
Thanks in advance.

PHP: 5.6.16-1byte1

Alert on iconv (older version)


texts: How do I force a 301 http status code using the redirect tag?

texts: Using Craft's redirect template tag creates a redirect with a 302 (Moved Temporarily) http status code. How can I force a 301 (Moved Permanently) status code?


texts:
Is there a workaround when using Craft with old versions of ImageMagick to prevent transformed images from being darker than the original?

I had a look within the Imagine code base and couldn't see a easy fix.

Unfortunately I'm stuck with ImageMagick 6.7.2-7 on shared hosting with no upgrade path.


texts: View Sprout Form Entries in CP displaying error

texts:
I'm running the latest Craft and Sprout Forms as of today.

On a clean install of Sprout Forms whenever I create a new form (even with just one text input field), I cannot access that specific form's entries in the CP. The "All Entries" view works, however.

There are two "unknown error" notifications in the CP. Here are the relevant errors in the log.

2016/02/23 11:40:06 [error] [system.db.CDbCommand] CDbCommand::fetchAll()
failed: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'form' in 'on
clause'. The SQL statement executed was: SELECT `elements`.`id`,
`elements`.`type`, `elements`.`enabled`, `elements`.`archived`,
`elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`,
`elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`,
`entries`.`id`, `entries`.`ipAddress`, `entries`.`userAgent`,
`entries`.`dateCreated`, `entries`.`dateUpdated`, `entries`.`uid`,
`forms`.`id` AS `formId`, `forms`.`name` AS `formName`, `forms`.`groupId` AS
`formGroupId`, `form-request-an-audit`.`title`, `form-request
an-audit`.`field_test` AS `test`

~

2016/02/23 11:40:06 [error] [exception.CDbException] exception 'CDbException'
with message 'CDbCommand failed to execute the SQL statement:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'form' in 'on clause'.
The SQL statement executed was: SELECT `elements`.`id`, `elements`.`type`,
`elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`,
`elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`,
`elements_i18n`.`enabled` AS `localeEnabled`, `entries`.`id`,
`entries`.`ipAddress`, `entries`.`userAgent`, `entries`.`dateCreated`,
`entries`.`dateUpdated`, `entries`.`uid`, `forms`.`id` AS `formId`,
`forms`.`name` AS `formName`, `forms`.`groupId` AS `formGroupId`, `form
request-an-audit`.`title`, `form-request-an-audit`.`field_test` AS `test`

I've uninstalled, re-installed, and everything in-between with the same outcome.


texts:
I want to iterate through my entries on the click of a 'next' and 'previous' button.

I have started off using getNext() and getPrev() by I'm in a bit of a rut.

{% set entry = craft.entries.section('comics').first() %}
{% set asset = entry.comic.first() %}
{% set params = craft.entries.section('comics').order('id asc') %}
{% set prevEntry = entry.getPrev(params) %}
{% set prevAsset = prevEntry.comic.first() %}
{% set nextEntry = entry.getNext(params) %}
{% set nextAsset = nextEntry.comic.first() %}

This is the Twig code. To display the prevEntry I have been using jQuery. Here is that code.

    function prevComic() {
      var $prevTitle = "{{ prevEntry.title }}";
      $(".comic-title").text($prevTitle);
      $(".comic").attr('src', '{{ prevAsset.url }}');
      $(".comic-caption").text("{{ prevEntry.body }}");
    };
    function nextComic() {
      var $nextTitle = "{{ nextEntry.title }}";
      $(".comic-title").text($nextTitle);
      $(".comic").attr('src', '{{ nextAsset.url }}');
      $(".comic-caption").text("{{ nextEntry.body }}");
    };

Then I'm using onclick() on the buttons to call the functions.
All I really want is for the 'previous' button to give me the previous entry to the entry currently displayed, and for the 'next' button to give me the next entry to the entry currently displayed.
Can anyone help me?
Thank you :)


texts: Inside a JSON template I find an entry using id, the result title can't be seen using entry.title but I can see it with entry[0].title. There is another step or encoding I have to use?


texts: Display X minute / hours / days in entries

texts:
I am trying to print if statement for x time or x day ago for each published entries. For example the entry is posted x minutes ago should display x minutes ago or x hours ago. Same for days and months.

Here is what I have used but not what I am after.

{{ date(category.dateCreated|date('c')).diff(now).format('%a') }}

But the code I have written does not work.

{% for category in entries %}

{% for time in category %}
{{ date(time.dateCreated|date('c')).diff(now).format('%i') }} minutes ago

{% else %}
{{ date(time.dateCreated|date('c')).diff(now).format('%h') }} hours ago

{% else %}
{{ date(time.dateCreated|date('c')).diff(now).format('%d') }} days  agos
{% endfor %}
{% endfor %}

The above code is too long or is there a better way to check whether the entry is posted min, hours, or days ago.


texts:
This may be asking the impossible, but I'm trying to do the following:
Say I have 3 channels, Country, Region, and Town. Town has an entry field to select a Region, a Region entry has a field to select a Country.
I want the URL for a Town entry to look like https://website.something/uk/west/torquay, or https://website.something/portugal/south/faro. Both of these URLs would load the template specified for the town. A URL of https://website.something/france/south would load a Region template.
I'm guessing I'll have to do some advanced routing?


texts:
I am using the UserModel to create a user, and then injecting that into the User API service as is instructed in the documentation. The only thing I am not seeing is how to set the group.

I looked in the Model class and there is no method for setting the group and it's not part of the defineAttributes() method.

In the documentation there is no method to set group, just read only the groups: https://craftcms.com/docs/templating/usermodel#getGroups

Nothing here about it: https://craftcms.com/classreference/services/UsersService

Here is what I am doing to save user.

$user = new UserModel;

$user->username = 'username';
$user->email = 'yourmom@email.com';
// $user->groupID = "group";
$user->firstName = 'first name';
$user->lastName = 'last name';
$user->getContent()->setAttributes([ 'usersAddress' => 'Your face' ]);

craft()->users->saveUser($user);

Am I missing something obvious?


texts:
I am building an event booking system for a restaurant using Charge 2.0. Everything is working great, but having problems implementing a feature that shows how many spots are left.

An Event channel entry (created by the restaurant) provides parameters such as price, event name, etc and passes them to a Charge form. The Event entry also includes a field that specifies the maximum number of guests.

The Charge form includes a field for specifying a 'number of guests' for the booking. To indicate how many spots are left, we first need to calculate how many guests have already been booked, which is a simple matter of getting the 'numberOfGuests' field from all of the existing Charge entries and summing them. The problem arises when trying to filter the results using a Search parameter, which limits the entries to a specific event (the Event name is passed to the Charge description field). Here is a bit of the code:

{% set q = 'description:' ~ '"' ~ entry.title ~ '"' %}
{% for entry in craft.charge.charges().search(q) %}
   //get the number of guests

I tried a few different things, including a wildcard search, and none of them return any results. Does anyone know if the Charge model supports a Search parameter?


texts: Get different kind of entries relatedTo one asset (many to one)?

texts:
I got an asset field called docs which is contained in 2 different entries.
Those entries are in different sections and they contain the docs field directly or through a matrix field called articleBody.

I made two queries relatedTo and merge them thereafter.
It works but would it be a better way by combining the two queries in one relatedTo call?

Query 1: pages section entries contain docs field inside a matrix field called articleBody
Query 2: library section entries contain docs field directly

        $criteria1 = craft()->elements->getCriteria(ElementType::Entry);
        $criteria1->section = 'pages';
        $criteria1->relatedTo = array(
            'targetElement' => $asset->id,
            'field' => 'articleBody.docs'
        );

        $criteria2 = craft()->elements->getCriteria(ElementType::Entry);
        $criteria2->section = 'library';
        $criteria2->relatedTo = array(
            'targetElement' => $asset->id,
            'field' => 'docs'
        );

        $criteria = array_merge($criteria1, $criteria2);


texts: I need to figure out if there's a way to track the amount of times an asset was downloaded. I need to display this in the back end on the site. I don't need to display it anywhere but on the back end of an admin user.


texts: What's the best practice for upgrading a versioned Craft site?

texts:
It's thrilling to click The Button and watch Craft update itself. I take advantage of multi-site configurations with every deploy, and my practice thus far is to...

Upgrade Craft in production.
Commit production file system changes via git.
Choose Settings → Backup Database and download the backup file.
Load the remote changes to my local environment via git.
Clear out and locally import the .sql backup I downloaded in step #3.

I specifically update in production because I like thrills, and because I had previously done the opposite (upgrade locally, push live) and ran into problems.

This has been working for me pretty reliably and Craft upgrades always go smoothly, but I doubt that system updates on the production server are the best idea.

Is there a better way?


texts: Updating just a single content field from a plugin

texts:
I have a Task that is running through a collection of elements, moving some data from one field to another. The problem I am hitting (more and more with situations like this) is that in order to update just one field of an element, using the recommended BaseElementModel::setContentFromPost() method, I have to also account for all kinds of other values to get it to validate and save.

I know you need to specify the IDs (from questions like these two) for any relation fields that are required, which is not ideal, but not a huge issue in this case.

However, on this project I also have the Venti plugin installed, with its Venti_EventFieldType for dates and RRULEs, and I'm having to manually pass through a big array of any existing start/end date information into setContentFromPost() just so the validation for that field will pass, even though I'm doing absolutely nothing with that field.

Is there not a single way to update a single field's value, without already knowing the way data needs to be formatted for any other fields that might be on that ContentModel? Otherwise I don't see how a general-release plugin could be made that can modify existing elements, without knowing about the setContentFromPost()-specific data format of every possible Field Type in advance.


texts:
I really spend a lot of time searching for a solution to this problem.  When I try using the Export plugin to export some entries with some Matrix fields and Neo fields for content, all that I can get is empty.

Seems to me that no one could've resolved the problem "Exporting / Importing all translatable Textfields of all entries in a section" or "How to export client-entered content for a specific channel to keep my local database in sync with staging" which my problem is similar to.  I tried to search in the database for the content of the entry added by the client, found it and I'm working on how to replace it in my DB without causing errors, but the relation between tables still confuses me.

So my questions are, is there any solution yet? If not do I need to create a plugin that read Matrix fields and export it as JSON data? Do I continue in my attempts in the database to try and find the entries and their related content (is it possible)?

I hope I have explained enough clearly my situation.

P.S : I'm still a novice in Craft CMS so take it easy on me ^^


texts: craft_searchindex is MyISAM all others InnoDB

texts: Looking at my database today notice this one table is MyISAM and also seems huge relative to all other tables with 147,835 rows.  Is that normal?  Shouldn't all tables be InnoDB?  What would cause one to be MyISAM?


texts: Get control panel asset thumbnails into a frontend template

texts:
My frontend template displays the assets that have been uploaded to Craft. I could create a series of asset transforms within that template to create a range of thumbnail sizes.

Not too sure about the way this works but am I correct in thinking that every transform generates a new asset, to be more efficient with storage could I not reuse the transformed assets that the Control Panel creates?

I inspect the Assets panel in the backend and it has a url http://localhost:8888/index.php?p=admin/actions/assets/generate-thumb&amp;uid=219035f4-92ae-41d6-ad95-0f6a4c38faa9&amp;width=30&amp;height=30&amp;v=1521142167 I could pass the UID of the image to that url or may be instead match the sizes the CP creates would this reuse the same images instead of adding to my S3 storage?


texts: Getting related project of a submitted 'wish' through the entry field.

texts:
I have a channel projects and a channel wishes (People can submit their 'wishes' for that particular project.

In a project I made the 'entry field' projectHasWishes to connect wishes to project.

Now we use guestentries plugin to get wishes from the visitors. This form is that particular projectpage on the frontend. How can I relate them easily to the right project? Can I use a hidden field for this? Or something else? Thanks for helping me out.


texts: Manipulating CP Elements List view with source filtering does not work for assets

texts:
I made a plugin which customize columns table view for all my elements and using a filter on the source :

Entries: section

public function modifyEntryTableAttributes(&$attributes, $source)
{
    // set fields for one section
    if ($source == 'section:8' )
    {
        unset($attributes['expiryDate']);
    }
}

User Groups : group

public function modifyUserTableAttributes(&$attributes, $source)
{
    if ($source == 'group:6' )
    {
        $attributes['unepRegionDelegateMember'] = Craft::t('Région');
    }
}

It is working great for these two but I got a problem with the assets source param, it just does not work, I tried folder as explained in Craft Doc but does not work:
http://buildwithcraft.com/docs/plugins/hooks-reference#modifyAssetTableAttributes

Assets: folder

public function modifyAssetTableAttributes(&$attributes, $source)
{
    if ($source == 'folder:2')
    {
        unset($attributes['dateModified']);
    }
}

EDIT
In fact my problem was that I was mistaken by the asset sourceID which has nothing to do with the folderID requested by the function modifyAssetTableAttributes. See what I mean here:

For entries or user groups you can find the ID in CP in the section/usergroup page, the CP page URL contains the ID:
http://craft.dev/admin/settings/sections/5
http://craft.dev/admin/settings/users/groups/5

But for the assets the ID in the url is not the folderID :
http://craft.dev/admin/settings/assets/sources/2

SO MY REAL QUESTION IS:
Is there a function to retrieve the main folder ID from an asset source handle to do $folderId = craft()->assets->source(‘asset-handle’)->id
So we could easily use function modifyAssetTableAttributes and provide source filter if ($source == 'folder:51’)
On the same pattern as for section : $sectionId = craft()->sections->getSectionByHandle('handle')->id;

ELEMENT MODEL + GETCRITERIA
I tried this
$criteria = craft()->elements->getCriteria(ElementType::Asset);
$criteria->source = ‘asset-handle’;
But I dont see how to get to main folder ID after...


texts: Save matrix block to new entry in plugin

texts:
I have been trying two separate methods to accomplish and both keep resulting in the same errors no matter what I try.

The entry I am saving has a few fields the last of which is a matrix block (I am able to save the entry fine when not trying to save the matrix field to it.). This matrix block has two entry field types and the last field is a table field. I do not need to save actual data to these fields; it's fine that they are null/empty. I made sure that in the matrix block settings for these fields are not marked as required.

I am testing this via ajax calls in jQuery.

First Method (described here):
Craft sends back an error stating that...

Argument 1 passed to Craft\MatrixService::validateBlock() must be an instance
of Craft\MatrixBlockModel, array given, called in
/path/to/project/app/fieldtypes/MatrixFieldType.php
on line 393 and defined

It appears to me that craft is expecting a matrix block model not an array. But even Brandon Kelly shows an example here of this method working...so what am I doing wrong..?

Here's my code:

private function _buildEntry ($college, $now, &$data) {
    $entry = new EntryModel();
    $matrixData = array();
    $entry->sectionId = 4;
    $entry->authorId = 1;
    $entry->typeId = 1;
    $entry->enabled = 1;
    $entry->getContent()->title = $college->collegeName." ".$now;
    $entry->getContent()->timeEntryStartDate = $now;
    $entry->getContent()->timeEntryCollege = array($college->id);

    //set up the matrix data
    $matrixData['new1'] = array(
        'type'      => 'weekBlock',
        'enabled'   => true
    );

    $entry->getContent()->timeEntryWeek = $matrixData;

    //save the new entry
    $success = craft()->entries->saveEntry($entry);

    if(!$success){
        Craft::log('Could not save the entry "'.$entry->title.'"', LogLevel::Error);
    } else {
        Craft::log('Saved the entry! '.$entry->title.'"', LogLevel::Error);
    }
}

Second Method (described here): Craft sends back an error stating that...

Trying to get property of non-object

My code for this second part which I call after craft successfully saves the entry (which works fine)

public function actionTest($id = 3) {

    $block = new MatrixBlockModel();

    $block->fieldId    = 20; // Matrix field's ID
    $block->ownerId    = 178; // ID of entry the block should be added to
    $block->typeId     = 6;
    $block->getContent()->setAttributes(array(
        'timeEntryHouse' => array(183),
        'timeEntryEmployee' => array(1),
        'timeEntryDays' => null
    ));

    $success = craft()->matrix->saveBlock($block, false);
    if (!$success)
    {
        Craft::log('Couldn’t save the entry "'.$id.'"', LogLevel::Error);
    } else {
        $this->returnJson('worked');
    }
}


texts: Find an authorId based on first and/or last name

texts:
Is there a way I can reverse use the User Model to return an authorId based on the first/last name (John Doe)?

Basically, I'm converting the first/last to a readable URI segment (using email addresses as username and I want something more readable than an ID in the URL):

{{ entry.author.firstName|lower ~ '-' ~ entry.author.lastName|lower }}

Returns: john-doe

Then on the listing page, grabbing the URI segment, setting that back to a readable name and spliting to array.

{% set authorName = craft.request.segment(3)|replace({'-':' '})|title|split(' ') %}

Which gives me (the equivalent of):

Array
(
  [0] => John
  [1] => Doe
)

I'd like to get the author id to return all the entries from said author. I thought something along the lines of below would work:

{% set author = craft.users.firstName(authorName.0).lastName(authorName.1) %}

With the above, I get the error:

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

However, if I return {{ authorName.0 }} it returns a string.


texts: Limit ElementAPI results with custom date/time field

texts:
What is the proper syntax in the ElementAPI 'criteria' configuration settings for limiting entries based on custom start and end date/time fields. I can't use the default postDate and expiryDate due to localization requirements.

I have the proper syntax working in my twig template:

.startDateTime('<=' ~ now.date,':empty:').endDateTime('>=' ~ now.date,':empty:')

How can I mimic this same logic in the ElementAPI config settings? This is what I have so far. It doesn't throw any php errors but doesn't return the results I am expecting:

'criteria' => [
    'section' => 'mySection',
    'type' => 'mySectionType',
    'startDateTime' => '<=' . date("Y-m-d H:i:s") . ', :empty:',
    'endDateTime' => '>=' . date("Y-m-d H:i:s") . ', :empty: '
],


texts: How to manually run pending tasks in Craft CMS 3

texts:
I have a task that I want to run, but unfortunately I dont seem to be able to disable mod_gzip/mod_deflate on this server, so that task will not run in the background and causes the site to hang while processing the task.

Therefore, I have set the "runQueueAutomatically" config setting to false.

I want to trigger the task queue to run manually (via a cron job), but I'm not sure how. In Craft CMS 2 I could visit "/index.php?p=actions/tasks/runPendingTasks" as per the docs here https://docs.craftcms.com/v2/config-settings.html#runtasksautomatically but I can't find the same action for v3. Have gone through the docs and can't see it anywhere - can someone help?

Thanks.


texts: More extensive documentation for defining models for plugins

texts:
I'm trying to get a better understanding of how to define new models in plugins, but the documentation at http://buildwithcraft.com/docs/plugins/models doesn't get me very far.

For example, there is:

protected function defineAttributes()
{
    return array(
        'name' => AttributeType::String,
        'type' => array(AttributeType::Enum, 'values' => "alcohol,mixer,other"),
    );
}`

I've seen other plugins define attributes with an array element of 'required' => true, but the only example I see here is 'values'. Is there somewhere I can see a list of the available options when defining attributes? Or is it a better practice to define the attributes simply and then define validation rules in the rules() method?

I know the docs say to check out the CModel documentation, but it doesn't even have defineAttributes. Does Craft itself have more in depth documentation on this topic?


texts: Sections, Categories, and EntryTypes. Which, when?

texts:
bit of a 'best practice' question, as I'm very sure there are many ways to do this sort of thing, but...

When/how do you decide whether to use a section, category, or entry type to organise your entries? I've been finding that my EntryTypes match 1:1 to the categories in my 'global' group, and that's lead me to wonder if there's any point in having them as global categories too, and whether I'm just not understanding how to use these tools properly.

For example, I've got sections: webDevelopment, generalWriting.

And categories (in a global group): Article, Tutorial, Links.

And EntryTypes in each section: Article, Tutorial, Links.

It's starting to look like there's little point in having global categories, but not having categories feels very weird / wrong.

So... how do you decide how to organise your stuff?


texts:
I have a condition that checks entry Id. The condition seems to not work for Japanese locale but works fine on English. I would think that entry ID remains the same irrespective of the locale. Please confirm or correct me if I'm wrong.

Thanks!


texts: Plugin Error: "Unable to find component class"

texts:
I'm suddenly getting an error on my plugin fieldtype even though I didn't make any changes to it. On Craft's publish page where my field is supposed to be I get the error:

Unable to find component class 'kgrote\siteutilities\fields\Regionselect'.

Really have no idea where to start looking here. The Regionselect class exists in the fieldtype file and the name of the file matches the class. It might help if I knew where this error was originating from.

Additionally, the plugin shows as "Disabled" in the Settings area and I can't enable it, and there is no "Uninstall" option available in the dropdown.


texts:
The builtin craft image resizer tool appears to be having issues with CMYK source images, we're using Craft 2.5 (latest version)

Original source image

http://2b45fe03c2dbd491035c-f318885d2d6632cd7d9eb38c0fa500f2.r62.cf1.rackcdn.com/new_site/film/images/EXM_D016_02432_42886.jpg

Transforms to this

http://2b45fe03c2dbd491035c-f318885d2d6632cd7d9eb38c0fa500f2.r62.cf1.rackcdn.com/new_site/film/images/_assetImageGrid/EXM_D016_02432_42886.jpg

Is there a solution to this issue that we can implement, or is it simply a case that CMYK images cannot be resized by the system?

Thanks


texts:
In a fresh installation the 'Home Page' seems to make use of the custom 'Heading' field whilst the 'News' channel makes use of the 'Title' field.

What is the advantage of using the 'Heading' field over the 'Title' field?


texts: Connection between twig template and website content

texts:
I am new to Craft and I am basically inheriting a site that I now need to maintain.  I am a developer, not really a web designer, and my current task is to change the layout on the homepage.  Something simple, I thought.

What I am trying to wrap my head around is the connection between the web content that is defined in Craft and the twig files I see in templates.

So in website content when I look at the Homepage, I see text boxes and other content containers that appear to be where an end user could maintain "changeable" stuff.  Going further, I can see in Settings the "Section" for homepage where there is name, handle, template, etc as well as option to "Edit Entry type" where it seems that you don't layout the page as much as define what parts of the page will be editable content.  Is that correct?

So "Define Your Field Layout" is a bit of a misnomer?  You aren't designing the layout as much as defining what content your "layout" will contain?  So that leaves me with:  Where do I actually lay out the page?  Where is stuff positioned "just so"?  I don't see a WYSIWYG tool for that.  So, can I assume that the "Entry Template" listed in the section is the twig for the actual layout of the content?  In this case, there is 'index' as a value there so I should look for an index.twig that will contain the html and css for the page?

I am just trying to piece together the components. The last piece, if my assumptions above are correct, is that the index.twig, when I find it, will have twig markup that points back to the fields in the "layout" I saw in the section definition?

There just seems to be many moving parts and my past experience with CMS's is if you fail to understand how stuff hangs together then you tend to do too much work to make it work, rather than following convention.  As a developer, my first instinct is to write code, which can be a bad approach with a CMS...

Just want to confirm if my understanding of the basic connections is correct..more questions after I start breaking stuff...

Thanks


texts: How can I parse environment variables in a string?

texts: I have a string in my plugin that contains environment variables. How can I parse them the same way Craft does?


texts:
I'm using the Store Hours plugin inside of a Matrix field along with a text input field. The global is called specialHours and the matrix has the same name.
I access the text input like this which works:
{% for block in specialHours.specialHours %}

{{ block.heading }}

{% endfor %}

What I don't understand is how to loop through the store hours days.  This is not working:
{% for day in block.specialHours %}

 {{ day.name }} 	{% if day.isBlank %}
                Closed
            {% else %}
                {{ day.open|time('ga') }} - {{ day.close|time('ga') }}
            {% endif %}

Any ideas?  Thank you!


texts: Make segment in the middle of a route optional

texts:
In the following route configuration i want to make the height segment optional.
So that

/images/400/200/placeholder.png
/images/400/placeholder.png

are both possible with one route.

$event->rules['/images/<width:\d+>/<height:\d+>/<imageName:([-\w.]+)>'] = 'module-name/image';

I tried the answer from this question Is it possible to define optional route segments? but couldnt bring it to work.


texts: Twig filter to convert special characters to URL friendly characters

texts:
I have a text field that will accept some German text in it as a headline of a section. I'm using Craft's |kebab filter to turn that into a lowercase-with-dashes id that my navigation scrolls down to when its corresponding link is clicked.

However, when there's a word like "Über Uns", the umlaut Ü stays in the output like so: "über-uns" and this messes up my javascript so the scrolling doesn't work for that one item. Is there a filter or something to have it be output to "ueber-uns"?


texts: Shipping for other category than what's set as default is not applied to total

texts:
Somehow, shipping rates are not applied to the total when checking out and paying. It does show when selecting the shipping method, but not on the final order review and is not submitted as part of the payment.

The way it's set up is essentially a single shipping method, with geographical rules/zones. There's a "General" category, which is the default, and then an "Accessories" category which applies to smaller items related to that category. In the shipping method's various rules there's a different price set for the two shipping categories, and the non-default "Accessories" category is not being applied.

I'm assuming/hoping it's a user-error on my part, and curious if anyone has run into this, and know of a fix?


texts:
Bit of an unusual one and sure must be missing something but know if we have a defined lightswitch field we want to filter against it can quite easily be done so like this:
{{ craft.products().myField(1) }}

However, if I have several lightswitch fields and a front-end filtering form I don't especially want to explicitly do this against all of them, eg {{ craft.products().myField(1).anotherField(9) }}. Was wondering then if it is possible to build out some kind of dynamic search or filter but unless doing something crazy looks like the Craft search parameter won't filter against lightswitch fields, eg the following won't work:
{{ craft.products().search('myField:1') }}

I think I have found a workaround using the where() parameter but feels a bit … inelegant … as essentially specifying my query now against DB values rather than against Craft elements/properties:
{{ craft.products().where('field_myField=1') }}

Any thoughts on improving? Is there a way to do this in native Craft/twig without having to query against specific database values?
Cheers,
Cole
PS above are examples working with Craft Commerce Products. Not entirely sure if this is an issue limited to products as opposed to - say - entries but as these are both essentially elements had assumed not.


texts: Text cut off after migration in some fields

texts:
I migrated a site from Craft 2 to Craft 3 and on some Redactor fields, half the text is gone. It looks completely random. In some fields, the text is gone. In some the text is about half as long as before and on others the text is fine. How is this possible?

I just noticed that when I copy the old text into the field it is cut off again on save. How is that possible?


texts: Registration Form twig add to an usergroup

texts:
I just started using Craft and I'm a little stuck with a public registration form.
I made a user group and wanted to add these to the saveUser form.

I found  this answer

but don't know where to find this code.

I'm working in a twig file. Do i have to make my own plugin for that? Or do I have to overwrite something?

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="users/saveUser">
    <input type="hidden" name="redirect" value="/">
    <input type="hidden" name="userGroups" = "1">

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

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

Username

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

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

Email

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

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

Password

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

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

    <input type="submit" value="Register">
</form>

I tried adding a userGroups hidden input but that didn't work.


texts: Haven't updated since version 2.6.2949 - are there any potential negative consequences of not updating? If so, what are they? Thanks.


texts: Is it possible to grab related entries that have been attached to a certain field?

texts:
So,

I want to grab all entries that are related to an entry but with the following criteria:

Only from my section ($section)
Only the ones that have been added to a certain field ($fieldId)

I currently have this:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = $section;
$criteria->limit   = null;
$criteria->relatedTo = array(
    'targetElement' => $element,
);
$elements = craft()->elements->findElements($criteria);
return $elements;

But if I add two relationship fields to an entry, this will return ALL the associated entries from either field. I want to limit it to just the entries attached to the one field.

Is this possible? Does the question make sense? :-)


texts: How can I pre-populate my billing/shipping information within Commerce?

texts:
When a user registers on my site, I am asking for their first, last, email and address.

I would like to be able to pass the data I already have along to commerce. So when I get to the /address screen, as much of that form is already pre-populated.

I see this:

{% set modelName = modelName is defined ? modelName : 'address' %}
{% set model = address is defined ? address : null %}

So I (think) the ideal solution is to set the model to the user model. I will never allow guest checkout on this site, yet I want to keep as much flexibility as possible (not delete a bunch of stuff). So I gave this a shot:

{% if currentUser %}
    {% set modelName = modelName is defined ? modelName : 'user' %}
    {% set model = user is defined ? user : null %}
{% else %}
    {% set modelName = modelName is defined ? modelName : 'address' %}
    {% set model = address is defined ? address : null %}
{% endif %}

And I get this error:

Craft\UserModel and its behaviors do not have a method or closure named "businessName".

Which makes perfect sense - that's not in the user model.

I could go into the form filed and just set the values like this:

<input type="text" id="{{ modelName }}-firstName" class="form-control"
                   name="{{ modelName }}[firstName]"
                   value="{{ currentUser.firstName }}">

But is that going to lead to disaster? Thank you for any suggestions!


texts: Only see 3 textarea field on Plugin Setting Page

texts:
I am developing the plugin to send user difference confirmation email which more than 20. I put those fields in templates/settings.html so that the admin could change and update the message content. However, after I put more 3 textareaFields, I only able to see 3 Textarea display on the setting page. The 4th one does not show up. Does anyone know how to solve that issue? Thanks

{{ forms.textareaField({
    label: "Customer Account Creation Confirmation Message"|t,
    instructions: "Customer email message when customer register" |t,
    name: 'custAccountCreation',
    value: settings.custAccountCreation,
    rows:5,
})}}

{{ forms.textareaField({
label: "Customer Account Appointment Confirmation Message"|t,
instructions: "Customer email message when customer appointment confirmed" |t,
name: 'custApptConfirmed',
value: settings.custApptConfirmed,
rows:5,
})}}

{{ forms.textareaField({
label: "Customer Appointment Reminder with Vet Identification"|t,
instructions: "Customer Appointment Reminder with Vet Identification" |t,
name: 'custApptReminder',
value: settings.custApptReminder,
rows:5,
})}}

{{ forms.textareaField({
label: "Customer Appointment Reminder with Vet Identification1"|t,
instructions: "Customer Appointment Reminder with Vet Identification1" |t,
name: 'custApptReminder1',
value: settings.custApptReminder1,
rows:5,
})}}


texts: How do you require specific dimensions when uploading an image?

texts: I think the transform feature is great, although in my case I need to request that certain images be uploaded at specific dimensions to an assets field. (i.e. 500 x 300 pixels). These dimensions will also need to be required on the front-end Guest Entries form. Although I don't see this option in the control panel or in the docs. Is this something that can be done?


texts: EntryModel attributeConfigs method throwing undefined index

texts:
I am attempting to read out the entry field attributes by using the attributeConfigs array of the EntryModel.

When I review the EntryModel object, using id and title as an example. I request the attribute configs like this:

    $entry->attributeConfigs['id'] // Works
    $entry->attributeConfigs['title'] // Undefined index error

All though the index exists in the array

    [_attributeConfigs:Craft\ContentModel:private] => Array
    (
        [id] => Array
            (
                [maxLength] => 11
                [min] => -2147483648
                [max] => 2147483647
                [decimals] => 0
                [type] => number
                [unsigned] =>
                [length] => 10
                [column] => integer
            )

        [title] => Array
            (
                [required] =>
                [maxLength] => 255
                [label] => Title
                [type] => string
            )

Is there any way I can access these configurations?


texts: Populate or change the selection options in one field based on selected option in another field in the CP

texts: I'm looking to change a select fields options with the onChange event from another select fields chosen option. Obviously this can be done with js on the frontend as per this post but has anyone done this for the control panel? I imagine it will need to be done via a fieldType plugin, but wondered if anything already exists for this type of functionality before I attempt to build something.


texts:
I'm trying to send a meta-data image from an entry template to the main layout template.  The image is in a matrix block on the entry.  It comes out correctly when I call it on the entry page, but when I try to pass it to the layout it doesn't see it and reverts to the default image called in the layout.  Any help is appreciated

_Layout template

<meta property="twitter:image:src" content={% if twitterpic is defined %}"{{ twitterpic }}"{%else%}"{{ siteImage.getUrl('twitterPic') }}" {%endif%}/>

_entry template

{#  social image  #}
{% for block in entry.projectImage%}
{% set image for block.projectImage.first() %}
{% set twitterpic =image.getUrl('twitterPic') %}
{% endfor %}


texts: How to get all images from entries including Matrix field

texts:
I have a photo gallery that pulls in all entries and then finds the images within them and then displays them along with links to the entries that used that image.
Except, it's not pulling in the ones that are in a matrix field named extendedContent with a block type of insertedImage and a asset field named image.
A simplified version of the code I'm using is:

{% set content = craft.entries({
    section: 'news,information,events',
    with: ['imageGallery','extendedContent.insertedImage:image']
}) %}

{% paginate craft.assets.relatedTo(content).order('elements.dateCreated desc').kind('image').limit(25) as pageInfo, usedPhotos %}

{# Loop through the array of assets #}
{% for imageGallery in usedPhotos %}
    <img src="{{ imageGallery.url }}">

    {# find all entries related to this asset #}
    {% set entry = craft.entries.relatedTo(imageGallery).order('title') %}
        {% for entry in entry %}
            {{ entry.title }}
        {% endfor %}

{% endfor %}

Added: I'm guessing the issue is that the relationship of the image in the matrix field isn't to the entry but to the block it's in?
Does that mean that it's not possible to do what I want?


texts: Has anyone ever limited access to Craft's back-end via ip address? What paths should I limit if I'm wanting to ensure only certain ip addresses can post updates? Thanks!


texts:
How can I get the number of a current entry in a structure? In other words, I'm getting the total number of entries like so:

{% set count = craft.entries.section('projects').total() %}
<h1>{{ count }}</h1>

But, I'd like to be able to output the number of the current entry in the hierarchy, i.e. something like 1/10. How do I do that?


texts:
I have a bunch of entries in a section called 'artikkel'. The 14 first of these entries are listed out in another section called 'forside'. Now I need to list out the entries that's not already been shown. Printing out the first 14 entries looks like this:

{% for entry in entry.artikkelbolk1.limit(14) %}

{% endfor %}

The rest of the articles that I'm loading in with ajax is like this:

{% for entry in craft.entries.section('artikkel').order('dateCreated desc') %}

{% endfor %}

Of course the last one now prints all the articles that's already been printed before. PS: This is the first time I'm working with Craft.


texts:
How to Use defineAttributes  To Specify NOT NULL and DEFAULT '1' in MySQL Record

I am porting a plugin from another framework and it has the following
MySql tables structure. Is there an easy way to create the same
table structure within craft plugin?

CREATE TABLE IF NOT EXISTS `exp_shortcut_shortcuts` (
`shortcut_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site_id` smallint(3) unsigned NOT NULL default '1',
`entry_id` smallint(3) unsigned NOT NULL default '0',
`field_id` smallint(3) unsigned NOT NULL default '0',
`autogenerated` char(1) NOT NULL default 'y',
`shortcut` varchar(100) NOT NULL default '',
`full_url_model` varchar(255) NOT NULL default '',
`full_url` varchar(255) NOT NULL default '',
`entry_date` int(11) unsigned NOT NULL default '0',
`edit_date` int(11) unsigned NOT NULL default '0',
PRIMARY KEY (`shortcut_id`),
INDEX (`shortcut`)
) ;;

namespace Craft;

class ShortcutRecord extends BaseRecord
{
    public function getTableName()
    {
        return 'shortcut_shortcuts';
    }

    public function primaryKey()
    {
       return 'shortcut_id';
    }

    protected function defineAttributes()
    {
        return array(
            'shortcut_id' => array(AttributeType::Number, 'column' => ColumnType::PK),
            'site_id' => array(AttributeType::Number, 'column' => ColumnType::TinyInt),

I see how to add TinyInt. How do I specify NOT NULL and default '1'?


texts: Is it possible to create event with multiple date/time (out of box)

texts:
I have an event that runs from Monday to Sunday from 9am to 6am but on Thursday the time is from 9m to 8pm.

How can I add repeat dates with diffrent time for Thursday?


texts:
I have a Craft 3 installation and want to add a tab/app to Facebook like domain.com/facebook

Facebook sends a post request to the configured secure tab URL. Now when Craft's CSRF protection is enabled, Craft gives an error. If I disable CSRF protection the tab shows up in Facebook.

I don't want to disable CSRF - what could i do... plugin with a controller to render the template?


texts: Craft 3 Registration Form Success Redirect

texts:
Is it possible to redirect the user to a specific page after they successfully complete the front-end registration form (before activation)? I've tried adding:

<input type="hidden" name="action" value="users/save-user">
<input type="hidden" name="redirect" value="registration-successful">

But it currently just redirects back to the home page. I really need to redirect the user to a page that prompts them to check their email for the activation link. It currently feels a bit broken.

Am I missing something?

Any help much appreciated.


texts: Can the “Commerce Products”-field allow for selection of variants?

texts:
The client wants related products on individual product pages.

Is it possible to have the “Commerce Products”-field allow for selection of variants rather than products as a whole? Or is there another way to achieve this functionality?

If not, I was thinking about letting the client paste the variant ids into a table field or something, then pull the variants onto the product page with ajax. Seems quite hacky though, so any alternatives are most welcome!

Thank you kindly


texts: Can I add another filter option to element index views?

texts:
What I am trying to do is adjust the entry index page to be more specific for our use case, I have already sorted out extra columns but I want to sort or filter by entry type. Of course I can already sort by typeId using modifyEntrySortableAttributes but this is not ideal.

I either want to be able to sort by an entry type's name using modifyEntrySortableAttributes or better still insert another filter button of all the types in-between the status filter and the search bar, see mock-up below.

Any help greatly appreciated!


texts: Why does the UserSessionService create a *state* cookie?

texts:
I'm trying to set a cookie using saveCookie(), and I'm puzzled by the UserSessionService's behaviour.

Instead of creating a plain old cookie, Craft actually creates a so-called state cookie, where the cookie name is prefixed with a hash key and the cookie value is also hashed.

Here's the code I'm running to set the cookie:

craft()->userSession->saveCookie('myAwesomeCookieName', $someAwesomeCookieData, 3600)

...and here's what the cookie looks like:

d9c79699028b2f1b123abbcd3e872e5dmyAwesomeCookieName : aa9de09d72cdbda2caac4551870e073d0f7307b3s

Reading over the source code, docs and other SE's on the subject, it's not apparent to me why Craft creates a state cookie instead of a regular (non-hashed) cookie.

Also, as far as I know, the only built-in method available to templates for retrieving a cookie is craft.request.getCookie – which is actually unable to read state cookies, so it all seems a bit odd.

I've currently implemented template variables for retrieving and reading the state cookie in my template (by wrapping the UserSessionService's getStateCookie and getStateCookieValue methods, respectively) but I'd love to know why the hashing happens in the first place, and if I can prevent it without an additional plugin (I'm aware of the LJ Cookies and the Cookie plugin).


texts: Assign an e-mail template to recurring payment with dynamic amounts

texts:
tl;dr;

How do I tell the webhook callback from Stripe to Charge which template to use for e-mailing the donor when a recurring payment is successfully charged when I don't know what planAmount the user will choose?

I have a form that I predefine some donation amounts as radio inputs defined as Craft fields...

{% set donationAmountOptions = craft.fields.getFieldByHandle('donationAmount').settings.options %}

{% set checkedStandard = (charge is defined and charge.planAmount == amt.value)? 'checked' : '' %}

        <input id="planAmount-{{ amt.value }}" type="radio" value="{{ amt.value }}" name="planAmount" {{ checkedStandard }}>
        ${{ amt.label }}

but then I offer the user an "other amount" number type input where they can define their own donation amount...

   <input id="planAmount-other-amt" type="radio" value="{{ (charge is defined ? charge.donationOtherAmount) }}" name="planAmount" {{ (charge is defined and charge.planAmount == charge.donationOtherAmount)? 'checked' }} required class="float-left small-4">
   Other Amount
   <input id="otherAmtInput" type="number" value="{{ (charge is defined ? charge.donationOtherAmount) }}" placeholder="0.00" name="fields[donationOtherAmount]" class="float-left small-4">

I use jQuery to assign the value to the accompanying radio input because the radio inputs all have to be called planAmount in order for Charge to send the correct amount over to Stripe.

In addition, I give them the ability to decide if that payment will be one-time or recurring on a monthly or yearly basis. Values must be either <empty>, month, or year, in order for Stripe to know what kind of recurring payment to set up.

{% set donationRecurrenceOptions = craft.fields.getFieldByHandle('donationRecurrence').settings.options %}

    Donation Recurrence
    <select name="planInterval" id="donationRecurrence" value="{{ (charge is defined ? charge.planInterval) }}" >
    {% for recurrenceOption in donationRecurrenceOptions %}
        <option value="{{ recurrenceOption.value }}">{{ recurrenceOption.label }}</option>
    {% endfor %}
    </select>
    <input type="hidden" name="planIntervalCount" value="0" id="planIntervalCount">

In case anyone comes across this in a similar situation, you must have this field above called planIntervalCount and it must be set to 1 if there was a recurring interval chosen. I do this through jQuery based on the dropdown choice above.

So far, I have everything working and Stripe will create a new "subscription" (if it doesn't exist) based on the planInterval chosen and the planAmount that the user either chooses from the radio inputs or the amount that the user inputs in the "other amount" field.

However, here comes the caveat: Since the user can choose their own amount instead of the predefined radio inputs, I don't know how to tell Charge or Stripe which e-mail template to use when a recurring payment gets successfully (or unsuccessfully) charged. I thought I could use this setting below:

{% set chargePaymentOptions = {
   'allowDynamic' : true,
   'planCurrency': 'usd',
   'actions': {
       'onSuccess':{
              'email':{ 0: 'donation-successful',
                        1: 'admin-donation-notification' },
              'subscription': 'recurring-donation'
        }
    }
 } %}

But then I realized that this is going to assign everyone to that subscription. How do I tell the webhook callback from Stripe to Charge which template to use for e-mailing the donor when a recurring payment is successfully charged?


texts: This is a specific question about the Dukt videos plugin. I have a site that's all HTTPS and I can't seem to find a way to switch all the embeds to also use HTTPS?  Is there an option anyone else knows of?


texts:
I am trying to install Craft on my server and I've hit a snug which I can't overcome, because I am just not that technically proficient.

I think I've followed all of the instructions on the Craft website to a t, however when I tried to get to the admin panel, I get the following error:

Could not find your craft/ folder. Please ensure that $craftPath is set correctly in /home/toaeroplano/public_html/index.php

I did some Googling on that and I found out that this might be an issue with open_basedir permissions.

So I went to my php.ini file and I saw that this was edited out. Like this:

; open_basedir, if set, limits all file operations to the defined directory
; and below.  This directive makes most sense if used in a per-directory
; or per-virtualhost web server configuration file. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
;open_basedir =

So I changed it to:

open_basedir = ON (and took the ; off)

So now I get a "No input file specified." message.

What can I do? Like I said, this is far from being my area of expertise.

Thank you


texts: Logging out users - logoutPath & logoutUrl

texts:
In the general config settings, one can set a logoutPath, and one can use it using the logoutUrl Global.

However, it says also in the docs: Note that Craft will automatically redirect users to your homepage after going here; there’s no such thing as a “logout page”.

In short; is there any other way to log a user out, besides "triggering" a visit to the predefined logoutPath, which logs users out, but immediately redirects them to the homepage; as it would be more elegant and userfriendly to show some kind of "you've been logged out" message instead first.


texts:
Is is possible to use Craft's URL validation without http:// or https:// in the URL?
Or use some sort of function / filter to conditionally add it to the URL if it is missing?

I'm posting a form using sprout forms. The form contains a field that is set to validate as url.
If you post this field without adding http:// or https:// it doesn't validate.
Is it possible to somehow to set the defaultScheme of an url field to http without changing the core Craft UrlValidator or Yii's CUrlValidator?


texts:
I would like to have some advise on the following:

I'll be running a site with events. These events (channel entries) will take place in a certain city. I don't want to setup every city as a category, but use tags instead. My questions are:

Is it logical to use tags for cities?
Can I list all events based on a city (tag) on my template?

Thanks.


texts: Showing a list of selected/related categories to entry

texts:
I have a suitability category field in my product type that allows the content writer to select which categories this product is associated with.

But my issue is that on the product page I need to show a full list of these 'suitability' categories with a "yes" or "no" next to them indicating which categories are appropriate.

So I am getting the 'suitability' category group:

{% set suitability = craft.categories.group('suitability').all() %}

Then I am simply looping over this list, but I'm unsure how to format my if statement to dictate if this category needs a "yes" or a "no". I know it's probably something to do with the .relatedTo() parameter but I'm not quite sure on the formatting.

{% for category in suitability %}

{{ category.title }}

        {% if product.relatedTo(category) %}Yes{% else %}No{% endif %}

{% endfor %}

Thanks!


texts: Craft v3 gives 500 error on installation... how to get v2 instead

texts:
I installed Craft v3 on a live server running Debian 10, apache, latest PHP, and Mariadb. My structure is /var/www/html, and everything except for the files in "web" are in the www folder (along with the html folder which holds the public files - tested with an index.html), and then all of the files in "web" are in that html folder. My new user owns all of the files and they are set to 744.

I ran the install in terminal (command line) and it checks for the database, user and password and says everything is successful. Then I go to the link specified to complete installation and get a 500 error. I've worked at this over the past 2 days and have never had any problems like this installing any PHP CMS or framework before. Can you tell if I'm missing something key here or direct me to a clearer set of instructions? I've seen the other posts about this issue and the solutions presented haven't worked for me yet.

I'm also wondering if it's possible or worthwhile to go back to a previous version? I want to recommend and use Craft for a commercial project but I need to be sure I can get past the installation first.


texts: spinning wheels on dashboard columns - can't edit site - unknown error

texts:
I'm getting constantly spinning wheels on columns on dashboard and can't edit the site - https://timetoshineleeds.org/ - but live site is fine. Got 'error unknown' message when going into dashboard.
Screenshot attached
Is anyone familiar with this problem?
Thanks
Rob


texts: Bootstrapping Craft for PHPUnit on command line

texts:
I'm trying to run some commands on a Jenkins server to have PHPUnit execute the tests and report the results.

When I do require_once 'craft/app/bootstrap.php'; It is giving an error saying: PHP Notice:  Undefined index: SERVER_NAME in craft/app/bootstrap.php on line 105

I read that you cannot use bootstrap.php in the craft/app folder because you're essentially trying to bootstrap a webapp (and this server isn't a webserver). It was suggested that I use craft/etc/console/yiic.php as my bootstrap file for PHPUnit. However, this is throwing errors about CDbConnection and is unable to connect.

Is there any way to bootstrap Craft from a command line to run PHPUnit? I'm unable to get it working without an apache server.


texts: TemplatesController error related to webfont!

texts:
I'm getting a very strange 404 error on my live site:

  Craft\HttpException: template = fonts/BlissBold-webfont.ttf in  /path/to/mydomain/craft/app/controllers/TemplatesController.php:72

I've searched my complete directory and the only reference to BlissBold-webfont.ttf is in a stylesheet.  How on earth is this affecting the TemplatesController?


texts: Show larger images in control panel entries

texts:
Is there a way to show the images in the control panel entries (both in the detail of the entry and in the overview list using the new customisable columns in 2.5).  The standard preview of the images is so small it hardly is visible to control panel users.

Edit:
On the feedback site this feature request seems to have made it in one way or another to the 2.5 build.  Does anyone know how to use it?

http://feedback.buildwithcraft.com/forums/285221-feature-requests/suggestions/7192735-better-image-preview-and-edit-window-for-asset-fie


texts: Advanced search returning 'Key "1" for array with keys "0" does not exist'

texts:
I have an advanced search that searches real estate properties by the usual criteria: price range, Bedrooms, Bathrooms... In the form, the default is "Any" if they don't care about a particular option.

On the results page, I'm checking for a null value in case an option wasn't selected. Despite this, I'm still getting the message 'Key "1" for array with keys "0" does not exist' if the price option is missing. What is causing this?

My search results page looks like this:

{% set price = craft.request.getParam('p') %}
{% set price = price ? price|split('-') %}

{% set br = craft.request.getParam('br') %}
{% set br = br ? br %}

{% set ba = craft.request.getParam('ba') %}
{% set ba = ba ? ba %}

Search Results

{% set searchResults = craft.entries({
    section: 'properties',
    propertyPrice: price ? ['and', '>= ' ~ price[0],'<= ' ~ price[1]],
    bedrooms: br ? [ 'and', '>= ' ~ br ],
    bathrooms: ba ? [ 'and', '>= ' ~ ba ],
    order: 'score'
}) %}

{% if searchResults|length %}

    {% for entry in searchResults %}

{{ entry.title }}: {{ entry.propertyPrice|currency('USD', true) }}: BR: {{ entry.bedrooms }}, BA: {{ entry.bathrooms }}

    {% endfor %}

{% else %}

No Results Found

{% endif %}


texts: Successful login with 'requireLogin' redirects to 404.shtml

texts:
I have recently migrated an intranet to its production environment, and the requireLogin is misbehaving:

I'd go to intranet.example.com/
Log in with my details
Craft will redirect me to intranet.example.com/404.shtml, showing 'Layout file - This content should not be seen.'

this page doesn't exist, and I can't find any reference to 404.shtml on any page.

If I reload intranet.example.com/, it will show me the homepage, logged in. It works fine after that
I can log out and in again, it will work fine. I need to log out, close the browser and log in again to replicate the error

I have no redirects or have changed anything on the Craft config. Basically is a default 2.5 installation with new templates.

It works fine both locally (MAMP) and on my dev environment, but not on the server I just migrated it to.


texts: Paginate entries when I do not have a criteria model?

texts:
I have to...

merge results from multiple different criteria models
use Supersort to order my entries in the desired sort order
[...]

...and need to paginate them for my index page. As the paginate tag doesn't work with arrays of element models, is there any other solution to get this working?


texts: Odd behaviour when uploading .svg Assets

texts:
Running 2.6.2983 on OS Sierra.

I'm noticing that some of my SVG files when uploading are going from 50kb to 1kb and then appear completely blank when trying to view them. Does anyone have a clue why this would be happening?

Thanks,


texts: Why is Craft loading jQuery via cpresources? And can I stop it?

texts:
I've been doing some performance checks on a website I'm building, and noticed that jQuery 3.5.1 is being loaded via cpresources:

Why is it doing this? And can I stop it? I'm already loading jQuery 3.5.1 in my scripts.js file (combined with some other stuff and minified using gulp & webpack).


texts:
When an order is submitted on the Craft Commerce website I'm currently building, an email is automatically sent to the customer. Inside this email is a link to download an invoice for that specific order.

I had accomplished this by putting the following link into my emails

Download your invoice

It's not ideal as you could actually download any invoice by changing the order.number, but we fixed that by using a url proxy.

But I realised a few minutes ago that this link is not public and requires a login. Which I don't want.
Is there any way to generate a public link for the invoice?


texts:
For a while I've been having difficulty handling large navigation in craft. I built this site a while ago, and if I am honest I would probably change the structure if I was doing it again, but that's for another time.

The nav is stored in a structure and each navigation entry is either linked to an entry or a custom url is entered. There are approximately 300 pages in the entire nav.

Here is the code I use to generate the nav:

{% macro navigation(pages, id='') %}

        {% nav node in pages %}
            {% set url          = node.url|length ? node.url : node.linkedEntry|length ? node.linkedEntry.first().url : node.customUrl %}
            {% set active       = node.slug == craft.request.getSegment(node.level) %}
            {% set class        = node.children|length ? "has-children" %}
            {% set class        = active ? class ~ " active" : url == craft.request.url ? class ~ " active" : class %}
            {% set separator    = node.separator  ? 'separator' %}

                   {{ node.title }}

                {% ifchildren %}

                        {% children %}

               {% endifchildren %}

        {% endnav %}

{% endmacro %}

The problem I have is that this is incredibly slow, in some cases I see load times of over 10s, which is unacceptable! I know that this is caused by the nav and not the rest of the page content.

I use caching to speed rendering up, and this works fine, but that only really masks the problem.

I reckon that the bulk of the time is taken up checking whether it is active, what class it has etc. Is it possible to store it as a blob and run some kind of regex match on it as a whole?

I'd prefer it if the user could change the nav through the CMS, but if I am honest, this is not a necessity. I've even thought about hardcoding it!

Any one have any pointers or experience in the past?


texts:
My login form  is not redirect like I want it to.

<form method="post" accept-charset="UTF-8">
{{ csrfInput() }}
<input type="hidden" name="action" value="users/login">
<input type="hidden" name="redirect" value="profile">

Username or email

<input id="loginName" type="text" name="loginName"
    value="{{ craft.app.user.rememberedUsername }}">

Password

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

    <input type="checkbox" name="rememberMe" value="1">
    Remember me

<input type="submit" value="Login">

Anybody know why?


texts: How can I add attributes to craft field?

texts:
In my template I have this,

{{
    craft.fields
    .getFieldByHandle('ethnicOrigin')
    .getFieldType()
    .getInputHtml( 'fields[ethnicOrigin]', '') | raw
}}

which returns me a <select> html element Is it possible to add specific class to this select and or data- attribute?


texts: Cannot upload assets when Imagick is set as image driver

texts:
EDIT after resolving: offtopic since the issue was that the php extension for ImageMagick was not installed on the server - therefore not Craft-related.

Because .gif's were not being transformed properly (only the first frame) I figured ImageMagick was not doing the image transforms.

Therefore I updated the general config file with the line to set the imageDriver to ImageMagick ('imageDriver' => 'imagick'). However, as from that point whenever I tried to upload an asset in the control panel, the black loading bar appeared, instantly full, and the loading icon in the top right kept spinning. The loading bar did not disappear, nor did the file get uploaded.

As soon as I removed this line from the general config, the uploading worked as normal again.

I have tested my server and ImageMagick is installed (v6.8.3-6). I am running PHP 5.4.

I am not running any plugins. The only other setting I have in the general config file is 'generateTransformsBeforePageLoad' => true

Does anybody know what could cause this issue? I would like to use ImageMagick for all the transfers, but of course especially for the .gif's.


texts: Display Relating Entry based on Page Routing

texts:
I'm trying to create a submission page at the following URL structure

/campaigns/this-is-a-test-creation/submissions

As you can see /campaigns/ is the Channel and the /this-is-a-test-creation/ is the entry slug. I'm trying to currently set up my page using routing and fetch the related entry, but I'm having difficulties.

My route in the CP is set up as follows and works.

/campaigns/{slug}/submissions

My code to fetch the relating entry doesn't

{% set entry = craft.entries.section('campaigns').slug('craft.app.request.getSegment(3)').one() %}
{{ entry.title }}

This returns:

  Impossible to access an attribute ("title") on a null variable.


texts:
I have a channel where I need each entry's URI include the year and then a sequential number, like this:
2018/1/
2018/2/
2018/3/
2019/4/

I have no problem getting the year, but is there a way to get the entry slug to be a sequential number?


texts:
Can someone tell me why I am going crazy and cannot figure this simple relatedTo issue out?

So I have a categories section called Case Studies and several categories within. I am trying to filter the results to show all entries within a specific category.

{% set entries = craft.entries.section('caseStudies').relatedTo('municipal').find() %}

won't show any results but using the ID will.

{% set entries = craft.entries.section('caseStudies').relatedTo(422).find() %}

I've tried all sorts of slugs and nothing is showing. Why can I not figure this out. someone please point out my obvious mistake...

My entry field is called 'caseStudyCategory'


texts:
I use the following code to link to the CP from the front end:

{% if entry.isEditable() %}
  Edit entry
{% endif %}

What do I have to add to link to the correct locale as it always jumps to the global locale instead of the current one?


texts: Can I have a Craft Commerce product with options that change the product’s price?

texts: I have a product with multiple options (e.g. colour, size, material) that all effect the price that the product then sells for. Is it possible for example if someone chooses the material:walnut that it adds $200 to the current price? How can I set this up inside Craft Commerce.


texts: Using a field multiple times in a single template

texts:
we have a problem over and over again and I wonder if we're missing something.
Using bootstrap we have a matrix field, let's call it Grid, that has blocks like "full column" "half column" etc. It's extremely usable across all pages.

Now the issue is we can have only one such matrix per template. And a standard page looks like this:

[some title]
[some grid] <- Grid
[some hero image]
[again some grid] <- Grid
[some other stuff]
[even more grid at the end!] <- Grid

The only solution is to create yet another Grid field that uses the same twig code for rendering only to use it again on the same side.

The solution would be a way to put a field in an entry type but with ability to manually set the handle. So we could put the same field (Grid) and refer to them using topGrid, middleGrid and bottomGrid.

Is there any way to solve this problem?

thanks!
Jan


texts:
Can I change the current locale?

I've set up a standard site, using CRAFT client version (one language). Apparently Craft installs the en_us as the primary language. Content is added (in Dutch) and now some months later the client decides to upgrade to Craft PRO and move to a multilingual site adding an additional locale. As en_us was the primary one nl_nl is added as the next locale.

However all Dutch content was added in the (old) en_us locale. Is there a way to swap this? Change the en_us to nl_nl while keeping the Dutch content in place?


texts:
I've uploaded the files, verified permissions and set up the database. When I run the install, I see the monkey, and I enter in my details. It appears to go well, until a screen showing only: "Oops"
Using Ben Croker's Craft Requirements Checker, I get:

Success
Minimum requirements met. Craft can run on this server!!

The server is running MySQL 5.1.56 with InnoDB, so I believe it's capable of running Craft.
Any advice?


texts: Solspace select options not being stored

texts:
I am populating a select drop down with custom options in the template, but those options are not being displayed in the individual Form submission page.

Example code below:

{% if field.handle == "country" %}

      <select name="{{ field.handle }}" id="form-input-{{ field.handle }}" required>
          <option value="">Country *</option>
          <option value="AF">Afghanistan</option>
          <option value="xx">another country...</option>

{% endif %}

The Country field handle is country

Outputted html is:

        <select name="country" id="form-input-country" required>
            <option value="">Country *</option>
            <option value="AF">Afghanistan</option>
            <option value="xx">Another country...</option>
        </select>

When I view the individual submission in admin I see the below:

But in the submission list page the value does appear:

Thanks


texts: How to create code blocks with syntax highlighting

texts:
I'm deciding on the best way to have code blocks in my content. I'm doing something similar to Craft Docs. Do you have any best practices?

Currently I'm thinking about having a matrix field for the whole entry content - and then just add a Title block, a Rich text block and a Regular text with line breaks for code. I'd then use Prism.js in the frontend to format the code.

I guess I could use another field to identify language for syntax highlighting for each Regular text block. Has anyone seen a special field type dedicated for syntax highlighting? I'd love to have syntax highlighting already in the admin and also a better way to choose language type.

Thanks for any insights!


texts:
Is it possible to query assets by it's filetype?

Example: I have a generic asset field, but I want to get the first asset that's an .mp4 file.


texts:
in the CP settings, timezone is set to UTC +1 Europe/Zurich
when I try this code:

{% set currDay = now|date() %}
    {{ currDay|date('l d F Y') }}

it outputs "Mercredi, 16 janvier 2019", but we're still Tuesday 15th

Craft 3.0.37


texts: Craft CMS 3 create custom field in plugin with two fields returning two values

texts:
I need to get two text fields under the same custom form and have it return two different values to be stored in the database.  Right now with what I have, it's storing the same variable for both, which I get why it's happening, but I can't come up with a viable solution to return two values.

setting the field

{% import "_includes/forms" as forms %}

{{ forms.textField({
    label: 'Value 1',
    instructions: 'test',
    name: name,
    style: 'width: 50%',
    value: value})
}}
{{ forms.textField({
    label: 'Value 2',
    instructions: 'test',
    name: name,
    style: 'width: 50%',
    value: value})
}}

Field function:

public function getInputHtml($value, ElementInterface $element = null): string
{
    return Craft::$app->getView()->renderTemplate('custom-plugin/cloudinary_field',
        [
                'name' => $this->handle,
                'value' => $value,
                'field' => $this,
        ]
    );
}

How can I make these two text fields each return a value to be stored in the database?


texts: How can I get the requested entry from a plugin?

texts: If I’m accessing an entry’s URL (the 4th check in Routing), how can I get the entry that the URL matched from a plugin?


texts:
I want to get the lates postDate of a List and format it for the cache tag

{% set latestSubmission = craft.amForms.submissions(
    { formHandle: 'reservation', order: 'dateCreated desc' }).datum('>= '~now).dateCreated().first()
%}

{{ latestSubmission }}

This Returns:

  Do., 07 Sep. 2017 10:32:05

But I want to pass it into the Cache Tag so I want to format it and write:

{{ latestSubmission | date('c') }}

This returns the error:

  DateTime::__construct(): Failed to parse time string (Do., 07 Sep. 2017 10:32:05) at position 0 (D): The timezone could not be found in the database

Why? Why can’t I reformat it when it is already returning a date?


texts: PHP Fatal error: Allowed memory size of X bytes exhausted

texts:
Getting the following when just querying the database for all records in a section (channel). There are about 75 entries.

I'm getting the PHP Fatal error:

  Allowed memory size of 33554432 bytes exhausted (tried to allocate 32 bytes)

Why would i be running out of 32MB for these pretty simple entries? The channel entry type just has a title, body, image URL, text field, and a field referencing another channel entry type.

I am using the SortByField plugin. Wonder if that's causing any issues. Here's my query:

{% for entry in craft.entries.section('people').find()|sortByField('lastName', 'asc') %}
     // ... outputting names of people, etc.
{% endfor %}


texts: Deleting one or all Assets from a fieldusing a front end form

texts:
Good afternoon All,
Im trying to setup the ability for users to delete 1 or more of their own images from a multi photo asset field and have got stuck.
This is what is have so far,  I assumed adding a blank value would remove the asset in question
{% set images = myAssetQuery.all() %}

{% for image in images %}

    <input type="checkbox" name="fields[businessStandardImages][]" value="" />

{% endfor %}

Any help would be greatfully received


texts: Related Projects (Structure + Channel Matrix)

texts:
I've looked around a good bit to see if I could solve this problem on my own. I've managed to get close I believe, but I think I don't quite understand Craft's relationships.

Basically, I have a related projects section on my site. I'm allowing the user to select the related projects with an Entries tag within my matrix. I would then like to compare their selected Entries with projects already added to a Structure - then output attributes that exist only in the Structure.

This is as far as I've gotten:

My Structure Content

{% for entry in craft.entries.section('homePageBanners').limit(3) %}
    {% for block in entry.banner.limit(3) %}

        {{ block.client }}
        {{ block.bannerImage }}

    {% endfor %}
{% endfor %}

My Matrix Entries Block:

{% for entry in block.projectsEntry %}
    {{ entry.title }}
{% endfor %}

I'm not sure how to compare them & pull content based on what the user selects. I looked into relatedTo(), but didn't have much luck with that.

If that's not clear, I can try to be more specific -- please go easy on me, I'm pretty new to Craft.

EDIT:

Maybe this will help clarify
    {% for entry in block.projectsEntry %}

 {% for project in craft.entries.section('homePageBanners').limit(3) %}
  {% set relatedProjects = craft.entries.section('homePageBanners').relatedTo(project) %}
   {% for project in relatedProjects %}
    {{ project[0].title }}
   {% endfor %}
  {% endfor %}
 {% endfor %}


texts:
I'm trying to filter entries on the front end by a date range but no matter what I do I end up with no results, despite there being results in the, temporarily hard coded, date range I am using.

  {% set page = page ?? 1 %}
  {# set search parameter here #}
  {% set search = q ?? '' %}
  {# stage #}
  {% set stage = stage ?? '' %}
  {# date #}
  {% set start = now|date_modify('-16 week')|atom %}
  {% set end = now|date_modify('-1 week')|atom %}

  {% set entryQuery = craft.entries
    .section('projects')
    .limit(limit)
    .stage(stage)
    .startDate(['and', '>= #{start}', '< #{end}'])
    .search(search) %}

    {% for entry in entries %}
      {% include '_includes/project-listing-card' %}
    {% endfor %}

The code above sets some parameters based on the url and defaults. Without the .startDate line this outputs entries as expected. However once I add in the startDate (a date field) nothing gets output.
How do I output entries that are in the date range?


texts: After updating, getting "Could not resolve the subpath" error

texts:
After updating to 2.6.2973, saving any entry fails, resulting in an Internal Server Error: "Could not resolve the subpath '{slug}'".

I've read the similar errors on here which trace back to Matrix Asset objects and dynamically-named folders, though I'm not using any dynamically-named folders, and I can't tell where it's pulling {slug} from, and/or what's causes the issue. I've gone through and double-checked and resaved both asset directory and field configurations.

The log again points in the direction of the Matrix Asset, and refers to the folder id "1" -- a Local Source which has both the System Path and URL completely hardcoded. The top of the trace looks like so:

#0 /[directory-path]/craft/app/fieldtypes/AssetsFieldType.php(707): Craft\AssetsFieldType->_resolveSourcePathToFolderId('1', '{slug}', true)
#1 /[directory-path]/craft/app/fieldtypes/AssetsFieldType.php(327): Craft\AssetsFieldType->_determineUploadFolderId(Object(Craft\Model))
#2 /[directory-path]/craft/app/services/ElementsService.php(1618): Craft\AssetsFieldType->onAfterElementSave()
#3 /[directory-path]/craft/app/services/MatrixService.php(778): Craft\ElementsService->saveElement(Object(Craft\MatrixBlockModel), false)
#4 /[directory-path]/craft/app/services/MatrixService.php(882): Craft\MatrixService->saveBlock(Object(Craft\MatrixBlockModel), false)
#5 /[directory-path]/craft/app/fieldtypes/MatrixFieldType.php(533): Craft\MatrixService->saveField(Object(Craft\MatrixFieldType))

This error stalls all the client's content entry, so I hoping for any additional insights or tips. Thanks so much.


texts: In my element type index view, why is the first column always empty?

texts: I am creating a simple Element Type to hold form submissions, but I have hit a wall with this one issue I am having. For some reason I cannot get anything to output in the first column of my element type's index view. I have attached a screenshot. It doesn't matter what column comes first it is always blank. If I inspect the contents of the empty cells there is an empty anchor tag that links correctly to the edit/view entry template. I am not sure what I am doing wrong.


texts: Get Entries from Section related to a category

texts:
I'm currently trying to get all entries which belong to a section which is related to that category. e.g.

Category

Brand

Offer

Offer belongs to a brand.

Brand has a category field.

{% set entries = craft.entries.section('offers').relatedTo(category).find() %}

Currently trying the above, but returns nothing.

Thanks

-- EDIT --

The offer entries belong to a brand, a brand section belongs to a category. I'm trying to fetch all offers of all the brands which belong to a category.


texts:
Is it possible to have Craft plugins in subfolders of craft/plugin/ instead of having them right in that folder?

So that I can have a parent directory that is my git repository craft/plugin/mypluginrepo/ containing a README.md and other files and folders besides the actual plugin craft/plugin/mypluginrepo/myplugin/.

I know you can change the plugins path via the PHP Constant:
define('CRAFT_PLUGINS_PATH', '../craft/plugins/subfolder/');

unfortunately this only allows me to set one folder.