I am creating a woocommerce custom shipping method. Its working fine, but when I use the shipping calculator it doesn't refresh.
<?php
/**
* Plugin Name: Expresso Jundiaí for WooCommerce
* Plugin URI: https://valoremarketing.com.br
* Description: Adds Expresso Jundiaí shipping methods to your WooCommerce store.
* Author: Valore + NSC
* Author URI: https://valoremarketing.com.br
* Version: 1.0.0
* License: GPLv2 or later
*
*/
if (!defined('ABSPATH')) {
exit;
}
/*
* Check if WooCommerce is active
*/
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
function expresso_jundiai_shipping_method()
{
if (!class_exists('Expresso_Jundiai_Shipping_Method')) {
class Expresso_Jundiai_Shipping_Method extends WC_Shipping_Method
{
private $args = '';
/**
* Constructor
*
* #access public
* #return void
*/
public function __construct($instance_id = 0)
{
$this->id = 'expresso-jundiai';
$this->title = 'Expresso Jundiaí';
$this->instance_id = absint($instance_id);
$this->method_title = __('Expresso Jundiaí Entregas', 'expresso-jundiai');
$this->method_description = __('Entregas feitas por Expresso Jundiaí', 'expresso-jundiai');
/**
* Utilized to woocommerce to verify the supported features by the shipping method
*/
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
'settings'
);
$this->init();
}
/**
* Init your settings
*
* #access public
* #return void
*/
public function init()
{
$this->init_form_fields();
$this->init_settings();
/// Actions.
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* Define settings field for this shipping
*
* To access the fields:
* $shipping_methods = WC()->shipping->get_shipping_methods();
* foreach ( $shipping_methods as $key => $shipping_method ) {
* $code = $shipping_method->settings->code;
* }
*
* #return void
*/
public function init_form_fields()
{...}
/**
* Get the args needed to make a post request to API target
*
* #param $package
* #return mixed
*/
private function get_request_args( $package )
{...}
/**
* This function is used to calculate the shipping cost.
* Within this function we can check for weights, dimensions and other parameters in package.
*
* #access public
* #param mixed $package
* #return void
*/
public function calculate_shipping( $package = array() )
{
$args = $this->get_request_args( $package );
$uri = $this->get_option( 'apiUri' );
$response = $this->request_to_api( $uri, $args );
if ($response !== NULL) {
$this->add_rate( array(
'id' => $this->id,
'label' => $this->title,
'package' => $package,
'cost' => $response->vlrFrete,
) );
}
}
/**
* Calculates the cubage of all products.
*
* #param $package
* #return float|int
*/
private function get_total_cubage( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$height = (float) $_product->get_height();
$width = (float) $_product->get_width();
$length = (float) $_product->get_length();
$total += $height * $width * $length;
}
return ( ($total > 0) ? ( $total/1000000 ) : 0 );
}
/**
* #param $package
* #return int
*/
private function get_total_volumes( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values ) {
$total += (int) $values['quantity'];
}
return $total;
}
/**
* Calculate the total wheight of all products of the order
* #param $package
* #return float|int
*/
private function get_order_total_weight( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$_product_weight = (float) $_product->get_weight();
$total += $_product_weight * $values['quantity'];
}
$total = wc_get_weight( $total, 'kg' );
return $total;
}
/**
* #param $uri
* #param $args
* #return mixed|void
*/
private function request_to_api( $uri, $args )
{
$response = wp_remote_post( $uri, $args );
var_dump($args, $response);
if ( is_wp_error( $response ) || '200' != wp_remote_retrieve_response_code( $response )) {
return;
}
$body = json_decode( wp_remote_retrieve_body( $response ) );
if ( empty( $body ) )
return;
return $body;
}
}
}
}
add_action('woocommerce_shipping_init', 'expresso_jundiai_shipping_method');
/**
* Adds the name of class into shipping methods
*
* #param $methods
* #return array
*/
function add_expresso_jundiai_shipping_method($methods)
{
/**
* The key of the array $method must match the shipping method id
*/
$methods['expresso-jundiai'] = 'Expresso_Jundiai_Shipping_Method';
return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_expresso_jundiai_shipping_method');
}
I need it to recalculate with the same rules when i use the shipping calculator in cart... when wordpress calls /?wc-ajax=update_shipping_method
I' trying two days... Please... help
Related
How to make that snippet using (Code Snippet in Wordpress) load only one page, because of home page and other pages loading time.
The code I'm using:
'''add_action( 'init', 'register_uzleteim_endpoint');
/**
* Register New Endpoint.
*
* #return void.
*/
function register_uzleteim_endpoint(){
add_rewrite_endpoint( 'uzleteim', EP_ROOT | EP_PAGES );
}
add_filter( 'query_vars', 'uzleteim_query_vars' );
/**
* Add new query var.
*
* #param array $vars vars.
*
* #return array An array of items.
*/
function uzleteim_query_vars( $vars ) {
$vars[] = 'uzleteim';
return $vars;
}
add_filter( 'woocommerce_account_menu_items', 'add_uzleteim_tab' );
/**
* Add New tab in my account page.
*
* #param array $items myaccount Items.
*
* #return array Items including New tab.
*/
function add_uzleteim_tab( $items ) {
$items['uzleteim'] = 'Üzleteim';
return $items;
}
add_action( 'woocommerce_account_uzleteim_endpoint', 'add_uzleteim_content' );
/**
* Add content to the new tab.
*
* #return string.
*/
function add_uzleteim_content() {}
I'm already tried something like this:
add_action( 'wp_footer', function () {
if ( ! is_page( array( 42, 'Page Name', 'about-us', 968 ) ) ) return;
// rest of snippet code here
} );
But it was not work, cause "unexpected if"
function custom_page() {
global $post;
if( $post->ID == 18) { ?>
<!-- do your stuff here -->
}
add_action( 'wp_footer', 'custom_page');
I'm trying to clean up some code done in a messy way and right now I'm having trouble with doctrine's paginator.
When I'm accessing a page that handle paginator in order to show all different articles of my blog I'm getting this error:
Neither the property "id" nor one of the methods "id()", "getid()"/"isid()"/"hasid()" or "__call()" exist and have public access in class "Doctrine\ORM\Tools\Pagination\Paginator".
In doctrine vendor bundle those methods are not set but my entity have them and I know that it is forbidden to edit a vendor file. I'm missing something because I don't know if I should extend my paginator entity and add those missing methods or is there a little bit more to do ?
I just started symfony and I know that my bases are not enough to understand it all by myself.
Thank you very much for you time and attention.
Here is my Article controller for route category:
/**
* #Route("/categorie/{id}", name="categorie")
*
* #param Request $request
* #param Helper $helper
* #param AuthorizationCheckerInterface $authChecker
* #param DocumentCategory $categorie
* #param TwitterService $twitterService
*
* #return RedirectResponse|Response
*/
public function categorie(
Request $request,
Helper $helper,
AuthorizationCheckerInterface $authChecker,
DocumentCategory $categorie,
TwitterService $twitterService
) {
if (!$authChecker->isGranted('IS_AUTHENTICATED_FULLY')
&& !$authChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('login');
}
$page = (int) ($request->get('page'));
if (0 === $page) {
$page = 1;
}
$userType = $this->getDoctrine()->getRepository('App:User')
->getManagerExpertCollabo($this->getUser());
$articleAlaUneListe = [];
$articleIdListe = $helper->getArticleIdAuth($authChecker);
$articleListe = $this->getDoctrine()
->getRepository('App:Document')
->getPage(
self::ITEM_PER_PAGE * ($page - 1),
self::ITEM_PER_PAGE,
'document.dateCreated',
'DESC',
'(documentCategory.id = \''.$categorie->getId().'\' and '.$helper->baseRequestArticle().')',
7,
[],
$articleIdListe
);
[$articlePopulaireListe, $categorieListe, $totalPage] = $this->getPopularArticleList(
$articleListe,
$helper,
$articleIdListe
);
$articlesList->getDocuments();
$feedData = $twitterService->getTwitterFeed();
return $this->render('article/list.html.twig', [
'pageClass' => 'backoffice withFooterLarge dashboard',
'totalPage' => $totalPage,
'page' => $page,
'feedData' => $feedData,
'categorieListe' => $categorieListe,
'categorie' => $categorie,
'articleAlaUneListe' => $articleAlaUneListe,
'articlePopulaireListe' => $articlePopulaireListe,
'articleListe' => $articleListe, ]);
}
Here is the document entity for categories field:
/**
* #ORM\JoinTable(name="ht_lk_document_category"),
* #ORM\ManyToMany(targetEntity="App\Entity\DocumentCategory", inversedBy="documents")
*/
private $categories;
/**
* #return Collection|array<DocumentCategory>
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function setCategories($category): self
{
$this->categories = $category;
return $this;
}
Here is the DocumentCategory entity :
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Document", mappedBy="categories")
*/
private $documents;
/**
* #return Collection|Document[]
*/
public function getDocuments(): Collection
{
return $this->documents;
}
Here is the Document Repository :
public function getPage($first_result, $max_results, $orderby, $direction, $criteria, $documentType = null, $searchWordArray = [], $articleIdListe = '')
{
$qb = $this->createQueryBuilder('docArticle');
$qb->select('docArticle')
->addSelect('documentCategory', 'documentCategory')
->addSelect('user', 'user')
/*
if(sizeof($searchWordArray) > 0){
$fieldIndice = 1;
foreach($searchWordArray as $searchWord){
$qb->andWhere('(document.name_fr LIKE ?'.$fieldIndice.' or document.name_en LIKE ?'.$fieldIndice.' or document.content_fr LIKE ?'.$fieldIndice.' or document.content_en LIKE ?'.$fieldIndice.')');
$qb->setParameter($fieldIndice++, '%'.$searchWord.'%');
}
} */
->leftJoin('docArticle.categories', 'documentCategory')
->leftJoin('docArticle.author', 'user')
->setFirstResult($first_result)
->setMaxResults($max_results);
if (!empty($criteria)) {
$qb->where('('.$criteria.')');
}
if (!empty($orderby)) {
$qb->orderBy($orderby, $direction);
}
$pag = new Paginator($qb->getQuery());
$qb->setFirstResult(0);
$qb->setMaxResults(PHP_INT_MAX);
$sql = $qb->getQuery()->getSql();
if ('()' !== $articleIdListe) {
$qb->where('(docArticle.id IN '.$articleIdListe);
}
$compte = \count($qb->getQuery()->getScalarResult());
return ['page' => $pag, 'compte' => $compte];
}
And finally here is the Document Category Repository :
/**
* #param $first_result
* #param $max_results
* #param $orderby
* #param $direction
* #param $criteria
* #param int|null $documentType
* #param array $searchWordArray
* #param string $articleIdListe
*
* #return array
*/
public function getPage(
$first_result,
$max_results,
$orderby,
$direction,
$criteria,
$documentType = null,
$searchWordArray = [],
$articleIdListe = ''
) {
$qb = $this->createQueryBuilder('document');
$qb->select('document')
->addSelect('documentCategory', 'documentCategory')
->addSelect('user', 'user')
->addSelect('documentType', 'documentType');
if (\count($searchWordArray) > 0) {
$fieldIndice = 1;
foreach ($searchWordArray as $searchWord) {
$qb->andWhere(
'('
.'document.name_fr LIKE ?'.$fieldIndice
.' or document.name_en LIKE ?'.$fieldIndice
.' or document.content_fr LIKE ?'.$fieldIndice
.' or document.content_en LIKE ?'.$fieldIndice
.')'
);
$qb->setParameter($fieldIndice++, '%'.$searchWord.'%');
}
}
if ($documentType) {
if (\mb_strlen($articleIdListe) > 3) {
$qb->andWhere('(documentType.id = :documentType OR document.id IN '.$articleIdListe.')')
->setParameter('documentType', $documentType);
} else {
$qb->andWhere('(documentType.id = :documentType)')
->setParameter('documentType', $documentType);
}
}
$qb->leftJoin('document.categories', 'documentCategory')
->leftJoin('document.documentType', 'documentType')
->leftJoin('document.author', 'user')
->setFirstResult($first_result)
->setMaxResults($max_results)
->andWhere('document.documentType<>6');
if (!empty($criteria)) {
$qb->andWhere('('.$criteria.')');
}
if (!empty($orderby)) {
$qb->orderBy($orderby, $direction);
}
$sql = $qb->getQuery()->getSql();
$pag = new Paginator($qb->getQuery());
dump($pag);
$qb->setFirstResult(0);
$qb->setMaxResults(PHP_INT_MAX);
$sql = $qb->getQuery()->getSql();
$compte = \count($qb->getQuery()->getScalarResult());
return ['page' => $pag, 'compte' => $compte];
}
/**
* #param int|null $documentType
*
* #return array
*/
public function getArticleIdList($documentType = null)
{
$qb = $this->createQueryBuilder('document');
$qb->select('document.id');
if ($documentType) {
$qb->where('(document.documentType = :documentType)')
->setParameter('documentType', $documentType);
}
$compte = $qb->getQuery()->getScalarResult();
return $compte;
}
(I deleted all unnecessary method for this question)
Add the following code to the entity class from which you want to show data:
public function getId(): ?string
{
return $this->id;
}
Or
if you do not want the property "id" to be displayed in the view, comment out or delete the lines of code in your Twig template for the entity in question. For example, delete
<td>{{ Category.id }}</td>
I am creating a simple mailer..
First you need to create a MailTemplate (Entity).
This exists of a subject, mailFrom and a Message.
Then you create the mail: This happens in two steps.
First you choose your account(s) to send to and your MailTemplate.
Then you redirect to another route where i set the subject, message and mailfrom, so i can adjust things.
When i send (Save the mail). it saved the mail but makes a copy of my MailTemplate and saved the Mailtemplate to.
So i got 1 mail and 2 Templates.
My Template entity
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 26-6-2018
* Time: 20:13
*/
namespace App\Project\MailBundle\Entity;
use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class MailTemplates
* #package App\Project\MailBundle\Entity
*/
/**
* #ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\MailTemplatesRepository")
*/
class MailTemplate extends BaseEntity
{
public function __construct()
{
parent::__construct();
$this->active = true;
$this->bulkmails = new ArrayCollection();
$this->mails = new ArrayCollection();
}
/**
* #var string $template
*
* #ORM\Column(name="template", type="string", length=191, nullable=false)
*
*
*/
private $template;
/**
* #var string $mailFrom
*
* #ORM\Column(type="string", length=191, nullable=false, options={"default": "noreply#nachtpost.be"})
* #Assert\NotBlank()
*
*/
private $mailFrom;
/**
* #var string $mailSubject
*
* #ORM\Column(type="string", length=191, nullable=false)
* #Assert\NotBlank()
*
*/
private $mailSubject;
/**
* #var string $mailMessage
*
* #ORM\Column(type="text", nullable=false)
* #Assert\NotBlank()
*
*/
private $mailMessage;
/**
* #ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\Mail", mappedBy="mailTemplate", orphanRemoval=true)
*/
private $mails;
/**
* #ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\BulkMail", mappedBy="mailTemplate", orphanRemoval=true)
*/
private $bulkmails;
/**
* #return string
*/
public function getTemplate(): ? string
{
return $this->template;
}
/**
* #param string $template
*/
public function setTemplate(string $template): void
{
$this->template = $template;
}
/**
* #return mixed
*/
public function getMailFrom()
{
return $this->mailFrom;
}
/**
* #param mixed $mailFrom
*/
public function setMailFrom($mailFrom): void
{
$this->mailFrom = $mailFrom;
}
/**
* #return mixed
*/
public function getMailSubject()
{
return $this->mailSubject;
}
/**
* #param mixed $mailSubject
*/
public function setMailSubject($mailSubject): void
{
$this->mailSubject = $mailSubject;
}
/**
* #return mixed
*/
public function getMailMessage()
{
return $this->mailMessage;
}
/**
* #param mixed $mailMessage
*/
public function setMailMessage($mailMessage): void
{
$this->mailMessage = $mailMessage;
}
/**
* #return mixed
*/
public function getMails(): collection
{
return $this->mails;
}
/**
* #param mixed $mails
*/
public function setMails($mails)
{
$this->mails = $mails;
}
/**
* #return mixed
*/
public function getBulkmails(): collection
{
return $this->bulkmails;
}
/**
* #param mixed $bulkmails
*/
public function setBulkmails($bulkmails)
{
$this->bulkmails = $bulkmails;
}
public function __toString()
{
return $this->getTemplate();
}
}
My mailEntity
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 26-6-2018
* Time: 20:13
*/
namespace App\Project\MailBundle\Entity;
use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Class BulkMail
* #package App\Project\MailBundle\Entity
*/
/**
* #ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\BulkMailRepository")
*/
class BulkMail extends BaseEntity
{
public function __construct()
{
parent::__construct();
$this->mailTo = new ArrayCollection();
$this->active = true;
}
/**
* #ORM\ManyToOne(targetEntity="App\Project\MailBundle\Entity\MailTemplate", inversedBy="mails", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="bulkMail_id", referencedColumnName="id", nullable=false)
*/
private $mailTemplate;
/**
* #ORM\ManyToMany(targetEntity="App\Project\AccountBundle\Entity\Account")
* #ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false)
* #Assert\NotBlank()
*/
private $mailTo;
/**
* #var string $mailFrom
*
* #ORM\Column(type="string", length=191, nullable=true)
*
*/
private $mailFrom;
/**
* #var string $mailSubject
*
* #ORM\Column(type="string", length=191, nullable=true)
*
*/
private $mailSubject;
/**
* #var string $mailMessage
*
* #ORM\Column(type="text", nullable=true)
*
*/
private $mailMessage;
/**
* #return mixed
*/
public function getMailTo()
{
return $this->mailTo;
}
/**
* #param mixed $mailTo
*/
public function setMailTo($mailTo): void
{
$this->mailTo = $mailTo;
}
/**
* #return mixed
*/
public function getMailFrom()
{
return $this->mailFrom;
}
/**
* #param mixed $mailFrom
*/
public function setMailFrom($mailFrom): void
{
$this->mailFrom = $mailFrom;
}
/**
* #return mixed
*/
public function getMailSubject()
{
return $this->mailSubject;
}
/**
* #param mixed $mailSubject
*/
public function setMailSubject($mailSubject): void
{
$this->mailSubject = $mailSubject;
}
/**
* #return mixed
*/
public function getMailMessage()
{
return $this->mailMessage;
}
/**
* #param mixed $mailMessage
*/
public function setMailMessage($mailMessage): void
{
$this->mailMessage = $mailMessage;
}
/**
* #param mixed $accountId
*/
public function setMail($account): void
{
$this->account = $account;
}
/**
* #return mixed
*/
public function getMailTemplate()
{
return $this->mailTemplate;
}
/**
* #param mixed $mailTemplate
*/
public function setMailTemplate($mailTemplate)
{
$this->mailTemplate = $mailTemplate;
}
public function __toString()
{
return $this->mailSubject;
}
}
My controller
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 5-7-2018
* Time: 22:41
*/
namespace App\Project\MailBundle\Controller;
use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
class BulkMailController extends BaseController
{
public function BulkMailIndexAction()
{
$MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
$items = $MailRepository->findAll();
return $this->render('#ProjectMail/mails/bulk/index.html.twig', array(
'items' => $items
));
}
public function bulkSelectAction(Request $request) {
$mail = new BulkMail();
$form = $this->createForm(BulkSelectmailAdminType::class, $mail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$TemplateRepository = $this->getDoctrine()->getRepository(MailTemplate::class);
$tId = $mail->getMailTemplate()->getId();
$template = $TemplateRepository->findOneBy(array('id' => $tId));
$mail->setMailSubject($template->getMailSubject());
$mail->setMailFrom($template->getMailFrom());
$mail->setMailMessage($template->getMailMessage());
$mail->setMailTemplate($template);
$this->container->get('session')->set('Bmail', $mail);
$response = $this->redirectToRoute('mailBulkSend');
return $response;
}
}
$label = "Email opmaken";
$response = $this->render('#ProjectMail/mails/bulk/addBulk_select.html.twig', array(
'form' => $form->createView(),
'label' => $label
));
return $response;
}
/**
* #param Request $request
* #param \Swift_Mailer $mailer
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {
$Bmail = $this->container->get('session')->get('Bmail');
if ($Bmail) {
$accounts = array();
$AccountRepository = $this->getDoctrine()->getRepository(Account::class);
$count = 0;
foreach ($Bmail->getMailTo() as $key => $account) {
$accounts[] = $AccountRepository->findOneById($account->getId());
$count ++;
}
$form = $this->createForm(BulkAddMailAdminType::class, $Bmail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$Bmail->setMailTo($accounts);
//dump($Bmail->getMailTemplate()); die;
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($Bmail);
$entityManager->flush();
// Get account emails in array
foreach($accounts as $key => $acc){
$persons[$acc->getEmail()] = $acc->getEmail();
}
$message = (new \Swift_Message($Bmail->getMailSubject()))
->setContentType("text/html")
->setFrom($Bmail->getMailFrom())
->setTo($persons)
->setBody(
$this->renderView(
'#ProjectTemplate/_templates/base_mail.html.twig', array(
'type' => 'emailDefault',
'template' => $Bmail
)
)
)
;
// $mailer->send($message);
$response = $this->redirectToRoute('mailsBulkList');
return $response;
}
}
$label = "Email verzenden";
$response = $this->render('#ProjectMail/mails/bulk/addMail.html.twig', array(
'form' => $form->createView(),
'mail' => $Bmail,
'accounts' => $accounts,
'label' => $label
));
} else {
$response = $this->redirectToRoute('mailBulkAdd');
}
return $response;
}
public function deleteAction(BulkMail $mail)
{
$em = $this->getDoctrine()->getManager();
$em->remove($mail);
$em->flush();
return $this->redirectToRoute('mailsBulkList');
}
}
I dont know why this happens and how to handle this right..
Suggestions? Ty in advance!!
Thanks for the help guys, really appreciated!
After some debugging i came out with this..
Not sure if its the way it should be but it works..
I save my mail in the first action and pass the id in my session, in the second action i pass the mail thru the form, (Can make changes if i need to) and send(Save it again).
Did some cleanup to :)
<?php
/**
* Created by PhpStorm.
* User: david
* Date: 5-7-2018
* Time: 22:41
*/
namespace App\Project\MailBundle\Controller;
use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
class BulkMailController extends BaseController
{
public function BulkMailIndexAction()
{
$MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
$items = $MailRepository->findAll();
return $this->render('#ProjectMail/mails/bulk/index.html.twig', array(
'items' => $items
));
}
public function bulkSelectAction(Request $request) {
$mail = new BulkMail();
$form = $this->createForm(BulkSelectmailAdminType::class, $mail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$template = $mail->getMailTemplate();
$mail->setMailSubject($template->getMailSubject());
$mail->setMailFrom($template->getMailFrom());
$mail->setMailMessage($template->getMailMessage());
$entityManager->persist($mail);
$entityManager->flush();
$this->container->get('session')->set('Bmail', $mail->getId());
$response = $this->redirectToRoute('mailBulkSend');
return $response;
}
}
$label = "Email opmaken";
$response = $this->render('#ProjectMail/mails/bulk/addBulk_select.html.twig', array(
'form' => $form->createView(),
'label' => $label
));
return $response;
}
/**
* #param Request $request
* #param \Swift_Mailer $mailer
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {
$BmailId = $this->container->get('session')->get('Bmail');
if ($BmailId) {
$entityManager = $this->getDoctrine()->getManager();
$mailRepo = $this->getDoctrine()->getRepository(BulkMail::class);
$Bmail = $mailRepo->find($BmailId);
$accounts = array();
$AccountRepository = $this->getDoctrine()->getRepository(Account::class);
$count = 0;
foreach ($Bmail->getMailTo() as $key => $account) {
$accounts[] = $AccountRepository->findOneById($account->getId());
$count ++;
}
$form = $this->createForm(BulkAddMailAdminType::class, $Bmail);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$Bmail->setMailTo($accounts);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($Bmail);
$entityManager->flush();
// Get account emails in array
foreach($accounts as $key => $acc){
$persons[$acc->getEmail()] = $acc->getEmail();
}
$message = (new \Swift_Message($Bmail->getMailSubject()))
->setContentType("text/html")
->setFrom($Bmail->getMailFrom())
->setTo($persons)
->setBody(
$this->renderView(
'#ProjectTemplate/_templates/base_mail.html.twig', array(
'type' => 'emailDefault',
'template' => $Bmail
)
)
)
;
// $mailer->send($message);
$response = $this->redirectToRoute('mailsBulkList');
return $response;
}
}
$label = "Email verzenden";
$response = $this->render('#ProjectMail/mails/bulk/addMail.html.twig', array(
'form' => $form->createView(),
'mail' => $Bmail,
'accounts' => $accounts,
'label' => $label
));
} else {
$response = $this->redirectToRoute('mailBulkAdd');
}
return $response;
}
public function deleteAction(BulkMail $mail)
{
$em = $this->getDoctrine()->getManager();
$em->remove($mail);
$em->flush();
return $this->redirectToRoute('mailsBulkList');
}
}
I am getting the above error after my entity name is correct and orm also. Why it is showing I am confused and didn't get the mapped superclass. Database table is also simple. Kindly help me out.
I have used entity " MasterQuestionHeading " in the following class to fetch the records.
Here my code:
namespace careerFutura\AptitudeProfileBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use careerFutura\webBundle\Entity\StudentRegistration;
use careerFutura\webBundle\Entity\StudentAnswer;
use careerFutura\webBundle\Entity\MasterQuestionHeading;
class AptitudeProfileTestController extends Controller
{
public function indexAction()
{
//return $this->render('careerFuturaAptitudeProfileBundle:Question:Aptitude_Profile_Test.html.twig', array('name' => $name));
$em = $this->getDoctrine()->getEntityManager();
$session = $this->get('request')->getSession();
$session->set('selected_tab','');
$id_student = $session->get('id_student');
$student_details = $em->getRepository('webBundle:StudentRegistration')->findBy(array('idStudent'=>$id_student));
$id_qualification = $student_details[0]->gettestClass();
if($id_student == ""){
return $this->redirect($this->generateUrl('_security_logout'));
}
else{
$test_1_number=array(); $test_2_number=array();
$test_3_number=array();$test_4_number=array();
$test_5_number=array();$test_6_number=array();
$test_7_number=array();
$test_1_answer=array(); $test_2_answer=array();
$test_3_answer=array();$test_4_answer=array();
$test_5_answer=array();$test_6_answer=array();
$test_7_answer=array();
//Define counters for each test.
$test_1_counter=0;$test_2_counter=0;
$test_3_counter=0;$test_4_counter=0;
$test_5_counter=0;$test_6_counter=0;
$test_7_counter=0;
$trait_numbers = array();$trait_counters = array();
$answer_array = array();$ans_array = array();
//set video.
$session->set('video_show',1);
/**************************This is for test 1*********************/
$test_1_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>23,
'idQualification'=>$id_qualification
),
array('sequence' =>'ASC'));
foreach($test_1_question as $test1_que){
array_push($test_1_number, $test1_que->getidAptitudeQuestion());
}
$row = array('Test_1'=>$test_1_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_1_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_1_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_1_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_1'=>$test_1_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 2*********************/
$test_2_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>24,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_2_question as $test2_que){
array_push($test_2_number, $test2_que->getidAptitudeQuestion());
}
$row = array('Test_2'=>$test_2_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_2_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_2_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_2_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_2'=>$test_2_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 3*********************/
$test_3_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>25,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_3_question as $test3_que){
array_push($test_3_number, $test3_que->getidAptitudeQuestion());
}
$row = array('Test_3'=>$test_3_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_3_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_3_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_3_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_3'=>$test_3_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 4*********************/
$test_4_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>26,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_4_question as $test4_que){
array_push($test_4_number, $test4_que->getidAptitudeQuestion());
}
$row = array('Test_4'=>$test_4_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_4_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_4_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_4_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_4'=>$test_4_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 5*********************/
$test_5_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>27,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_5_question as $test5_que){
array_push($test_5_number, $test5_que->getidAptitudeQuestion());
}
$row = array('Test_5'=>$test_5_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_5_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_5_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_5_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_5'=>$test_5_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 6*********************/
$test_6_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>28,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_6_question as $test6_que){
array_push($test_6_number, $test6_que->getidAptitudeQuestion());
}
$row = array('Test_6'=>$test_6_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_6_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_6_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_6_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_6'=>$test_6_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
/**************************This is for test 7*********************/
$test_7_question = $em->getRepository('webBundle:AptitudeQuestion')
->findBy(
array(
'idHeader'=>29,
'idQualification'=>$id_qualification
),
array('sequence' => 'ASC'));
foreach($test_7_question as $test7_que){
array_push($test_7_number, $test7_que->getidAptitudeQuestion());
}
$row = array('Test_7'=>$test_7_number);
$trait_numbers = array_merge((array)$trait_numbers, (array)$row);
$test_7_answer = $em->getRepository('careerFuturaStudySkillsBundle:studentAnswer8th')
->findBy(array('id_student' => $id_student,
'id_qualification'=>$id_qualification,
'id_test_type' => 9)
);
foreach($test_7_answer as $ans){
if(!in_array($ans->getIdQuestion(), $array_array)){
$test_7_counter++;
array_push($array_array, $ans->getIdQuestion());
}// end if
} // end foreach loop.
$row = array('Test_7'=>$test_7_counter);
$trait_counters = array_merge((array)$trait_counters, (array)$row);
$status = $em->getRepository('webBundle:StudentTestStatus')
->findBy(array('idStudent' => $id_student,
'idTestType' => 9
)
);
$test_time = $em->getRepository('webBundle:MasterQuestionHeading')
->findAll();
$test_times = array();$completed_trait = array();
foreach($test_time as $time){
foreach($status as $st){
if($time->getPriority() == $st->getPriority()){
if($st->getStatus() == 0){
$session->set('current_trait', $st->getPriority());
}else{
array_push($completed_trait,$st->getPriority());
}
$test_times[$time->getPriority()] = $st->getRemainingTime();
}else
$test_times[$time->getPriority()] = $time->gettestTime();
}
}
if(sizeof($test_times) == 0){
foreach($test_time as $time){
$test_times[$time->getPriority()] = $time->gettestTime();
}
}
return $this->render('AptitudeBundle:Question:index.html.twig',
array(
'timing' => $test_times,
'numbers' => $trait_numbers,
'counters' => $trait_counters,
//'answer' => $answer_string,
'completed' => implode("|",$completed_trait),
'qualification' => $id_qualification
)
);
}//else end here
}//end function here.
}// class end here
Here is my Entity COde:
<?php
namespace careerFutura\webBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* careerFutura\webBundle\Entity\MasterQuestionHeading
*/
class MasterQuestionHeading
{
/**
* #var integer $idHeader
*/
private $idHeader;
/**
* #var integer $idQualification
*/
private $idQualification;
/**
* #var string $heading
*/
private $heading;
/**
* #var string $description
*/
private $description;
/**
* #var integer $priority
*/
private $priority;
/**
* #var datetime $createdon
*/
private $createdon;
/**
* #var integer $createdby
*/
private $createdby;
/**
* #var datetime $updatedon
*/
private $updatedon;
/**
* #var integer $updatedby
*/
private $updatedby;
/**
* #var integer $active
*/
private $active;
/**
* #var integer $version
*/
private $version;
/**
* #var careerFutura\webBundle\Entity\MasterTesttype
*/
private $idTestType;
/**
* #var careerFutura\webBundle\Entity\MasterTrait
*/
private $idTrait;
/**
* Get idHeader
*
* #return integer
*/
public function getIdHeader()
{
return $this->idHeader;
}
/**
* Set idQualification
*
* #param integer $idQualification
*/
public function setIdQualification($idQualification)
{
$this->idQualification = $idQualification;
}
/**
* Get idQualification
*
* #return integer
*/
public function getIdQualification()
{
return $this->idQualification;
}
/**
* Set heading
*
* #param string $heading
*/
public function setHeading($heading)
{
$this->heading = $heading;
}
/**
* Get heading
*
* #return string
*/
public function getHeading()
{
return $this->heading;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set priority
*
* #param integer $priority
*/
public function setPriority($priority)
{
$this->priority = $priority;
}
/**
* Get priority
*
* #return integer
*/
public function getPriority()
{
return $this->priority;
}
/**
* Set createdon
*
* #param datetime $createdon
*/
public function setCreatedon($createdon)
{
$this->createdon = $createdon;
}
/**
* Get createdon
*
* #return datetime
*/
public function getCreatedon()
{
return $this->createdon;
}
/**
* Set createdby
*
* #param integer $createdby
*/
public function setCreatedby($createdby)
{
$this->createdby = $createdby;
}
/**
* Get createdby
*
* #return integer
*/
public function getCreatedby()
{
return $this->createdby;
}
/**
* Set updatedon
*
* #param datetime $updatedon
*/
public function setUpdatedon($updatedon)
{
$this->updatedon = $updatedon;
}
/**
* Get updatedon
*
* #return datetime
*/
public function getUpdatedon()
{
return $this->updatedon;
}
/**
* Set updatedby
*
* #param integer $updatedby
*/
public function setUpdatedby($updatedby)
{
$this->updatedby = $updatedby;
}
/**
* Get updatedby
*
* #return integer
*/
public function getUpdatedby()
{
return $this->updatedby;
}
/**
* Set active
*
* #param integer $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* Get active
*
* #return integer
*/
public function getActive()
{
return $this->active;
}
/**
* Set version
*
* #param integer $version
*/
public function setVersion($version)
{
$this->version = $version;
}
/**
* Get version
*
* #return integer
*/
public function getVersion()
{
return $this->version;
}
/**
* Set idTestType
*
* #param careerFutura\webBundle\Entity\MasterTesttype $idTestType
*/
public function setIdTestType(\careerFutura\webBundle\Entity\MasterTesttype $idTestType)
{
$this->idTestType = $idTestType;
}
/**
* Get idTestType
*
* #return careerFutura\webBundle\Entity\MasterTesttype
*/
public function getIdTestType()
{
return $this->idTestType;
}
/**
* Set idTrait
*
* #param careerFutura\webBundle\Entity\MasterTrait $idTrait
*/
public function setIdTrait(\careerFutura\webBundle\Entity\MasterTrait $idTrait)
{
$this->idTrait = $idTrait;
}
/**
* Get idTrait
*
* #return careerFutura\webBundle\Entity\MasterTrait
*/
public function getIdTrait()
{
return $this->idTrait;
}
}
Add #ORM\Entity as shown below:
namespace careerFutura\webBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* careerFutura\webBundle\Entity\MasterQuestionHeading
* #ORM\Entity
*/
You don't have any annotation in this class. I think (based on your Controller) this class will not be a MappedSuperclass so you need to add #ORM\Entity and #ORM\Id to your code (and don't forget others variables).
<?php
namespace careerFutura\webBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* careerFutura\webBundle\Entity\MasterQuestionHeading
* #ORM\Entity
*/
class MasterQuestionHeading
{
/**
* #ORM\Id
* #ORM\Column(type=integer)
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
}
I have 3 questions (need help):
I do not know, how to run this plugin (gives me fatal error) please check my script (I am beginner)
Need help with admin page to set up APIkey and choose language for call url http://xxx.CZ or http://xxx.SK (This page is not scripted yet)
How to add my plugin admin page to woocommerce admin page?
This plugin is for Woocommerce. It is supposed to call specific URL (http://heureka.cz/or .sk/dotaznik/"Clients API set up in admin page in woocommerce"/"Customers email"/"Order ID"/"bought Products ID"/) when customers order si complete.
I am beginner in PHP and Wordpress. Thank you all for helping me.
CODE:
<?php
/*
Plugin Name: Overené zákazníkmi Heureka
Plugin URI: http://www.podujatie.eu
Version: 0.1
Description:
Author: Podujatie.eu, Ing. Igor Kóňa
Tested up to: 3.6
Author URI: http://www.podujatie.eu
Text Domain: woocommerce-new-badge
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/**
* Check if WooCommerce is active
**/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
if ( ! class_exists( 'WC_HO' ) ) {
class WC_HO {
function heurekaovereno( $order_id ) {
error_log( "Order complete for order $order_id", 0 ); }
add_action( 'woocommerce_order_status_completed', 'heurekaovereno' );
// order object (optional but handy)
$order = new WC_Order( $order_id );
// do some stuff here
private function sendRequest($url)
{
$parsed = parse_url($url);
$fp = fsockopen($parsed['host'], 80, $errno, $errstr, 5);
if (!$fp) {
throw new HeurekaOverenoException($errstr . ' (' . $errno . ')');
} else {
$return = '';
$out = "GET " . $parsed['path'] . "?" . $parsed['query'] . " HTTP/1.1\r\n" .
"Host: " . $parsed['host'] . "\r\n" .
"Connection: Close\r\n\r\n";
fputs($fp, $out);
while (!feof($fp)) {
$return .= fgets($fp, 128);
}
fclose($fp);
$returnParsed = explode("\r\n\r\n", $return);
return empty($returnParsed[1]) ? '' : trim($returnParsed[1]);
}
}
/**
* Sends request to Heureka Overeno service and checks for valid response
*
* #return boolean true
*/
public function send()
{
if (empty($this->email)) {
throw new HeurekaOverenoException('Customer email address not set');
}
// create URL
$url = $this->getUrl() . '?id=' . $this->apiKey . '&email=' . urlencode($this->email);
foreach ($this->products as $product) {
$url .= '&produkt[]=' . urlencode($product);
}
foreach ($this->productsItemId as $itemId) {
$url .= '&itemId[]=' . urlencode($itemId);
}
// add order ID
if (isset($this->orderId)) {
$url .= '&orderid=' . urlencode($this->orderId);
}
// send request and check for valid response
$contents = $this->sendRequest($url);
if ($contents == FALSE) {
throw new HeurekaOverenoException('Unable to create HTTP request to Heureka Overeno service');
} elseif ($contents == self::RESPONSE_OK) {
return TRUE;
} else {
throw new HeurekaOverenoException($contents);
}
}
/**
* Adds ordered products using item ID
*
* #param string $itemId Ordered product item ID
*/
public function addProductItemId($itemId)
{
$this->productsItemId[] = $itemId;
}
/**
* Adds ordered products using name
*
* Products names should be provided in UTF-8 encoding. The service can handle
* WINDOWS-1250 and ISO-8859-2 if necessary
*
* #param string $productName Ordered product name
*/
public function addProduct($productName)
{
$this->products[] = $productName;
}
/**
* Heureka endpoint URL
*
* #var string
*/
const BASE_URL = 'http://www.heureka.cz/direct/dotaznik/objednavka.php';
const BASE_URL_SK = 'http://www.heureka.sk/direct/dotaznik/objednavka.php';
/**
* Language IDs
*
* #var int
*/
const LANGUAGE_CZ = 1;
const LANGUAGE_SK = 2;
/**
* Valid response value
*
* #var string
*/
const RESPONSE_OK = 'ok';
/**
* Shop API key
*
* #var string
*/
private $apiKey;
/**
* Customer email
*
* #var string
*/
private $email;
/**
* Ordered products
*
* #var array
*/
private $products = array();
/**
* Order ID
*
* #var int
*/
private $orderId;
/**
* Current language identifier
*
* #var int
*/
private $languageId = 1;
/**
* Ordered products provided using item ID
*
* #var array
*/
private $productsItemId = array();
/**
* Initialize Heureka Overeno service
*
* #param string $apiKey Shop API key
* #param int $languageId Language version settings
*/
public function __construct($apiKey, $languageId = self::LANGUAGE_CZ)
{
$this->setApiKey($apiKey);
$this->languageId = $languageId;
}
/**
* Sets API key and check well-formedness
*
* #param string $apiKey Shop api key
*/
public function setApiKey($apiKey)
{
if (preg_match('(^[0-9abcdef]{32}$)', $apiKey)) {
$this->apiKey = $apiKey;
} else {
throw new OverflowException('Api key ' . $apiKey . ' is invalid.');
}
}
/**
* Sets customer email
*
* #param string $email Customer email address
*/
public function setEmail($email)
{
$this->email = $email;
}
// Default options
add_option( 'wc_nb_newness', '30' );
// Admin
add_action( 'woocommerce_settings_image_options_after', array( $this, 'admin_settings' ), 20);
add_action( 'woocommerce_update_options_catalog', array( $this, 'save_admin_settings' ) );
/*-----------------------------------------------------------------------------------*/
/* Class Functions */
/*-----------------------------------------------------------------------------------*/
// Load the settings
function admin_settings() {
woocommerce_admin_fields( $this->settings );
}
// Save the settings
function save_admin_settings() {
woocommerce_update_options( $this->settings );
}
if (!isset($wpdb)) $wpdb = $GLOBALS['wpdb'];
$heurekaovereno_ver = '1.00';
$WC_HO = new WC_HO();
}
}
}
?>
This script works (it has few bugs, but it works) only when you put it in functions.php
Here is where I am asking, why is it.