loadByAttribute don't list disabled product - plugins

I'm writing a plugin to load a product with an attribute name, but this plugin loads only the enabled product, yet I need disabled product as well
$p = $product->loadByAttribute($att, $attid);

Try loading the products by dependancy injection of collection
public function __construct(
...
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
...
)
{
...
$this->productCollectionFactory = $collectionFactory;
...
}
and load your data like this
$productcollection = $this->productCollectionFactory
->addAttributeToSelect('*')
->addAttributeToFilter('attribute code', 'option id');

Related

Security Group subpanel doesn't exist for quotes, contrats, invoices, and events modules

I am using suiteCRM 7.7.4 (Sugar Version 6.5.24) and I need to use Security group subpanel in quotes, contracts, invoices and events modules, but for some reasons I can't find it ! I did some researches and I found that this subpanel doesn't appear by default for custom modules.. some developers recommand to do not use the studio to build this kind of relationship, because simply it will not work ! for paid version of sugarCRM they say that there was a tool called "hookup tool" that creates the relationship for you... but As I am using a free version I can't use it !
Do you have any idea ?
Thank you very much !
I finaly find a solution :
Adding this few lines to "modules/AOS_Contracts/metadata/subpaneldefs.php" :
'securitygroups' => array(
'top_buttons' => array(array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'SecurityGroups', 'mode' => 'MultiSelect'),),
'order' => 900,
'sort_by' => 'name',
'sort_order' => 'asc',
'module' => 'SecurityGroups',
'refresh_page' => 1,
'subpanel_name' => 'default',
'get_subpanel_data' => 'SecurityGroups',
'add_subpanel_data' => 'securitygroup_id',
'title_key' => 'LBL_SECURITYGROUPS_SUBPANEL_TITLE',
),
QRR
Verifying permissions.
follow this following steps:
1. Go to Admin
2. Go to studio
3. Select your module where you want subpanel like "invoices"
4. Go to relationship
5. Add 1 to many relationship with Security group module.
6. Now repair rebuild you will find the subapnel in invoice module.
When you create 1 to many relationship with any module it will create the subpanel.
IF its not working then go for custom subpanel.
Refer this linnk I put code from same link it worked for me
This tutorial should hopefully help you to create a new subpanel under the Contacts module in Sugar using a custom link class and driven by SugarCRM 7's new SugarQuery API.
Create a new link class
This should go into custom/modules/<YourModule>/YourNewLink.php and this class will act as the custom functionality that will build your link between the two records.
<?php
/**
* Custom filtered link
*/
class YourNewLink extends Link2
{
/**
* DB
*
* #var DBManager
*/
protected $db;
public function __construct($linkName, $bean, $linkDef = false)
{
$this->focus = $bean;
$this->name = $linkName;
$this->db = DBManagerFactory::getInstance();
if (empty($linkDef)) {
$this->def = $bean->field_defs[$linkName];
} else {
$this->def = $linkDef;
}
}
/**
* Returns false if no relationship was found for this link
*
* #return bool
*/
public function loadedSuccesfully()
{
// this link always loads successfully
return true;
}
/**
* #see Link2::getRelatedModuleName()
*/
public function getRelatedModuleName()
{
return '<Your_Module>';
}
/**
*
* #see Link2::buildJoinSugarQuery()
*/
public function buildJoinSugarQuery($sugar_query, $options = array())
{
$joinParams = array('joinType' => isset($options['joinType']) ? $options['joinType'] : 'INNER');
$jta = 'active_other_invites';
if (!empty($options['joinTableAlias'])) {
$jta = $joinParams['alias'] = $options['joinTableAlias'];
}
$sugar_query->joinRaw($this->getCustomJoin($options), $joinParams);
return $sugar_query->join[$jta];
}
/**
* Builds main join subpanel
* #param string $params
* #return string JOIN clause
*/
protected function getCustomJoin($params = array())
{
$bean_id = $this->db->quoted($this->focus->id);
$sql = " INNER JOIN(";
$sql .= "SELECT id FROM accounts WHERE id={$bean_id}"; // This is essentially a select statement that will return a set of ids that you can match with the existing sugar_query
$sql .= ") accounts_result ON accounts_result.id = sugar_query_table.id";
return $sql;
}
}
The argument $sugar_query is a new SugarQuery object, the details of which are documented here. What you essentially need to do is extend this query with whatever join/filters you wish to add. This is done in the inner join I've specified.
Note: The inner join can get really complicated, so if you want a real working example, checkout modules/Emails/ArchivedEmailsLink.php and how the core sugar team use this. I can confirm however that this does work with custom joins.
Here is the getEmailsJoin to help you understand what you can actually produce via this custom join.
/**
* Builds main join for archived emails
* #param string $params
* #return string JOIN clause
*/
protected function getEmailsJoin($params = array())
{
$bean_id = $this->db->quoted($this->focus->id);
if (!empty($params['join_table_alias'])) {
$table_name = $params['join_table_alias'];
} else {
$table_name = 'emails';
}
return "INNER JOIN (\n".
// directly assigned emails
"select eb.email_id, 'direct' source FROM emails_beans eb where eb.bean_module = '{$this->focus->module_dir}'
AND eb.bean_id = $bean_id AND eb.deleted=0\n" .
" UNION ".
// Related by directly by email
"select DISTINCT eear.email_id, 'relate' source from emails_email_addr_rel eear INNER JOIN email_addr_bean_rel eabr
ON eabr.bean_id = $bean_id AND eabr.bean_module = '{$this->focus->module_dir}' AND
eabr.email_address_id = eear.email_address_id and eabr.deleted=0 where eear.deleted=0\n" .
") email_ids ON $table_name.id=email_ids.email_id ";
}
Add a new vardef entry for the link field.
For this example, I'm going to create the custom link on the contacts module. So this code goes in custom/Extension/modules/Contacts/Ext/Vardefs/your_field_name.php
<?php
$dictionary["Contact"]["fields"]["your_field_name"] = array(
'name' => 'active_other_invites',
'type' => 'link',
'link_file' => 'custom/modules/<YourModule>/YourNewLink.php',
'link_class' => 'YourNewLink',
'source' => 'non-db',
'vname' => 'LBL_NEW_LINK',
'module' => '<YourModule>',
'link_type' => 'many',
'relationship' => '',
);
Add the new link as a subpanel
This goes under custom/Extension/modules/Contacts/Ext/clients/base/layouts/subpanels/your_subpanel_name.php
<?php
$viewdefs['Contacts']['base']['layout']['subpanels']['components'][] = array (
'layout' => 'subpanel',
'label' => 'LBL_NEW_LINK',
'context' =>
array (
'link' => 'your_field_name',
),
);
Add the label
Under
custom/Extension/modules/Contacts/Ext/Language/en_us.new_link.php
<?php
$mod_strings['LBL_ACTIVE_OTHER_INVITES'] = 'Your New Link';
Quick Repair and Rebuild
That should hopefully get you started. Keep an eye on the sugarlogs while you're debugging your queries. I also found using xdebug and SugarQueries compileSql function invaluable in figuring out what I needed to do to get a working INNER JOIN statement.
I've found this to be a surprisingly powerful solution, it means that if you need to show information related to a module that might be a few joins away, this allows you to create the links manually without having to create pointless related fields in-between the two.

