I am developing a custom module in which I want to:
Upload an image through a form.
Move image from default folder to my desired folder.
And finally display the image under the same form (below the submit button).
I've achieved the first goal by implementing hook_menu and hook_form but I am stucked very badly in the remaining two goals for last 3 days. Whenever I try to move uploaded image from default folder I get the error message of "Invalid location" and for the third point I didn't understand what to do? I want when the user selects the image and submits the form the image is displayed on the same page under the submit button. Any help would be really appreciated. Here's my code:-
function create_ad_form($form, &$form_submit)
{
...
$form['image_file'] = array(
'#title' => t('Upload Banner:'),
'#type' => 'file'
);
$form['#attributes']['enctype'] = 'multipart/form-data';
...
}
function create_ad_form_submit($form, &$form_state)
{
$module=drupal_get_path('module', 'create_ad');
$validators = array();
$file = file_save_upload('image_file', $validators,"public://",FILE_EXISTS_RENAME);
if ($file)
{
$file->status=FILE_STATUS_PERMANENT;
file_save($file);
$result = file_unmanaged_copy($file, $module, FILE_EXISTS_RENAME);
if ($result == 1)
{
}
else
{
drupal_set_message('Couldn\'t copy file: '.$file->name);
}
}
else
{
form_set_error('create_ad', t("Failed to save the file."));
}
}
I've managed to display the image, however still can't move the image to any folder so placed them in the default "public://" directory. Display image on the same page without ajax is discussed here: Drupal 7 FAPI- Adding form elements in validate or submit handlers and with ajax discussed here: Drupal 7 FAPI - ajax image preview
Related
I'm trying to generate an excel file using PHPExcel Module in the action_info function with the following code :
function mymodule_export_data_action(&$object, $context = array()) {
if (isset($object->uid)) {
$uid = $object->uid;
}
elseif (isset($context['uid'])) {
$uid = $context['uid'];
}
if ($uid) {
module_load_include('inc', 'phpexcel');
$filename = 'mymodule--download-' . uniqid() . '.xls';
$filepath = variable_get('file_public_path', conf_path() . '/files') . '/' . $filename;
$result = phpexcel_export(
array('Nom', 'Prenom', 'Date de naissance', 'Adresse email'),
array(
array('A1', 'B1'),
array('A2', 'B2'),
), $filepath);
if ($result === PHPEXCEL_SUCCESS) {
drupal_set_message(l('Click to download', $filepath));
}
else {
}
}
}
This is working pretty fine when having just one node, but when there's more than one it generates a new file for each one, which also good but my purpose is to have one file for all nodes. It has been days and I really hope for someone to put me in the right direction.
Thank you in advance
Here is the solution by using views module, views_data_export module, 2 lines of PHP code and some lines of jQuery.
Just follow these steps:
1st Install views and views_data_export modules
2nd (a) Create views page and data export, this video
will help you to export the data according to the
filter(s)
2nd (b) Don't forget to add nid field in the views page that will use to get NIDs
2nd (c) Now, create one more views data export (that again starts here, if you need) and create exporting PATH different than the first data export (created on step 2nd (a)) but keep remember you don't have to update Attach to option under the DATA EXPORT SETTINGS section, it should looks like this Attach to: none.
2nd (d) Now, add nid as contextual filter in the views and choose Provide default value = Content ID from URL like this and check the checkbox Allow multiple values like this
3rd Add two lines of PHP code somewhere in the template.php OR top of the tpl of views page if you have already created (by the way I did it with the tpl named as views-view--export-multiple-rows--page.tpl.php).
if($_SERVER['REQUEST_METHOD'] == 'POST') {
drupal_goto("export_selected/".implode(',', $_POST['export']));
}
4th Add below jQuery code in the JS file that will be render on this page like custom.js and **change classes **
jQuery(function($){
jQuery('.feed-icon a:first-child').text('Export All');
jQuery('td.views-field-nid').each(function() { //class of NID added in step 2nd (b)
var t = jQuery(this);
var id = jQuery.trim(t.text());
t.html('<input type="checkbox" name="export[]" value="" />');
t.find('input').val(id);
});
//Below .view-export-multiple-rows class is of views class (main views page)
$('.view-export-multiple-rows').wrap('<form method="POST" class="export-form"></form>');
$('.export-form .view-content').append('<input type="submit" value="Export Selected" name="submit" />');
});
If you follow all these steps properly, I believe you have done with:
To export all rows
To export filtered rows
To export specific rows
I hope this will help you or at least give you an idea.
Thanks
Hi i'm new in Laravel and i've this simple problem. I have app where user can create some article and also can to upload main image for that article and it works perfect. I also want to give possibility to user to upload more images for his article. I already create model (ArticleImage) and add relationship between Article and ArticleImage. And i created form field for uploading multiple file inside the article form. But i don't know now how to tell laravel to save all names of these paths into database and store image inside the public/images folder, than later in views i can use these images. Do i need now to create ArticleImage controller and inside controller to write that function or i should do that inside Article controller inside store function. Tnx in advance for every help.
Here is link to github-repo(https://github.com/Dabizlja/Laravel-blog)
If form sends input as array.
<input name="picures[]" />
In your ArticleController on save you can use a json type
$files=[];
$pictures = $request['pictures'];
if (count($pictures) > 0 && $pictures[0] != null) {
foreach ($pictures as $picture) {
$validator = Validator::make([$picture], ['mimes:jpeg,jpg,bmp,png']);
if ($validator->fails()) {
return $validator->messages()->all();
}
$picture->move(public_path() . '/images/', $picture->getClientOriginalName());
array_push($files, $picture->getClientOriginalName());
}
}
$article->images = json_encode($files);
To get it back in the view
<?php
foreach ( $images as $file) {
echo '<img src="'asset('/images/' . $file)'"/>';
}
?>
In your controller on edit remember to decode the json
$files = json_decode($article->images);
To delete a picture you would have to go through the array and remove it the same way.
Hope this works for you.
May be
$article->articleImages()->saveMany($images);
Hopefully this will solve your problem
How do I use the Form for creating a Cohort in Moodle in my own plugin?
I want to use the form, create the Cohort and return to a URL specified by with the Cohort id as a GET parameter ie http://myip/moodle/myplugin/myscrip.php?cohort_id=0
I've taken a look at the moodle files for the form but it's all chinese for me as i'm a complete novice as it comes to moodle development. What is the 'nice' way of using it?
The forms take a bit of getting used to, they are based on quickforms.
https://docs.moodle.org/dev/Form_API
https://docs.moodle.org/dev/lib/formslib.php_Usage
https://docs.moodle.org/dev/lib/formslib.php_Form_Definition
Usually there is a file named edit.php which uses the class in edit_form.php - but the file names can be anything.
You could take a copy of /cohort/edit.php and put it into your local plugin. If you are only creating cohorts and not updating them, then remove the update and delete code and keep the add cohort code:
$cohortid = cohort_add_cohort($data);
if ($usetags) {
if (isset($data->otags)) {
tag_set('cohort', $cohortid, tag_get_name($data->otags));
} else {
tag_set('cohort', $cohortid, array());
}
}
//update textarea
$data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'cohort', 'cohort', $cohortid);
$DB->set_field('cohort', 'description', $data->description, array('id' => $cohortid));
Then redirect to your link
$url = new moodle_url('/myplugin/myscrip.php', array('cohort_id' => $cohortid));
redirect($url);
I've installed the latest version of yii2 using the advanced template. The website is working fine. For some reason the Gii generation tool is stuck and does not react as expected after clicking the preview button. Instead of showing a new form with the "Generate" button, it shows the same form unchanged without any messages as to what is happening.
Using xdebug I can see in the "actionView" method of the DefaultController that the array value $_POST['preview'] is not set, i.e. it doesn't exist in the $_POST array. I have not changed anything in the Form of the view and everything looks OK. The submit button has the name "preview" and the form is submitted but the $_POST array is not being filled with the value of the submit button. Therefore the controller does not proceed with the next steps of the generation process.
public function actionView($id)
{
$generator = $this->loadGenerator($id);
$params = ['generator' => $generator, 'id' => $id];
// ###############################################################################
// ### THIS IF STATEMENT IS NOT TRUE BECAUSE $_POST['preview'] IS NOT SET !!! ###
// ###############################################################################
if (isset($_POST['preview']) || isset($_POST['generate'])) {
// ###############################################################################
if ($generator->validate()) {
$generator->saveStickyAttributes();
$files = $generator->generate();
if (isset($_POST['generate']) && !empty($_POST['answers'])) {
$params['hasError'] = !$generator->save($files, (array) $_POST['answers'], $results);
$params['results'] = $results;
} else {
$params['files'] = $files;
$params['answers'] = isset($_POST['answers']) ? $_POST['answers'] : null;
}
}
}
return $this->render('view', $params);
}
Does anyone have an idea what could be causing this? I have a hunch that it is something quite simple that I'm overlooking, but I've never had a situation where POST variable from a Form are not being sent to the server.
False Alarm. I've found the problem. The Gii view was creating the HTML Form incorrectly.
iam using ckeditor in my website to add the content to the pages.
But I'm not able to understand how I get this content in ckeditor for editing it later...
How to load content into the ckeditor? Iam using the following code to load the editor:
if ( !#file_exists( '../../ckeditor/ckeditor.php' ) )
{
if ( #file_exists('../../ckeditor/ckeditor.js') || #file_exists('../../../ckeditor/ckeditor_source.js') )
printNotFound('CKEditor 3.1+');
else
printNotFound('CKEditor');
}
include_once '../../ckeditor/ckeditor.php';
include_once '../../ckfinder/ckfinder.php';
// This is a check for the CKEditor class. If not defined, the paths in lines 57 and 70 must be checked.
if (!class_exists('CKEditor'))
{
printNotFound('CKEditor');
}
else
{
$ckeditor = new CKEditor();
$ckeditor->basePath = '../../ckeditor/';
$ckfinder = new CKFinder();
$ckfinder->BasePath = '../../ckfinder/'; // Note: BasePath property in CKFinder class starts with capital letter
$ckfinder->SetupCKEditorObject($ckeditor);
$ckeditor->editor('message');
}
One way is to pre-populate the <textarea> field with the appropriate (htmlentities() processed) HTML content. CKEditor will automatically fetch the data, and insert it into the WYSIWYG editor.
See the Integration chapter in the developers guide
For those who not found the answer, the "editor" method of ckeditor allow to load default value
public function editor($name, $value = "", $config = array(), $events = array())
Just pass your default value in the second parameters.