I want to change a function definition by extending WC_Order class. But it gives an "Unable to create order" error. How can I properly extend WC_Order class?
I created a class as below:
class AWCDP_Payment extends WC_Order{
function get_created_via($context = 'view'){
return 'admin';
}
}
and used as below:
$partial_payment = new AWCDP_Payment();
$partial_payment->add_item($item);
.
.
.
Related
How can I call a stored procedure from a Web API controller?
I have the following code to get data from the SQL Server database using Web API, I have api which working fine, but I wanted to use stored procedures instead.
The stored procedure name is uspStaffDirectoryGetAllXXXEmployeeInfo, I imported it into the .edmx as GetEmployeeInformation.
Note: the stored procedure contains fields from another database.
Here is my code which is working for me but I want to replace it using stored procedures.
private EmployeesEntities db = new EmployeesEntities();
public IHttpActionResult GetEmployees()
{
var query = (from emp in db.employees
select new
{
emp.employee_number,
emp.employee_photo,
emp.first_name,
emp.last_name,
});
var employees = query.ToList();
return Ok(employees);
}
Here Is the code I used to get data using the stored procedure uspStaffDirectoryGetAllXXXXEmployeeInfo:
private EmployeesEntities db = new EmployeesEntities();
//[HttpGet]
public List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result> Get()
{
List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result> emplist = new List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result>();
using (EmployeesEntities db = new EmployeesEntities())
{
var results = db.uspStaffDirectoryGetAllXXXXEmployeeInfo();
foreach (var result in results)
{
var employee = new uspStaffDirectoryGetAllXXXXEmployeeInfo_Result()
{
id = result.id,
Employee_Display_Name = result.Employee_Display_Name,
first_name = result.first_name,
last_name = result.last_name,
Employee_Phone = result.Employee_Phone,
Employee_Email = result.Employee_Email
};
emplist.Add(employee);
}
return emplist;
}
But when I run the API I keep getting this error, I don’t have a field called 'Column1' anywhere
System.Data.Entity.Core.EntityCommandExecutionException: 'The data reader is incompatible with the specified 'EmployeesModel.uspStaffDirectoryGetAllXXXXEmployeeInfo_Result'. A member of the type, 'Column1', does not have a corresponding column in the data reader with the same name.'
On this line
public virtual ObjectResult<uspStaffDirectoryGetAllXXXEmployeeInfo_Result> uspStaffDirectoryGetAllXXXXEmployeeInfo()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result>("uspStaffDirectoryGetAllXXXXEmployeeInfo");
}
What did I miss? How can I fix it?
Do you have a named or calculated name column that is returned by the stored procedure ?
In this case you have to give it a name :
ex select "my value" as "colName"
I have a website built with Symfony 2.8 and Gedmo Translatable.
In order to use HINT_INNER_JOIN and filter items which don't have a translation I had to set persist_default_translation to true:
stof_doctrine_extensions:
default_locale: '%locale%' # TODO: what does it happen when removing this line?
translation_fallback: true
persist_default_translation: true
orm:
default:
timestampable: true
blameable: true
translatable: true
Unfortunately this caused that my existing translations for the default language are no more persisted (and they appear empty).
I would need to force re-save all of my entities to generate the default locale again.
How can I do that? I tried with clone and persist but it creates a duplicate of the entity.
Is it possible to force Doctrine to update all the fields again?
I ended up creating a custom command to migrate all the translations. I created a fake translation called "kr" and then updated all the record with "kr" to "fr" with an SQL query.
I used reflection and other "black magic" to get the properties with the Translatable annotation, maybe this could help someone with the same problem. Here is the code:
class NormalizeTranslationsCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
// the name of the command (the part after "app/console")
->setName('app:normalize-translations')
// the short description shown while running "php app/console list"
->setDescription('Normalizes the translations.')
// the full command description shown when running the command with
// the "--help" option
->setHelp('This command allows you to normalize the translations...')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// all the translatable classes
$classes = [
Entities\MyClass1::class,
Entities\MyClass2::class,
];
foreach ($classes as $class) {
$this->processClass($class, $output);
}
}
private function processClass($class, $output)
{
$output->writeln(sprintf('Processing class <info>%s</info>', $class));
// gets all the properties
$properties = $this->getProperties($class);
// gets the translatable properties
$translatableProperties = $this->getTranslatableProperties($properties, $class);
$output->writeln(sprintf('Found %d translatable properties: %s', count($translatableProperties), implode(', ', $translatableProperties)));
$defaultLanguage = 'kr'; // fake language
$em = $this->getContainer()->get('doctrine')->getManager();
$repository = $em->getRepository('Gedmo\\Translatable\\Entity\\Translation');
$items = $em->getRepository($class)->findAll();
$propertyAccessor = PropertyAccess::createPropertyAccessor();
foreach ($items as $item) {
foreach ($translatableProperties as $translatableProperty) {
$value = $propertyAccessor->getValue($item, $translatableProperty);
$repository->translate($item, $translatableProperty, $defaultLanguage, $value);
}
$em->flush();
}
}
private function getProperties($class)
{
$phpDocExtractor = new PhpDocExtractor();
$reflectionExtractor = new ReflectionExtractor();
// array of PropertyListExtractorInterface
$listExtractors = array($reflectionExtractor);
// array of PropertyTypeExtractorInterface
$typeExtractors = array($phpDocExtractor, $reflectionExtractor);
// array of PropertyDescriptionExtractorInterface
$descriptionExtractors = array($phpDocExtractor);
// array of PropertyAccessExtractorInterface
$accessExtractors = array($reflectionExtractor);
$propertyInfo = new PropertyInfoExtractor(
$listExtractors,
$typeExtractors,
$descriptionExtractors,
$accessExtractors
);
return $propertyInfo->getProperties($class);
}
private function getTranslatableProperties($properties, $class)
{
$translatableProperties = [];
// https://gist.github.com/Swop/5990316
$annotationReader = new AnnotationReader();
foreach ($properties as $property) {
try {
$reflectionProperty = new \ReflectionProperty($class, $property);
$propertyAnnotations = $annotationReader->getPropertyAnnotations($reflectionProperty);
foreach ($propertyAnnotations as $propertyAnnotation) {
if ($propertyAnnotation instanceof Translatable) {
// this property is translatable
$translatableProperties[] = $property;
}
}
} catch (\ReflectionException $e) {
// missing property
continue;
}
}
return $translatableProperties;
}
}
I'm using Zend Framework description and I'm trying to customize title tag like ZF2 documetation recommends, but I've got this error:
Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException:
Unable to resolve service "viewHelperManager" to a factory; are you
certain you provided it during configuration? in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:681
Stack trace: #0
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(757):
Zend\ServiceManager\ServiceManager->getFactory('viewHelperManag...')
1 /var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(200):
Zend\ServiceManager\ServiceManager->doCreate('viewHelperManag...') #2
/var/www/html/basketmetrics/module/Stats/src/Module.php(43):
Zend\ServiceManager\ServiceManager->get('viewHelperManag...') #3
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(322):
Stats\Module->setLayoutTitle(Object(Zend\Mvc\MvcEvent)) #4
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(171):
Zend\EventManager\E in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php
on line 681
This is my code on Module.php
namespace Stats;
class Module
{
const VERSION = '3.0.2';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function onBootstrap($e)
{
// Register a render event
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function setLayoutTitle($e)
{
$matches = $e->getRouteMatch();
$action = $matches->getParam('action');
$controller = $matches->getParam('controller');
$module = __NAMESPACE__;
$siteName = 'BasketMetrics';
// Getting the view helper manager from the application service manager
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
// Getting the headTitle helper from the view helper manager
$headTitleHelper = $viewHelperManager->get('headTitle');
// Setting a separator string for segments
$headTitleHelper->setSeparator(' - ');
// Setting the action, controller, module and site name as title segments
$headTitleHelper->append($action);
$headTitleHelper->append($controller);
$headTitleHelper->append($module);
$headTitleHelper->append($siteName);
}
}
I don't know If I'm doing something wrong, or if I cannot do it like in ZF2.
And meta tag "description" how can I customize it?
->get('ViewHelperManager')
Up case
Added toolbar in joomla 3.0 html.php file. When the addNew button is clicked it displays
An error has occurred. 0 Invalid controller:
name='Comboscategories', format=''
html.php file as follows.
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class ComboscategoriesViewsStatisticsHtml extends JViewHtml
{
function render()
{
$app = JFactory::getApplication();
//retrieve task list from model
$model = new ComboscategoriesModelsStatistics();
$this->stats = $model->getStats();
$this->addToolbar();
/*$this->displayComboslist();*/
//display
return parent::render();
}
protected function addToolbar()
{
$canDo = ComboscategoriesHelpersLendr::getActions();
// Get the toolbar object instance
$bar = JToolBar::getInstance('toolbar');
JToolbarHelper::title(JText::_('Combos Category'));
JToolBarHelper::addNew('Comboscategories.add');
/* JToolbarHelper::preferences('com_comboscategories');*/
JToolBarHelper::save();
JToolBarHelper::cancel();
JToolBarHelper::deleteList();
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
}
}
controller.php(display.php)
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class ComboscategoriesControllersDisplay extends JControllerBase
{
public function execute()
{
// Get the application
$app = $this->getApplication();
// Get the document object.
$document = JFactory::getDocument();
$viewName = $app->input->getWord('view', 'statistics');
$viewFormat = $document->getType();
$layoutName = $app->input->getWord('layout', 'default');
$app->input->set('view', $viewName);
// Register the layout paths for the view
$paths = new SplPriorityQueue;
$paths->insert(JPATH_COMPONENT . '/views/' . $viewName . '/tmpl', 'normal');
$viewClass = 'ComboscategoriesViews' . ucfirst($viewName) . ucfirst($viewFormat);
$modelClass = 'ComboscategoriesModels' . ucfirst($viewName);
$view = new $viewClass(new $modelClass, $paths);
$view->setLayout($layoutName);
// Render our view.
echo $view->render();
return true;
}
}
I searched related to this but i dont find the solution. kindly help me to sort this
Hi im new to joomla but i think that your classes have bad names. it Should be ComboscategoriesViewStatisticsHtml or ComboscategoriesControllerDisplay
You have to use the name of the model: if you have a controller called ComboscategoriesControllersDisplay your call should be JToolBarHelper::addNew('display.add').
Best read this: http://docs.joomla.org/J3.x:Developing_a_MVC_Component/Adding_backend_actions
I've got a problem with class-scope aces. I've created an ace for a
class like this :
$userIdentity = UserSecurityIdentity::fromAccount($user);
$classIdentity = new ObjectIdentity('some_identifier', 'Class\FQCN');
$acl = $aclProvider->createAcl($classIdentity);
$acl->insertClassAce($userIdentity, MaskBuilder::MASK_CREATE);
$aclProvider->updateAcl($acl);
Now, I'm trying to check the user's permissions. I've found this way
of doing things, which is not documented, but gives the expected
results on a class basis :
$securityContext->isGranted('CREATE', $classIdentity); // returns true
$securityContext->isGranted('VIEW', $classIdentity); // returns true
$securityContext->isGranted('DELETE', $classIdentity); // returns false
This method is well adapated to the "CREATE" permission check, where
there's no available object instance to pass to the method. However,
it should be possible to check if another permission is granted on a
particular instance basis :
$entity = new Class\FQCN();
$em->persist($entity);
$em->flush();
$securityContext->isGranted('VIEW', $entity); // returns false
This is where the test fails. I expected that an user who has a given
permission mask on a class would have the same permissions on every
instance of that class, as stated in the documentation ("The
PermissionGrantingStrategy first checks all your object-scope ACEs if
none is applicable, the class-scope ACEs will be checked"), but it
seems not to be the case here.
you are doing it right. and according to the bottom of this page, it should work, but it does not.
the easiest way to make it work is creating an AclVoter class:
namespace Core\Security\Acl\Voter;
use JMS\SecurityExtraBundle\Security\Acl\Voter\AclVoter as BaseAclVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Doctrine\Common\Util\ClassUtils;
class AclVoter extends BaseAclVoter
{
public function vote( TokenInterface $token , $object , array $attributes )
{
//vote for object first
$objectVote = parent::vote( $token , $object , $attributes );
if( self::ACCESS_GRANTED === $objectVote )
{
return self::ACCESS_GRANTED;
}
else
{
//then for object's class
$oid = new ObjectIdentity( 'class' , ClassUtils::getRealClass( get_class( $object ) ) );
$classVote = parent::vote( $token , $oid , $attributes );
if( self::ACCESS_ABSTAIN === $objectVote )
{
if( self::ACCESS_ABSTAIN === $classVote )
{
return self::ACCESS_ABSTAIN;
}
else
{
return $classVote;
}
}
else if( self::ACCESS_DENIED === $objectVote )
{
if( self::ACCESS_ABSTAIN === $classVote )
{
return self::ACCESS_DENIED;
}
else
{
return $classVote;
}
}
}
return self::ACCESS_ABSTAIN;
}
}
then in security.yml set this:
jms_security_extra:
voters:
disable_acl: true
and finally set up the voter as a service:
core.security.acl.voter.basic_permissions:
class: Core\Security\Acl\Voter\AclVoter
public: false
arguments:
- '#security.acl.provider'
- '#security.acl.object_identity_retrieval_strategy'
- '#security.acl.security_identity_retrieval_strategy'
- '#security.acl.permission.map'
- '#?logger'
tags:
- { name: security.voter , priority: 255 }
- { name: monolog.logger , channel: security }
You need to ensure each object has its own ACL (use $aclProvider->createAcl($entity)) for class-scope permissions to work correctly.
See this discussion: https://groups.google.com/forum/?fromgroups=#!topic/symfony2/pGIs0UuYKX4
If you don't have an existing entity, you can check against the objectIdentity you created.
Be careful to use "double-backslashes", because of the escaping of the backslash.
$post = $postRepository->findOneBy(array('id' => 1));
$securityContext = $this->get('security.context');
$objectIdentity = new ObjectIdentity('class', 'Liip\\TestBundle\\Entity\\Post');
// check for edit access
if (true === $securityContext->isGranted('EDIT', $objectIdentity)) {
echo "Edit Access granted to: <br/><br/> ";
print_r("<pre>");
print_r($post);
print_r("</pre>");
} else {
throw new AccessDeniedException();
}
That should work!
If you would check for "object-scope" you could just use $post instead of $objectIdentity in the isGranted function call.
I have tried to find the best solution for this problem and I think the best answer is the one of rryter / edited by Bart. I just want to extend the solution.
Let's say you want to give access to a specific object type for a specific user, but not for a concrete object instance (for example id=1).
Then you can do the following:
$aclProvider = $this->get('security.acl.provider');
$objectIdentity = new ObjectIdentity('class', 'someNamspace\\SeperatedByDoubleSlashes');
$acl = $aclProvider->createAcl($objectIdentity);
// retrieving the security identity of the currently logged-in user
$securityContext = $this->get('security.context');
$user = $securityContext->getToken()->getUser();
$securityIdentity = UserSecurityIdentity::fromAccount($user);
// grant owner access
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
$aclProvider->updateAcl($acl);
$securityContext = $this->get('security.context');
// check for edit access
if (false === $securityContext->isGranted('EDIT', $objectIdentity)) {
throw new AccessDeniedException();
}
The difference to the example given by the symfony cookbook is that you are using the class scope and not the object scope.
There's only 1 line that makes the difference:
$objectIdentity = new ObjectIdentity('class', 'someNamspace\\SeperatedByDoubleSlashes');
instead of:
$objectIdentity = ObjectIdentity::fromDomainObject($object);
You can still add specific permissions for specific object instances if you have at least one class scope permission in your classes acl.