I search and I can not find the piece of code implemented for checking the password provided by user during registration. That's the code who check if there has the correct number of characters. .. the many figures and many symbols ... etc.
I believe that's this function is implemented since joomla 3.0, my version is joomla 3.2
I would like to "copy" this code for one of my joomla personal scripts.
I searched the in the controllers and models of "com_users", and in plugin "users" without success.
I also studied the bind() methode and save() methode of class JUser but I found nothing.
Does anyone know where this code? I would be saving valuable time.
It is in a jform : components/com_users/models/forms/registration.xml
<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_REGISTRATION_DEFAULT_LABEL"
>
<!-- STUFF HERE -->
<field name="password2" type="password"
autocomplete="off"
class="validate-password"
description="COM_USERS_DESIRED_PASSWORD"
field="password1"
filter="raw"
label="COM_USERS_PROFILE_PASSWORD1_LABEL"
message="COM_USERS_PROFILE_PASSWORD1_MESSAGE"
size="30"
validate="equals"
required="true"
/>
<field name="password1" type="password"
autocomplete="off"
class="validate-password"
description="COM_USERS_PROFILE_PASSWORD2_DESC"
filter="raw"
label="COM_USERS_PROFILE_PASSWORD2_LABEL"
size="30"
validate="password"
required="true"
/>
<!-- OTHER STUFF THERE -->
</fieldset>
</form>
And in libraries folder : libraries/joomla/form/fields/password.php
/**
* Method to attach a JForm object to the field.
*
* #param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the form field object.
* #param mixed $value The form field value to validate.
* #param string $group The field name group control value. This acts as as an array container for the field.
* For example if the field has name="foo" and the group value is set to "bar" then the
* full field name would end up being "bar[foo]".
*
* #return boolean True on success.
*
* #see JFormField::setup()
* #since 3.2
*/
public function setup(SimpleXMLElement $element, $value, $group = null)
{
$return = parent::setup($element, $value, $group);
if ($return)
{
$this->maxLength = $this->element['maxlength'] ? (int) $this->element['maxlength'] : 99;
$this->threshold = $this->element['threshold'] ? (int) $this->element['threshold'] : 66;
$meter = (string) $this->element['strengthmeter'];
$this->meter = ($meter == 'true' || $meter == 'on' || $meter == '1');
}
return $return;
}
/**
* Method to get the field input markup for password.
*
* #return string The field input markup.
*
* #since 11.1
*/
protected function getInput()
{
// Translate placeholder text
$hint = $this->translateHint ? JText::_($this->hint) : $this->hint;
// Initialize some field attributes.
$size = !empty($this->size) ? ' size="' . $this->size . '"' : '';
$maxLength = !empty($this->maxLength) ? ' maxlength="' . $this->maxLength . '"' : '';
$class = !empty($this->class) ? ' class="' . $this->class . '"' : '';
$readonly = $this->readonly ? ' readonly' : '';
$disabled = $this->disabled ? ' disabled' : '';
$required = $this->required ? ' required aria-required="true"' : '';
$hint = $hint ? ' placeholder="' . $hint . '"' : '';
$autocomplete = !$this->autocomplete ? ' autocomplete="off"' : '';
$autofocus = $this->autofocus ? ' autofocus' : '';
if ($this->meter)
{
JHtml::_('script', 'system/passwordstrength.js', true, true);
$script = 'new Form.PasswordStrength("' . $this->id . '",
{
threshold: ' . $this->threshold . ',
onUpdate: function(element, strength, threshold) {
element.set("data-passwordstrength", strength);
}
}
);';
// Load script on document load.
JFactory::getDocument()->addScriptDeclaration(
"jQuery(document).ready(function(){" . $script . "});"
);
}
// Including fallback code for HTML5 non supported browsers.
JHtml::_('jquery.framework');
JHtml::_('script', 'system/html5fallback.js', false, true);
return '<input type="password" name="' . $this->name . '" id="' . $this->id . '"' .
' value="' . htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . $hint . $autocomplete .
$class . $readonly . $disabled . $size . $maxLength . $required . $autofocus . ' />';
}
I think it is what you want.
If you're lost with Joomla Jforms, then use jquery validation plugin. Its documentation.
You can create plugin that check if password is valid and return true is yes;
<?php
defined('_JEXEC') or die ;
class plgUserHookbizz extends JPlugin {
function onUserBeforeSave($user,$options)
{
$app = JFactory::getApplication();
// Joomla session parameters
$userId = $user['id'];
$name = $user['name'];
$password = $user['password'];
$username = $user['username'];
$email = $user['email'];
if($this->validate($password)){
return true;
}else{
$app->enqueueMessage('Please enter a valid password');
return false;
}
}
function validate($password){
//Your validation here
//Return true if valid
return true;
}
}
Related
It's the First time that I use SP Page Builder component with Joomla. I want to use their contact form, but it doesn't support Google ReCaptcha.
I'm good enough with coding to thought that I could manually add it into : /com_sppagebuilder/addons/ajax_contact/site.php and get it to work.
I did add : <div class="g-recaptcha" data-sitekey="My_Key"></div>;
And the Joomla ReCaptcha plugin is activated.
I didn't know if I had to, but I added <script src='https://www.google.com/recaptcha/api.js'></script> into the head tag.
With this the ReCaptcha is showing fine.
My problem is with the validation.
I did try to add some validation code in the site.php but I believe SP Page Builder uses JFactory::getMailer(); to get the email ready and send it, and I don't know anything about that.
Thus, I do not know where I can add my ReCaptcha validation code, and as I did find few versions of that code online, I really don't know which one to use.
I've been searching everywhere for some answers to how to do this verification... and I tried many things, but it's still not working.
Can anyone help me through this one ?
Thank you very much !
EDIT
I think my question is not clear enough :
I want to add Recaptcha, that is already working fine in other forms on my website (so it's not a configuration with Joomla problem). I want to use the following SP Page Builder contact form and not a RSFormPro as on the rest of the Website. The validation process should be done around this section, but I tried to add the Google validation code, and I tried a few versions of it I found around the Internet, and it's not working at all :
public static function getAjax() {
$input = JFactory::getApplication()->input;
$mail = JFactory::getMailer();
//inputs
$inputs = $input->get('data', array(), 'ARRAY');
foreach ($inputs as $input) {
if( $input['name'] == 'recipient' ) {
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' ) {
$email = $input['value'];
}
if( $input['name'] == 'name' ) {
$name = $input['value'];
}
if( $input['name'] == 'subject' ) {
$subject = $input['value'];
}
if( $input['name'] == 'message' ) {
$message = nl2br( $input['value'] );
}
}
/*Try at the validation*/
$captcha_plugin = JFactory::getConfig()->get('captcha');
if ($captcha_plugin != '0') {
$captcha = JCaptcha::getInstance($captcha_plugin);
$field_id = 'google-recaptcha';
print $captcha->display($field_id, $field_id, 'g-recaptcha');
}
$sender = array($email, $name);
$mail->setSender($sender);
$mail->addRecipient($recipient);
$mail->setSubject($subject);
$mail->isHTML(true);
$mail->Encoding = 'base64';
$mail->setBody($message);
if ($mail->Send()) {
return '<span class="sppb-text-success">'. JText::_('COM_SPPAGEBUILDER_ADDON_AJAX_CONTACT_SUCCESS') .'</span>';
} else {
return '<span class="sppb-text-danger">'. JText::_('COM_SPPAGEBUILDER_ADDON_AJAX_CONTACT_FAILED') .'</span>';
}
}
Any suggestions ?
Thank you !
I have successfully added captcha to the Ajax contact form. Although the code still needs some improvements, Here is what I did:
See that I am using the n3tseznamcaptcha captcha plugin, I still need to implement the changes for other captchas to work (recaptcha,etc) but you can adapt it to your needs.
An SP Pagebuilder addon consists of two files, admin, and site. In the admin site I removed the default captcha, which lacks many security measures. Then in the site part I added the following:
function ajax_contact_addon($atts)
{
global $formcaptcha;
(...)
if($formcaptcha)
{
// TODO: Add Joomla's captcha:
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
// This will put the code to load CAPTCHA's JavaScript file into your <head>
$dispatcher->trigger('onInit', 'dynamic_captcha_1');
// This will return the array of HTML code.
$captcha = $dispatcher->trigger('onDisplay', array(null, 'dynamic_captcha_1', 'class=""'));
// I have only 1 recaptcha plugin enabled so the HTML is at 0 index, this will be improved in next version, following the contact component
$output .= (isset($captcha[0])) ? $captcha[0] : '';
$output .= '<div class="clearfix"></div><p></p>';
}
(...)
}
function ajax_contact_get_ajax()
{
global $formcaptcha;
$jinput = JFactory::getApplication()->input;
$mail = JFactory::getMailer();
$config = JFactory::getConfig();
// TODO: CHECK CAPTCHA and add a Helper Class to get the captchas fields
$captchaset = 'n3tseznamcaptcha';
if ($captchaset === 'n3tseznamcaptcha')
{
$captcha_field_hash = 'n3t_seznam_captcha_hash';
$captcha_field_answer = 'n3t_seznam_captcha';
}
//inputs
$inputs = $jinput->get('data', array(), 'ARRAY');
foreach ($inputs as $input)
{
if( $input['name'] == 'title' )
{
$title = $input['value'];
}
if( $input['name'] == 'recipient' )
{
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' )
{
$email = $input['value'];
}
(...)
if( $input['name'] == $captcha_field_hash )
{
$captcha_hash = $input['value'];
}
if( $input['name'] == $captcha_field_answer )
{
$captcha_answer = $input['value'];
}
}
if($formcaptcha)
{
// get the plugin
JPluginHelper::importPlugin('captcha');
$dispatcher = JEventDispatcher::getInstance();
// In order the plugin can check the code, we have to insert it into the request data:
$jinput->set('n3t_seznam_captcha_hash', $captcha_hash);
$jinput->set('n3t_seznam_captcha', $captcha_answer);
// Here we check for the code:
$res = $dispatcher->trigger('onCheckAnswer', $captcha_answer);
if(!$res[0])
{
// There is a problem with pagebuilder cache and captchas, so we need to clean the cache, to renew the captcha code:
$cache = JFactory::getCache('page');
$cache->clean();
return '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_FORM_WRONG_CAPTCHA') .'</span>';
}
}
}
I think that's all. Hope it helps you to find out.
So here you have the complete solution. Note that I changed a few things in the admin side too. This version will display and validate the default captcha selected in Joomla config, but it will only work for recaptcha and n3tsezam.. other should be added manually. The reason is that this addon does not add the challenge and response fields in the request, which the captcha plugins use for validation, therefor we need to retrieve it and write to the jinput within our ajax function (ajax_contact_get_ajax), and what complicates the whole thing is that every captcha plugin use different fields. Anyway.. if you need any other captcha plugin just can add it to the switch and you should be done.
function ajax_contact_addon($atts)
{
extract(AddonAtts(array(
"title" => '',
"show_title" => '',
"heading_selector" => 'h3',
"title_fontsize" => '',
"title_fontweight" => '',
"title_text_color" => '',
"title_margin_top" => '',
"title_margin_bottom" => '',
"recipient_email" => '',
"formcaptcha" => '',
"class" => '',
), $atts));
JHtml::script('media/com_pagebuilder/js/ajax-contact.js');
// There is a problem with pagebuilder cache and captchas
$cache = JFactory::getCache('page');
$cache->clean();
$output = '<div class="pb-addon pb-addon-ajax-contact ' . $class . '">';
if(boolval($show_title) && $title)
{
$title_style = '';
if($title_margin_top !='') $title_style .= 'margin-top:' . (int) $title_margin_top . 'px;';
if($title_margin_bottom !='') $title_style .= 'margin-bottom:' . (int) $title_margin_bottom . 'px;';
if($title_text_color) $title_style .= 'color:' . $title_text_color . ';';
if($title_fontsize) $title_style .= 'font-size:'.$title_fontsize.'px;line-height:'.$title_fontsize.'px;';
if($title_fontweight) $title_style .= 'font-weight:'.$title_fontweight.';';
$output .= '<'.$heading_selector.' class="pb-addon-title" style="' . $title_style . '">' . $title . '</'.$heading_selector.'>';
}
$output .= '<div class="pb-addon-content">';
$output .= '<form class="pb-ajax-contact-form">';
$output .= '<div class="pb-form-group">';
$output .= '<input type="text" name="name" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_NAME') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<input type="email" name="email" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_EMAIL') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<input type="text" name="subject" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SUBJECT') .'" required="required">';
$output .= '</div>';
$output .= '<div class="pb-form-group">';
$output .= '<textarea type="text" name="message" rows="5" class="pb-form-control" placeholder="'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_MESSAGE') .'" required="required"></textarea>';
$output .= '</div>';
if($formcaptcha)
{
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger('onInit', 'dynamic_captcha_1');
$captchas = $dispatcher->trigger('onDisplay', array(null, 'dynamic_captcha_1', 'class=""'));
$index = 0;
foreach (JPluginHelper::getPlugin('captcha') as $plugin)
{
if (JFactory::getApplication()->get('captcha', '0') === $plugin->name)
{
$captcha = $captchas[$index];
break;
}
$index++;
}
$output .= (isset($captcha)) ? $captcha : '';
$output .= '<div class="clearfix"></div><p></p>';
}
$output .= '<input type="hidden" name="recipient" value="'. base64_encode($recipient_email) .'">';
$output .= '<input type="hidden" name="title" value="'. $title .'">';
$output .= '<button type="submit" class="btn btn-default"><i class="fa"></i> '. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SEND') .'</button>';
$output .= '</form>';
$output .= '<div style="display:none;margin-top:10px;" class="pb-ajax-contact-status"></div>';
$output .= '</div>';
$output .= '</div>';
return $output;
}
function ajax_contact_get_ajax()
{
$config = JFactory::getConfig();
$jinput = JFactory::getApplication()->input;
//inputs
$inputs = $jinput->get('data', array(), 'ARRAY');
$mail = JFactory::getMailer();
// TODO: Find the way to check if captcha is enabled in the addon
$formcaptcha = true;
$message = "";
// TODO: CHECK CAPTCHA and add a Helper Class to get the captchas
switch (JFactory::getApplication()->get('captcha', '0'))
{
case 'recaptcha':
// v.1:
//$captcha_challenge_field = 'recaptcha_challenge_field';
//$captcha_answer_field = 'recaptcha_response_field';
// v.2:
$captcha_challenge_field = '';
$captcha_answer_field = 'g-recaptcha-response';
break;
case 'n3tseznamcaptcha':
$captcha_challenge_field = 'n3t_seznam_captcha_hash';
$captcha_answer_field = 'n3t_seznam_captcha';
break;
default:
// disable captcha as we could not find the right fields
$formcaptcha = false;
}
foreach ($inputs as $input)
{
if( $input['name'] == 'title' )
{
$title = $input['value'];
}
if( $input['name'] == 'recipient' )
{
$recipient = base64_decode($input['value']);
}
if( $input['name'] == 'email' )
{
$email = $input['value'];
}
if( $input['name'] == 'name' )
{
$name = $input['value'];
}
if( $input['name'] == 'subject' )
{
$subject = $input['value'];
}
if( $input['name'] == 'message' )
{
$message = nl2br( $input['value'] );
}
if( $input['name'] == $captcha_challenge_field )
{
$captcha_challenge = $input['value'];
}
if( $input['name'] == $captcha_answer_field )
{
$captcha_answer = $input['value'];
}
}
$valid_captcha = true;
if($formcaptcha)
{
// get the plugin
JPluginHelper::importPlugin('captcha');
$dispatcher = JEventDispatcher::getInstance();
$jinput->set($captcha_challenge_field, $captcha_challenge);
$jinput->set($captcha_answer_field, $captcha_answer);
$res = $dispatcher->trigger('onCheckAnswer', $captcha_answer);
$index = 0;
foreach (JPluginHelper::getPlugin('captcha') as $plugin)
{
if (JFactory::getApplication()->get('captcha', '0') === $plugin->name)
{
$valid_captcha = $res[$index];
break;
}
$index++;
}
if(!$valid_captcha)
{
$msg = '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_FORM_WRONG_CAPTCHA') .'</span>';
}
}
if ($valid_captcha)
{
// We do not want to send the email as a fake user, it may cause spam problems
$sender = array(
$config->get( 'mailfrom' ),
$config->get( 'fromname' )
);
$subject = (($title)? '['.$title.'] ' : '') . $subject;
$message .= JText::sprintf('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_EMAIL_SIGNATURE', JUri::getInstance()->toString(), JUri::getInstance());
$mail->setSender($sender);
$mail->addRecipient($recipient);
$mail->setSubject($subject);
$mail->AddReplyTo($email);
$mail->isHTML(true);
$mail->Encoding = 'base64';
$mail->setBody($message);
if ($mail->Send())
{
$msg = '<span class="pb-text-success">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_SUCCESS') .'</span>';
} else {
$msg = '<span class="pb-text-danger">'. JText::_('COM_PAGEBUILDER_ADDON_AJAX_CONTACT_FAILED') .'</span>';
}
}
// There is a problem with pagebuilder cache and captchas
$cache = JFactory::getCache('page');
$cache->clean();
return $msg;
}
That functionality is now integrated into SP Page Builder Contact Form Addon.
1) Grab the reCaptcha API keys from the console: https://www.google.com/recaptcha/admin
2) Enable reCaptcha plugin in Joomla's backend:
Joomla Control Panel and navigate to Extensions > Plugins > captcha - reCaptcha
3) Enable reCaptcha in your Joomla configuration:
Go to System > Global Configuration > Site Settings > Default Captcha
4) Go to your Contact Form (or create a new one) and enable captcha. Then choose "CAPTCHA - reCAPTCHA" in Captcha type selector.
After completing the above steps, if you don't see a reCAPTCHA box on the contact form frontend, it means that your template uses the old contact addon code. In most cases, you can safely take a backup and then delete the (bold) folder: templates\YOUR-TEMPLATE-NAME\sppagebuilder\addons\ajax_contact
All the info you need is available in this article: https://www.joomshaper.com/blog/google-recaptcha-joomla-contact-forms-integration
how do make it so that when I edit an entry, the correct value for my custom field type is selected? I have this so far:
class JFormFieldCustom extends JFormField {
protected $type = 'Custom';
// getLabel() left out
public function getInput() {
return '<select id="'.$this->id.'" name="'.$this->name.'">'.
'<option value="1" >1</option>'.
'<option value="2" >2</option>'.
'</select>';
}
}
How do I pass the selected value to this class so I can do:
<option value="1"SELECTED>1</option>
or
<option value="2" SELECTED>2</option>
Thanks!
It's easier to use what's already there, i.e. extend JFormFieldList in place of JFormField, then all you have to do is return the option's for your list. The inherited functionality will do the rest for you - including selecting the option that matches $this->value
<?php
/**
* Do the Joomla! security check and get the FormHelper to load the class
*/
defined('_JEXEC') or die('Restricted Access');
JFormHelper::loadFieldClass('list');
class JFormFieldMyCustomField extends JFormFieldList
{
/**
* Element name
*
* #var string
*/
public $type = 'MyCustomField';
/**
* getOptions() provides the options for the select
*
* #return array
*/
protected function getOptions()
{
// Create an array for our options
$options = array();
// Add our options to the array
$options[] = array("value" => 1, "text" => "1);
$options[] = array("value" => 1, "text" => "1);
return $options;
}
}
Use $this->value to get selected value.Try this-
class JFormFieldCustom extends JFormField {
protected $type = 'Custom';
// getLabel() left out
public function getInput() {
return '<select id="'.$this->id.'" name="'.$this->name.'">'.
'<option value="1" <?php echo ($this->value==1)?'selected':''?>>1</option>'.
'<option value="2" <?php echo ($this->value==2)?'selected':''?>>2</option>'.
'</select>';
}
}
Hope this will help.
Select for Joomla
http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* #copyright (c) 2017 YouTech Company. All Rights Reserved.
* #author macasin
*/
defined('_JEXEC') or die;
JFormHelper::loadFieldClass('list');
class JFormFieldSelect extends JFormFieldList
{
protected $type = 'select';
protected function getInput()
{
$html = array();
$attr = '';
// Initialize some field attributes.
$attr .= !empty($this->class) ? ' class=select ' . $this->class . '"' : ' class=select ';
$attr .= $this->readonly ? ' readonly' : '';
$attr .= $this->disabled ? ' disabled' : '';
$attr .= !empty($this->size) ? ' size="' . $this->size . '"' : '';
$attr .= $this->required ? ' required aria-required="true"' : '';
// Initialize JavaScript field attributes.
$attr .= $this->onchange ? ' onchange="' . $this->onchange . '"' : '';
// Get the field options.
$options = $this->getOptions();
// Load the combobox behavior.
JHtml::_('behavior.combobox');
$html[] = '<div class="select input-append">';
// Build the input for the combo box.
$html[] = '<select name="' . $this->name . '" id="' . $this->id . '" value="'
. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . $attr . ' autocomplete="off" >';
foreach ($options as $option)
{
$html[] = '<option '.($option->value == $this->value ? "selected" : "").' value='.$option->value.'>' . $option->text . '</option>';
}
$html[] = '</select></div>';
return implode($html);
}
}
I use CI 2.1 and GroceryCRUD 1.3.3, i use this 2 function in my controller Admin, but i cant update value of row wher i have 2 values 0/1:
bolean from my view side by click on link or with AJAX (prefered)
function programs_management()
{
if($this->input->get("enable_recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation")=="1")?"1":"0",
);
$this->db->update('programs',$data_for_update,array('program_id' => $this->input->get("programs")));
}
}
function enable_recomandation($value, $row = NULL)
{
// or For AJAX some solution need
// return "<form action='' method='post'>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='activ'>Activ<br>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='inactiv'>Inactiv
// </form>";
if($value=="1")
return '<a href="'.base_url().'/admin/programs_management/?recomandation=0&program_id='.$row->program_id.'" >Active</a>';
else
return '<a href="'.base_url().'/admin/programs_management/?recomandation=1&program_id='.$row->program_id.'" >Inactive</a>';
}
Or somebody can help with alternative, how to do this with AJAX ?
function programs_management()
{
if ($this->input->get("recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation") == "y") ? "1" : "0",
);
$this->db->update('programs', $data_for_update, array('program_id' => $this->input->get("program_id")));
}
}
function enable_recomandation($value, $row = NULL)
{
if ($value == "1")
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=n&program_id=' . $row->program_id . '" >Active</a>';
else
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=y&program_id=' . $row->program_id . '" >Inactive</a>';
}
How to get specific product attribute value if i know product ID without loading whole product?
Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);
A way that I know of:
$product->getResource()->getAttribute($attribute_code)
->getFrontend()->getValue($product)
you can use
<?php echo $product->getAttributeText('attr_id') ?>
Please see Daniel Kocherga's answer, as it'll work for you in most cases.
In addition to that method to get the attribute's value, you may sometimes want to get the label of a select or multiselect. In that case, I have created this method which I store in a helper class:
/**
* #param int $entityId
* #param int|string|array $attribute atrribute's ids or codes
* #param null|int|Mage_Core_Model_Store $store
*
* #return bool|null|string
* #throws Mage_Core_Exception
*/
public function getAttributeRawLabel($entityId, $attribute, $store=null) {
if (!$store) {
$store = Mage::app()->getStore();
}
$value = (string)Mage::getResourceModel('catalog/product')->getAttributeRawValue($entityId, $attribute, $store);
if (!empty($value)) {
return Mage::getModel('catalog/product')->getResource()->getAttribute($attribute)->getSource()->getOptionText($value);
}
return null;
}
It seems impossible to get value without loading product model. If you take a look at file app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php you'll see the method
public function getValue(Varien_Object $object)
{
$value = $object->getData($this->getAttribute()->getAttributeCode());
if (in_array($this->getConfigField('input'), array('select','boolean'))) {
$valueOption = $this->getOption($value);
if (!$valueOption) {
$opt = new Mage_Eav_Model_Entity_Attribute_Source_Boolean();
if ($options = $opt->getAllOptions()) {
foreach ($options as $option) {
if ($option['value'] == $value) {
$valueOption = $option['label'];
}
}
}
}
$value = $valueOption;
}
elseif ($this->getConfigField('input')=='multiselect') {
$value = $this->getOption($value);
if (is_array($value)) {
$value = implode(', ', $value);
}
}
return $value;
}
As you can see this method requires loaded object to get data from it (3rd line).
First we must ensure that the desired attribute is loaded, and then output it. Use this:
$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
Try this
$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
You don't have to load the whole product.
Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
This one works-
echo $_product->getData('ATTRIBUTE_NAME_HERE');
You can get attribute value by following way
$model = Mage::getResourceModel('catalog/product');
$attribute_value = $model->getAttributeRawValue($productId, 'attribute_code', $storeId);
$orderId = 1; // YOUR ORDER ID
$items = $block->getOrderItems($orderId);
foreach ($items as $item) {
$options = $item->getProductOptions();
if (isset($options['options']) && !empty($options['options'])) {
foreach ($options['options'] as $option) {
echo 'Title: ' . $option['label'] . '<br />';
echo 'ID: ' . $option['option_id'] . '<br />';
echo 'Type: ' . $option['option_type'] . '<br />';
echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
}
}
}
all things you will use to retrieve value product custom option cart order in Magento 2: https://www.mageplaza.com/how-get-value-product-custom-option-cart-order-magento-2.html
You could write a method that would do it directly via sql I suppose.
Would look something like this:
Variables:
$store_id = 1;
$product_id = 1234;
$attribute_code = 'manufacturer';
Query:
SELECT value FROM eav_attribute_option_value WHERE option_id IN (
SELECT option_id FROM eav_attribute_option WHERE FIND_IN_SET(
option_id,
(SELECT value FROM catalog_product_entity_varchar WHERE
entity_id = '$product_id' AND
attribute_id = (SELECT attribute_id FROM eav_attribute WHERE
attribute_code='$attribute_code')
)
) > 0) AND
store_id='$store_id';
You would have to get the value from the correct table based on the attribute's backend_type (field in eav_attribute) though so it takes at least 1 additional query.
If you have an text/textarea attribute named my_attr you can get it by:
product->getMyAttr();
Magento Admin has a store select drop down list of all the stores.
I have added an addititional "SELECT ALL STORES" value to allow me to know when a user wishes to carry out a task on all stores.
I based this customisation on enterprise magento version 1.9 although I think the version is quite irrelevant since my question is quite generic to magento I think.
How do I stop my "SELECT ALL STORES" from being selected by default in the search ?
/index.php/admin/admin/urlrewrite/index
The store list select form is built here:
app\code\core\Adminhtml\Block\Widget\Grid\Column\Filter\Store.php
Once I found that, I could override it to the local code pool and make the modifications I needed.
public function getHtml()
{
$storeModel = Mage::getSingleton('adminhtml/system_store');
/* #var $storeModel Mage_Adminhtml_Model_System_Store */
$websiteCollection = $storeModel->getWebsiteCollection();
$groupCollection = $storeModel->getGroupCollection();
$storeCollection = $storeModel->getStoreCollection();
$allShow = $this->getColumn()->getStoreAll();
$html = '<select name="' . $this->_getHtmlName() . '" ' . $this->getColumn()->getValidateClass() . '>';
$value = $this->getColumn()->getValue();
//if ($allShow) {
$html .= '<option value=""' . (**$value == 0** ? ' selected="selected"' : '') . '>' . Mage::helper('adminhtml')->__('All Store Views') . '</option>';
//} else {
// $html .= '<option value=""' . (!$value ? ' selected="selected"' : '') . '></option>';
//}