How to get the url for admin page (including the key) in magento 2x custom module controller

I need the page url in Magento 2x including key in my custom module controller.
here something similar but this is for magento 1x. i need for magento 2x.
for magento 1x : Mage::helper('adminhtml')->getUrl('adminhtml/framexport/index') but i need similar for magento 2x.
The right way is, inject the UrlInterface in you model block or whatever class constructor
Then call the getUrl() function
class SomeClass extends \Some\Other\Class
{
protected $_backendUrl;
public function __construct(
...........
...........
\Magento\Backend\Model\UrlInterface $backendUrl,
...........
) {
$this->_backendUrl = $backendUrl;
}
public function someFunction()
{
$params = array('some'=>'url_parameters');
$url = $this->_backendUrl->getUrl("the/url/path", $params);
}
}
You can easily get Admin url By calling
$this->getUrl('adminhtml/module/action');
Please not that "Context" type of object is loaded in the $this object
You can get admin url as follows:
public function __construct(\Magento\Backend\Helper\Data $HelperBackend
) {
$this->HelperBackend = $HelperBackend;
}
/**
*
* #param \Magento\Framework\Event\Observer $observer
* #return void
*/
public function getAdminUrl()
{
echo $this->HelperBackend->getHomePageUrl();
}
Somehow adminhtml/module creates an extra admin slug which does not work.
My solution is:
// $this->urlBuilder is defined in __constructor() \Magento\Framework\UrlInterface $urlBuilder
$query = [
'method' => 'confirm',
'id' => $order->getEntityId()
];
$url = $this->urlBuilder->getUrl('module', $query);
It works well for secure URLs (with keys) and non-default /admin URLs, such as /backend.

CakePHP - Using a different model in current model

