texts: User activation success path not working (Craft v2.3.2621)

texts:
I'm at a loss. I've set up a font-end user activation workflow that looks like this:

User registers via a front end form based on Craft's example form
User is redirected to a page informing them that they'll be receiving an email with an activation link
User clicks the activation link and lands on a welcome page

Right now my user registration form is working. When a user registers, I can see them added to the CP user list with their email address, firstName and lastName (which I'm also collecting from the registration form). The redirect to the "you'll be receiving an email..." page is working as well.

But when I click the activation link to test, I end up on the homepage of my site, not on the uri I've specified in my config settings which look like this:

return array(
    '*' => array(
        'omitScriptNameInUrls' => true,
        'defaultImageQuality' => '65',
        'useEmailAsUsername' => true,
        'loginPath' => 'member/login',
        'logoutPath' => 'member/logout',
        'postLoginRedirect' => 'member/my-account',
        'autoLoginAfterAccountActivation' => true,
        'activateAccountFailurePath' => 'member/activation-failed',
        'activateAccountSuccessPath' => 'member/activation-success',
    ),
other settings below...

I'm making sure that when I test sign-ups, I'm logged out in a different browser. I've also tried the sequence without autoLoginAfterAccountActivation set to true but in that case, I just end up logged out on the homepage of my site rather than on the activation-success page.

The activation works, which I can verify in the CP, but I can't figure out why the site isn't respecting my config setting for activateAccountSuccessPath.

Anyone have any ideas?


texts:
I am using {{ siteUrl }} for absolute links. It works 95% of the time. But if I press the reload button multiple times in a few seconds (overloading or something) my links look like this:

href="$DEFAULT_SITE_URL/css/order.css"

instead of

href="http://localhost/craft/web/css/order.css"

other Twig commands are working fine at the same time. What's happening?


texts:
I have a site running Craft 3.6.11.1. I've been working on it for a while, have multi environment config set up and everything working great. I have recently installed and uninstalled quite a few plugins. I'm not sure exactly when something went wrong but now in terminal when I do ./craft I get:
Exception 'yii\base\InvalidArgumentException' with message 'Invalid path alias: @'

in /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/BaseYii.php:154

Stack trace:
#0 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/base/Module.php(257): yii\BaseYii::getAlias('@')
#1 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(245): yii\base\Module->getControllerPath()
#2 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(240): yii\console\controllers\HelpController->getModuleCommands(Object(modules\sitemodule\SiteModule))
#3 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(172): yii\console\controllers\HelpController->getModuleCommands(Object(craft\console\Application))
#4 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(192): yii\console\controllers\HelpController->getCommands()
#5 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(292): yii\console\controllers\HelpController->getCommandDescriptions()
#6 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/controllers/HelpController.php(67): yii\console\controllers\HelpController->getDefaultHelp()
#7 [internal function]: yii\console\controllers\HelpController->actionIndex(NULL)
#8 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#9 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/base/Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#10 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/Controller.php(184): yii\base\Controller->runAction('', Array)
#11 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/base/Module.php(534): yii\console\Controller->runAction('', Array)
#12 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/Application.php(181): yii\base\Module->runAction('', Array)
#13 /srv/users/serverpilot/apps/dev-odette-craft/vendor/craftcms/cms/src/console/Application.php(89): yii\console\Application->runAction('', Array)
#14 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/console/Application.php(148): craft\console\Application->runAction('', Array)
#15 /srv/users/serverpilot/apps/dev-odette-craft/vendor/yiisoft/yii2/base/Application.php(392): yii\console\Application->handleRequest(Object(craft\console\Request))
#16 /srv/users/serverpilot/apps/dev-odette-craft/craft(22): yii\base\Application->run()
#17 {main}

Any ideas on how to fix this would be much appreciated.


texts: Make dimensions common for all variants in Craft Commerce

texts:
When I enable multiple variants for product type that has Dimensions and Weight, fields "Dimensions and Weight" become available for every single variant. Product is tablet and all variants have a same dimensions and weight.
Is it possible to have common "Dimensions and Weight" fields for a single product, not for every variant?
Application info:

Craft Pro 3.4.27
Craft Commerce 3.1.11


texts: How to check for an HTML element in a rich text field?

texts:
I want to do something special in my template if there's an HTML table in the rich text field. I tried this:

{% if "</table>" in entry.richTextFieldHandle %}

but it doesn't work. How can I do this? Or can you think of a better way?

Thanks.


texts: Offline update then upload files to server

texts:
What's the best way to update Craft offline and then upload the files to the server? Reason I'm asking is because my updates often fail because of too low PHP memory and I don't have control over the server to update the minimum value.

This is my process right now:

Backup everything (files + db)
Updating the composer.json file manually to the versions that are shown in the admin panel.
Run 'composer update --no-dev'
Upload vendor directory, composer.json and composer.lock to the server
Refresh admin panel and finish update.

Is this the way to go or am I missing something?


texts:
We have a single DB and multiple web servers and are finding that unless we enable sticky sessions on the load balancer, we aren't able to login (or we can login then lose the session).

I can see a sessions table and there appears to be no config setting, so what might be going wrong here?

Do we need to set overridePhpSessionLocation to false?


texts:
I'm writing a plugin to duplicate a Structure within Craft 2.
I've covered off duplicating the section, entry types, field layouts and can duplicate the entries, covering of the main Craft fields.

However I'm completely stumped on duplicating a Neo field. I've figured out to access all the field types and content within the Neo blocks, but can't get the Neo field to validate for the new Entry.

Right now, I'm considering dumping the SQL and using that because I've tried everything else!


texts: Twig Cycle - how to show different html based on cycle

texts:
Here is my code so far:

{% for event in post.get_field('timeline_event') %}
{% set items = [odd, even]%}
{{ cycle (items, loop.index0) }}

{% if cycle == odd %}

{% endif %}

{% if cycle == even %}

{% endif %}

This is working for the most part, the issue is the code I have is being duplicated twice.

Here is an image:

I know how to do this in jekyll liquid using capture, hit a roadblock using twig for php


texts: Error when trying to view a previous version of an entry

texts:
I got this weird error message when trying to view a previous revision...

Internal Server Error
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_8mvcY59Y5sz9qAyfufetQi5LWATEmqwdMnVR' in 'field list'

I didn't really do anything too unusual... I simply tried to view a previous version of the entry.

Disclaimer... This is a very large website, and it's evolved a lot over the past year or so. I'm guessing this might have something to do with a field that has changed, but I really have no clue.
What does this mean? How did I get here? And how do I fix it?


texts: Loop through JSON object in Twig from the database

texts:
I've written a custom plugin that stores data as JSON in a TEXT column (field_gridcontrol) in Craft's content table that looks something like this:

[
  {
    "id": "35", // id is an element's id
    "classes": "item w1 h2", // classes to add to the dom element
    "x": 0 // x coordinate on where it shows up in a grid
  },
  {
    "id": "56",
    "classes": "item w2 h2",
    "x": 0.25
  },
  {
    "id": "24",
    "classes": "item w1 h1",
    "x": 0.75
  }
]

I can print this as a string {{entry.fieldcontrol}}, which is all well and good, but I'd like to be able to loop through it as an object like a traditional element criteria model:

{% for block in entry.gridcontrol %}
  {% set entry = craft.entries.id(block.id) %}

    {{entry.title}}

{% endfor %}

However when I try this I don't get any errors, just an empty ul. I guess this is because it's not seeing gridcontrol as an object.

My question is: Did I go about structuring this the wrong way? I've seen other plugins, like nystudio107's SEOmatic, that store data this way. Or am I missing something super silly to get this up and running?


texts: Is it possible to import the content of a rich text field into matrix using FeedMe without parsing reference tags to entries/assets?

texts: Currently I have content that I’m trying to migrate from a single rich text field into a rich text field living in a Matrix content builder. Migrating most of the content is fine, but I would like to know if it’s possible to migrate the reference tags so that I keep the established relationships. I’m concerned with those entries that are rendered on export/import as  and not


texts: I am unable to insert a link into a Rich Text field.  The modal opens, I enter the data but nothing happens when I click ‘save’, no errors seem to be thrown.  I am able to insert a link to anther entry in the same modal. Field(s) are set to default and no plugins are being used.  The entries are both in a structure with no urls of their own, and in Craft Commerce product types.


texts: How Can I Output Only the First Word of the Title of an Entry in a Template?

texts: Is it possible to output only the first word of the title of an entry in a template? If so, how? Thanks!


texts: How does a CMS work ? How to add articles and manage them?

texts:
I would like to design a news outlet website, if that's the correct name.

I've drawn a little sketch and I have a pretty good idea about the user interface; things like the site logo, nav-bar, content placement, footer, the easy stuff.

The thing that I don't understand is how does content management work?. I assume that I don't make a webpage.html for each article, right ? And if that's the case, then I am sure that there are other optimized methods of doing this. How will that work ? Let's say that a user clicks on a preview (that's on the first page), where do I send him if I assume that I don't make websites for each article ?

Also, how can I make a top 100 articles based on a marking of my own choosing; example: game reviews with scores from 0 to 100; if a user clicks on Top 100 Games I would like to present him with an ordered list of the top 100 games reviewed by my website.

What about auto-arranging the articles in a chronological order in a specified [div][/div] ? For example: the last five written articles presented chronologically in the middle of the screen from left to right.

I would prefer to design this website using HTML, CSS, JavaScript, PHP, without using platforms like WordPress. This is because I have never used WordPress.

Any advice is welcomed. I have never done such a big project before. I've mainly done simple websites for my job. This is a project form which I hope I can learn lots of new stuff.

Also, please do give me advice if you think that implementing my idea into WordPress is easier than doing it from the ground-up. I mean, I am pretty sure that it's easier, but I haven't used it before and I don't know if I can customize it to my heart's content. I assume that, when using WordPress, you select a "News" Theme that has a built-in CMS for your site which gives you, let's say, a slideshow that arranges the articles in a chronological order. Now, what if I want to change that slideshow into a design of my own ? How do I take take the CMS from point A and implement it over point B ?

Thank you.


texts: How do I define an entry's META description?

texts:
I'd really like some help with Craft CMS, that's probably a very basic thing to achieve, but I've so far got no idea how to. In another post about SEO, I saw something like this written:

<meta name="title" content="{% if title is defined %}{{ title }}{% endif %}">
<meta name="description" content="{% if description is defined %}{{ description }}{% endif %}">

The first part, regarding the title, is in the _layout.html by default. And, in the CMS, above each entry's body, I have managed to display a box for the user to enter a title.

BUT, were I to add the second part, regarding the description, I have so far been unable to find out how in the CMS, I can add a box for the user to enter a description.

Thanks in advance for any help that anyone can provide.

With kind regards,

Mark


texts: Loop through entry titles in a select field

texts:
Im trying to use entry titles as options in a select field, similar to the last example on this page in the docs

My code looks like this:

<label>Position Applying For</label>
<select name="{{ positionApplyingFor.handle }}">
{% for entry in craft.entries.section('careers') %}
  <option value="{{ entry.title }}">
    {{ entry.title }}
  </option>
{% endfor %}
</select>

Although the form submits, the fields content is not shown in the admin.

If I add {% if field.value == entry.handle %} selected{% endif %}, I get the error "Variable "field" does not exist"

Any help appreciated!

Martin


texts: Opening and closing table within a switch

texts:
Within my matrix I have two blocks: Day and Event. Day is just a date field while the event block has two text fields.

What's the best way to wrap the event data, which needs to show up as a table format within this loop?

This currently spills everything out in the correct order but the table doesn't open and close correctly around the event block.

The final output should look something like

Title (h2)

Table open
TR
TR
TR
Table close

{% for block in entry.scheduleMatrix %}

{% switch block.type %}

{% case 'day' %}

{{ block.day.format('l - F j, Y') }}

{% case 'event' %}

{{ block.eventTime }}
            {{ block.eventName }}

{% endswitch %}

{% endfor %}


texts:
I'm trying to set a variable within my templates which does the following:

  If this field is empty then use another field instead.

I have 2x Fields called affiliateUrl and offerLink, if offerLink is empty, then use the affiliateUrl instead.

The current code I'm running is this:

{% set affiliateLink = relatedEntry.offerLink ? relatedEntry.affiliateLink : relatedEntry.affiliateUrl %}

Error Code:

  Calling unknown method: craft\elements\Entry::affiliateLink()

The rest of the code is below:

        {% set affiliateLink = relatedEntry.offerLink ? relatedEntry.affiliateLink : relatedEntry.affiliateUrl %}

        {% if relatedEntry.offerCode is empty %}

            Get This Offerchevron_right

        {% else %}

                window.aPopunder = [
                    ['{{ relatedEntry.offerLink }}']
                ];

            Reveal Code & Visitchevron_right

        {% endif %}


texts: How to relate a long survey to a user and later query by values

texts:
I'm working on a new project that requires users to fill out a lengthy survey to assess their skills. These skills will then be used to query for users with a front-end interface. My question has to do with how to store these ~120 skills and query them later.

Each skill with have a range of values such as:

Skill: Crosscut Saw Experience
Possible values: 0) none 1) performed with supervision 2) performed independently 3) Have Supervised 4) Trainer

