This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

carmelo.magnafico6209
carmelo.magnafico6209

Hello everybody,

I'm writing a plugin. I'm writing the Module:: class and I would access to the form posted data. I'm building my plugin with builder.

If I would use $this->fieldname, in afterValidate() function I get nothing, or, if the item is already saved the saved field and not the edited field in the form.

It's driving me crazy, anyone can say me how to get the field?

Thank you in advance.

Carmelo

Last updated

Crazymodder
Crazymodder

In which context you call $this? In your model? or in a controller? Please post some code.

carmelo.magnafico6209
carmelo.magnafico6209

In module, I'm trying to store it in Session handler and to get it in Controller

Here it is my Module



namespace Citrino\Contentesimporter\Models;

use File as FileExt;
use Config;
use Flash;
use Cms\Classes\ComponentBase;
use Model;
use Exception;
use Redirect;
use Session;

use Storage;
use System\Models\File;

use Citrino\Contentesimporter\Classes\htmlExporter;

use RainLab\Pages\Classes\Controller;
/**
 * Model
 */
class Import extends Model
{

    /*
     * Validation
     */
    use \October\Rain\Database\Traits\Validation;

    public $rules = [
        'title'         => 'required|min:4',
        'slug'   => 'required'    ];

    /*
     * Disable timestamps by default.
     * Remove this line if timestamps are defined in the database table.
     */
    public $timestamps = false;

    /**
     * @var string The database table used by the model.
     */
    public $table = 'citrino_contentesimporter_imports';

    public $attachOne = [ 'filegen' => ['System\Models\File'] ];

public $attachMany = [ 'images' => ['System\Models\File', 'order' => 'sort_order'] ];

    public function beforeFetch(){
        //var_dump($this->getLayoutOptionsList());
    }

    public function getLayoutOptions($keyValue = null)
    {
        $layouts_directory_path = base_path()."/themes/".Config::get("cms.activeTheme",'')."/layouts";
        $layouts = FileExt::files($layouts_directory_path);
        $options = [];
        foreach ($layouts as $key=>$value) {
            $options[basename($value)] = basename($value,'.htm');
        }

        return $options;

    }
    public function afterValidate()
    {
        //Session::put('override',$this->override);
        var_dump($this->slug);
        Session::put('slug',$this->slug);
        Session::put('title',$this->title);

    }
    public function filterFields($fields, $context = null){

        if($fields->filegen->value == -1){

            $chapter = $this->fileGetContent();

            $fields->title->value = $chapter['title'];
            $fields->import_contents->hidden = false;

            $chapter_struct = 'il contenuto del capitolo: '.$chapter['title'].'
';

            foreach ($chapter['paragraphs'][0] as $key => $paragraph) {
                if (array_key_exists('title',$paragraph)){
                     $chapter_struct .= nl2br(e('-  '.$paragraph['title'])).'
';
                }
            }

            $fields->import_contents->value = $chapter_struct ;

            //var_dump($fields->force_update);
        }

    }

    public function beforeDelete(){
        define('DS',DIRECTORY_SEPARATOR);

        $local_path = DS.'Rapporto';

        $chapter_directory_name = "Chapter_".substr($this->slug,1);
        $content_directory_path = base_path().DS."themes".DS.Config::get("cms.activeTheme",'').DS."content";
        $page_directory_path = base_path().DS."themes".DS.Config::get("cms.activeTheme",'').DS."pages".$local_path;
        $chapter_directory_path = $content_directory_path.DS.$chapter_directory_name;
        $page_full = $page_directory_path.DS.'Chapter_'.substr($this->slug,1).'.htm';

        if(FileExt::isDirectory($chapter_directory_path)){
            FileExt::deleteDirectory($chapter_directory_path,true);
        }
        if(FileExt::isFile($page_full)){
            FileExt::delete($page_full);
        }

    }
/*
     public function getForceUpdate(){
        $sessionKey = \Input::get('_session_key');
        return $this->force_update;

     }
*/
/*
     public function beforeCreate(){

        //var_dump(Session::get('chapter_create'));

        if(Session::get('chapter_create')==true){
            //throw new \Exception("The given name already exists");

        }else{
            Redirect::back();
            return false; 
        }

     }
*/

    public function fileGetContent(){

        $sessionKey = \Input::get('_session_key');

        // returns the latest file uploaded in the current session
        // is this a reliable approach?
        $file = $this
            ->filegen()
            ->withDeferred($sessionKey)
            ->latest()
            ->first();

        $filename = $file->getLocalPath();   

        $htmlExporter = new htmlExporter;
        $images = $this->getImageAttribute();

        $chapter = $htmlExporter->generateParagraphs($filename, $images );

        return $chapter;

    }

