texts: Smart Map - pass options into markers individually

texts:
I have successfully got Smart Map up & running and now want to tailor it for my own purposes.

I will have hundreds of markers for businesses, which I am categorising via fields in Craft. What I would love to do is pass custom options to the markers on an individual basis. E.g.:

Marker 1 - Business-type: Retail; Market-sector: Domestic, Educational; Products: Chair, Table, Upholstery.

Marker 2 - Business-type: Manufacturer; Market-sector: Office, Children; Products: Soft seating, Divider panels.

As you see there are 3 keys with multiple values in each.

-

I know I can pass custom options into the map using the API, but can it be done manually in conjunction with the plugin?

It is possible to pass information per-marker for the info Bubble, but I don't see anything in the documentation about custom option data.


texts:
I have a Craft 3 site that's been running on a production server. Recently we switched over to https but this has caused issues in the CP (multiple 'An unknown error occurred' red flags, can't view any of the individual entries or assets, CP utilities like clearing the cache tasks don't run).

Trying to debug it, this seems to largely resolve itself if I set enableCSRF => false in config/general. I can then use the CP to see & edit my entries & assets (although I still get an unknown error flag on the dashboard where the console shows a 400 error get-feed-items for the Craft News widget).

So seems to be related to the enableCSRF config setting. Whenever set it to true I get the error 400 items in the console. I've cleared the browser cache multiple times but that doesn't fix it. I've cleared the Craft cache via the cp (but had to set CSRF to false again otherwise the script doesn't run and gives the 400 error again). Lastly I've manually nuked the cpresources folder in order for it to rebuild.

Web dev isn't my strong point so looking for suggestions so I can try and understand what's going on and what to try next.


texts: Order products by lowest product variant

texts:
Currently using Craft Commerce 2.

I was wondering if it's possible to order products by the lowest priced variant. I have tried something along the lines of this, but it doesn't do anything different with the ordering:

{% set products = craft.products.type('accommodation').all() %}

{% for product in products %}
   {% if product.getVariants()|length %}

        {% set variants = craft.variants ({
            product: product,
            orderBy: 'price asc'
        }) %}

        {% for purchasable in variants %}
            // Products Here
        {% endfor %}

    {% endif %}
{% endfor %}

I have also tried something else along the lines of this:

{% set products = craft.commerce.products({
    relatedTo: 'accommodation',
    order: 'defaultPrice asc',
}) %}