So, that first makes me thing of radio button fields. The issue is that there is about 120 of these skills that need to be recorded for each user with a front-end form. And, the must be the ability to quickly query user based on skill/skill level.

At first I considered a static Super Table, but I don't believe querying that is easy or efficient, based on other questions I've browsed.

Plan B is to create a Skills channel, creating ~120 skill records, related to each user. This would make querying simple a matter of finding records relatedTo a skill. But how to create all these records on the front end as the user is filling out a form?

I've not used any of the form plugins, such as Sprout Forms or Freeform. Anyone have any experience with these that might shed some light?

Any other suggestions on how to best go about this?

Thank you for any ideas or advice.


texts: Add custom fields to the cart line items in Craft Commerce 3

texts:
I have a product variants with the custom field for the variant image.
In a cart overview I need to show an image of added line item (image should be of the added product variant if there are variants set for this product).
I have to do this with axios request, and I'm not using any twig templates; I'm using headless Craft with decoupled frontend on Nuxt.js.
How can I fetch one with the cart request? thank you in advance


texts:
I have a matrix field with two block-types ("sound" and "video")
I want to get all entries that have a matrix field with a certain block-type.
At the moment I have:
{% set entries = craft.entries()
        .section(['events', 'sessions'])
        .orderBy('datum desc')
        .matrixField(':notempty:')
        .limit(30)
        .all() %}

how can i get all entries that have a "video"-block in the matrix-field?
I want to paginate the results.
Thanks!


texts: Getting ancestors for manually set parent in template

texts:
I have a a few pages outside of a structure but I want to display a breadcrumb for it as part of a structure. I am currently setting the parent page like so:
{% set parent = craft.entries.section('pages').slug('phone-directory') %}

{{ parent.ancestors }}

But when I loop through to get the ancestors it is only getting the current parent not all ancestors? Any idea how to achieve this?

The structure is
Staff
     Phone Directory

The reason I am trying to do this, is the 3rd level pages are either category pages or is a single with some specific routes. I want to manually set the real parent in the template, so I can get the ancestors for the breadcrumb trail as though it is part of the same section.

How can I manually set the parent entry in the template and get the ancestors from this entry?

**** UPDATED ****
This is an update on the above to show my exact code and what isn't working and How I expect it work...If anyone ca shed some light?

So by default I am getting my breadcrumbs like so;

