Joomla, Sp Page Builder and ReCaptcha - joomla

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

Related

use route in controller

i'm trying to fetch data(jobs) and display each single job i have route for jobs and route for single job but when i use route in controller i get route not defined even all is good please check my question
ajax call
<script>
$(document).on('click','.submit', function(e) {
var category = $("input[name=category_id]").val();
var location= $(".js-example-basic-single option:selected" ).val();
console.log(location);
$.ajax({
type:'get',
data: {location : location,category : category},
url:'/job_listing',
success:function(data) {
$('.job-list').html(data);
console.log(category);
console.log(location);
}
})
});
function in cotroller
public function show_offers(Request $request){
$category = $request->category;
$location= $request->location;
if($request->ajax()) {
$data = Job_offer::where([
'category_id' => $category,
'location_id' => $location,
])->orwhere('location_id','=',$location)->orwhere('category_id','=',$category)->get();
// ->orWhere('location_id','LIKE','%'.$input.'%')->with('location')->get();
$output = '';
if (count($data)>0) {
$output = '';
foreach ($data as $row){
$output .= '<div class="job-info"> <div class="job_offer-img"><img class="offer-img" src='.'img/'.$row->offer_image.'></div>';
$output .= '<div class="job-title"> <span class="job"> '.$row->offer_title.'</span>';
$output .= '<span class="location">'.$row->location->Name.'</span></div>';
$output .= '<div class="job-contrat"> <span class="contract"> '.$row->type_emploi.'</span></div></div>';
}
$output .= '';
}
else {
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
return $output;
}
route
Route::get('single_offer/{offer_id}','job_seeker\Job_offers#single_offer')->name('single/offer');
Route::get('job_listing','job_seeker\home_job_seeker#show_offers');
Your routes need to be in routes/api.php file instead of routes/web.php file.
Use like this
href='."{{route('single/offer',['offer_id'=>$row->id])}}".'

How to use Ajax pager in Drupal7

I want to use ajax_pager in my block.
I've installed Libraries API and Ajax Pager API (as it described on the AP API page). But it's still not working.
When I use 'pager' instead of 'ajax_pager' it works.
What I'm doing wrong?
<?php
function latest_news_block_info() {
$blocks['latest_news_block'] = array(
// info: The name of the block.
'info' => t('Latest News'),
);
return $blocks;
}
function latest_news_block_view($delta = '') {
// The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'latest_news_block':
// Create your block content here
$block['subject'] = t('Last news');
$query = new EntityFieldQuery();
//change news by the name of your content type
$entities = $query->entityCondition('entity_type', 'node')
->pager(5, 0)
->entityCondition('bundle', 'news')
->propertyOrderBy("created", "DESC")
->execute();
$content = "";
foreach($entities['node'] as $obj) {
$node = node_load($obj->nid);
$content .= "<img src='" .file_create_url($node->field_image['und'][0]['uri']) . "' width='200px' height='200px'>" . l($node->title, "node/" . $node->nid) . truncate_utf8($node->body['und'][0]['value'], 200, true, true) . '<br><hr>';
$block['content'] = $content;
}
break;
}
$pager = theme('ajax_pager', array('parameters' => array('selector' => 'block-system-main')));
$block['content'] .= $pager;
return $block;
}

Changing Joomla 2.5 behaviour for opening articles that shall be edited in a new window

I would like to have it so that users that are logged into the frontend of my Joomla site can edit their articles in a new window without any template applied as soon they press on the edit Button, so that only the editor (in this case JCE) is shown.
I found the source code in components/com_content/helpers/Icon.php, but have no idea if it's possible at all or how I have to re-code it. Any idea?
// Show checked_out icon if the article is checked out by a different user
if (property_exists($article, 'checked_out') && property_exists($article, 'checked_out_time') && $article->checked_out > 0 && $article->checked_out != $user->get('id')) {
$checkoutUser = JFactory::getUser($article->checked_out);
$button = JHtml::_('image', 'system/checked_out.png', NULL, NULL, true);
$date = JHtml::_('date', $article->checked_out_time);
$tooltip = JText::_('JLIB_HTML_CHECKED_OUT').' :: '.JText::sprintf('COM_CONTENT_CHECKED_OUT_BY', $checkoutUser->name).' <br /> '.$date;
return '<span class="hasTip" title="'.htmlspecialchars($tooltip, ENT_COMPAT, 'UTF-8').'">'.$button.'</span>';
}
$url = 'index.php?option=com_content&task=article.edit&a_id='.$article->id.'&return='.base64_encode(urlencode($uri));
$icon = $article->state ? 'edit.png' : 'edit_unpublished.png';
$text = JHtml::_('image', 'system/'.$icon, JText::_('JGLOBAL_EDIT'), NULL, true);
if ($article->state == 0) {
$overlib = JText::_('JUNPUBLISHED');
}
else {
$overlib = JText::_('JPUBLISHED');
}
$date = JHtml::_('date', $article->created);
$author = $article->created_by_alias ? $article->created_by_alias : $article->author;
$overlib .= '<br />';
$overlib .= $date;
$overlib .= '<br />';
$overlib .= JText::sprintf('COM_CONTENT_WRITTEN_BY', htmlspecialchars($author, ENT_COMPAT, 'UTF-8'));
$button = JHtml::_('link', JRoute::_($url), $text);
$output = '<span class="hasTip" title="'.JText::_('COM_CONTENT_EDIT_ITEM').' :: '.$overlib.'">'.$button.'</span>';
return $output;
You should create a template override for the view, in that you can place the link to edit adding:
&tmpl=component
to the url so that only the component part will be shown; and add the
target="_blank" to the <a href or the <form tag so it goes to a new window.
This will most likely open in a new tab, if you want a new window, build the url and pass it to the window.open call.

set a chosen image-file-input as a featured image from wp frontend

SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}