texts:
Need a hand on a conditional to see if my table has any data, and if it does, output the table. The second thing I  need help is the code to output the table. When I look at tutorials, they always seem to output the table as an HTML list. Like:

   {% if block.codePoints | length %}

    {% for row in block.codePoints %}
         {# Assuming 'text' is the column handle of the text field #}

{{ row.text }}

    {% endfor %}

{% endif %}

I can't find an example of:

Thanks.


texts: Is there a way to integrate Craft with Magento?

texts:
Is there a method or for integrating Craft with Magento?

We have a new project coming up and we've done this with EE, but would like to try with Craft.

Ideally it would be a single login, but if we can even just get it so that they share the same header/footer stuff, that would be awesome.  I know you can do this with WordPress too, but again, we'd rather use Craft here. And I know there is Craft Commerce, but it just doesn't have all of the functionality we need, where Magento does.

Has anyone integrated the two and/or have any suggestions?


texts:
We are launching 2 different sites, using the same craft installation on multiple domains.

a.com and b.com

a.com points to the main craft install

b.com should point to a subpage/single in this same craft install.
(So basically could be reached via a.com/subpage

What is the best craft internal way of doing this?

I know there is mod proxy..but we wanna handle it internally. So basically different "start" points for different domains or subdomains.

Thanks in advance.


texts: Programaticaly create entry with simpleMaps field

texts:
In a plugin I am writing, I am importing data from a older system and part of it is latitude and longitude data.  One of the fields in Craft is a simpleMap field where that data will go.

I would like to create a new entry that has a simpleMap field as one of the fields.  The github page doesn't have any documentation on how to do this, it mostly covers how to read data and display it in a template.

I have latitude and longitude data and I would like to add it to the simpleMap field.  This code doesn't work but its what I'm looking for.

$entry->setContent([
    'simplemap_field' => [$lat, $long],
    'some_other_field' => 'some text',
]);

I think I probably have to create a simpleMap object first and pass it to the entry field, something like this:

$smap = New SimpleMap([$lat, $long]);
...
    'simplemap_field' => $smap,
...


texts: Is there an easy way to download the assets directory to a local install?

texts:
I'm trying to speed up the process of synchronizing my production site down to my local install. Currently, it is: Back up database, wipe local database, import database backup. It's not perfect, but it is pretty fast.

But synchronizing the assets down is still a pain. Is there a process or plugin that makes it easy/easier to synchronize assets (uploaded photos, etc.) between installs?


texts:
I am working on a plugin that is requiring several DB tables, some of which are relational pivot tables. This is more of a general how-to, but also best practice question on managing those relationships. I can post code examples if requested, but I'm more curious if A) I'm missing anything withing Craft and/or Yii or B) if there are already ways to do what I'm asking.

As far as I can tell, Yii does have a way to automatically manage related records, in either a HAS_MANY or MANY_MANY relationship. Meaning, you need to manually save them and also manually how they are updated or deleted.

This is a basic example of the HAS_MANY relationship:

Table A (HAS_MANY Table B records)
----------
id (PK)
attributes

Table B
----------
id (PK)
attributes

Table C (pivot)
----------------
id (PK)
aId (FK)
bId (FK)

I have all of the models and records setup (I think) correctly. If I understand Yii correctly, when saving Table A records and relating Table B records via the pivot Table C, this has to be done via separate calls to TableCRecord->save(). This seems fine, but the question is, is there a way or best practice to handle updating and deleting these relations? And, is there a better way design-wise to handle this either with functionality within Craft or Yii?

Any help or advice is greatly appreciated. If you need more info, I will be happy to provide whatever is needed.

Thanks!
Michael


texts:
i am getting an 'Internal Server Error' when I go to my 'domain.com/sitemap.xml' page. The plugin itself loads fine in the backend and I can change all the settings etc.

Any idea why this might be happening?

Malcolm


texts: Preview PDF doesn't work in Safari but works in other browser

texts:
I'm trying to figure out why I am able to preview a PDF in all other browser apart from Safari. The PDF is generated using DOMPDF (printmaker plugin) and output to the browser though PHP using Craft CMS.

An example of the PDF is https://kendal.ac.uk/courses/2018.pdf

Any help with this would be greatly appreciated


texts: I recently converted my old site from Craft2 to Craft3. My body text field is Redactor, but I want to be able to post in markdown. From what I can tell, markdown only works with plain text fields. Is there a way to get markdown working with Redactor? Or is there a field type I can convert those to which will allow inserting images and also markdown?


texts:
Creating a plugin that contains a custom field. I need to have some custom html for the settings of the field. I have the following in my field class:

/**
 * @inheritdoc
 */
public function getSettingsHtml()
{
    return Craft::$app->getView()->renderTemplate("src/templates/settings.html", [
        'field' => $this,
    ]);
}

I have a "settings.html" in "src/templates".

What am I doing wrong?


texts: How would I allow guests to add comments and ratings to existent entries?

texts:
I have a page with a bunch of images that I'd like people to rate and comment on.  The rating would be a select custom field, and the comment would be a simple textarea custom field.

I'd like to allow guests to submit their ratings and comments, but the Guest Entries plugin doesn't seem to handle editing.

Any ideas how to get this to work?


texts:
I made my first Craft site with MAMP locally. I am trying to get my site running on AWS but I'm having a hard time with understanding the process.
Are there any good tutorials or suggestions about how to deploy it?


texts: Is it possible to update a Twig variable based on user interaction without page refresh?

texts:
I'm currently trying to use the excellent "Charge" plugin to set up a simple Stripe checkout form for charity donations. The basic example provided in the docs works nicely.

<form method="post">
  <input type="hidden" name="action" value="charge/charge"/>
  {% set options = {
    planAmount : 99.99,
    description : 'This is an extra description',
   checkout : {
     name: 'Acme Corp',
   }} %}
  {{ craft.charge.setCheckoutOptions(options) }}
</form>

However I'm trying to update the 99.99 to use an amount that can be chosen by the client. My attempt at doing this involved having a separate form with a select box which when updated needs to update the planAmount.

I tried to do this using craft.request.getPost('name') tying up to a jQuery post submit but I'm not sure if I'm even going about this the right way?

Is there any other way to update a variable in Craft/Twig through JS (or other user interaction)?


texts: What is the best way to track, record or view search terms?

texts: Pretty much like the title says - What is the best way to track, record or view search terms when using the built in Search form?


texts: I want to have one template handle all of my error pages (instead of creating 404.html, 500.html, &c.).


texts:
So i have a client that wants fast e commerce store, currently I've narrowed it down to 2 solutions.
Headless Magneto CMS with a Magneto PWS studio as the front-end. Its based on react which should be fast and Magento's search uses elastic search which I've read is faster than MySQL.
The second is a simpler solution, Craft Commerce. Is a flexible and light commerce platform.
However how will a "light" PHP/MySQL platform compare to a react front-end with a "heavy" back-end using elastic search back-end.


texts:
I am trying to show a list of users but only if they have created a post in a certain section... the code I am using isn't working as expected. Perhaps I have the syntax wrong when it comes to the user model

Help would be greatly appreciated.

{% set entries = craft.entries.section('news') %}
{% set authorList = craft.users.relatedTo(entries) %}

{% for author in authorList %}

{{author.fullName}}

{% endfor %}


texts:
Or to say it in a different way, paginate siblings.

I found this question on stack: How do you page through child entries in a structure? which seems to have a working answer. However trying this myself I get no results.

To be clear, I have a two level structure.

Level 1 (parent)
 - Level 2 (child)
 - Level 2 (child)
 - and so on..

How can I paginate the children?

Thank you for any input!


texts: Programatically Adding Fields to a Layout

texts:
I am looking to add a field (or perhaps a group?) to the userlayout via a database migration.  I've looked over the docs, and found Is it possible to add a custom field to User model from a plugin? but that isn't exactly what I want.  I do not wish to delete the layout and then recreate it.  I just want to add a new field to it.

I was hoping to be able to use the getFields() and setFields() methods directly on the FieldLayoutModel but thus far no dice.  Is there a better way to do with, with a service or something?

Right now I am:

Creating a new FieldModel, populating it and saving it.
Finding the fieldLayout I want through craft()->fields->getLayoutByType()
Calling getFields() on it and saving the result to a variable
Popping my saved field onto the end of that array
Calling setFields on the fieldLayout with that new updated array

But it's not functioning.

Thank you for your time!


texts: Redactor won't allow simple styling in heading tags

texts:
On a fairly fresh site (and also on some more built up sites) I noticed that Redactor is preventing you from doing the following:

Create a heading such as an H1 or H2 with two or more words
Select only one of the words in the heading
Attempt to apply styling, such as bold or italic to that word

This should result in some simple markup such as:

My list of words

But it does not apply this styling.

Is this a bug with redactor? Intended behavior? Do you know a clever work around that would utilize Redactor's native buttons?

Edit:

The Clean Up HTML? field is unchecked on this redactor settings type.
This bug seems to be a redactor bug, it exists on http://imperavi.com/redactor/


texts: Do the number of Sites in a Multi-Site have a practical limit?

texts:
My use case is creating microsites for hundreds to thousands of customers, allowing them to edit/create their own site.  Currently it is set up with channels with auto-created entries for users and no permission to create or edit other's (to mimic a single).  Having similar functionality using Multi-Site
seems nicer so I can use actual singles and allow multiple users to that site.  I noticed when creating multiple sites for testing, that they are all listed on the section page to enable/disable leading me to believe that having hundreds/thousands of Sites enabled is a use-case it was not made for.  Are Multi-Sites able to handle thousands of Sites?


texts:
Please excuse this newbie question (newbie to Git that is). I'm trying to set up my CraftCMS environments with Git and wonder about best practices and how others configure your repositories.

In specific, do you have separate Git repos for separate sites, or is it all in one big repo? Do you have separate repos for the outward-facing portion of a single Craft site and its application files or is that all in one repo?

Thank you in advance.


texts:
Been at this a couple of hours and my head is scrambled. Wonder if anyone has already solved it and cares to share? I'm trying to paginate a list of entries grouped by day - showing 3 days worth of entries on each page. This is slightly different (I think) to other threads on SE. Here's where I'm at so far:

{% set allEntries = craft.entries.section('stories').with(['categories']).all() %}
{% set allEntriesByDay = allEntries|group(e => e.postDate|date('long')) %}
{% for day, entriesInDay in allEntriesByDay %}
    <h2>{{ day }}</h2>
    {% for entry in entriesInDay %}
        ...
    {% endfor %}
{% endfor %}
{% include "_includes/pagination" ignore missing %}


texts: Uninstalling a plugin from Craft control panel

texts:
I'm new to Craft CMS and I'm having trouble figuring out how to uninstall a plugin.  Specifically, it's the "Redactor Custom Styles" plugin.
I gather from searching (please correct me if I'm wrong) that I need to first uninstall it from within the Craft control panel, and then use composer to remove it i.e. composer remove vendor/plugin-handle.  I'm stuck on the first part of that.
Within my control panel, I can't seem to find a list of installed plugins anywhere. The only way I can even see that Redactor Custom Styles plugin is installed is by going to the Plugin Store, searching for it again as if I was going to install it, clicking the result, and then I see a checkmark and "Installed".  However, there's no option to uninstall it.
I must be missing something. Can someone point me in the right direction?


texts: How to set hero image for root and children in a structure

texts:
I am puzzling the best way to implement hero images per 'section' of a site.
I can set a global default hero image no problem. But I want to set one header image for the root and children of a particular section.
I can't use url segments as the site is multi-lingual and it will change.

I've tried detecting the root of the current structure to base my template code on.

{% set rootEntry = entry.getAncestors().first() %}

But this returns null - like there is no model returned.

UPDATE:
NO answer yet but a repharasing of the question.
IN order to do this you need to get the top level entry based on where you are in the site structure/tree. This link Building a nav from the top level page of a structure demonstrates great working code.

However the assumption in the above posts and many others is that the structure is built out of the actual entry pages themselves.

I have two structures. Pages and menus. The menu structure has related entry fields that 'point' to the pages.

So in in my scenario the menu structure is built out of related entry fields - not the entry being viewed. Hence, the reasons getAncestors was not working was because it was taking the existing entry a visitor was viewing and looking for a hierarchy structure that was flat.

So the question is now more complex - how do you get the top level tree branch of your structure menu based on the current entry viewed when that current entry is a related entry field in your structure menu? It seems very complicated to achieve. Especially just for flexible headers per sections....

FINAL UPDATE
Thanks Mats - i couldn't have done this without your diligent replies.
Below is my final solution to find out what the top level root is. It is expressed as sub navigation for structure menu but it does two things - build s the sub nav and identifies the root of the tree where you are. NB macro is used for active links.

{# Get the sidebar structure subnavigation #}
{# check for entry so channels do not break #}
{% if entry is defined %}
    {% set navEntry = craft.entries.section('menu').relatedTo({
    targetElement: entry,
    field: 'entryLink'
    }).first() %}

    {# get the root entry of the structure set to null if we are at top #}
    {% set root = navEntry ? craft.entries.ancestorOf(navEntry).level(1).first() : null %}

    {# setup variables in switch for ouput of heading and sub links#}
    {% switch root %}
        {% case null %}
            {% if navEntry.hasDescendants() %}
                {% set heading = navEntry.title %}
                {% set thisSubMenu = craft.entries.descendantOf(navEntry) %}
            {% endif %}
            {% set rootEntry = navEntry %}
        {% case true %}
            {% set heading = root.title %}
            {% set thisSubMenu = craft.entries.descendantOf(root) %}
            {% set rootEntry = root %}
    {% endswitch %}
{% endif %}

{% if heading is defined %}

{{ heading }}

{% endif %}

{# Get entries to build the sub-menu #}
{% if thisSubMenu is defined %}
{% set subMenu = thisSubMenu %}

    {% for entry in subMenu %}

        {% if entry.entryLink.first|length %}

            {% set subNavLink = entry.entryLink.first().uri %}

        {% elseif entry.customMenuUrl|length %}

            {% set subNavLink = entry.customMenuUrl %}

    {% endif %}

        {{ entry.title }}

    {% endfor %}

{% endif %}


texts: Tagging and Associating Photos with Entry Type

texts: We have hundreds of photos on our theater website from past performances. In order to sustainably manage the relationship between cast members and which photos they were in, we wanted to explore setting up some type of tagging system. Would there be a way to associating a person (Entry type) with a photo (Asset Type) at the asset level? That way, we could query the database for any photos a person is in from their bio page and assemble them into a slider.


texts: Why can't I set the 'type' of my Asset source?

texts: When I try to add an asset source under Admin > Settings > Assets, I can't see the type-field on the 'Create a new Asset source'-page. Why not?


texts:
Is it possible to find the seconds left / TTL when retrieving cache (when set to Redis) via plugins? I'm using short-lived cache (~600 seconds) to put users on "cooldown" to limit how often they can create new forum topics, by creating a user-specific cache whenever they create a topic. Then I can check and see if this cache exists when they create a new topic.

When getting the cache like:

$cache = craft()->cache->get( $cacheKey );

If it returns true (exists,) I'd like to be able to tell the user how long they need to wait until they can post again (like Reddit.)

I've tried methods like

$cache->ttl; // doesn't work; not an object
$cache['ttl']; // doesn't work, no 'ttl' key

Maybe I am missing something in the Cache Service Doc? Or is this meta information simply not available?

Any information would be awesome. Cheers!


texts: Craft Commerce: Addresses not showing in profile

texts:
I have recently added the Customer Info field to user profiles for the CP. I noticed however that the recorded addresses for the user are not listed. I checked against the order and there is addresses associated with it. Is there something I need to be doing to enable the address to show?

See screen shot:


texts:
I just built a membership site and created a Member Directory template which includes all users and then a Board Members Directory template which only lists users who have a "Board Member Title" custom user field filled out in their user profile.

I sort the Member Directory page by last name, but my client would like to be able to manually sort the board members on the Board Members Directory page.

In trying to keep things DRY, I like that in order to turn somebody into a board member, as an admin, I simply add content to the Board Member Title field and I'm done.

Originally I was thinking of something like the old Low Reeorder used to be for EE, but haven't come across anything like that for Craft yet.

Hoping there's an elegant solution I'm just not thinking of. Thanks for your help!


texts:
I have a checkbox field which I want the sum of a certain checkbox:

{% set countPremiere = 1 %}
{% set iterationPremiere = 0 %}
{% set premiereTotal = 0 %}

{% for entry in allEntries %} // the normal loop starts

  {% for premiereItem in entry.kompositonsart %} //the checkbox loop starts
    {%- if premiereItem.value == 'ua' -%} // only return checked value with 'ua'
      {{ countPremiere }}
    {% endif %}
  {%- endfor -%}

  {% set premiereTotal = iterationPremiere +  premiereTotal %}

{% endfor %}

{{ premiereTotal }}

That's basically the same as I did here. This doesn't work however. I suspect it is not working because the way checkboxes are looped. Any ideas?


texts:
I have a project that the user choose a tag (tags are already created) and save the information.

I try save a entry which has a tag field, all the stuff saves, but the tags don't.  I try search information about that, but any where have a solution or the solution doesn't work.

I try entry form.


texts:
I created a new Single section and named it "test", added some content and tried to view it on domain.com/test. Unfortunately I get my default server 404 and not the new single section.

I tried to add a new route using "test" => "_layout" but can't see any change.

Do you have any idea why this isn't working?

EDIT:

Here the both screenshots.

http://i.stack.imgur.com/RtgBB.jpg

http://i.stack.imgur.com/JomkJ.jpg

I hope that helps.


texts:
I'm trying to send some assets links through email, but using {{ siteUrl  ~ file.link }} returns an url with double forwards slashes like: http://example.com//public/assets/sdfsdfds.jpeg

I couldn't find a method on the AssetsFileModel that generates a direct link to it. Is there an easy way to do this?

Thanks!


texts:
I have been staring at this SE post on deleting using ajax and it's just not clicking.

For example, I have a plugin with a list of users. Each user has a delete icon next to it.

template

....

....

To get my javascript, I am using the init method in my main plugin class.

MyPlugin.php

if (craft->request->isCpRequeset() && craft()->userSession->isLoggedIn())
{
    craft->template->includeJsResource('path/to/script.js');
}

So far, so good.

script.js

....
$('.delete-user').click(function(event){
    var data = {
        'id': event.currentTarget.dataset.id,
        'csrfToken': // this is where i'm stuck
    };

    $.ajax({
        'type': 'post',
        'contentType': 'application/x-www-form-urlencoded; charset=utf-8',
        'cache': false,
        'url': 'path/to/deleteUser',
        'data': data,
        'dataType': 'json',
         'timeout': 5000
    }).done(function(status){
        console.log(status);
    }).fail(function(error){
        console.log(error);
    })
});
....

UserController.php

....
actionDeleteUser() {
    $this->requireAjaxRequest();
    error_log(__FUNCTION__); // to just test im getting this far.
}

As you can imagine, I'm getting a 400 Bad Request The CSRF token could not be verified.

I can put a hidden text field on my users "home page" using {{getCsrfInput}} and then grab that value no problem.

If I log out my data object, I can see it's got the correct id and csrfToken but I will still get the 400.

I'm not sure how to pass the token along with the data to the controller just yet it seems.

Thank you for your time!

EDIT

Well, I believe I see my error, but I'm confident there is a better way (at least I think there could be)

I wasn't passing the correct name/key.

script.js

var data = {
     'id': event.currentTarget.dataset.id,
     'CRAFT_CSRF_TOKEN': $('[name="CRAFT_CSRF_TOKEN"]).val()
}

I'm getting a 404 back now - great. I can figure that out. What i'm curious about is: Is there a better way?

I've put the {{getCsrfInput}} on my "home" page of my plugin that lists the users. I feel like i've just done a nice hack-job on my plugin.


texts:
I have two plugins that I want to use in a single form.  One is a Guest Entry plugin to save the data submitted in the form, and the other is a Plugin that sends an email notification when the form is submitted.

I want to use both of these in the same form but I'm not sure how.  If I have

<input type="hidden" name="action" value="guestEntries/saveEntry">
<input type="hidden" name="action" value="formNotification/getForm">

It won't work since both have the name "action"
and I can't change the name or the functions never get called.

What can I do to make both of them work?


texts:
Is there a way with SuperSort to sort an array by multiple variables? For example, let's I have the following data and I want to sort by count and then alphabetically:

pineapples (2)
grapefruits (4)
apples (2)
bananas (3)

Ideally, I would want that to be sorted as:

grapefruits (4)
bananas (3)
apples (2)
pineapples (2)


texts: Commerce Stripe Authorize Only - Capture partial amount in Craft admin panel

texts:
It doesn't look possible but can you capture partial amounts using the Craft admin panel?  E.g. Authorize $1000, then capture $700.

Also, when performing Captures in the Stripe panel, these transactions do not show in Craft in the Order Transactions box.  This looks like a bug to me.

Last, if we can't perform partial captures in Craft and need to do it in Stripe, how can we mark Orders as paid?


texts: Send activation email only for users created over the Control Panel

texts:
We have a website that allows users to register themselves with a front-end registration form, and are automatically logged-in once they're done (thanks to autoLoginAfterAccountActivation).

But we also need to create users directly from the Control Panel on a regular basis.
Since autoLogin doesn't work with the "Verify email addresses?" user setting, I'm looking for a way to send the activation email only to the users that we have manually created over the Control Panel, so they're able to set a password.

Is there any way to send the verification email only to users created over the Control Panel?


texts: P&T Contact Form v1 adding code for 'beforeSend'

texts:
Very new to Craft, so can someone please tell me what class/file I'd add the 'The beforeSend event' code, as I'd like to filter out some spam?

The documentation https://docs.craftcms.com/v2/plugins/hooks-and-events.html#hooks says that the new event listener should be added to the plugins 'init' function, but there isn't one.

many thanks


texts: How to exclude multiple email addresses from an order query

texts:
When doing an order query I want to omit results for 2 particular email addresses.

It's easy enough to omit results for one address;

$order = Order::find()
    ->isCompleted(true)
    ->email('not email1@somedomain.com')
    ->all();

But how do I omit more than one email? If I pass an array using ['not', 'email1@somdomain.com', 'email2@otherdomain.com'] then an error is returned stating that email expects a string.
For example, this doesn't work

$order = Order::find()
        ->isCompleted(true)
        ->email(['not', 'email1@somedomain.com', 'email2@otherdomain.com'])
        ->all();

Nor does passing in an array of addresses within the array

$order = Order::find()
        ->isCompleted(true)
        ->email(['not', ['email1@somedomain.com', 'email2@otherdomain.com']])
        ->all();

If I pass in 2 email criteria then only the latter is applied.

There has to be a neat way to do this.


texts: Hook into Entry::EVENT_AFTER_SAVE when user saves it

texts:
I want to send a Mail to an admin, whenever a User of group ‚Cook‘ creates an Entry of Type ‚Recipe‘.
For that I created an Event reacting on Entry::EVENT_AFTER_SAVE :
Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE, static function (ModelEvent $event) {

    /** Entry @entry */
    $entry = $event->sender;

    /** @var User $user */
    $user = Craft::$app->getUser();

    if (!$event->isNew) {
        if ($user->identity->isInGroup('cook') &&
            ElementHelper::isDraftOrRevision($entry) &&
            $entry->getStatus() === Entry::STATUS_DISABLED) {

            $cpUrl = $entry->cpEditUrl;
            $bodyText = "Dear Admin. /n $userName has created $entry.";

        };
    }
});

As your can see - I tried a lot to only react on the first creation of the entry. But all this does not the trick.
Behind the scenes craft created an Entry (and saves it initially) even when the Cook presses the ’New Entry’ Button.
So I don’t know hook in only when the message is first saved directly by the user pressing the ‚Create‘ Button after entering the content.
It would be nice if your could help me with that.
Thanks in advance.
Michael


texts: Custom field type that has multiple fields to extend the default field types

texts:
Ok scenario that I'd like to create.
Create a custom field type lets call it videos. In this field type you would have 5 separate fields title, description, caption, link, thumb. This would make up the field type which could then be selected from the field type when creating a new field in the CP.

The objective is that this grouped field type could then be re-used within separate matrix fields or as a field in it's own right.

I know you can create field types for plugins but is there a way to create the above?


texts:
I edited .htaccess as described here http://buildwithcraft.com/help/remove-index.php and added this 'omitScriptNameInUrls' => true, to craft/config/general.php, but it doesn't work.

Image:

I also have my .htaccess file set up:

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

This file is inside public folder and I also tried putting in in the directory that contains the public folder.

What happens is this: whether 'omitScriptNameInUrls' => true is added or not, the home displays fine without the index.php, but the internal pages require index.php to display.

The only thing that happens when I add 'omitScriptNameInUrls' => true is that the navigation spits out links without the index.php, and so the navigation breaks.

The good people at Craft said that my site (which is a retooling of the Happy Lager demo site) has been changed to a multi-environment config, which is why my config file looks the way it looks. Not sure if there's anything else that needs to me added to a multi-environment config to get the thing to work.

I have not been able to get any more clarification from Craft about this issue yet.


texts: How can I set a BOGOF (Buy One, Get One Free) promotion using Craft Commerce?

texts:
Under Commerce > Promotions there are the two options: Sales & Discounts. Sales is a flat rate with little conditions, so that leaves Discounts.

Discounts have a bit more flexibility, but only seem to have a minimum quantity option. So, if I want to make a buy one get one free deal, I can't limit it to the quantity to a maximum of 2, therefore the discount gets applied to the total amount regardless of how many are added.

Has anyone else had any success setting up a BOGOF deal or anything similar?


texts: I have two sites. Everytime I add global field content (slogan for example) it adds the same to the second site, and vice-versa. Anyone has any idea how to stop that?


texts: Is there a way to manually trigger an asset transform before calling getUrl()?

texts:
I have a site where I serve quite the amount of images which are saved on Google Cloud Storage. I have set generateTransformsBeforePageLoad to true in my general config because I'm caching the output for Fastly (based on Varnish). The downside is that on first request it's awfully slow and at one point even returns a 503 error.

Is there a way that assets can be transformed before getUrl() is being called? Other solutions are more than welcome.


texts:
I'm having a bit of trouble showing a message if there's no entries in my blog. I tried the length filter but my empty message wont show:

{% for entry in craft.entries.section('volunteerPosition').find() %}
  {% if entry.volunteerPosition|length %}

      {{entry.volunteerShortDescription}}

  {% else %}

      Sorry, Nothing to show.

  {% endif %}
{% endfor %}


texts: What is the value of hosting assets on Amazon S3? Best practices question

texts:
Starting a substantial project. There will be 100s of images on the site. Few are part of the general design, but there are slide carousels, photos, etc.

I understand what S3 is, but I'm wondering what the specific value is of using it over local storage. There is plenty of room on the web host's server.

S3 isn't a CDN, right? Or will it replicate files across to other locations?

Should I expect S3 to be faster than local storage? And is my S3 bucket backed up elsewhere, should Amazon's servers crash?

Thanks.


texts:
Is it possible to use the search in the CP to search let's say by id? Or even one of the fields?

Thanks in advance,
Sidney


texts: Output number of children in a structure

texts:
In my template I'm displaying all entries of a structure: ('areas').level(1) using a loop.

I would also like to display the number of children entries in each of the 'areas'.

Like: "Area 1, 4 properties", "Area 2, 7 properties", "Area 3, 5 properties" and so on.

Anyone?


texts: Wrap embeds with HTML in rich text field

texts:
When using rich text fields, is there a way to automatically wrap embedded content (specifically, videos) in some kind of custom HTML?

I'd like to, at the very least, wrap the embed in some element (a
, for instance) with some kind of class or ID, so that it'd be something like
EMBED HERE
.

I've found my way to the Craft docs for rich text fields, and see that I may be able to add this functionality via Redactor, but I'm not sure how to go about doing so.

Any suggestions are appreciated.


texts: Using PayPal Standard with Craft Commerce

texts: Is it possible to use PayPal Standard with Craft Commerce? The docs are saying that Paypal is "fully supported", but I only see PayPal Express and PayPal Pro in gateways dropdown in conrol panel.


texts: Check if entry has a descendant with a certain field enabled

texts:
Whew, complicated thing to described in a short subject line! :)

Okay, so I have a structure like this:

Asia

Peking

weekend ( field howLongWillYouBeGoing == 'shortStay' )
long weekend ( field howLongWillYouBeGoing == 'mediumStay' )
week ( field howLongWillYouBeGoing == 'longStay' )

Europe

Peking

weekend ( field howLongWillYouBeGoing == 'shortStay' )

South America
(no subpages)

I have a navigation bar that just lists the continents and turns them into a link as soon as it has descendants. When it doesn't have descendants, it just shows the continent name as a non-clickable text.

Now this is the thing. I have used the following code, but it doesn't work. It still shows Europe in this example as a link, even though I believe the conditions are not met. I would LOVE love love any input because I've been staring myself blind on this the last few hours :)

{# loop through continents #}
{% for entry in craft.entries.section('destinations').type('continent').find() %}
    {# only show links to continent pages if it has any travelguides #}
    {% if entry.hasDescendants(3) %}

        {% set mediumStay = 0 %}
        {% for subPage in entry.getDescendants(2) %}
            {% if subPage.howLongWillYouBeGoing == 'mediumStay' %}
                {% set mediumStay = 1 %}
            {% endif %}
        {% endfor %}

        {% if mediumStay == 1 %}
            {# if subpage is marked as mediumstay, show a link to it #}

{{ entry.title }}

        {% endif %}
    {% else %}

{{ entry.title }}

    {% endif %}
{% endfor %}


texts: I have a DIV wrapping a Rich Text field.  I would like to add a class name to the DIV only if an image is present in the text field.  Is there a way to check for an image?


texts:
I want to show a list of entries that excludes two or more specifically by id.

This works:

{% for entry in craft.entries.section('boardOfDirectors').id('not 12') %}

This does not:

{% for entry in craft.entries.section('boardOfDirectors').id('not 12,18') %}

Is this possible?
Anyone know the correct syntax?


texts:
I'm looking to purge all the html from a text field, but leave the line breaks in there. I currently have the following code, which makes line breaks happen, but unfortunately, people can add html to the text field and it will render it.

    {{ user.userAbout|raw }}

Is there any way to do this?


texts: Why is Craft extremely slow when using a shared, external database?

texts:
Every now and then I work in developer teams where we all use our local development environment to work on the code, but share the same database on a remote server (like discussed here etc.).

Most of the time this will kill Crafts performance big time on our local machines. Requests take up to 30 seconds in the Control Panel and in the front-end as well.

Does anyone else encounter the same behavior and/or has an idea how to improve that? The logs don’t explain much.

Time:   25.85331s
(index):3505 Memory: 25,723Kb
(index):3506 Total Queries: 287
...

The site on the remote server is snappy like you would expect it.


texts: How can I change status of all the entries in a channel to closed?

texts: I've looked through all the tables, and I can not find a column for status. I'd like to close all entries in channelId X. Is there a way to bulk edit entries via DB?


texts:
I tried to upload an image in the backend, but I always get the error: Upload failed for 'image.jpg'. In the logs is this:

[16-Jul-2015 21:33:48 UTC] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 4966029 bytes) in /var/www/virtual/conwave/html/service/cgk/craft/app/vendor/imagine/imagine/lib/Imagine/Image/Metadata/ExifMetadataReader.php on line 72

Can anybody help me? I have no idea what the problem is.

Thanks!


texts:
I know this is a really suck egg question, but I finding the Craft docs far less straightforward than EE (I'm just switching over), and so I'm struggling with the easy task of displaying an entry's category.
{% for entry in craft.entries.section('blog').limit(1) %}

{{ entry.title }}

   {% if entry.byLine %}

{{ entry.byLine }}

   {% endif %}

Category: { ???? }

   {% endfor %}

Can anyone help?


texts: Freeform Lite update on Craft 2 deleted tables

texts:
I am on Craft 2.6.3015 and have Freeform 1.3.0 installed. I'm trying to update to the latest Freeform Lite 1.8.7 but it consistently fails.

When I try on my local environment I just get the message:

  Craft was unable to install this update :(
  The site has been restored to the state it was in before the attempted update.
  There was a problem updating your database.

But on my remote server it deleted two thirds of the tables in the db.

I actually have 7 similar sites where I have done this same update no problem but this one site fails every time. I'm not sure what the difference could be.

I wonder if I can get my hands on an intermediate version of Freeform to try updating to if that would help?


texts: Can I have non-boolean TargetBlank output using HTMLPurifier and the Redactor plugin?

texts:
I'm using the Redactor plugin throughout a Craft 3 site and I'm also using a custom HTML Purifier config to clean up the HTML (surprise).

{
  "HTML.ForbiddenElements": ["&nbsp;", "br"],
  "AutoFormat.RemoveEmpty.RemoveNbsp": true,
  "AutoFormat.RemoveEmpty": true,
  "AutoFormat.Linkify": true,
  "AutoFormat.RemoveSpansWithoutAttributes": true
}

However it looks like it overrides Redactor's link target blank option and that override is either on (open in new tabs) or off (strip target blank).

Is there any way I can give that choice back to the user? Maybe I can stop Craft using the full url for links other than external links?


texts: How can I stop expired entries appearing as 404

texts:
I'm trying to find the best way to let expired entries display.

My client has jobs that are filled / expire.

A typical job url looks like this:

https://flourish-uk.com/jobs/sous-chef-maidstone-20881

In the section settings I've got:

Entry URL format set to:

jobs/{jobTitle|kebab}-{jobCity|kebab}-{jobId|kebab}

And the entry template set to:

jobs/_entry

Everything works great. When a job expires/entry expires it no longer appears, but of course the google index remains and so I'd like the page to still 'exist' rather than redirect to a 404.

I've done a bit of work with the 404 so that the /jobs/ part is recognised in the URL and I change the content, as well as fetch expired job data, such as the jobTitle and integrate it into the content. The problem is, Google still sees a 404 page, and the content of the page is different which will invariably create some negative page rank issues given the number of expired jobs that are accruing.

So rather than a 404, I'd like the expired:

/jobs/sous-chef-maidstone-20881

Entry to go to the _entry template and show the original unexpired layout (albeit with some tweaks to explain the job has expired).

But despite following the details found here:

Is it possible to view 'Expired' entrys on the front end?

The _entry still redirects to the 404 page when an entry is expired.

Is there any way to stop this so I can perform some .status('expired') voodoo on it?

Many thanks.


texts: I've inherited a Craft 2 site to do maintenance. I don't yet have access to production server. I need to grab the production server DB to run locally on my machine. When I click "Backup Database" from the sites cms back-end, it doesn't appear to download a local .sql file. I assume it's backing up as a file on the actual server. How can I download that backup locally?


texts: How to install cURL on Ubuntu 14.04 to run Craft CMS?

texts:
I'm in the process of installing Craft on my Ubuntu 14.04 server and ran into an issue.

When I run the installer at http://example.com/admin, I get the "Can't run Craft" error message:

Craft requires cURL in order to run

I have these packages installed using sudo apt-get install:

curl
libcurl3
libcurl3-dev
php5-curl

No clue what's going on. Could be a configuration issue? or are my packages not properly installed?

Thanks for the help!


texts: Are there any intentions to release multisite support for Craft?

texts:
We're currently using a single ExpressionEngine install with MultiSite Manager to serve up 11 total sites that share the same database. After investigating Craft, and asking questions via Twitter it appears that multisite may not be supported.

Is there a way to use a single Craft install to serve up completely separate sites, or any knowledge of this being implemented in the future?


texts: Get entries from a specific level (4) of categories, but go back up the levels if there is not enough content

texts:
What would be the best way to achieve this in twig logic?
All entries are related to categories.
These categories could be between 1 -> 4 levels deep.
I would like to start at the deepest level and then work back up...
So if the page is linked to a level 4 category it would show this.
 {% set topic = entry.processAndOperation.level('>= 4') %}
however, if there is no level 4 then it would look up a level to 3, then 2 and then 1 etc.
I want to only look at the deepest level first, so not include levels 1-3 if level 4 is present. Or rather and better still if there are less than 8 entries go up a level (as entries will be randomised).
I could do this I believe;
{% set topic = entry.processAndOperation.level('>= 1') %}
But I think that would include all levels regardless, so this dilutes the relevancy of the related content......
tldr;
How can I get related content from level 4 categories, but go back up a level each time until I have at least 8 related articles to randomise.....
Any thoughts?


texts: Searching for HTML markup in Rich Text fields

texts:
It seems HTML markup (tags, classes, etc) is excluded when searching (at least in the CP/Entries page).

Any way around this?


texts: Apply image transform after image is placed on page

texts:
I have an overview (i.e. list with around 150 items). Each of those items has an appropriate "teaser image". When a user is hovering a list item the appropriate teaser image fades in, on mouse out it fades out again.

As I didn't want to add all images into the page on load I am doing that effect with JS and loading the image url I've attached to each html list item as data-attribute, e.g.

//html
Item Title

// js
link.addEventListener("mouseover", () => {
  image.setAttribute("src", imageUrl)
})

My problem is that I can't apply an image transform now as the image is not "generated" on page load but on hover only. Is there any way of applying an image transform in such a scenario?
(I think I know the answer as the asset is coming from the server via JS and its url and not via rendering on load)

Or would you simply recommend a using a plugin and applying the transform in the CP?


texts: On multisite setup, currentUser not true in LivePreview

texts:
On multisite setup, I have problem to get LivePreview working (Craft 3.3.4). I have one domain live, other not, so it displays Maintenance Page. But I need the editors to edit the entries on that domain and check them in LivePreview.

My templates begin like this:

{% if not currentUser %}
  {% include "_main/maintenance_page" %}
{% else %}
  {% include "_main/general_page" %}
{% endif %}

It should show the page when the user is logged in. But this doesn't work in LivePreview. Maintenance page is displayed in LP, what is not what I need to achieve.

I have also tried

{% if craft.app.request.isLivePreview %}

but it returns FALSE for the inactive domain, when tested on LivePreview. So it is not working neither.

Am I missing something? There is no guide in the Docs, afaik.

Thanks


texts: How do I redirect traffic from a legacy category URL to a new category URL?

texts:
Within Craft, I am renaming the top-level entry URL format for a section from legacy-subdirectory/{slug} to new-subdirectory/{slug}. How do I redirect traffic from the legacy URL to the new format within Craft?

I am aware that I may use the rewrite rule within .htaccess in exchange for a slight performance hit:

    RewriteRule ^legacy-subdirectory/(.*)$ /new-subdirectory/$1 [R=301,NC,L]

I would prefer handling this within Craft. As there is only one slug in which I need the redirect, I would prefer handling this without plug-ins.


texts: How to Update an If Rule Based on Different Parameters Passed to a Macro?

texts:
I have a macro that can take up to six parameters which serve to populate nav links. The parameters are basically grouped into twos, with someone needing to pass in both a link and a title to make a nav link.

Below is my current code, which works as intended, but is not very DRY.

{% macro mobileNav(navLink1, navTitle1, options={}) %}

{% import _self as self %}

  {% set options = {
    navLink2: null,
    navTitle2: null,
    navLink3: null,
    navTitle3: null,
    navClass: '',
    navItemClass: ''

  }| merge(options) %}

      {% if navLink1 | length %}

          {{ navTitle1 }}

      {% endif %}

      {% if options.navLink2 | length %}

          {{ options.navTitle2 }}

      {% endif %}

      {% if options.navLink3 | length %}

          {{ options.navTitle3 }}

      {% endif %}

{% endmacro %}

I would like to DRY it out and have one list element where the number associated with the parameter dynamically increases.

Something like this (with the flexibility to an argument being passed via options as well):

 {% if navLink(a number between 1 & 3 that is passed in) | length %}

          {{ navTitle(a number between 1 & 3 that is passed in) }}

      {% endif %}

I haven't been able to figure out how to make it work though. Any help would be appreciated. Thanks!


texts: Obfuscating email set by global variable

texts:
Is there a way to obfuscate an email address link that's generated by a global variable? I tried using Sprout's Encode Email, but it doesn't seem to work with an email address I've generated by a global variable. Specifically, the global variable doesn't work within an anchor tag. For example, the following doesn't work with Sprout's Encode Email:

{% set email = "{{ emailContact.emailField }}" %}
{{ email | rot13 }}

In the code above, "emailContact" is the global set and "emailField" is the associated handle for the actual email address.

It'd be great to figure this one out, especially because it seems a lot of folks would want to use a global variable for a contact email address. Thanks!


texts: How to use the native datepicker ui in custom fieldTypes?

texts:
I would like to impliment the native craft datepicker ui in my custom fieldType. From looking at the native date template (craft/app/templates/_includes/form/date.html) I can see that it inserts javascript using includeJs, which I have followed exactly. Here is my template code:

        <input type="text" autocomplete="off" value="" size="10" id="trial_end" data-stripe="trial_end" class="text hasDatepicker">

{%- set js %}
    var $datePicker = $('#{{ 'trial_end'|namespaceInputId|e('js') }}');
    $datePicker.datepicker({
        constrainInput: false,
        dateFormat: '{{ craft.i18n.datepickerJsFormat }}',
        defaultDate: new Date(),
        prevText:   '{{ "Prev"|t|e('js') }}',
        nextText:   '{{ "Next"|t|e('js') }}',
    });
{%- endset %}
{%- includeJs js %}

I have confirmed that the js output is identical to the other native date fields, and that the namespaced id matches between the js selector and the html input field id. But no datepicker. Is there a piece missing?

Update: Perhaps my question needs some clarification. My field type includes additional 'dummy' fields that will never get stored in the database, but rather are only used to collect information from the user that will be sent via ajax to a 3rd party service, with the result customerId being stored in the database. One of those dummy fields is a date field that I would like to use the native datepicker for. Here is an image:

Yes. That is all one field! that only stores a customerid from a third party service (Stripe), and loads all of the customer account info via ajax. The actual field 'customerID' is never exposed to the client, as it generated automatically.


texts: Does the default local content show when you toggle another locale/s off?

texts: With multiple locales setup when you toggle a specific locale off in the control panel for that entry, does the entry not show or will the output show the default locale content?


texts:
Has anyone used a pagination token when paginating Feedme? I currently use Firestore and they don't use a full pagination URL but a token you append onto your next URL.
Initial URL
https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA
Pagination URL
https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA?pageToken=Ab7e2991jej91od727
In the Response
"nextPageToken": "AFTOeJwxKBJYSXXPpKyhOmB4_-SifKCDzUH0mhJchn1u5hknl3iutUKaPez8OVyR99PZM2014ZU1EpZt4GnUHwHBnwM0P1B9Z-yDhTyqTrmsVt4SIffOXCyxq1Yl7iZQJ0c1ltGHpuV9KWgUH6mvl6rHdCA"


texts:
I just accidentally dragged a root category onto another. Now, all of the entries that were assigned to that category are assigned to the one I accidentally dragged it onto.

Luckily, I have like 7 entries but if this happened with a lot of them I'd be pretty screwed. It seems like a disaster waiting to happen.

Is there an easy way to "bulk assign" categories? If that's not possible is there anyway to add a "Save" button to the category manager so I'd have to click save before the database actually updates? Am I overlooking something really, really obvious here? Definitely wouldn't be the first time.


texts:
Not sure if this is related to Craft 3.1.x, but since I ran that update this afternoon, I can't update details of my Site anymore. If I go to Settings > Sites and try to update anything in there (like changing @siteUrl to @web), I get this error:

Getting unknown property: craft\records\SiteGroup::craft\errors\SiteNotFoundException


texts:
I'm using the saveRelations method in the RelationsService to save entry relationships in a plugin I'm working on. Everything is working as expected, however, saveRelations is returning null on success, which seems odd.

Here is a portion of the code I'm working with:

public function addCategoryRelation(CategoryModel $category, EntryModel $entry)
{
    $field        = $craft()->fields->getFieldByHandle('handle');
    $handle       = $field->handle;
    $relations    = $category->$handle;
    $relationsIds = [];

    /**
     * Get the ids for the relations.
     */
    foreach ($relations as $entry) {
        $relationsIds[] = $entry->id;
    }

    if (!in_array($entry->id, array_values($relationsIds))) {
        $relationsIds[] = $entry->id;
        return craft()->relations->saveRelations($field, $category, $relationsIds);
    } else {
        return [
            'error' => 'Entry already saved.',
        ];
    }
}


texts:
I already had this question posted but I didn't include enough relevant information so I deleted it and here I go again...

I have a weird issue currently on my Craft setup. I have removed index.php from my URLs, so all my single-page links are loading via www.siteurl.com/about-us etc...

The issue I'm having now is that when I created a new single page section, index.php isn't being removed from the URL. It's the only section doing this on the entire site, and everything is perfectly the same as the other sections.

I'm going to run through my setup in case anyone can spot what the issue is.

I currently have a .htaccess file within my project foot folder. The contents of that are here:

RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ /public/$1 [L]

Then inside my public folder, (which is the same level as the Craft folder) I have another .htaccess, with the contents from https://craftcms.com/support/remove-index.php.

<IfModule mod_rewrite.c>
RewriteEngine On

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

This setup works perfectly for the entire site, except the new section I created. Does anyone know what the issue could or might be?

I've went into my Apache http.conf file and made sure the

 LoadModule rewrite_module modules/mod_rewrite.so

is enabled.

and

AllowOverride All

is set.

Also inside my general.php file I have added,

'omitScriptNameInUrls' => true,

But when I push this up to my staging server, the same issue is there. So I assume the default Apache configuration is correct.

The really weird issue is why it works across the entire site except the one new section.


texts: How can I delete entries from an entries field from a front-end from?

texts:
I have an entries field that lives on a user's profile. I am using ajax to add entries to this field.

Example: "Click to add to favorites". Everything works great.

Now I am trying to delete an entry from the entires field, and I'm not quite sure how to pass the right data back to my controller.

Here is what my js looks like:

var data = [];
$('.remove').click(function (event) {
    var clicked = $(this).data('id');

    $('input[name="fields[myEntriesField][]"]').each(function (key, val) {
        var value = $(val).val();

    if (clicked != value) {
        data.push(value);
    }});
});

    ...

onRemove(data, function (response) {
    // response
});

function onRemove(data, callback) {
    data[window.csrfTokenName] = window.csrfTokenValue;
    ...
    // ajax
}

What I am doing here is adding all of the entry id's to my data array EXCEPT the one that I clicked on. I was going to pass that array to my controller.

Let's say I have 3 entries in my entries field. This is what is returned:

["1131", "1363"]

It's every entry except the one I clicked on.

In my controller I was going to loop through the array (of entry ID's) and re-populate the entries field - save the user.

I'm getting stuck trying to add the CSRF token - since I am passing in an array I guess I can't seem to append the CSRF token.

The above is currently getting me this far:

  The CSRF token could not be verified

If I log out all of the data just after I append the CSRF token, I get this:

["1131", "1363", _token: "TOKEN_NAME|TOKEN_VALUE"]

I've read through this SO thread. Which works - but I don't want to actually delete the entry - in essence I just need to re-populate the field.

Thank you for any suggestions!

EDIT

I've ben able to pass the value(s) to my controller, but now just struggling how to actually re-populate the entries field.

This is what I'm passing into my controller:

data: Array(2)
    0:"1131"
    1:"1363"
_token:"TOKEN_NAME|TOKEN_VALUE"

In my controller, I can access the values like this:

error_log(print_r(craft()->request->getPost('myField'), true));

Array(
    [0] => 1131
    [1] => 1363
)

Now just to repopulate the entries field?

// fields[myEntriesField] is an entries field type.
$userModel->getContent()->setAttributes(array(
    'fields[myEntriesField]' => , ???
));


texts: Sprout Forms - Possible to reduce available field types in form builder

texts:
Is it possible to reduce the available field types that can be used in the Sprout form plugin form builder section.

It would be useful to not let my clients be able to select the Matrix or Tags fields amongst others.


texts: Enable the user to upload multiple background Images that come from a matirx loop

texts:
I am trying to enable the user to have mutliple full width css background images, my loop works going through the matrix and grabbing the images but the trouble is they all have the same css class mid-banner and one overrides the other so they all end up being the same image, how can I make it so that each one has a different class as it loops through, or each have an individual id would probably make more sense.

Thanks in advance for any help

{% for block in entry.homeMatrix %}
    {% if block.type == "homeMatrix" %}
    {% set oddOrEven = cycle(['even', 'odd'], loop.index0) %}

{{ block.txtTitle }}

                {{ block.txt }}

        {% for image in block.image %}

        {% endfor %}

{{ block.imageTitle }}

    {% endif %}
{% endfor %}


texts: Having problems with dynamic Asset folders and {owner.slug}

texts:
I have a Matrix field with four blocks currently, a header (text), explanation (rich text), slideshow (assets), and single image (assets). Both the slideshow and single image blocks have two fields, image and caption.

The image field is the same in both with the exception of the slideshow assets field allows multiple images to be uploaded while the single is obviously limited to one. Both have "Restrict uploads to a single folder?" and "Restrict allowed file types?" checked and the latter only allows images. Both also have the same Asset Location selected and {owner.slug} as the path. Recently I discovered that I can no longer upload images to {owner.slug}, instead Craft is trying to upload images to /craft/storage/runtime/assets/tempuploads/field_##.

I've checked file permissions for my assets directory and there shouldn't be a problem writing to it. I used to be able to create subfolders based on the entry slug and what's even more bizarre is that I can edit an existing single image or slideshow block image field and it will use/upload to the proper directory.

Any ideas why it would stop doing this?


texts:
What is the preferred image handling method when using the WYSIWYG editor? Are inline transforms the only way to prevent large images, or are there any other solutions?

Although I am aware of offering more control by "bodybuilding" the front end, this question is specifically related to the WYSIWYG editor.


texts: Looking for an advanced form plugin for Craft CMS

texts:
I'm currently using amforms from a&m impact on a couple of sites. However, it looks like this plugin won't get a craftcms version 3 update. In addition, my requirements for a form plugin have expanded considerably since my clients want more advanced functionality. Therefore, I am now searching for a good alternative.

My requirements are as follows:

It should be possible to prepopulate fields with existing data
Duplicating forms should be possible
Templating completely customizable
Ability to dynamically add more rows of fields (like in a reservation for a hotel where you can add more rooms or persons)
Validation for at least the basic field types
File uploads should be possible
Custom conditions for custom fields (like a checkbox only checkable after checking another one before)
Custom email template
Translatable
Good documentation
Active development

Right now Solspace's Freeform looks most promising and I already know their calendar plugin. However, Sprout Forms also looks quite capable.

Does anyone of you has experience with one of these plugins or can recommend another plugin that meets all or most of the criteria?

Thank you so much for your help!


texts:
I would like to add tabs in setting page in my plugin. I have the following code in /[myplugin]/templates/_setting.html. However, the tabs do not show up, does anyone have any sample code to set up the tabs? Thanks

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

{% set tabs = {
customer: { label: "Customer"|t, url: url('emailUser/_settings') },
veterinarian:    { label: "Veterinarian"|t, url: url('emailUser/_vetSettings') }
} %}

{{ forms.textField({
label: "Customer Account Creation Confirmation Subject"|t,
instructions: "Customer Account Creation Confirmation Subject" |t,
name: 'custAccountCreationSubject',
value: settings.custAccountCreationSubject,
})}}

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

In myplugin.php

public function getSettingsHtml()
{
    return craft()->templates->render('emailuser/_settings',array(
                'settings'=>$this->getSettings()
    ));
}


texts:
I'm looking for a plugin like ContactForm from P&T but with more options like validation for custom fields or the possibility to build a own mail template for the mail at his self.

I want to handle all with the same plugin if this is possible.


texts: Asset dynamic subfolder paths referencing entry section not available until saved

texts:
I have an asset field within a matrix block, for which uploads are restricted to a single folder. The upload location path is set to {owner.section.handle}/{owner.slug}. Using this pattern the asset is uploaded to the correct folder on save, however it's not possible (even after the entry has been saved previously) to view and pick existing assets from this folder - it always appears empty in the asset picker.

It seems like it's related to this question: Assets Content/Fields not available until entry is saved? but specifically to do with accessing the {owner.section.handle} of the field.

The use-case for this is that it allows a single matrix field (with asset pickers) to be shared between sections but still have the assets saved to a section-specific subfolder.

I assume this is a bug? If so, is there any other way to achieve this behaviour to prevent me having to duplicate the matrix field and hard-code the section in the path for each section?


texts: Outputting Matrix blocks with grouped values based on Entries field id

texts:
This is the setup:

I have a Matrix field called Breads. There is 1 block called Bread.

Within, I have two fields:

An Entries field called Selected bread (limited to 1 entry)
A Number field called Quantity.

Lets say I have 3 rows. Row 1 and 3 have the same entry selected, but different quantities. Is there a way to group by the Bread entry id, but get the different quantities?

The goal is to consider all entries with same id as "one", and to make it easy to sum them together.


texts: Internal Server Error while migrating to new server

texts:
I'm trying to migrate to a server from my local environment. I keep getting Internal Server Error. I have the latest version of 3+ of CraftCMS. Everything works fine locally but on the server not so much. Here is what I'm seeing in my Craft log file.

    2019-02-08 05:02:35 [-][-][-][error][yii\base\ErrorException:8] yii\base\ErrorException: unserialize(): Error at offset 352 of 93525 bytes in /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php:997
Stack trace:
#0 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/web/ErrorHandler.php(76): yii\base\ErrorHandler->handleError(8, 'unserialize(): ...', '/home/kinolicli...', 997)
#1 [internal function]: craft\web\ErrorHandler->handleError(8, 'unserialize(): ...', '/home/kinolicli...', 997, Array)
#2 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php(997): unserialize('a:17:{s:12:"dat...', Array)
#3 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php(982): craft\services\ProjectConfig->_getStoredConfig()
#4 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php(912): craft\services\ProjectConfig->_getLoadedConfig()
#5 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php(227): craft\services\ProjectConfig->_getConfigurationFromYaml()
#6 /home/kinoliclients/public_html/jbbls/cms/vendor/yiisoft/yii2/base/BaseObject.php(109): craft\services\ProjectConfig->init()
#7 [internal function]: yii\base\BaseObject->__construct(Array)

The PHP log file gives a bit more information.

[08-Feb-2019 13:36:48 UTC] PHP Notice:  unserialize(): Error at offset 352 of 93525 bytes in /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php on line 997
[08-Feb-2019 13:36:48 UTC] An Error occurred while handling another error:
TypeError: Return value of craft\services\ProjectConfig::_getStoredConfig() must be of the type array, boolean returned in /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php:997
Stack trace:
#0 /home/kinoliclients/public_html/jbbls/cms/vendor/craftcms/cms/src/services/ProjectConfig.php(982): craft\services\ProjectConfig->_getStoredConfig()

Also, just for context. I had the site running on the remote server but then did an update (the one that said, this is a difficult update). The update put it in a vegetative state (internal server error). The same update worked locally, so I then copied the files and database to the remote server hoping that would fix the issue remotely. However, it didn't. Was their a new PHP extension requirement or something, that might have done this?


texts: Including and reusing common code per matrix block

texts:
In each matrix block, I'm allowing users to set a background image, background color etc with a settings field.

In each matrix block template, I have:

{% block content %}

  {% set backgroundColor = '' %}
  {% set backgroundImage = '' %}

  {% for row in block.settings %}
    {% set backgroundColor %}background-color: {{ row.backgroundColor }};{% endset %}
    {% set backgroundImage %}background-image: url({{ row.backgroundImage.first().url }});{% endset %}
    ... more fields go here...
  {% endfor %}

  <div style="{{ backgroundColor }} {{ backgroundImage }}">
    ... content here ...
  </div>

{% block content %}

Rather than repeating {% for row in block.settings %} in each template, is there a way that I could write it once and reuse it using a single include call?

I could use

{% include "_widgets/_settings" with {
  backgroundColor: backgroundColor,
  backgroundImage: backgroundImage
} %}

But that doesn't really reduce the amount of code duplication. Ideally I like to use a single of code to make these variables available.


texts: craft-imageoptimize plugin cropping position

texts:
I am using imageoptimize plugin to crop images, but I am unable to find cropping position setup in a template.

{% set optimzedImages = craft.imageOptimize.createOptimizedImages(
       entry.backgroundImage.one(),
          [
                    {
                        'width': 1440,
                        'useAspectRatio': true,
                        'aspectRatioX': 1.0,
                        'aspectRatioY': 0.35,
                        'retinaSizes': ['1'],
                        'quality': 82,
                        'format': entry.backgroundImage.one().extension,
                        'position' : 'top-center'
                    }
                ]
            ) %}

The above code is cropping image in center-center and I want to crop an image from top to aspect ratio height.


texts: How to query an entry by a custom field in Craft 3

texts:
How do you query an Element by a custom field in Craft 3?
My first try, according to craftcms/docs was:

$country = Entry::find()
                ->section('countries')
                ->where(['LIKE', 'code', 'CA'])->one()

But this throws an exception. Here code is a custom text field. I've also tried some answers on stack exchange and many other combinations but they're for Craft 2 and neither they work.


texts: Use value of a dropdown field for an `include`

texts:
I'm trying to have this include be updated by the option I choose in my dropdown.

{% include 'subnav_programs.html' %}

My dropdown is called entry.dropSubsection

I put {% include '{{ entry.dropSubsection }}' %} in my html file but it keeps giving me errors.

I get this error:

  Unable to find the template “{{ entry.dropSubsection }}”.


texts: How can I access the raw profile photo for any given user?

texts:
I am using the profile photo on users' posts (author image) and I would like to provide a link to download a larger image. I am currently able to get the "full" size of the cropped image like this:

<img src="{{ entry.author.getPhotoUrl('original') }}" alt="{{ entry.title }}">

Is there a way to get to the image that looks like is stored here:

/craft/storage/userphotos/*


texts: How to create a basic plugin front-end controller?

texts:
I'm trying to create a very simple controller from a "foo plugin", but it seems there is something i did not understand because i can't make it work. (404 error)
I looked at contactForm plugin as an example; except i'm trying to respond to a "GET" http request.

My plugin is enable and OK.
My plugin is "foo". Here is my controller, in plugins/foo/controllers :

<?php
namespace Craft;

/**
 * Contact Form controller
 */
class fooController extends BaseController {

  function actionHello() {
     $this->renderTemplate('foo/test');
  }

}
?>

This is not supposed to be called with this uri ?

http://craft.local/index.php?p=actions/foo/Hello

Must i register a route to make this work ?

Also tried renaming my controller and class to "foo_testController", and then calling :

http://craft.local/index.php?p=actions/foo/test/Hello

without success.

What am i missing ?


texts:
after searching around for awhile I still cannot find a clear answer to templating Supertables within a matrix field.

I have a field called 'about' which is the matrix field, within that there is a block called 'biography' which holds both a Rich Text Field called 'copy', and a SuperTable field called hgroup, within hgroup there is a plain text field called heading. How do I go about outputting these within the template.

There are other blocks, similar to 'biography', but I'm encountering the same issue with them.

I'm still very new to CraftCMS so some of this has me puzzled.

{% block content %}
  {% for block in entry.about %}
    {% switch entry.about %}
        {% case 'biography' %}

                {% for row in entry.hgroup %}

{{ entry.heading }}

                {% endfor %}
                  {{ entry.copy }}

    {% endswitch %}
  {% endfor %}
{% endblock %}

Thanks.


texts: Craft 3: how to call methods in another plugin's service?

texts:
In Craft 2, we used to be able to do so by doing:

craft()->plugin1->myMethod();

from Plugin 2's service for example.

Now in Craft 3, I couldn't figure out a way to do it.

Plugin1::$plugin->myService->myMethod();

seems to only work within the Plugin 1's code base.


texts:
When {% cache %} in conjunction with {% include ... %} is it better to wrap the Cache outside of the include or put inside of the included file?

{% cache %}
    {% include %}
{% endcache %}

or

{% include "..." %}

with the cache directives inside the include file?

Assume for this question that the entire contents of the include file will be cached (complex nav).


texts:
I created a form on the frontend that allows users to upload their profile photos:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="redirect" value="users/{{ currentUser.username }}">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    <input type="file" name="photo">
    <input type="submit" value="upload">
</form>

But I get the following error:

  Serialization of 'Closure' is not allowed from /Users/rain/dev/valet/tr3ndsideas/vendor/yiisoft/yii2-queue/src/serializers/PhpSerializer.php

Any ideas on how to fix this problem?


texts:
I'm very new to craft and I'm having trouble finding an answer to my question (I've scoured the questions on here - but the only answers appear to be for plugins).

Basically, I want to submit a form to an action in a controller - which will be inside a Module.

I have this form in a template:

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="site/say">
    <input class="btn submit" type="submit" value="submit me">
</form>

I'm trying to get it to go to this controller (which is in modules/controllers/SiteController):

<?php

namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
    // ...existing code...

    public function actionSay($message = 'Hello')
    {
        die('in say action');
    }
}

I'm constantly getting a 404 - I've tried different variations for the value of action, e.g. actions/site/say.
Do I need to add a route somewhere like in Laravel?
Really, really stuck on this, any help would be appreciated.


texts: Custom Shipping Method Availability in Commerce - User Messages

texts:
I have multiple custom shipping methods, each with rules which determine whether or not they will be available to the user. Basic things like minimum order cost and their address which would determine if a certain shipping method is available.

There are some scenarios where a shipping method wont be available and the reason could depend. I need to be able to tell the user what exactly caused it to be unavailable.

So for example:

public function matchOrder(\Craft\Commerce_OrderModel $order){

    // If this is true, do not enable shipping method.
    if($scenario_1) { return false; }

    // If this is true, do not enable shipping method.
    if($scenario_2) { return false; }

    return true;

}

In the event that one of those is true, the shipping method is not available to the user. On the shipping page, I can check if it is enabled or not like this:

{% if 'myShippingMethod' not in craft.commerce.availableShippingMethods|keys %}{% endif %}

But that only does me good in simply whether or not it's available - not for knowing why it isn't available. Is there a way I could somehow 'pass' information to the templates for the shipping methods that didn't return true? That way I could tell user "This shipping method isn't available because of $scenario_1" or "This shipping method isn't available due to $scenario_2."

Does this make sense? Trying to think of a good way to go about this. Any thoughts about how I should go about this would be super appreciated.


texts:
I'm using Solspace Calendar for Craft and I'm currently trying to implement the edit event form. Once a user selects an event on the calendar they are taken to the event page. On this page I have the edit event form.

The fields in this form will be added to the event entry once submitted. The issue I'm having is getting the form to submit.

<form method="post">
                    {{ csrfInput() }}
                    <input type="hidden" name="action" value="calendar/events/save-event" />
                    <input type="hidden" name="redirect" value="{{ (siteUrl~"availability/event/{id}")|hash }}" />
                    <input type="hidden" name="eventId" value="{{ event.id }}" />
                    <input type="hidden" name="slug" value="{{ event.slug }}" />

Looking at the demo documentation, the two fields I'm not too sure about is the 'action' and 'redirect' fields. I have changed the redirect field to match the current event page. But I don't know what needs to go into the 'action' field.

Currently as you can see, it's 'calendar/events/save-event'. Is this a demo template I have missed. Does this need to be changed to something more specific. Any help much appreciated.


texts: How to search for a specific field using getCriteria()?

texts:
I'm looking at making a plugin and need to search news entries.
I can use:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'news';
$find = $criteria->find();

However, I want to add a criteria where I search a specific field, for example: fieldabc = 'zyx'

What is the correct syntax for this?

Thanks!


texts: some assets have volumeId set to NULL in database

texts:
I noticed that some of my assets have volemeId column set to NULL in the database table assets.

Is it normal? Should I attach them manually to some volume?


texts: Loop through fields in field layout when `entry` is not set

texts: Is there a way in a template to loop through the fields in a field layout without having to tie them to an entry? I'm currently grabbing that list with entry.getFieldLayout(3).getFields(), but that only works when entry is set.


texts: How to eager load user Images (photoUrl)?

texts:
I've been trying to eager load user Photos, but it does not seem to work.

Here's my stripped down code:

{% set entries = craft.users({
    group: 'coWorkers',
    orderBy: 'lastName',
    with: [
        'getPhoto',
    ],

}) %}

{% for entry in entries %}
    {% set userImage = entry.getPhoto[0] ?? null %}
    {% if userImage|length %}

    {% endif %}
{% endfor %}

No photos are displayed.

Preferrably I would eager load with the transform as well:

{% set entries = craft.users({
    group: 'mitarbeiter',
    orderBy: 'lastName',
    with: [
        ['getPhoto', { withTransforms: ['user'] }],
    ],

}) %}

In Craft 2 I could eager load the following way:

{% set entries = craft.users({
    group: 'mitarbeiter',
    orderBy: 'lastName',
    with: [
        'getPhotoUrl(320)',
    ],

}) %}

Anyone has done this before?

Cheers
Stefan


texts:
I'll start off by saying my plugin is working perfectly locally. The problem is when I upload to my server. My plugin is for a contact form. It handles the submission, and logs the entry in the db.
I have a page in the CP for it as well - this is the page that is giving me the white screen.
With devMode I am seeing this in the logs:
[error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /path-to-my-site/craft/app/controllers/TemplatesController.php:59

So I looked up that file, and to me it seems that the system can't find a template?
I don't get any errors - although when I try to submit my form, I do get a 500 error. Could it be a permissions problem?
EDIT
Everything else in the entire site/app is working perfectly, so I know it's something with the plugin page.
My plugin "settings" page renders/works fine. It's when I click on the top "tab" to access my plugin's page within the CP that fails.
EDIT 2
I'm wondering if it's a case-sensitive thing now though. I don't see that exact error in the log file anymore.
I know with CodeIgniter, locally things work great, but when I upload to my server (CentOS) I get white screens. It's because of the case is all strange.
I have followed the suggested guidelines for plugin development:
controllers
    ContactFormPlugin.php
    controllers
        ContactFormController.php
            class ContactFormController extends BaseController {...}
    models
        ContactFormModel.php
            class ContactFormModel extends BaseModel{...}

   records
        ContactFormRecord.php
            class ContactFormRecord extends BaseRecord{...}

   resources
        ...

   services
         ContactFormService.php
             class ContactFormService extends BaseApplicationComponent {...}

   templates
       ...

   variables
       ContactFormVariable.php
           class ContactFormVariable {...}

...and so on.
My host is Rackspace, has anyone experienced this?


texts: Why can't I drag and drop fields in settings on a mobile phone?

texts: Each field has no option to move them on a phone. Using Firefox and Chrome on a Samsung Galaxy 5.


texts: Assets Content/Fields not available until entry is saved?

texts:
I've got Asset location setup with a Photo Caption field. And a Photo Gallery field which references said Asset.

When creating a new entry, I'm uploading images to the Photo Gallery field. When the images are uploaded, double-clicking brings up the modal but the Photo Caption field is not available. Only after saving the entry and then re-opening it to edit is the Photo Caption field available in the Assets modal.

Is the normal behavior? Did I miss something?

It would be ideal for my clients to be able to edit the photo meta information while they're creating a new entry.


texts: How do I maintain paragraph formatting on textarea Guest Entries submission?

texts:
I have set up a guest entries form that receives data from the textarea snippet below and saves it into a rich text field.

<textarea name="fields[comment]" placeholder="Join the discussion..."></textarea>

When I view the entry on the front-end there is no formatting, but on the backend there is formatting. Then when I save the entry on the back-end, suddenly there is formatting on the front-end.

Is there anyway to bypass having to re-save the entry to get the desired formatting?


texts: What is the best way to setup Right to Left language locale in Craft?

texts:
I have been working on setting up locales for left-to-right languages. I wanted to know the support Craft provides for Right-to-Left languages like Arabic, Hebrew etc. Is there a plugin that could help or is it just the way other locales are setup (but with additional step)?

Any insight on this topic is helpful!
Thanks!


texts:
I want to display the first character in a paragraph with a drop cap. It works fine with normal text or setting it with js, but when I use an entry field it doesn't pull out the first character. The code looks like this:

// css
p.dropcap {
float: left;
font-size: 4em;
…
}

// html

{{ entry.body }}

The first letter isn't dropped, but if I change the html to:

This is {{ entry.body }}

The T is dropped as expected.

Any ideas on how to fix this?


texts: I have a user I am running some Commerce order tests with. I have 6 orders they have placed. If I add a Commerce Customer Info field to their profile, I can see all their past orders on their Profile in the Users area (left side of screen below). However, if I view one of their orders in the Commerce Orders section, the Order History section only ever shows the current order (right side of screen below). Shouldn't it show all their orders like on their profile?


texts: Getting logged out of admin area when refreshing site

texts:
The problem seem to be that the session file in /craft/storage/runtime/sessions is getting removed any time I refresh the actual page, so that I have to do a new login everytime I've changed content, looked at the site, and then want to add more content.

This i running on Apache, PHP 5.3.29, locally through MAMP on Yosemite.

Is there some config setting I'm missing here?


texts:
I'm trying to pull entries from a database where the postDate is a specific date.

{% set today = thisyear ~ "-" ~ thismonth ~ "-" ~ day %}
{% set today = today|date('Y-m-d') %}

{% set entries = craft.entries(params).section('calendar').status('null').postDate(today|date('Y-m-d'))%}

This only gets the entry if the Time element of the Post Date is empty or 00:00
How can I correct this to pull the entries even if it has a time associated with the Post Date


texts:
I usually use {% block %}{% endblock %} to build my template but for the SEO plugin I'll be needing {% set %}{% endset %}. However my pages don't seem to render. If I change it to {% block %}{% endblock %} it works fine.

Anyone know what is causing this?

This is my base file _master.html (partly):

<body class="boxed bg-cover" style="background-image: url(img/backgrounds/street.jpg)">
 <div class="global-wrap">
     {% set header %}
     {% endset %}

this is my index.html (partly):

{% extends "_master" %}
 {% set header %}
   {% include 'header.html' %}
 {% endset %}


texts: Deciding between multiple products and variants

texts:
I'm trying out Craft Commerce for a jewellery website and I'm stuck between creating different products for each material (silver, gold and platinum) or using variants.

Take rings for example. They're available in all three materials and a number of sizes.

By creating a separate product for each material:

Plain band (Silver)
Plain band (Gold)
Plain band (Platinum)

this gives me the advantage of a unique URL for each colour, and I only have to manage one variant (the size) for each product.

It would also make it easier to implement an "Also available in" where the site admin can link to the other colour products in a relationship field (as I understand it it's not possible to link to variants yet).

Am I missing an advantage of having only one product (Plain band) and variants for both the colour and the size?

Thanks in advance,

Tom


texts:
So i copied the craft files onto my server. Web directory went into my public folder. I type in my address, I get the Craft service unavailable page, good so far.
I cant get to the installer. http://HOSTNAME/index.php?p=admin takes me to url/admin not found on the server.
What can I look for to see why Im not getting to the install directory.?

Thank you.


texts:
This question is related to a previous question I asked: Sort entries in a category via entry field

I have a page that is running the same query from the previous question:

{% set businesses = craft.entries.relatedTo(category) %}
{% set state  = entry.bizTown.first.townCounty.first.countyRegion.first.regionState.first ?? 'N/A' %}
{% set businessesByTown = businesses|group('bizTown.first.townCounty.first.countyRegion.first.regionState[0].title') %}

{% if businesses|length %}
    {% for town, businessesInTown in businessesByTown %}

{{town}}

                {% for business in businessesInTown %}

                    {% if business.ytVideoId|length %}

                    {% endif %}
                    {{ business.link }}

                    {% set twn = business.bizTown.first %}
                    {{twn.title}}

                {% endfor %}

    {% endfor %}
{% else %} ... {% endif %}

This is on a template which is displaying entries of a given sub-category. It separates the entires (the businesses) according to its state. It also displays what town each business belongs to.

Unforunately this takes the page ~20 seconds to render! I've tried looking into using plugins for custom SQL queries, and using eager loading.

I have read through this article a lot and have poked around inside their plugin, but I still don't know where/how to start! Likewise with eager loading, with all the crap I have going on in this/these queries, I'm not sure where to start with that, either.

At this point I feel like this is abstracting beyond my comfort level, and I'd love some expert input. Thanks!


texts: Trouble parsing JSON with getBodyParams()

texts: I'm trying to use getBodyParams() to parse a JSON posted to a module controller action from an API. The incoming headers have content-type set as application/json; charset=utf-8, and I've tested to make sure there is a valid JSON string in the body. But when I try to get the retrieve the body  using getBodyParams(), I only get an empty array as a response. The documentation makes it sound like it's possible to parse JSON and other content types. Does anyone know the correct way to use getBodyParams() to parse a JSON body?


texts: Cannot hide redactor strikethrough button when table plugin is enabled

texts:
I am trying to set a Redactor field so that it only shows the table button, though no matter what I do... the strikethrough button appears, it looks like the correct name is strike though doesn't appear to work (tried multiple variations) though no luck. Are there any suggestions on how to hide it? Here is my redactor config:

{
  "buttonsHide": ["link", "lists", "strikethrough", "Strikethrough", "strike", "italic", "bold", "format", "html"],
  "plugins": ["table"]
}


texts: Commerce 1 with Apple Pay, is it possible?

texts:
We are using Stripe on our website. Craft CMS 2.6.2997 and Commerce 1.2.1351. Can we use the apple pay function?

I read the Stripe document(https://stripe.com/docs/stripe-js/elements/payment-request-button#html-js-testing-chrome). It seems possible to do that. But, I am not sure is it work on Commerce 2...

Anyone know?

Thanks!


texts: Get a twig | replace to output html rather than the text

texts:
I've got a craft field where I have an such as:

Learn more about this great %Job Title% job.

I'm then using Twig Replace to insert the actual entry.jobTitle into the %Job Title% space.

This works great.

But visually, I'd like to highlight the job entry. So I'm wrapping it in a span tag.

Here is an example of the output I want:

Fantastic opportunity for a Head Chef

So at the moment I've got it looking like this, pulling in the jobStatement (The line with %Job Title% somewhere in it):

{{ jobs.jobStatement|replace({'%Job Title%': "" ~ jobs.jobTitle ~ "" }) }}

Alas, when the template is rendered, it is rendering the entries as text. How can I insert the HTML span tags around the Job Title area?

Any help much appreciated,

Stephen


texts: Can't find S3 bucket using Craft Pro in trial mode

texts:
I am using the Craft Pro trial version and I want to use S3 for my Assets.  However, I enter my credentials but the refresh button does not show my bucket.  Also, when I try the refresh with wrong credentials it shows the error message but with correct it just doesn't show anything. I tried to connect to by bucket with other tools and was successful so this is why am thinking that is a restriction on the trial version of Pro.

So is it a Craft trial issue? Are you allowed to connect to S3 in trial version of Craft Pro?


texts: Order/sort a structure section by date too?

texts: Is it possible to have a Structure section ordered by date (desc) as a default and then take the custom ordering in the CP into account?


texts: Least CPU intensive way to get number of matching elements?

texts:
Which is the least CPU intensive (SQL-intensive) way to get the sum of products that are relatedTo a category?

Like this?

{% set productCount = craft.products.relatedTo(category)|length %}


texts:
Hi I'm creating a site that will be used in 4 locales which each have their own domain.

Australia: project.com.au
New Zealand: project.co.nz
South Africa: project.co.za
USA: project.co

In short, from a content management perspective I only want two locales. English AU and English USA. However, I need the content on the au locale to be accessible from the au,nz,za domains.

Is it possible to have an array of URL for one locale config?


texts: forms.timeField not respecting time zone

texts:
I have a plugin that uses a datetime variable to record a class start time.  When I save the training record the time is changed from local MDT to GMT into the database, and when displayed again it is six hours off.  Changing the form as follows fixes the problem:

{{ forms.timeField({
    id: 'classTime',
    required: false,
    name: 'training[classTime]',
    value: training.classTime  ? training.classTime|date_modify("+6 hour") : null,
    errors: training.errors ? training.errors('classTime') : null,
    }) }}

I notice my training dates are also impacted.  Listing date on index.html shows one day prior, but the database stores values correctly.

Where and when do I fix dates coming and going from the mysql store?


texts: Previous and next entries nav – within a categeory

texts:
I'm not sure what I've done, I had this working at the top of my entry.html template:

{% set params = craft.entries.section('ourWork').relatedTo(category) %}

{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

{% if prevEntry %}Previous{% endif %}
{% if nextEntry %}Next{% endif %}

For some reason I just get:
Variable "category" does not exist

The section name is correct and this does have a category field assigned.

my index template category part is:

{# Projects
---------------------------------------------------------------------------#}

  {#
  Display catgeory nav 'ourWork'
  #}
    {% nav category in craft.categories.group('ourWork').level(1) %}

          {#
{{ category.WorkCategoryDescription }}
 #}

 {{ category.title }}

    {% endnav %}


texts:
I am trying to display entries based on the last segment in the url and then paginate.

Here's what I have so far but it's not displaying any entries:

{% set categorySlug = craft.request.getLastSegment() %}
  {% set category = craft.categories.slug(categorySlug).first() %}

  {% if category %}

      {% set entries = craft.entries.relatedTo(category).limit(12) %}

      {% paginate entries as entries %}

      {% for entry in entries %}

      {% for block in entry.resource.type('resource') %}

{{ block.resourceTitle }}

{{ block.resourceAuthors }}

{{ block.resourceSummary }}
      Read more

      {% endfor %}

      {% endfor %}

      {% if paginate.prevUrl %}
          Previous
      {% endif %}

      {% if paginate.nextUrl %}
          Next
      {% endif %}
      {% endpaginate %}

  {% endif %}

Even this simplified version outputs zero entries:

  {% set categorySlug = craft.request.getLastSegment() %}
  {% set category = craft.categories.slug(categorySlug).first() %}

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

  {# Output them #}
  {% for entry in entries %}
      {{ entry.title }}
  {% endfor %}

Any thoughts?


texts: Images containing EXIF orientation tag are not rotated on upload

texts:
The Craft CMS instance where I noticed this is running version 2.6, but I updated it last month from version 2.2.

While we did not notice any problem, according to the client, they were able to upload pictures taken with their smartphone and Craft would rotate the images correctly before the update.

As far as I can tell, Imagick is not available on this server (I checked PHPInfo) so GD has always been used. I also made sure that the "rotateImagesOnuploadByExifData" setting is set to true by adding it explicitly to the general config.

Any idea what could be causing the issue and would installing Imagick solve the problem?


texts: Does Craft have a styleguide for the admin, like Bootstrap? I'd like to know how to create plugin interfaces that match with Craft


texts: 'Unknown error' caused by redirect in htaccess

texts:
I was getting an 'unknown error' when trying to access the admin. I couldn't see anything in the Craft logs apart from 404 related errors.
I replaced the app folder but still no luck, eventually I discovered it was a rewrite rule in my .htaccess causing the problem.

# redirect PHP or HTM to no extension
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.(php|htm?)
RewriteRule ^ /%1 [L,R=301]

I'd love to understand why, and how I can get around this in the future?


texts: How can I programmatically change the system's status?

texts: I have a console controller action that needs to change the site's status under certain conditions. I have not been able to find any documentation or even questions out there about how to do this. Is it even possible?