{% if entry is defined and entry.section.handle != 'homepage' %}
{% set crumbs =  parent.ancetors ?? entry.ancestors|default([]) %}
{% set crumbDivider = '
/
' %}

You are in:

Home

    {% for crumb in crumbs %}
    {{ crumbDivider|raw }}

{{ crumb.getLink() }}

    {% endfor %}
    {{ crumbDivider|raw }}

{{ entry.title ?? category.title }}

{% endif %}

This works as expect for normal standard entries. For example, within my Pages structure I have a parent of News with a Child of Internal News and on the Internal News page, the breadcrumb is reflected as;
Home / News / SWH Internal News

Now on the news entry pages I want the breadcrumb to read as follows;
Home / News / SWH Internal News / {{ Entry Title }}

I thought by setting the parent on the news/_entry.html template to the SWH Internal News page like so;
{% set parent = craft.entries.section('pages').slug('archive') %}

Would then give me the ancestors of News / SWH Internal News but instead it only outputs SWH Internal News.


texts:
I'm try to use related entries from different channels to display content on a home page. Using the code following with "selectNews" as a entries fieldHandle in the Home Page:

  {% set entry = entry.selectNews.first() %}
  {% if entry %}
     ...
  {% endif %}

This places field entries from craft section "news", the first & only entry. Following that is a div with the same code, but with a new entries field and fieldHandle, "messageBanner", relating to an channel named "Banners". This second set of code fails to display anything. I see that

... {{ entry }}...

tested in the failed div, outside of {%set entry =... endif %}, prints to screen the related entry title from the previous code. How can I get this fixed and what am I missing. Pretty confused.

{% set entry = entry.selectNews.first() %}
  {% if entry %}
...

   {% set asset = entry.newsImage.first() %}
      {% if asset %}

      {% endif %}

...
{% endif %}

{% set entry = entry.messageBanner.first() %}
  {% if entry %}

 some text  {{entry.bannerText}}

{% endif %}


texts:
We have an issue on our server when our Security Headers are not working. We added the following to our htaccess file after installing Craft CMS: -

<IfModule mod_headers.c>
    Header always set X-Xss-Protection "1; mode=block"
    Header always set X-Content-Type-Options "nosniff"
    Header always append X-Frame-Options ALLOWALL
    Header always set Strict-Transport-Security "max-age=31536000"
    Header always set Referrer-Policy no-referrer
</IfModule>

These settings worked on our previous CMS which was completely developed in house. We have recently upgraded our server to PHP 7 and Apache 2.4. We have been using https://securityheaders.io to check our results.

Any help trying to get this to work would be really appreciated.


texts: Contact Form: Name and Email in Message Body

texts:
This is a follow-up to an earlier question from 2014: P&T Contact Form plugin: How can I copy “name” and “email address” in the body of the mail? ... it seems that Craft (and the plugin) has gone through significant updates since that question was answered.

How would I include fromName and fromEmail into the body of the message?

I read about events in the documentation, but it doesn't say where they go. Do I put those into the craft>config>contactform.php file? How would I setup an event to handle that inclusion?


texts: Pagination, display 'Next 20 Results' etc

texts:
Just a quicky regarding pagination.
I have a paginated results list with a limit of 20 results in a page.

I'm wondering how I owuld go about making a pagination that shows the number of results on the next page.

i.e.
If I have 105 results, the pagination link says 'next 20 results', up to the fifth page, which would then say 'next 5 results'.

Not sure if there is an easier way to do it other than a load of maths to work it out.

Thanks!


texts: How to output a Rich Text Link to an Entry as a tooltip?

texts:
I have a Glossary channel on my site, with Term and Definition fields. I would like Terms to display their definitions throughout the site...whenever so assigned by the content editor.

I currently have Rich Text fields allowing editors to create links from Terms to their Definitions by using Link to an Entry. This is not great in terms of UX as it forces sends site visitors to the main Glossary index page to view the Definitions; I'd like to implement a hover text for the Terms that shows the Definition right there, wherever the visitor is reading.

How can I filter these rich text fields in the templates to check for links to Glossary entries and output a hover text instead of a link? I haven't written any custom plugins or filters (yet), so I'm looking for pointers in the right direction.

Any other approaches that might solve my problem are welcome.

Thanks in advance for your help.


texts: By reordering entries in structure Craft doesn't show up some entries on front-end using {% nav %} tag

texts:
Sometimes I need to reorder or drop certain entry to different ancestor entry in control panel. By doing that I "lose" some entries on front end using {% nav %} tag. A behaviour is depended on how I reorder entries. Why?

{# We excluded the entry id which is ancestor of all entries in structure #}
{% set shop = craft.entries.section('shop').id('not 96') %}

{% nav page in shop %}
{% set slug = page.slug %}

        {{ page.title }}

    {# Link description #}
    {% if lastSeg == page.slug %}
      {{ description|ucfirst }}
    {% endif %}

    {% ifchildren %}

        {% children %}

    {% endifchildren %}

{% endnav %}

The structure section in control panel

Not complete entries in front end


texts: How to create a secondary menu to filter entries?

texts:
I have a page where by default it lists all of the entries inside the section 'work'. I'd like to have a secondary menu where I can filter these entries by the field 'projectCategories'.

        {% for entry in craft.entries.section('work').find() %}

                {% for asset in entry.mainProjectImage %}

                {% endfor %}

{{ entry.title }}

                    {% for option in entry.projectCategories %}

                        {% if loop.last %}
                            {{ option }}

                        {% else %}
                            {{ option }} +

                        {% endif %}

                    {% endfor %}

        {% endfor %}

My current solution is a secondary menu above the entries that links to a url where it filters the entry for just for that project category with:

{% for entry in craft.entries.section('work').search('projectCategories:Packaging') %}

This works but isn't DRY and unfortunately because of AJAX the secondary menu fades out and back in again when you change the URL.

Is there a way to filter entries by a field without changing the url? Or alternatively is there a way of making the secondary menu not reload with AJAX when on a url that begins with 'work'?


texts:
Tried the 1 Click Update and it bombed.

on domain.com/admin/utlities/updates url I get

Twig Runtime Error – Twig_Error_Runtime
Variable "CraftPersonal" does not exist.
1. in /vendor/craftcms/cms/src/templates/_layouts/basecp.html

And then on the domain.com/admin/dashboard url:

Twig Runtime Error – Twig_Error_Runtime
Variable "CraftClient" does not exist.
1. in /vendor/craftcms/cms/src/templates/_components/widgets/RecentEntries/body.html

The CP is now unusuable


texts: How can I concatenate 2 variables to access array values?

texts:
I am using this SO post to try to concatenate two variables in twig.

I am very close, but can't seem to get over the hump of rendering the correct syntax.

This is what I am currently using:

 {% for user in plugin.data.users %}
     ...
     {{ attribute(user, 'foo' ~ loop.index0)|raw|nl2br.bar }}
     ...
 {% endfor %}

This is what I am currently getting back:

Key "foo0"... for array with keys "...does not exist."

What I am trying to create is foo[0], foo[1] etc.

Well, I couldn't figure it out so this is how I did it. If there is a better way, I'd be happy to update the post.

{% set i = 0 %}
    {{ user.foo[i].bar }}
    ...
{% set i = i + 1 %}


texts: Matrix: get the index number of a certain block

texts:
I have a matrix set up with some blocks in it, and one of those blocks is to add "steps" to a page in a matrix. Now I'm trying to get the number of the step so that they only have to enter the content of the "steps" block, and that it automatically numbers it.

For example:

The matrix has 2 block types: "steps" and "image".
If I make 2 "steps" blocks and 1 "image" block in this order: step - image - step, index.loop numbers the first step as one, and the 2nd step as three since image is in between them.

Is it possible to have the "steps" numbered by position in the "steps" loop, and not in the full matrix?


texts:
I have a very simple plugin to update a user's name. All I'm doing is:

    $userId = craft()->userSession->id;

    $user = craft()->users->getUserById($userId);

    $post = craft()->request->getPost();

    $user->firstName = $post["firstName"];

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

The problem I'm having is after the page reloads from the POST submit the output still shows the old name, but then if I refresh the page without resubmitting I see the new name. Point is the name is changing but it seems like maybe this data is cached somewhere? How do I fix this?

UPDATE

To be more clear, this does not happen on all field types. First name and last name do it. Custom plain text fields do not. Category fields do it.

UPDATE

Here is the code I'm using in one of my controllers. This will not be the final code but I don't feel like that matters. Just these few lines will produce the problem I'm talking about:

public function actionEditContactInfo()
{
    $userId = craft()->userSession->id;

    $user = craft()->users->getUserById($userId);

    $post = craft()->request->getPost();

    $user->firstName = $post["firstName"];

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

For AJAX calls I'm doing a little bit more:

public function actionEditContactInfo()
{
    $userId = craft()->userSession->id;

    $user = craft()->users->getUserById($userId);

    $post = craft()->request->getPost();

    $user->firstName = $post["firstName"];

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

    $editUser = $user->getContent();

    $template = craft()->templates->render("users/profile-form/_contact-info-form", array("editUser" => $editUser));

    $this->returnJson(array('template' => $template ));
}

In both cases not all fields display the updated content after a form submit is made. Custom plain text fields seem to be ok. The default user model first name and last name are problematic as are category fields. Not sure about other field types.

UPDATE

It has been brought to my attention that I should probably be more clear in my explanation of this problem. Here it goes from top to bottom:

I have a form with 2 fields:

A category field
A plain text field

The form submits data to the server by making an AJAX call to a controller. The controller updates the info as needed then renders a template representing the updated form. The template is then encapsulated in a JSON array and passed to a JavaScript function which updates the user's browser.

The problem I'm experiencing is not that the data is not saving, but that when the new form is re-rendered not all of the fields reflect the changes. But if I refresh the page after saving everything is fine.

Of the two fields mentioned above, plain text works as expected but the category field is problematic. Even if I dump() the user data in the re-rendered template I am given the old value for the category field even though it was updated. Here is my controller code:

public function actionEditNetworks()
{

    $userId = craft()->userSession->id;

    $user = craft()->users->getUserById($userId);

    $user->setContentFromPost('fields');

    // Save the user
    $result = craft()->users->saveUser($user);

    $editUser = $user->getContent();

    $template = craft()->templates->render("users/profile-form/_network-links-form", array("editUser" => $editUser));

    $this->returnJson(array('template' => $template));
}


texts: I'm using the SEOmatic plugin and would like the query string in my URL to display with the site's title. Is this possible to add with the plugin?


texts: What's the best way to set up a content-manageable 404 page?

texts:
I'd like to make my 404 page editable through Craft, but when I create a single for it, a URI is required.

Is there a way to make a single with no URI, or is the best route to setup globals for managing this content? Or is there a better way that I don't know about?


texts: Add Matrix Blocks to existing Entry with Form without discarding existing Matrix Blocks

texts:
When I want to save an new Matrix block with an form to an existing Entry:

<form method="post" accept-charset="UTF-8">
  {{ csrfInput() }}
  <input type="hidden" name="action" value="entries/save-entry">
  <input type="hidden" name="entryId" value="{{ userentry.id }}">
  <input type="hidden" name="enabled" value="1">
  <input type="hidden" name="fields[matrixhandle][new1][type]" value="antworten">
  <input type="hidden" name="fields[matrixhandle][new1][enabled]" value="1">
  <input type="hidden" name="fields[matrixhandle][new1][fields][teilnehmer]" value="{{currentUser.username}}">
  <textarea id="antwort" name="fields[matrixhandle][new1][fields][antwort]">
  <input type="submit" value="Antwort speichern">
</form>

The Problem is the Entry gets completely overwritten. The new Matrix block is saved correctly, but old blocks of the entry are discarded.

I see the possibility to read the old entry and add the old Matrix blocks as new ones, but this would not scale good and doesn't feel right.

How can I add new Matrix blocks to an existing entry with a front-end form?


texts: How to get my craft projectConfig settings inside JS on the front end

texts:
So I am trying to work with twig templates and I want to inject my project configuration in my js so I can use it.

I can do this

{% set admin_email = craft.app.projectConfig.get.email.fromEmail %}

And this gives me access to {{ admin_email }} anywhere in the document, just like <?php echo $admin_email ?> would do.

But I want to access these settings inside my JS as well. I have some tokens and other things stored inside there.

I tried doing this:

{% js %}
    let admin_email = {{ admin_email }};
    console.log(admin_email);
    alert(admin_email);
{% endjs %}

But in vain. How do I get the settings inside my JS variables?


texts: orderBy title, but remove the word "The" from titles

texts:
If I have a huge list of TV shows and Movies, many of them have "The" in the title, meaning they all get grouped together if you order by title.
Is it possible to "filter out" a word in entry titles when using orderBy?
{% set entries = craft.entries().section('media').orderby('title asc').limit(24).all() %}


texts:
I have setup 10 languages for a project which are all working fine when accessed directly, eg 'craft.dev/fr/page','craft.dev/zh/page','craft.dev/es/page'.

However when in admin there are two ways of previewing the translated content.
Side by side preview shows the translation fine and uses an admin URI with the locale on the end of the admin url.
But if you external preview the local is not in the URL so throws a 404.

Is this a missing feature or a config issue? I was expecting the locale to appear in the external url

Update

My config looks like

'siteUrl' => array(
    'en' => 'http://craftyCMS.dev/en/',
    'ar' => 'http://craftyCMS.dev/ar/',
    'zh' => 'http://craftyCMS.dev/zh',
);

Share link never has the locale in it.


texts:
I'm working with Solspace Calendar and need to allow guest access to post events to a calendar. I'm currently only working with the demo templates and have guest access turned on. But I seem to be getting a Craft internal server error when trying to load the Create Event form.
The form does display if I log into the site which suggests that the guest access option isn't quite working. Can anyone help me with this? Is there another setting I may have forgotten?


texts: I have a blog. I want to output an entry author's first and last name. What is a good method to accomplish this?


texts: Form fields not visible after creating content fields using A&M Forms plugin

texts:
I'm new to Craft 2, and I created about 20 new form fields in the Settings>Content>Fields section.  I created a new group for them to go in.

Then, I went to create a new Form, but I cannot see those new form fields.

Is there a way to see them?  Thanks


texts:
Weird issue where a tag was not found using the tags search query.  That tag is in the CMS (in news entries) as well as the DB, and even shows up in other queries.  Query in question:

{%
    set tag = craft.tags({
        search: { query: slug }
    }).limit(1)
%}

All but this tag can't be found for some odd ghostly reason.


texts: Map one asset attribute field to another using MySQL

texts:
In Craft, is it possible to map one field containing string value to another?

I have a bunch of image assets that has a title field and altTag fields. I've entered data into the alt tag field, but now I would like to copy that data for each asset into the title field for that same asset.

Doing this manually for each asset would take forever, but it sounds like something that could be done with mysql queries.

I poked around the database to see where the title fields or the altTag fields are stored. The altTag field is in the craft_fields table, and I can see all my assets in the craft_assetfiles table. But title is not one of the columns in this table, I do see the filename column. But I think my knowledge of the structure of craft tables are lacking to find where the values for the altTag fields are stored or how to copy the value of each alt tag into the corresponding title field for the asset.


texts: getting the current user entries from elementapi

texts:
How do I use the elementapi to get the list of entries for the logged in user?

I've tried a couple of options to no avail, like

'api/v1/user/<userId:\d+>.json' => function($userId) {

            $author = craft()->users->getUserById($userId);

            return [
                'elementType' => 'Entry',
                'criteria' => [
                    'section' => 'jobs',
                    'author' => $author
                ],
...

as an example of one I thought should have worked but it just returns everything.


texts: Craft Commerce: No Emails sent on Default Order Status

texts: I noticed while doing some testing that assigned emails for the default order status do not get sent. An email does get sent on every other order status change without any problems. Has anyone else had this issue?


texts: Entry template category loop repeats URI when HTML added

texts:
My entry template looks for the category of the entry

{% for category in entry.productCategory %}
      {{ category.uri }}
{% endfor %}

This will output products/[category slug] as I intended. There is only one value in the loop.

As soon as I wrap the category URI in HTML like this:

{% for category in entry.productCategory %}
     view
{% endfor %}

The URI doubles: eg the output is repeated so the template renders {{ category.uri }} as

products/[category slug]/products/[category slug]

Am I missing something in the loop / or Twig behaviour?


texts:
I am trying to insert records into the same entry using FeedMe with Matrix and Table for one of the fields.  My table field is a plain text.  So I have one programLevel, one program and a field that collects many text entry lists in a Table field.  No matter what I do, depending on the structure of the JSON.  I either overwrite the record already there or it gets 2 entries into the Matrix field but combines all the plain text entries into the Table field (code below).  Not sure what I am doing wrong here.

Basically I end up with 2 Matrix entries but a combined Table field called Lists.  Basically, Test text 1, Test text 2, Test text 3, etc in the Table field for both Matrix records in the entry. Is there a proper way to get this formatted correctly please?

[
    {
        "title":"Test Entry",
        "programs": [
            {
                "programLevel":"Alpha",
                "program":"Vector1",
                "listItems": [
                    "Test text 1",
                    "Test text 2"
                ]
            },
            {
                "programLevel":"Beta",
                "program":"Vector1",
                "listItems": [
                    "Test text 3",
                    "Test text 4"
                ]
            }
        ]
    }
]


texts: How to create a migration for the main Craft DB?

texts:
Let's say we add a section or other elements (field, category, tags, assets, etc) in the CP on our dev servers and want to roll that change out to a stage or production environment, is there a way to capture the changes we've made through the CP as a migration, or is there some other recommended way to reverse engineer that into a migration?

I have checked out the documentation on creating plugin migrations and a couple of questions here and here, but nothing addressing creating a migration for the craft DB itself.


texts: Need to access each item's converted price from payment gateway

texts:
I am trying to implement multi currency to my payment gateway plugin.

I need to get converted price of the line item. Each item from Omnipay\Common\Item has the price of non converted, main price of the item.

This cause trouble because my payment gateway adds the line items and matches sum of all individual items to total sum of paid amount.


texts: Cache not invalidating when new entry is created

texts:
I realise this is probably a duplicate of the other questions just like it but I thought I'd raise it here before filing a bug with P&T.

Basically, when a new entry is added to a section, the template cache isn't invalidating. Here is the template in question, is there anything in the code that would cause this?

    {% extends "_layouts/two-col" %}

    {% block main %}

        {% cache unless not craft.config.cache %}

        {{entry.body}}

        {% set cutoffDate = now|date_modify('- ' ~ '1' ~ ' days') %}
        {% set events = craft.entries.section('whatsOn').order('dateStart') %}

        {% set eventIds = [] %}
        {% for event in events if (event.dateEnd ? event.dateEnd : event.dateStart) >= cutoffDate %}
          {% set eventIds = eventIds|merge([event.id]) %}
        {% endfor %}

        {% set allEvents = craft.entries.id(eventIds).fixedOrder('true') %}

        {% paginate allEvents.limit(12) as events %}

            {% for event in events %}

                            <time itemprop="startDate" content="{{event.dateStart}}" datetime="{{event.dateStart}}">{{event.dateStart|date("jS F Y")}}</time>

                            {% if event.dateEnd|length %}
                                — <time itemprop="endDate" content="{{event.dateStart}}" datetime="{{event.dateStart}}">{{event.dateEnd|date("jS F Y")}}</time>
                            {% endif %}

{{ event.title }}

                            {{event.eventType}}
                             {{event.location}}

                        Find out more

            {% endfor %}

        {% if paginate.totalPages > 1 %}

                {# First Page #}
            {# {% if paginate.prevUrl %}Previous Page{% endif %} #}

            {% for page, url in paginate.getPrevUrls(5) %}

                {{ page }}

            {% endfor %}

{{ paginate.currentPage }}

            {% for page, url in paginate.getNextUrls(5) %}

                    {{ page }}

            {% endfor %}

           {#  {% if paginate.nextUrl %}Next Page{% endif %}
            Last Page #}

        {% endif %}

        {% endpaginate %}

        {% endcache %}

    {% endblock %}

    {% block sidebar %}

        {% include '_partials/newsletter-signup' with { grid:'false' } %}

        {% include '_partials/social' %}

    {% endblock %}

If this all looks normal, I guess it is a bug with Craft?


texts: On users page I want to display the users of their own group not any other group, how can I override this in backend?

texts:
I have 6 roles in the application, each role has different responsibility, now one role has the responsibility to change/modify user details only of his own group.
The problem first here is, he is able to first of all see all the users in the list, that should not happen.
Next he should not be able modify other user groups details.
Also for creating any new user, automatically those new users should come under the user group which this admin user belongs to.
Is there any overriding way where we can do all these tasks?
Can you help me in this?


texts: Front end Entry form with validation error support?

texts:
The official example ( https://craftcms.com/docs/templating/entry-form ) seems to assume that the form itself is not already on a page which is an Entry. Dropping this form into a template that has an entry loaded already spits out that entry's entry.title or entry.body.

How should this work? We want the "new entry form" to live on a page that the client controls the content for.


texts: How can I get the count of entries in a structure?

texts:
I'm using this in the root of a structure to try and get the count of entries in another part of the structure.

{% set count = craft.entries.section('hotelDetails').descendantOf('oakview-hotel').level(3).type('review').total() %}
        {{ count }}

But it's including entries from other hotels, I hoped descendantOf('oakview-hotel') would restrict the count to only oakview-hotel. When I replace escendantOf('oakview-hotel') with descendantOf(17) 17 being the ID oakview-hotel the count is restricted to oakview-hotel and the entry count is correct.

Ca anyone please telly me why descendantOf('oakview-hotel') isn't working for me or suggest a better way to do this?


texts:
My client needs to input apostrophes in text fields for staff names, such as ’ or just the plain ' and as you can imagine, it is causing issues.

I have tried this replace({'\'',''}) and this replace({'\&rsquo;',''}) but to no success. Thoughts?


texts: Create a New Entry with Fields Populated from an Existing Entry Table

texts:
I am still learning how to work with craft on the back end but so far I can see it is a very powerful platform!
I was wondering if there is a way that within an existing entry channel say "foo" I have an entry comprised of a table made up of multiple numerical values under specific headings (say column A has a value of 1, B:2, C:3,..Z:X)- I was wondering if there is any way that I can grab the values in columns A:1 and B:2 from the table entry in channel "foo" and create a new entry under a different existing channel "bar" where those two values A:1 and B:2 are pre-filled in the new entry type form?
Apologies if this is confusing- I am attempting to eliminate the steps involved in copying values from one entry type (large table of values) to another entry type (a form made up of fields that make up content on the front end of the site) and consolidate it into one step where I can find the row containing the values I need in channel "foo" and just click to create a new entry type with those values pre-populated in channel "bar"- eliminating the need to copy and paste the values.
I am not sure how to tackle this or where to begin as I am still new with the platform.
Thank you in advance for any help!


texts:
The project that I'm working on requires that I generate an EAN13 barcode for display on vouchers.

I'm attempting to implement the following as a Craft Plugin: https://github.com/rlt3/php-barcode

The part that I am unclear about is how exactly to define my Model to return an image to the calling template. Do I even need a Model ?


texts:
I have a page which lists assets by source. I've added a date field to the asset.

How can I order the assets by this field so that the most recent is first?

Here is my markup:

{% set assets = craft.assets.find({sourceId: 2}) %}

{% for asset in assets %}
    {{ asset.date | date('M Y') }}
{% endfor %}

Looking at the cheat sheet for Assets it seems that these are my only options for order:      title, id, sourceId, folderId, filename, kind, width, height, size desc'.

Ideally I could do something like this:

{% set assets = craft.assets.find({sourceId: 2, order: '{{ asset.date }}'}) %}


texts: Accessing the raw post data from an $event

texts:
My users have an accountBalance field and there's a createInvoice service in my plugin. I'd like to autogenerate an invoice whenever the accountBalance changes (including from the admin cp), while optionally passing in extra invoice info. Is there a way to access the raw post data from the event to check for extra info like invoice skus and descriptions?

In my plugin I have the following code.

craft()->on('users.onBeforeSaveUser', function(Event $event)
{
    $userId = $event->params['user']->id;
    $user = craft()->users->getUserById($userId);

    //raw post data is private so these lines are pseudo code
    if ($extraPostData != null)
    {
        $desc = $event->params['_rawPostData']['invoiceDescription'];
        $sku = $event->params['_rawPostData']['invoiceSku'];
    }

    $oldBalance = $user->accountBalance;
    $newBalance = $event->params['user']->accountBalance;
    if ($newBalance != $oldBalance)
    {
        $balanceDelta = $newBalance - $oldBalance;

        //plugin service has defaults if $desc/$sku are empty or null
        craft()->myPlugin->createInvoice($balanceDelta, $userId, $desc, $sku);
    }
}

Alternatively, is there a way to disable adjusting the accountBalance user field from the admin cp?


texts: FeedMe + Google Maps plugin Address fields missing

texts:
Just upgraded to GoogleMaps plugin (from SmartMap) and trying to replicate FeedMe feeds.
When I go to assign field -> feed element, I see

my regular entry field
I don't see the address sub fields, but rather just a singular address field.

I don't see the subfields as displayed here:
https://plugins.doublesecretagency.com/google-maps/guides/importing-addresses/#feed-me
Halp?


texts: Only executing if a matrix checkbox has a specific value

texts:
I currently have checkboxes in a matrix block that allow a user to select where an image will be placed in the layout (as a featured slider image and/or in an image gallery). I've gotten the slider image to function but if, for some reason, there are no featured images I have a couple of unnecessary
 tags. Because I am selecting only featured images from the matrix block I can not use loop.first and loop.last to move those divs in my for loop.

I had seen an article that seems close to finding the answer to my problem here : Only execute twig block if a Matrix radio has a certain value but I haven't been able to make it work.

Any help would be greatly appreciated.

{# Add Feature Images - Slideshow #}
    {% set photos = entry.photoGallery.type( 'photos' ) %}
    {% if photos|length %}

                {% for block in photos if block.imageLocation.contains('featured')%}
                    {# Get the photo #}
                    {% for photo in block.photo %}

                        {# Get the caption #}
                        {% if block.caption|length %}

{{ block.caption }}

                        {% endif %}

                    {% endfor %}
                {% endfor %}

    {% endif %}

I've attached a screen snapshot of my field setup.


texts: Omit Featured Entry from loop of entries with additional omissions

texts:
I have a homepage single section has a field for entries (only 1 can be selected).
This field is called featuredEntry.

In my homepage template (index.html) I set a variable {% set featured = entry.featuredEntry %} for the field
I then loop thru that to pull in that entries content {% for mainEntry in featured %}

I have a listing of entries below it that pull from the same News channel as the featured entry above.
I don't want the featured entry to show in that list.

I followed the answer here (Exclude "featured" entries from a "recent" entries {% for %} loop) with slight changes to try and omit that entry.

However, setting a variable {% set featuredIds = featured.ids() %} for the above featured entry doesn't seem to work.

I am omitting additional entries that are marked with a certain tag as explained here:
List entries without specific tag

What am I missing here or what is wrong for my code to not pull in that id of the featured entry?

{% set featuredIds = featured.ids() %}

{% set mainTag = craft.tags.search('All-Stars').first() %}
{% set allEntries = craft.entries.section('news') %}
{% set taggedEntries = craft.entries.section('news').relatedTo(mainTag).ids %}

{% set omitIds = 'and, not ' ~ taggedEntries|join(', not ') ~ allEntries|join(', not featuredIds') %}
{% set untaggedEntries = craft.entries.section('news').id(omitIds) %}

{% for feedItems in untaggedEntries.limit(5) %}

In that code above in the omitIds variable, if I do this:
{% set omitIds = 'and, not ' ~ taggedEntries|join(', not ') ~ allEntries|join(', not SPECIFIC ID') %}

It works.

Thanks in advance.


texts: How do I print the name of the Section on an index page

texts:
I have an index page for articles in a section.  Call the section "dogs."

How do I template to output the name of the section?  This is not an entry, but an index page.


texts: DB not connecting on Namespro linux server

texts:
I am not a developer nor do I have a technical background, striving to solve a lingering issue with our it/hosting company. This means I unfortunately can't supply code for reference; simply seeking community support if anyone has encountered a similar issue.

We launched a new site that is configuring on the Namespro server but not connecting to the Craft Pro CMS DB. It seems to be a port or permissions error but our hosting company hasn't been able to resolve the issue for a couple of months now. The site has been live and encountered zero issues launching on our developer's digital ocean droplet.

Any thoughts??? Don't want to waste anyone's time but hopeful someone has encountered this issue with Namespro before.

Thank you in advance.


texts:
I could not find it in the docs and hope someone that has used it before can answer it.

How does Solspace Calendar handle location data.  I did not see a way to add a location like Venti 2 has.  Right now I am using VZ Address in conjunction with Calendar. Is that the best way to go about achieving an address for an event with Solspace Calendar?


texts: Pass Craft Instance to A Vendor PHP File

texts:
I created my own class file that I include in one of my Craft Services files. Is there any way I can access the craft instance inside of this file?

For example, inside my Craft service I create a new instance of my class like:

$wally = new Wally();

Inside of the actual Wally class file, I'd like to be able to create a variable in my constructor that gives me access to stuff like this:

craft()->elements->getCriteria(ElementType::Entry);

For further clarification:

class Wally {
   function __construct($craftInstance) {
      $this->craft = $craftInstance;
   }
}

If it sounds like I don't know what I'm doing, I probably don't. Any help would be appreciated. Using Craft 2.6 btw.


texts: Twitter API request for images with DUKT twitter

texts:
I am using DUKT's Twitter 1.0.32 but am fresh at reading APIs, so would like a little help.
I would like to request tweets with image only from our main ID.

 {% set tweets = craft.twitter.get('statuses/user_timeline', {count:3}) %}

This works fine, but even an attempt to play around with the other parameters within user_timeline baffles me.

Could I ask for some examples to display tweet text & image, plus some other relevant parameters?


texts:
I'm using Feedme to add entries via an external JSON feed.
There was an issue with matching duplicates and now need to remove >4000 entries from the site.

To avoid further issues would ideally like to build this into the feedme script we are running but the built-in delete method times out due to memory issues. I've looked at other ways we can achieve this, eg by deleting via the entries model:

$entriesRecord = EntryRecord::model()->findAllByAttributes(array('sectionId' => $sectionId));
$entriesRecord->delete();

But this is also timing out. Mike Pepper pointed me in the direction of the a&m command add-on at https://github.com/am-impact/amcommand but this is also struggling. Is the only way to deal with such large quantities of entries to do this directly via SQL?

Help!


texts: Image Transform change causes 500 Internal Server Error

texts:
I had an image transform set on an entry that was working as expected. I updated the code, and it didn't work, so I reverted back to the old transform. It was literally going from

src="{{ image.getUrl('featuredImage') }}"

to

src="{{ image.getUrl('cardImage') }}"

The image didn't load, so I reverted back to featuredImage, and it still isn't working. I checked my server logs and there wasn't anything noticeable. In my dev console the request URL is Request URL:https://example.com/index.php?p=actions/assets/generate-transform&transformId=1 and Status Code: 500 Internal Server Error

Any thoughts?

Thanks in advance!


texts: How do I apply taxes to subscriptions with Stripe plugin?

texts:
I need to apply taxes to subscriptions. How do I do that? The idea is that prices are first shown without taxes. Then – on the payment page – I need some kind of "bill" that shows all the relevant infos and charges the correct price (subscription plus taxes):

Monthly Subscription    5€
VAT                  0,95€
--------------------------
SUM                  5,95€

Is that even possible with commerce-stripe at the moment?

Cheers,
Mark


texts:
I'm trying to use a custom action with Charge. When a successful charge has been made I want to edit a user field. Charge appears to have Actions but little documentation on how they should be used ( http://demos.squarebit.co.uk/charge/actions )

So, I had opened charge/services/Charge_ActionsService.php and created a new one in there, which worked...

private function triggerActionCredits($details, ChargeModel $chargeModel)
{
    craft()->charge_log->action('Credits action triggered successfully');

    if (!is_array($details)) {
        craft()->charge_log->action("Details passed were: $details");
    } else {
        $detailsAsString = print_r($details);
        craft()->charge_log->action("Details passed were: $detailsAsString");
    }

    $userID = $chargeModel->userId;
    $theUser = craft()->users->getUserById($userId);
    $currentCredits = $theUser->creditsAvailable;

    craft()->charge_log->action("Got the user: $theUser");
    craft()->charge_log->action("Current credits: $currentCredits");
    craft()->charge_log->action("Details passed were: $detailsAsString");

    ... do stuff ...

    return true;
}

However, this should really be a plugin - so I've tried to port that code out of the Actions file and into its own plugin as follows:

public function init()
{
    craft()->on('charge.onCharge', function($charge){
        craft()->charge_log->action('Credits action triggered successfully');

        $pounds = $charge->amount;
        ...
}

The problem is that the line $pounds = $charge->amount; is throwing an error:

Property "Craft\Event.amount" is not defined

But; the event should be getting a Charge model? What am I doing wrong? http://squarebit.co.uk/software/craft/charge/usage/developer/hooks-and-events & http://squarebit.co.uk/software/craft/charge/usage/models/charge-model


texts: Triggering mailshot when new entry published - solutions?

texts:
A client has a Campaign Monitor email list that he wants his new site to integrate with. We want to have a form that adds new subscribers to the list, and we also need to trigger a mailout to the list when a new blog post is published (not saved, but published on the site). He also wants the text of the blog post in the email that's sent out.

We are struggling to think of a solution that would work and can't find a plugin that would do the job. Sprout Email almost does it, but the Notifications part of that plugin doesn't hook into Campaign Monitor.

Anyone got any ideas for solving this?


texts: How to get the nginx deny functionality to work for Heroku using heroku-buildpack-nginx?

texts:
I am a novice to Nginx, but I have my app hosted on Heroku and I am using heroku-buildpack-nginx to add Nginx on my project. There is a Fastly layer in front of the app, but I am trying to use Nginx's deny functionality to block an IP. Though have found that nothing happens when I add it. My nginx code is below and I have tried adding the deny at the top of the file and in the location block. For both of those attempts nothing happened on the url. I also attempted adding a server block, but that broke everything and heroku threw an error stating that the server block is not meant for that file. Am I missing something?
client_max_body_size 0;
deny 00.000.00.000; // My ip address

location / {
    deny 00.000.00.000; // My ip address
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /index.php$1 last;
}

# php-fpm configuration
location ~ [^/]\.php(/|$) {
    try_files $uri $uri/ /index.php?$query_string;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_pass heroku-fcgi;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS on;
    fastcgi_param PATH_INFO $fastcgi_path_info;

    # Security headers via https://securityheaders.io
    add_header Strict-Transport-Security "max-age=31536000; preload";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    add_header Referrer-Policy "no-referrer-when-downgrade";

    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}


texts:
We are building a family community website with more than 600 members all over the world.

In craft.users we have added many fields and one of them is country.

We want to display and count all countries.

Example of the desired output could be something like:

Our members are living in the next 5 countries

the Netherlands (545)
Chili (26)
USA (14)
Italy (6)
Sweden (8)


texts: How html title is generated in entry index page in CP

texts:
I am trying to find out how HTML title is generated in entry index page in Control Panel.

i know it is generated in src/templates/_elements/element.html file   by $this->hook('cp.elements.element', [$this, '_getCpElementHtml']); in src/web/View.php and i see there is a line in entry.php which calls author with

return $author ? Craft::$app->getView()->renderTemplate('_elements/element', ['element' => $author]) : '';

but i can't find how craft calls for title attribute.?


texts:
IM running into an issue where I have one page that lists latest restaurant entries in a given section. However I also have a form to filter the entries by postcode (a category element and by cuisine type (tag element).

I'm also required to give some rudimentary search functionality, which for now is governed by a seperate form. Both forms redirect to the same root page,

Here i my slimmed down code

{% set restaurants = craft.entries.section('restaurants').limit(null) %}
{% set locations = craft.categories.group('postcode').relatedTo(restaurants).limit(null) %}
{% set types = craft.tags.group('imageTags').relatedTo(restaurants).limit(null) %}

{% set l =  craft.request.getParam('l') %}
{% set t = craft.request.getParam('t') %}
{% set q = craft.request.getParam('q') %}

{% set locId = craft.categories.group('postcode').slug( l ).ids() %}
{% set locName = craft.categories.group('postcode').slug( l ).first.title %}
{% set typeId = craft.tags.group('imageTags').name( t ).ids()  %}

{% if (l or t) %}
    {% set relatedTo = ['and'] %}

    {% for id in locId %}
      {% set relatedTo = relatedTo|merge([id]) %}
    {% endfor %}

    {% for id in typeId %}
      {% set relatedTo = relatedTo|merge([id]) %}
    {% endfor %}

{% else %}

{% endif %}

{% set params = {
        section : 'restaurants',
        limit: 24,
        relatedTo: relatedTo ? relatedTo,
        search : q ? q,
        }
%}

{% set entries = craft.entries(params) %}

Pagination and for loop

{% paginate entries as galEntries %}

                {% for entry in galEntries %}

                    {% include 'restaurants/includes/_rest-item' %}

                {% endfor %}

{% endpaginate %}

My form elements

<form action="{{ url('restaurants') }}" method="get" action="" class="rest-filter">

            <label>Filter :</label>

            <select name="l" id="">
                <option value="">All Locations</option>

                {% for loc in locations %}
                <option value="{{ loc.slug }}" {{ loc.slug == l ? 'selected' }}>{{ loc.title }}</option>
                {% endfor %}

            </select>

            <select name="t" id="">
                <option value="">All Types</option>

            {% for type in types %}
                <option value="{{ type.name }}" {{ type.name == t  ? 'selected' }}>{{ type.name | capitalize }}</option>
            {% endfor %}

            </select>

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

        </form>

        <form action="{{ url('restaurants') }}" method="get" action="" class="rest-search">
            <input type="text" name="q" class="text" value="{{ searchq }}" placeholder="Search for restaurants&hellip;" required />
                            <button type="submit"  class="ss-icon sn-search-button">Search</button>
        </form>

It works for the most part except for when I only filter by one element. Which throws the following error CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1116 Too many tables; MySQL can only use 61 tables in a join

ANy ideas where I'm going wrong?


texts: Plugin FieldType giving error on live server - fine locally

texts:
I have a plugin with a FieldType - I used the CocktailRecipes plugin as a template.

It extends BaseFieldType; it has 3 methods (getName, defineContentAttribute [AttributeType::Mixed] and getInputHtml)

It it working fine on a local PHP install.

However, on the server, when I create a new field, the plugin's custom field type isn't listed in the drop-down; this works fine on my local PHP install.

If I use my local install connected to the server's database, I can add the field type - but if I look at the field list in the admin back on the server, the field Type isn't the string returned but the getName function in the FieldType model (as it usually is) - it's the full class name, highlighted in red (it has a wrapping element with a class of "error").

I can't see anything in the log files about why - even in dev mode.

The only differences I can think of between my local and the server setups is that the PHP version is higher on the server - and the server OS is case-sensitive for file names.

I've checked the casing used, and it looks correct based on the CocktailRecipes plugin example.

It feels like the issue is that the class can't be found on the server, despite it being there; and perhaps a casing issue, which is being masked on my local machine, is the reason the issue isn't occurring locally.

Has anyone encountered this issue before? With no error messages being logged, I haven't had much luck digging out the issue.

What I'm basing it on:

<?php

namespace Craft;

/**
 * Ingredients Fieldtype
 *
 * Allows entries to select associated ingredients
 */
class CocktailRecipes_IngredientsFieldType extends BaseFieldType
{
    /**
     * Get the name of this fieldtype
     */
    public function getName()
    {
        return Craft::t('Cocktail Ingredients');
    }

    /**
     * Get this fieldtype's column type.
     *
     * @return mixed
     */
    public function defineContentAttribute()
    {
        // "Mixed" represents a "text" column type, which can be used to store arrays etc.
        return AttributeType::Mixed;
    }

    /**
     * Get this fieldtype's form HTML
     *
     * @param  string $name
     * @param  mixed  $value
     * @return string
     */
    public function getInputHtml($name, $value)
    {
        // call our service layer to get a current list of ingredients
        $ingredients = craft()->cocktailRecipes->getAllIngredients();

        return craft()->templates->render('cocktailrecipes/_fieldtypes/ingredients', array(
            'name'      => $name,
            'options'   => $ingredients,
            'values'    => $value,
        ));
    }
}

What works fine locally:

<?php
namespace Craft;

class ECOffers_OfferPeriodFieldType extends BaseFieldType {

    public function getName() {
        return Craft::t('Offer period');
    }

    public function defineContentAttribute(){
        return AttributeType::Mixed;
    }

    public function getInputHtml($name, $value) {
        $offer_periods = craft()->eCOffers_offerPeriods->getOfferPeriodsForLocale($this->element->getContent()->getAttributes()['locale']);
        $options = array();
        if ($offer_periods) {
            foreach ($offer_periods as $offer_period) {
                $options[] = array(
                    'label' => $offer_period->name.': '.$offer_period->fromDate->format('H:i D jS M Y').' - '.$offer_period->toDate->format('H:i D jS M Y'),
                    'value' => $offer_period->id
                );
            }
        }
        return craft()->templates->render('ecoffers/_fieldtypes/offerperiods', array(
            'options' => $options,
            'value' => ((!is_null($value)) ? $value:craft()->eCOffers_offerPeriods->getCurrentOfferPeriod($this->element->getContent()->getAttributes()['locale'])->id)
        ));
    }
}


texts: Propagate entries manually between sites

texts:
I have a client that wants to setup a multilingual site, but for the purpose of this site they only want certain entries to be translated.
If I setup sites that use a section which is configured to NOT propagate entries across sites, then I haven't found a way to link entries manually for entries that I DO want to propagate. Is this not possible? One could of course just create the entries manually, but then I loose the linking between them to provide a language switcher though. Also, I can't really re-save an entry on another site easily.
Is the preferred approach to do propagate and keep them unpublished? I feel that that makes it unwieldy very quickly...


texts: Image transforms return cpresources URL and doesn't apply crop

texts:
Despite having tried the tips from Image transforms returning cpresources url, I am still having issues with image-transforms.

the problem is when i put the image without transform it work fine, but when i add the transform parametre it vanish, and even i tried to apply transfom in the template, the image show up but without crop option, only adjust the width and height in the front.

I have tried clearing the cache and db table already as well as updating the asset index. I have double checked the sources paths and it is not a file permission issue.

I am running Craft Pro 2.6.2992

'generateTransformsBeforePageLoad' => true is set in craft/config/general.php

template-code :

          {% set  blocWith = "large-12" %}
          {% if block.image.first.url is defined %}
          {% set imageUrl = block.image.first.getUrl('imagewidthlarge') %}
          {% set imageHeight = block.image.first.getHeight('imagewidthlarge') %}
          {% set imageWidth = block.image.first.getWidth('imagewidthlarge') %}

      {% endif %}

                {% if block.heading is not empty %}
{{ block.heading }}
{% endif %}
                {% if block.subtitle is not empty %}
{{ block.subtitle }}
{% endif %}
                {{ include(template_from_string(block.text)|raw) }}

this is what the page-source looks like

vu front :

please i'm on a deadline on this projects i tryied all i could to work it out but still, i need this image transform to work


texts: JS login form on different domain and handling the CSRF token

texts:
Having sorted out the CORS issue and succesfully logging into Craft from a different domain using Javascript, I've now turned CSRF protection back on. I've got a module returning the CSRF token name and value fine. I fetch the CSRF token with a GET request, then use that token in my login form submission. But I cannot get past Craft being unable to verify the data submission. The same code works fine when run from the same domain.
Does anyone have any experience of doing this?
function fetchCSRFToken() {

    var url = 'http://server.localhost/actions/server-module/server/get-csrf';

    function status(response) {
      if (response.status >= 200 && response.status < 300) {
        return Promise.resolve(response)
      } else {
        return Promise.reject(new Error(response.statusText))
      }
    }

    function json(response) {
      return response.json()
    }

    return fetch(url)
        .then(status)
        .then(json)
        .then(function(tokenData) {
            return tokenData;
        }).catch(function(error) {
        });

}

function login(event, tokenData) {

    var rawAction = "http://server.localhost/" + event.target.action.value;
    var action = encodeURIComponent(event.target.action.value);
    var csrfTokenName = encodeURIComponent(tokenData.name);
    var csrfTokenValue = encodeURIComponent(tokenData.value);
    var loginName = encodeURIComponent(event.target.loginName.value);
    var password = encodeURIComponent(event.target.password.value);

    var data = "action="+action+"&"+csrfTokenName+"="+csrfTokenValue+"&loginName="+loginName+"&password="+password;

    var ajax=new XMLHttpRequest();
    ajax.onreadystatechange = function(){
        if(this.readyState == 4 && this.status ==200){
            console.log(this.responseText);
        }

    }

    ajax.open('POST', rawAction, true);
    ajax.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
    ajax.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

    ajax.send(data);

}

document.querySelector('#loginform-js').addEventListener('submit', function(event) {

    event.preventDefault();

    fetchCSRFToken().then(function(token) {
        login(event, token);
    });

});

And how I get the CSRF token from a module controller:
    /**
     * @return Response
     */
    public function actionGetCsrf(): Response
    {
        return $this->asJson([
            'name' => Craft::$app->getConfig()->getGeneral()->csrfTokenName,
            'value' => Craft::$app->getRequest()->getCsrfToken(),
        ]);
    }

EDIT: I suspect the preflight CORS request is invalidating the CSRF token? The preflight is only necessary on the remote server.


texts: Express Forms Not Sending Notification Emails

texts:
Craft 3.3.0.1
Express Forms 1.0.4

I have an Express Forms set up. It submits and saves entries to the DB which can be viewed in the CP, however email notifications are not sent.

Sending a test email via settings > email works as expected as does a different Express Forms form, but this one does not and I am flummoxed.

when I check the Express forms log I see this:

Here is a simplified template of my form where you can see the notification email address are set to a field in the page entry or if that is empty default email addresses are used.

{#
// set send email address from careers entry
#}
{% set sendEmailAddress %}
  {# loop through emails from job entry page and set the form to send to those emails #}
  {% for email in entry.applicationEmails %}
    "{{ email.emailAddress }}"{% if not loop.last %},{% endif %}
  {% else %}
  {# if empty send to this address #}
    "test@domain.com", "test2@domain.com"
  {% endfor %}
{% endset %}

{# this testing div outputs emails as expected #}

  {{ sendEmailAddress }}

{% set form = craft.expressforms.form("jobapplication") %}

{# General Error Handling #}
{% if not form.valid %}

        {{ "Error! Please review the form and try submitting again."|t }}
        {% if form.errors|length %}

                {% for error in form.errors %}

{{ error|t }}

                {% endfor %}

        {% endif %}

{% endif %}

{{ form.openTag({
   return: '?success=1',
   dynamicNotifications: {
      to: [sendEmailAddress],
      template: "job-application.twig",
   }
}) }}

  {#
    Various Fields here
  #}

  <button type="submit" data-application-submit class="btn btn-default" disabled>{{ "contact_submit"|t }}</button>

{{ form.closeTag }}

I've tried various approaches to using dynamic emails notifications but nothing seems to work.

My email notification template looks like this where {eMail} is the email field name in the form.

---
name: 'Job Application Email Notification Template'
description: 'submits job applications to reciever'
fromName: 'Strongco'
fromEmail: '$SYSTEM_EMAIL'
replyTo: '{eMail}'
cc: null
bcc: null
subject: 'Job Application: {positionAppliedFor}'
includeAttachments: true
---

The following submission came in on {{ dateCreated|date('l, F j, Y \\a\\t g:ia') }}.

    {% for field in form.fields %}

{{ field.label }}: {{ field.valueAsString }}

    {% endfor %}

Please advise.


texts: Is Craft a good fit for a project w/ social network features?

texts:
I'm wondering if Craft would be a good fit for a project that would require social features like:

users being able to submit content to the site
users being able to 'like' content
users being able to create 'folders/collections' and add/save content in them
users being able to follow each other to keep up with each others content


texts: Search across Entries and Assets and paginate combined results

texts:
I need to search both entries and assets and paginate the combined result.

I have tried:

{% set entries = craft.entries.search(query|trim).order('score').status('pending, live').find() %}
{% set assets = craft.assets.source('documentLibrary').search(query).find() %}
{% set searchResults = entries | merge(assets) %}

But then I can't get paginate to work:

{% paginate searchResults as results %}

... brings up the following error:

  Argument 1 passed to Craft\TemplateHelper::paginateCriteria() must be an instance of Craft\ElementCriteriaModel, array given

If I don't use a .find(), I can't merge the two objects.

Any ideas how this can be achieved?


texts: Multi-site - Setup remote asset volume to store assets on a per site/folder basis

texts:
We've got a Craft 3 (3.1.25) multi-site setup with three sites:

Corporate (default)
Brand A (brandA)
Brand B (brandB)

For this install there's 3 users setup with the following access to the sites.

User 1 (Admin - all sites)
User 2 (Brand A)
User 3 (Brand B)

The site has an 'Images' asset volume (remote - S3) for images to be uploaded into.

What we're trying to work out is how to make images uploaded into an asset volume specific to the site they relate to and make sure users can only see/edit images relating to the site they have access to.

It would be even better we could store them like below:

S3/images/brandA/
S3/images/brandB/

When you access the asset folder via the CP you can see the site switcher at the top - but when uploading via this area the assets are automatically appearing under all sites (when logged in as User 1).

This is especially important for the 'Products' section we've created that uses a 'Product Image' asset field that we've created. We want User 2 & 3 to see only the images relating to the site that the entry they're editing is related to.

There is a similar question below but doesn't entirely answer how to achieve the above.
How to setup assets in multi site where each site should have its own assets?


texts: I have a rich text output section I want to limit to specific number of characters or words. So user able preview the blog post and link to the full blog. I try  entry.body|slice(0, 100) ~ '...'. But it slice of my html tag and display html code in front end.


texts:
I have a section named Contest.
In there, you can choose a Solspace Freeform using its fieldtype.
I am using the cp.entries.right-pane hook to show the editor the number of submission directly in the Contest edit view.

I want to put a link : "Show submissions"
How can I (pre) filter the submissions for a given form knowing that Solspace  dosen't have a route for this and uses only JS ?


texts: Multiple dropdown filters interfering with each other

texts:
I have a multiple dropdown filters that lets users pick the category that they want to display results for below. See my previous question Search entries by location or name for screenshot.

So I have one working, but I need some guidance on how to do the code for the other filters as well, as currently my code for linking up to the second filter is stopping the first filter from working correctly. So clearly I'm doing it wrong.

So I have four dropdown filters, but I'll simplify it to two filters for this example. The filters are named name="county1" and name="development1" in their respective  tags.

And then I'm using the following to access them:

{% set query = craft.request.getParam('county1') %}
{% set query = craft.request.getParam('development1') %}
{% set queryFilter = craft.categories.group('developments').search(query).order('title asc') %}

{% for category in queryFilter %}

....markup...

{% endfor %}

Can someone tell me what i need to do to fix this so that the filters don't interfere with each other?


texts: How to calculate the number of hours left?

texts:
This question relates to my previous question on stackexchange about the difference in days between 2 dates. This ended up being the working solution:

{{ date( inschrijven.datumEvenement|date ).diff( now ).days }}

So the same question applies but this time how can I calculate the number of hours left between ( now ) and a future date {{ inschrijven.datumEvenement }}?


texts: Correct IAM settings for Amazon S3 bucket

texts:
I'm trying to setup an Asset source on S3, but i'm having trouble getting the correct permissions.

This is my current policy file:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": [
                "arn:aws:s3:::"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::bucketname"
            ]
        },
        {
            "Sid": "Stmt1456139254000",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::bucketname/*"
            ]
        }
    ]
}

This gives me "Permission denied" when trying to list the buckets.


texts: How do I use the section Entry URL format for registerSiteRoutes() in a plugin?

texts:
I'm trying to register a site route in my plugin based on the Entry URL format for a section chosen in the plugin settings.

So if it's the default news section in the Craft install the URL format stored in the database would be: news/{postDate.year}/{slug} or for an About single section it would be: about.

I want to add /login to the end of the url:

e.g. news/2016/amazing-title/login or about/login

Then use a login template (e.g. news/_login) in the section for this registered route.

I know how to manually do this with registerSiteRoutes() and the setting stored in a plugin service:

public function registerSiteRoutes()
{
    $section = craft()->pluginName->getSettingsSection();

    return array(
        $section . 'REGEX\/login' => $section . '/_login'
    );
}

What's the best way to convert the Entry URL format for the section into something that can be used in the return array of registerSiteRoutes()?


texts: Asset Upload via Plugin - S3 gets wrong Content-Type

texts:
I have a plugin that creates a local JSON file and uploads it to S3 using insertFileByLocalPath. The file is created, saved, and uploaded to s3 successfully. However, S3 detects the content-type to be text/plain and not application/json. Does anyone know of a way to force the content-type when creating an asset?

    $jsonStr = json_encode($arrayToBecomeJson);

    $fileName = $myFileName . '.json';

    $tempPath = AssetsHelper::getTempFilePath('json');

    file_put_contents($tempPath, $jsonStr);

    $assetSaveSuccess = craft()->assets->insertFileByLocalPath(
        $tempPath,
        $fileName,
        $assetFolderId,
        AssetConflictResolution::Replace
    );


texts: How to set a button's active state in WYSIWG (Redactor plugin)?

texts:
I am currently writing a simple Redactor plugin which adds a button to the WYSIWYG editor in Craft 2. This one just formats the selected text like the existing bold button does.

Now, my problem is that whenever some text is marked as bold and the text cursor is placed onto that text then the bold button's state is changed to active – as expected.

Like so:

But the same thing with my custom button that is added by my plugin won't work. The button's state is still inactive.

Have a look on the official docs of Redactor about how to Add Sup and Sub Buttons which comes with an example plugin (including the plugin code and the resulting WYSIWYG). There a superscript (x²) button is added. Even that one doesn't work.

As you can see in the screenshot the superscript button (x²) doesn't change its state to active.

So, my question is:
How can I achieve that the superscript button (x²) gets active when placing the text cursor onto superscripted text within the WYSIWYG editor?

This superscript button is just an example. Of course, the solution should work for all other custom buttons as well.
Also, I assume that my code base is the same that you can find on the how-to page I linked above.


texts: Craft Commerce Product Options that increase price, but do NOT affect stock

texts:
My client wishes to sell artwork online. They're all one-off pieces and once one is sold, it should not be available to purchase thereafter.
However, the artwork needs to have an option to be framed which would increase the price.
I can't see how this can be achieved with Variants as each variant has their own stock level.


texts:
I'm wondering what the best way to export order data from Craft Commerce would be for the client's order and revenue reporting.

Ideally they'd like to be able to export a report after filtering by date on the Commerce > Orders screen, which I think would also be a great feature request.

For now it looks like Sprout Export might be the only/best option. I'm wondering if this has come up for anyone who might have other suggestions?


texts: Fatal error: Class 'Craft\FileCache' not found when trying to install

texts:
I've been trying to install Craft on a DigitalOcean server. I used DO's LAMP stack application on Ubuntu 14.04 and downloaded the latest version of Craft. After uploading everything to my web root (the default is /var/www/html so the craft folder is at /var/www and the contents of public are at /var/www/html), whenever I try and go to the website, I get an error saying: "Fatal error: Class 'Craft\FileCache' not found in /var/www/craft/app/services/CacheService.php on line 59". If I go to example.com/admin, I get an Apache 404 error. If I try example.com/index.php/admin, I get the same fatal error as I described above.

I know this means I need to enable mod_rewrite (I've already renamed htaccess to .htaccess), but I should still be seeing something. I'm not sure what to do about the fatal error. I've redownloaded the Craft files to be sure nothing got corrupted in the original download, but I still have the same problem. I've also tried it on a server I have from A Small Orange and got the same thing. I also changed the required folders' permissions to 777 just to rule out any permissions problems.

Any ideas? Thanks!


texts: User Notifications/subscriptions to content

texts:
I'm quoting on a project where users need to recieve email notifications/subscriptions to content updates.
Essentially they should be able to login to the site and once on a page subscribe to that page to be notified when the entry is updated.
Is there a way to do this in Craft? If so what would be the best approach?


texts: HTTP 503 – Service Unavailable – craft\web\ServiceUnavailableHttpException [installation]

texts:
I tried installing Craft 3.0 using composer (php composer.phar create-project craftcms/craft PATH)

And when I try to access the /web folder it's giving me the following error. I have tried removing the folder and installing it afresh again. I am currently using MAMP on my osx localhost.

  in /Applications/MAMP/htdocs/craft/vendor/craftcms/cms/src/web/Application.php at line 498
  in /Applications/MAMP/htdocs/craft/vendor/craftcms/cms/src/web/Application.php at line 175 – craft\web\Application::_processInstallRequest(craft\web\Request)
  in /Applications/MAMP/htdocs/craft/vendor/yiisoft/yii2/base/Application.php at line 386 – craft\web\Application::handleRequest(craft\web\Request)
  in /Applications/MAMP/htdocs/craft/web/index.php at line 21 – yii\base\Application::run()


texts: Only allow one Lightswitch to be active at a time

texts:
I am working on a news section. There is a single featured news story so the lightswitch marked with ('1') displays the latest entry as the featured story.

Below this the rest of the entries are displayed so here I then display all other latest entries with the lightswitch marked with ('0') or in this case ('not 1').

My problem is that if two or three entries are all marked as the featured story (or a user creates an entry and marks it as featured then repeats a few days later and doesn't uncheck the previous one) then they will not display in the below section. Is there anyway to only allow one lightswitch to be checked as ('1') at any one time.

Featured entry:

  {% for entry in craft.entries.section('news').featured('1').limit(1) %}

All other news entries:

  {% for entry in craft.entries.section('news').limit(4).featured('not 1') %}


texts: Removing headers from blog post "excerpts" (using Hacksaw)

texts:
I'm using hacksaw to display the first part of my article on a blog listing page.

{{ entry.body|hacksaw(chars='300',allow='<p>', append='...') }}

The issue I have is when an article starts with a heading in it's body it looks like the attached. I'd ideally like to remove any headings from the excerpts.

As you can see the headings 'Reducing the size...' and 'Scaling' come through as plain text and the rest continues with my allowed

The only way I can think to do this is to allow their headings (h2 and h3) and then hide them in CSS, but I'm hoping there's a better way.


texts: Limitation of adding a Category from the CP field modal within an entry

texts:
Is there a way to either add a parent selector to the category field modal, or remove/hide the "+ New Category" button when editing an entry?

We are using a category group to contain Locations, which are nested as State > County > City. I recently noticed that several new Cities have been added to the site, but they are all at the root level instead of being nested under the correct State and County parent categories.

This is because when an author creates a new City via the Location field modal while adding or editing an entry, there is no visible way to specify a parent like there is when adding it from the main Categories CP area.

I can see this getting out-of-hand quickly without some way to keep these categories nested properly, so any advice would be appreciated.  Thanks!


texts: How can I follow relations in ElementCriteriaModels from plugin code?

texts:
In Twig code you can use craft->entries->relatedTo to do all sorts of neat things.

From plugin code I am not sure how this works?

$c = craft()->elements->getCriteria(ElementType::Entry);
$c->section = 'concepts';
$c->relatedTo(array('targetElement'=>$e, 'field'=>'entry'));
$concepts = $c->find();

This doesn't throw an error - but it doesn't work either.

How can I use the criteria model to retrieve entries that have some relationship?

Cheers!


texts: ElementCriteriaModel exclude list of ids

texts:
I'm trying to exclude a list of ids from a query using an ElementCriteriaModel

This is what I have so far, but it's resulting in nothing coming back when I'm expecting at least 1 result. Is something wrong with my syntax or is my method way off?

$criteria->id = 'and';
for ($i = 0; $i < count($idList); ++$i)
    $criteria->id .= ', not' . $idList[$i];

Also, I've tried removing the $criteria->id = 'and'; to no avail

A nudge in the right direction would be much appreciated

Thanks


texts: Invalid username or password, errorCode:0 but I'm using correct credentials

texts:
When I try to log in to CP as admin with correct credentials I'm getting "Invalid username or password" error and the response contains errorCode: 0 (I'm guessing CBaseUserIdentity::ERROR_NONE)

Weird part is that when I pull the same database to my local dev I can login using same credentials.

Only thing I can see in the logs is:

  Tried to restore session from a cookie, but the given login name does not match the given uid. UID: bd098373-8d73-4f6c-8326-9f5a2825f5a4 and loginName: Guest.

PHP can write into /craft/storage folder. I tried clearing out craft_session table, overridePhpSessionLocation => false and removing craft/storage/runtime/, nothing helped.

I'm using PHP7.1 and MySQL 5.7.


texts: Image Transforms not generated - permission problem?

texts:
Since I installed my Craft based website on the production server the image transforms are no longer generated. The tasks runs through more than 5000 images but doesn't generate new ones.
There have been other issues with permissions on this server we solved but we can't figure out what the problem is now, since there are no errors about this.
Does Craft use any temp folders or so when generating the image transforms? When I know which folders are affected I can check the permissions again.
PHP version                 7.4.10
OS version                  Linux 4.9.0-9-amd64
Database driver & version   MySQL 5.5.5
Image driver & version      Imagick 3.4.4 (ImageMagick 6.9.7-4)
Craft edition & version     Craft Pro 3.5.11.1
Yii version                 2.0.38
Twig version                2.12.5
Guzzle version              6.5.5
Imagine version             1.2.3-dev


texts: How to list an entries selected nested categories?

texts:
I have a entry field populated by categories. The number of categories an entry can have is unlimited and the categories are set up as nested categories i.e.

first level
---second level
------third level
first level 2
---second level 2
------third level 2

I want to be able to list out any categories selected at the third level that the entry may have selected if a certain parent category is identified. So far I have the following code. This works but lists all child categories for the identified parent instead of just the selected ones.

What am I missing?

{% set cats = entry.categories %}
{% for cat in cats %}
    {% if cat.slug == 'secondlevel1' or cat.slug == 'secondlevel2' %}
        {% set catChildren = cats.descendantOf(cat.id).descendantDist('1') %}
        {% if catChildren | length %}
            {% for childCat in catChildren %}
                {% set image = childCat.buildingBlockIcon.first() %}
                    {% if image %}
                        <img alt="{{ childCat.title }}" src="{{ image.url }}" />
                    {% endif %}
            {% endfor %}
        {% endif %}
    {% endif %}
{% endfor %}

----- EDIT Solution -----

I worked this out

by changing one line of code line 4 above from

{% set catChildren = cat.level(2).children %}

to

{% set catChildren = cats.descendantOf(cat.id).descendantDist('1') %}

Now works a treat. Any better solutions feel free to post.


texts:
I have recently been given access to a Craft site's control panel. I need to edit the homepage to add data in the footer. As I didn't create the Craft website, how can I access the HTML I need to add the code?
I've seen tutorials opening it from your localhost but as this is on an external server I am unaware how to access it.


texts: Issue trying to use function from DateTimeHelper class: "timeAgoInWords() is not defined"

texts:
Not quite sure how to use functions defined in Helper classes in my templates. For example, trying to use "timeAgoInWords" on an entry's dateCreated attribute. I get an internal server error and a "Unknown "timeAgoInWords" function" message when I try to visit the page. It occurs to me that perhaps I have to include or import the DateTimeHelper class? I'm not sure how to go about this.

Here's a link to the Craft docs on the package that I'm trying to include:

https://craftcms.com/classreference/helpers/DateTimeHelper

I'm trying to include the timeAgoInWords function in my index.html template within the templates folder.

Thanks a bunch!


texts: Craft 2 JS error in CMS since upgrade to 2.7.0

texts:
My Control Panel has stopped working since upgrading to Craft v2.7.0. in chrome. I get the following JS error no matter what is clicked in the entry fields and no action is taken. So for example if I want to remove and image and click the minus button nothing happens. If I try and add Matrix fields nothing happens. All of these were working prior to the update.

  Uncaught TypeError: Cannot read property 'length' of null
      at n.constructor.getWorkingTaskInfo (cp.js:863)
      at n.constructor.setTaskInfo (cp.js:832)

I'm running on PHP 7.0.13 any ideas?


texts:
How do you display select Fields from a Matrix Block Type when there are multiple Fields?

I have 1 Matrix Field with Handle ‘Quotation’

The configuration for this Matrix is as follows:

1 Block Type with handle ‘quote’

This Block Type has 3 plain text Fields:
‘Quotetext’
‘QuoteBy’
‘QuoteUrl’

I havent been able to get any output at all from this Matrix following the documentation and into following HTML structure:

Quotetext

    QuoteBy
    QuoteUrl

Can anyone help me solve this issue?
Thank you


texts: Display entries by category (multiple categories)

texts:
I would like to know how I can create a page that contains all entries from a section e.g. 'news'. I want to divide the entries by their given category.

News (section)

Category 1:

entry in category 1
second entry in category 1
third entry in category 1

Category 2:

entry in category 2
second entry in category 2
third entry in category 2

etc.

Does anyone know the code for this? The categories are all in the same category group.