    public function getImageAttribute(){
        $sessionKey = \Input::get('_session_key');
        $img = $this->images()->withDeferred($sessionKey)->get();

        $images = [];
        foreach ($img as $key => $image) {
            $images[$image->getFileName()] = $image->getPath();
        }

        return $images;

    }

    public function pageGeneration($chapter,$meta = array('robot_index'=>'index','robot_follow'=>'follow')){

        $title = $chapter['title'];
        $slug = $this->slug;
        $layout = $this->layout;
        if(!$layout){$layout = 'defalut';};
        $page = '
title = "'.$title.'"
url = "/Rapporto/'.substr($slug, 1).'"
layout = "'.$layout.'"
is_hidden = 0
robot_index = "'.$meta['robot_index'].'"
robot_follow =  "'.$meta['robot_follow'].'"
==
{% partial "chapterRender" capitolo="'.substr($slug, 1).'" title="'.$title.'" %}';

        return $page;

    }

}

here the controller:


namespace Citrino\Contentesimporter\Controllers;

use Backend\Classes\Controller;
use Backend\Classes\ControllerBehavior;
use BackendMenu;
use Model;
use Input;
use Session;
use Config;
use Flash;
use Redirect;
use ValidationException;

use File as FileExt;

class Imports extends Controller
{
    public $implement = ['Backend\Behaviors\ListController','Backend\Behaviors\FormController','Backend\Behaviors\ReorderController'];

    public $listConfig = 'config_list.yaml';
    public $formConfig = 'config_form.yaml';
    public $reorderConfig = 'config_reorder.yaml';

    public $requiredPermissions = [
        'citrino.contentesimporter_manage_import' 
    ];

    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('Citrino.Contentesimporter', 'ContentesImporter', 'imports');
    }

    public function formBeforeSave($model){

        define('DS',DIRECTORY_SEPARATOR);

        $slug = Session::get('slug');
        $title = Session::get('title');
        $override = Session::get('override');

 $chapter = $model->fileGetContent();
        $local_path = DS.'Rapporto';

        $chapter_directory_name = "Chapter_".substr($slug,1);
        $content_directory_path = base_path().DS."themes".DS.Config::get("cms.activeTheme",'').DS."content";
        $page_directory_path = base_path().DS."themes".DS.Config::get("cms.activeTheme",'').DS."pages".$local_path;
        $chapter_directory_path = $content_directory_path.DS.$chapter_directory_name;
        $page_full = $page_directory_path.DS.'Chapter_'.substr($slug,1).'.htm';

        //page Content
        $meta = array('robot_index'=>'index','robot_follow'=>'follow');
        $pageContent = $model->pageGeneration($chapter, $meta);

        if(!FileExt::isDirectory($chapter_directory_path)){
            $out = FileExt::makeDirectory($chapter_directory_path);
            foreach ($chapter['paragraphs'][0] as $key => $paragraph) {
                if (array_key_exists('title',$paragraph)){
                    FileExt::put($chapter_directory_path.DS.'paragraph'.($key+1).'.htm', $paragraph['plaintext']);
                }
            }
            // write the page files
            FileExt::put($page_full,$pageContent);

            //go 
            Flash::success('Il Capitolo '.$chapter['title'].' é stato creato correttamente!');
        }else{

            if($override){

                throw new ValidationException(['override' => "Il Capitolo ".$title." esite già, se vuoi aggiornarlo spunta l'opzione Override!"]);

            }else{

                FileExt::deleteDirectory($chapter_directory_path,true);
                // write the page files
                FileExt::delete($page_full);

                foreach ($chapter['paragraphs'][0] as $key => $paragraph) {
                    if (array_key_exists('title',$paragraph)){
                        FileExt::put($chapter_directory_path.DS.'paragraph'.($key+1).'.htm', $paragraph['plaintext']);
                    }
                }
                FileExt::put($page_full,$pageContent);

                Flash::success('Il Capitolo '.$model->title.' é stato aggiornato correttamente!');

        }

    }

}

}//end Controller

Last updated

carmelo.magnafico6209
carmelo.magnafico6209

Hello everybody,

finally I found it!!!

Get the data from the form, as they where pushed to the page from ajax, it's simple:


$attributes = $this->getAttributes();
$myfield = $attributes['myfield'];

Hope it can help someone.

Carmelo

1-4 of 4

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.