Codeigniter Form Helper - How to add additional parameters to "select" control?

I need to modify a site that was written in Codeigniter but I'm no expert.
One thing I'd like to do is modify a select control in a form to use ms-dropdown for a drop-down list including pictures.
However, I can't work out how to make the Codeigniter form helper render parameters other than ID and Value in each option. In this case, to make ms-dropdown work, it would need to also render data-image="..." in each option.
The current code looks like:
$dropdown = array(
'name'=>'MyDropDown',
'options' => array('Op1'=>'First Option', 'Op2' =>'Second Option')
);
echo form_dropdown($dropdown['name'],$dropdown['options']);
This renders as
<select name="MyDropDown">
<option value='Op1'>First Option</option>
<option value='Op2'>Second Option</option>
</select>
Is there a way for me to make Codeigniter render
<select name="MyDropDown">
<option value='Op1' data-image="filepath1">First Option</option>
<option value='Op2' data-image="filepath2">Second Option</option>
</select>
You can't. You would need to extend CI's Form Helper and modify
form_dropdown to accept other attributes like ID's
you will have to extend the helper .
to extend the native Form Helper you'll create a file named
application/helpers/MY_form_helper.php, and add or override
functions:
if you want to override function form_dropdown
simply write the function the way you want in MY_form_helper.php
here is the base function
if ( ! function_exists('form_dropdown'))
{
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
}
you have to edit this part ,
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
as you can see , only the option's value attribute is set by the function , you can edit this code and
do the thing you want ,
try it , if you could not do it , tell me i ll help you , but first give it a try :)
Consider doing something like this:
<script type="text/javascript">
var filepath = <?=json_encode($dropdown['filepath'])?>;
</script>
$dropdown['filepath'] would use the option value as keys and store the filepath as the value. Then you can simply access filepath[$(this).val()] upon change event.
Example output:
<script type="text/javascript">
var filepath = { 'Op1' : 'filepath1', 'Op2' : 'filepath2' };
$('select').bind('change', function() {
console.log(filepath[$(this).val()]);
});
</script>
As much as I love using data- attributes, one must not forget other ways to achieve their goals.
In case it helps anyone, I found a work-around using JQuery.
I made a javascript function that applied the data-image attribute to each option field once the page was ready, then called the msDropdown function afterwards.
function PiccifyShowDropdown(){
var Diagrams = new Array(
"/assets/images/icons/SixtyToHundredPercent.png",
"/assets/images/icons/LessThanThirtyPercent.png",
"/assets/images/icons/ThirtyToSixtyPercent.png",
"/assets/images/icons/SixtyToHundredPercent.png"
);
$("#Show > option").each(
function() {
$(this).attr("data-image",Diagrams[this.index]);
}
);
$("#Show").msDropdown({visibleRows:2});
}
This seems to have worked, so now I just need someone to solve the same problem as this guy...

Resources