I am creating a custom validation function in my model in CakePHP. After reading similar questions I have understood that I could be using ClassRegistry::init('Model'); to load a foreign model in my current model. But it doesn't say much more on the syntax and how to actually use it afterwards. This is what I have tried, but nothing "is happening" when I am trying to print the array to see if it contains the right stuff. Basically I want to pull out the User data to use it in my validation.
class Booking extends AppModel {
public $name = 'Booking';
public $validate = array(
'start_time' => array(
'noOptionViolation' => array(
'rule' => 'noOptionViolation',
'allowEmpty' => false
)
),
);
public function noOptionViolation ($start_time) {
$this->User = ClassRegistry::init('User');
$allUsers = $this->User->find('all');
print_r($allUsers);
}
Is this correct syntax? Can I use all the methods of $this->User just like I would in a controller?
You can use import as detailed on this post:
https://stackoverflow.com/a/13140816/1081396
App::import('Model', 'SystemSettings.SystemSetting');
$settings = new SystemSetting();
$mySettings = $settings->getSettings();
In your example it would be like:
App::import('Model', 'Users.User');
$user = new User();
$allUsers = $user->find('all');
print_r($allUsers);
You could better use the import at the beginning of the model.
You could use this too to load Models
$this->loadModel('User');
and access all functions by
$this->User

How to implement data model with this code

I am new to zend frame work . I am trying to learn zf create db-table tblename,zf create model tblname,zf create model tblnameMapper.
add user.php (form)
<?php
class Application_Form_Adduser extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',10);
$password=$this->createElement('text','password');
$password->setLabel('Password')
->setAttrib('size',10);
$reg=$this->createElement('submit','submit');
$reg->setLabel('save');
$this->addElements(array(
$username,
$password,
$reg
));
return $this;
}
add user view:
<?php
echo 'Add user';
echo "<br />" .$this->a;
echo $this->form;
?>
admin controller:
<?php
class AdminController extends Zend_Controller_Action
{
public function adduserAction(){
$form = new Application_Form_Auth();
$this->view->form = $form;
$this->view->assign('a','Entere new user:');
if($this->getRequest()->isPost()){
$formData = $this->_request->getPost();
$uname=$formData['username'];
$pass=$formData['password'];
$msg=$uname." added to database successfully";
$this->view->assign('a',$msg);
$db= Zend_Db_Table_Abstract::getDefaultAdapter();
$query="INSERT INTO `user` ( `id` , `uname` , `password` )
VALUES ('', '{$uname}', '{$pass}');";
$db->query($query);
}}
i want to implement db-table with the above code .i am new to zend frame work i spend some time on reading programmers guide but in vain .It is very hard to get things from manual.So please some one explain step by step procedure for implementing the same .Thanks in advanced.
Ok here is a quick example:
Create DbTable Model (Basically an adapter for each table in your database):
at the command line: zf create db-table User user add -m moduleName if you want this in a module. This command will create a file name User.php at /application/models/DbTable that looks like:
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract {
protected $_name = 'user'; //this is the database tablename (Optional, automatically created by Zend_Tool)
protected $_primary = 'id'; //this is the primary key of the table (Optional, but a good idea)
}
now to create a method in your DbTable model that executes the query from your controller, add a method similar to:
public function insertUser(array $data) {
$Idata = array(
'name' => $data['name'] ,
'password' => $data['passowrd']
);
$this->insert($Idata); //returns the primary key of the new row.
}
To use in your controller:
public function adduserAction(){
$form = new Application_Form_Auth(); //prepare form
try{
if($this->getRequest()->isPost()){//if is post
if ($form->isValid($this->getRequest()_>getPost()){ //if form is valid
$data = $form->getValues(); //get filtered and validated form values
$db= new Application_Model_DbTable_User(); //instantiate model
$db->insertUser($data); //save data, fix the data in the model not the controller
//do more stuff if required
}
}
$this->view->form = $form; //if not post view form
$this->view->assign('a','Entere new user:');
} catch(Zend_Exception $e) { //catach and handle exception
$this->_helper->flashMessenger->addMessage($e->getMessage());//send exception to flash messenger
$this->_redirect($this->getRequest()->getRequestUri()); //redirect to same page
}
}
This is about as simple as it gets. I have barely scratched the surface of what can be accomplished in simple applications with Zend_Db and a DbTable model. However you will likely find as I have, that at some point you will need more. That would be the time to explore the domain model and mappers.
For a really good basic tutrial that includes all of this and more please check out Rob Allen's ZF 1.x tutorial
I hope this helps.

is it different 'default ' and 'Default' in zend default session namespace?

I am using sessions in zend framework.
the question is i need to know is there a difference between
new Zend_Session_Namespace("default");
and
new Zend_Session_Namespace("Default");
in my application, I have used both, it seems the code is not working correctly,
if there is a difference, what is the correct one to use.
here is my code
<?php
class Admin_DashboardController extends Zend_Controller_Action
{
function init()
{
//
}
/**
* Add hotelId to default session
* redirect to admin/hotels if hotelId is not avialble
*/
public function indexAction()
{
$params = $this->getRequest()->getParams();
$hotelid = NULL;
$config_session = new Zend_Session_Namespace("default");
$config_session->hotelid = $params['id'];
if(isset($params['id']) && !empty($params['id'])){
}else{
//redirect user to select hotels page
$redirector = new Zend_Controller_Action_Helper_Redirector();
$url = array(
'action' => 'admin/hotels/index'
);
$redirector->gotoRouteAndExit($url);
}
}
}
All Zend_Session_Namespace does internally is create a named array inside the $_SESSION superglobal. As array keys in PHP are case sensitive, "Default" and "default" will be treated as separate namespaces.
You can use whichever one you want, just be consistent if you expect to use the same data.